three.js 920 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747
  1. // File:src/Three.js
  2. /**
  3. * @author mrdoob / http://mrdoob.com/
  4. */
  5. var THREE = { REVISION: '76dev' };
  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. // DDS / ST3C Compressed texture formats
  181. THREE.RGB_S3TC_DXT1_Format = 2001;
  182. THREE.RGBA_S3TC_DXT1_Format = 2002;
  183. THREE.RGBA_S3TC_DXT3_Format = 2003;
  184. THREE.RGBA_S3TC_DXT5_Format = 2004;
  185. // PVRTC compressed texture formats
  186. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  187. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  188. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  189. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  190. // ETC compressed texture formats
  191. THREE.RGB_ETC1_Format = 2151;
  192. // Loop styles for AnimationAction
  193. THREE.LoopOnce = 2200;
  194. THREE.LoopRepeat = 2201;
  195. THREE.LoopPingPong = 2202;
  196. // Interpolation
  197. THREE.InterpolateDiscrete = 2300;
  198. THREE.InterpolateLinear = 2301;
  199. THREE.InterpolateSmooth = 2302;
  200. // Interpolant ending modes
  201. THREE.ZeroCurvatureEnding = 2400;
  202. THREE.ZeroSlopeEnding = 2401;
  203. THREE.WrapAroundEnding = 2402;
  204. // Triangle Draw modes
  205. THREE.TrianglesDrawMode = 0;
  206. THREE.TriangleStripDrawMode = 1;
  207. THREE.TriangleFanDrawMode = 2;
  208. // Texture Encodings
  209. THREE.LinearEncoding = 3000; // No encoding at all.
  210. THREE.sRGBEncoding = 3001;
  211. THREE.GammaEncoding = 3007; // uses GAMMA_FACTOR, for backwards compatibility with WebGLRenderer.gammaInput/gammaOutput
  212. // The following Texture Encodings are for RGB-only (no alpha) HDR light emission sources.
  213. // These encodings should not specified as output encodings except in rare situations.
  214. THREE.RGBEEncoding = 3002; // AKA Radiance.
  215. THREE.LogLuvEncoding = 3003;
  216. THREE.RGBM7Encoding = 3004;
  217. THREE.RGBM16Encoding = 3005;
  218. THREE.RGBDEncoding = 3006; // MaxRange is 256.
  219. // File:src/math/Color.js
  220. /**
  221. * @author mrdoob / http://mrdoob.com/
  222. */
  223. THREE.Color = function ( color ) {
  224. if ( arguments.length === 3 ) {
  225. return this.fromArray( arguments );
  226. }
  227. return this.set( color );
  228. };
  229. THREE.Color.prototype = {
  230. constructor: THREE.Color,
  231. r: 1, g: 1, b: 1,
  232. set: function ( value ) {
  233. if ( value instanceof THREE.Color ) {
  234. this.copy( value );
  235. } else if ( typeof value === 'number' ) {
  236. this.setHex( value );
  237. } else if ( typeof value === 'string' ) {
  238. this.setStyle( value );
  239. }
  240. return this;
  241. },
  242. setScalar: function ( scalar ) {
  243. this.r = scalar;
  244. this.g = scalar;
  245. this.b = scalar;
  246. },
  247. setHex: function ( hex ) {
  248. hex = Math.floor( hex );
  249. this.r = ( hex >> 16 & 255 ) / 255;
  250. this.g = ( hex >> 8 & 255 ) / 255;
  251. this.b = ( hex & 255 ) / 255;
  252. return this;
  253. },
  254. setRGB: function ( r, g, b ) {
  255. this.r = r;
  256. this.g = g;
  257. this.b = b;
  258. return this;
  259. },
  260. setHSL: function () {
  261. function hue2rgb( p, q, t ) {
  262. if ( t < 0 ) t += 1;
  263. if ( t > 1 ) t -= 1;
  264. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  265. if ( t < 1 / 2 ) return q;
  266. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  267. return p;
  268. }
  269. return function ( h, s, l ) {
  270. // h,s,l ranges are in 0.0 - 1.0
  271. h = THREE.Math.euclideanModulo( h, 1 );
  272. s = THREE.Math.clamp( s, 0, 1 );
  273. l = THREE.Math.clamp( l, 0, 1 );
  274. if ( s === 0 ) {
  275. this.r = this.g = this.b = l;
  276. } else {
  277. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  278. var q = ( 2 * l ) - p;
  279. this.r = hue2rgb( q, p, h + 1 / 3 );
  280. this.g = hue2rgb( q, p, h );
  281. this.b = hue2rgb( q, p, h - 1 / 3 );
  282. }
  283. return this;
  284. };
  285. }(),
  286. setStyle: function ( style ) {
  287. function handleAlpha( string ) {
  288. if ( string === undefined ) return;
  289. if ( parseFloat( string ) < 1 ) {
  290. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  291. }
  292. }
  293. var m;
  294. if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) {
  295. // rgb / hsl
  296. var color;
  297. var name = m[ 1 ];
  298. var components = m[ 2 ];
  299. switch ( name ) {
  300. case 'rgb':
  301. case 'rgba':
  302. if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  303. // rgb(255,0,0) rgba(255,0,0,0.5)
  304. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  305. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  306. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  307. handleAlpha( color[ 5 ] );
  308. return this;
  309. }
  310. if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  311. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  312. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  313. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  314. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  315. handleAlpha( color[ 5 ] );
  316. return this;
  317. }
  318. break;
  319. case 'hsl':
  320. case 'hsla':
  321. if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  322. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  323. var h = parseFloat( color[ 1 ] ) / 360;
  324. var s = parseInt( color[ 2 ], 10 ) / 100;
  325. var l = parseInt( color[ 3 ], 10 ) / 100;
  326. handleAlpha( color[ 5 ] );
  327. return this.setHSL( h, s, l );
  328. }
  329. break;
  330. }
  331. } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) {
  332. // hex color
  333. var hex = m[ 1 ];
  334. var size = hex.length;
  335. if ( size === 3 ) {
  336. // #ff0
  337. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  338. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  339. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  340. return this;
  341. } else if ( size === 6 ) {
  342. // #ff0000
  343. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  344. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  345. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  346. return this;
  347. }
  348. }
  349. if ( style && style.length > 0 ) {
  350. // color keywords
  351. var hex = THREE.ColorKeywords[ style ];
  352. if ( hex !== undefined ) {
  353. // red
  354. this.setHex( hex );
  355. } else {
  356. // unknown color
  357. console.warn( 'THREE.Color: Unknown color ' + style );
  358. }
  359. }
  360. return this;
  361. },
  362. clone: function () {
  363. return new this.constructor( this.r, this.g, this.b );
  364. },
  365. copy: function ( color ) {
  366. this.r = color.r;
  367. this.g = color.g;
  368. this.b = color.b;
  369. return this;
  370. },
  371. copyGammaToLinear: function ( color, gammaFactor ) {
  372. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  373. this.r = Math.pow( color.r, gammaFactor );
  374. this.g = Math.pow( color.g, gammaFactor );
  375. this.b = Math.pow( color.b, gammaFactor );
  376. return this;
  377. },
  378. copyLinearToGamma: function ( color, gammaFactor ) {
  379. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  380. var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  381. this.r = Math.pow( color.r, safeInverse );
  382. this.g = Math.pow( color.g, safeInverse );
  383. this.b = Math.pow( color.b, safeInverse );
  384. return this;
  385. },
  386. convertGammaToLinear: function () {
  387. var r = this.r, g = this.g, b = this.b;
  388. this.r = r * r;
  389. this.g = g * g;
  390. this.b = b * b;
  391. return this;
  392. },
  393. convertLinearToGamma: function () {
  394. this.r = Math.sqrt( this.r );
  395. this.g = Math.sqrt( this.g );
  396. this.b = Math.sqrt( this.b );
  397. return this;
  398. },
  399. getHex: function () {
  400. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  401. },
  402. getHexString: function () {
  403. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  404. },
  405. getHSL: function ( optionalTarget ) {
  406. // h,s,l ranges are in 0.0 - 1.0
  407. var hsl = optionalTarget || { h: 0, s: 0, l: 0 };
  408. var r = this.r, g = this.g, b = this.b;
  409. var max = Math.max( r, g, b );
  410. var min = Math.min( r, g, b );
  411. var hue, saturation;
  412. var lightness = ( min + max ) / 2.0;
  413. if ( min === max ) {
  414. hue = 0;
  415. saturation = 0;
  416. } else {
  417. var delta = max - min;
  418. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  419. switch ( max ) {
  420. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  421. case g: hue = ( b - r ) / delta + 2; break;
  422. case b: hue = ( r - g ) / delta + 4; break;
  423. }
  424. hue /= 6;
  425. }
  426. hsl.h = hue;
  427. hsl.s = saturation;
  428. hsl.l = lightness;
  429. return hsl;
  430. },
  431. getStyle: function () {
  432. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  433. },
  434. offsetHSL: function ( h, s, l ) {
  435. var hsl = this.getHSL();
  436. hsl.h += h; hsl.s += s; hsl.l += l;
  437. this.setHSL( hsl.h, hsl.s, hsl.l );
  438. return this;
  439. },
  440. add: function ( color ) {
  441. this.r += color.r;
  442. this.g += color.g;
  443. this.b += color.b;
  444. return this;
  445. },
  446. addColors: function ( color1, color2 ) {
  447. this.r = color1.r + color2.r;
  448. this.g = color1.g + color2.g;
  449. this.b = color1.b + color2.b;
  450. return this;
  451. },
  452. addScalar: function ( s ) {
  453. this.r += s;
  454. this.g += s;
  455. this.b += s;
  456. return this;
  457. },
  458. multiply: function ( color ) {
  459. this.r *= color.r;
  460. this.g *= color.g;
  461. this.b *= color.b;
  462. return this;
  463. },
  464. multiplyScalar: function ( s ) {
  465. this.r *= s;
  466. this.g *= s;
  467. this.b *= s;
  468. return this;
  469. },
  470. lerp: function ( color, alpha ) {
  471. this.r += ( color.r - this.r ) * alpha;
  472. this.g += ( color.g - this.g ) * alpha;
  473. this.b += ( color.b - this.b ) * alpha;
  474. return this;
  475. },
  476. equals: function ( c ) {
  477. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  478. },
  479. fromArray: function ( array, offset ) {
  480. if ( offset === undefined ) offset = 0;
  481. this.r = array[ offset ];
  482. this.g = array[ offset + 1 ];
  483. this.b = array[ offset + 2 ];
  484. return this;
  485. },
  486. toArray: function ( array, offset ) {
  487. if ( array === undefined ) array = [];
  488. if ( offset === undefined ) offset = 0;
  489. array[ offset ] = this.r;
  490. array[ offset + 1 ] = this.g;
  491. array[ offset + 2 ] = this.b;
  492. return array;
  493. }
  494. };
  495. THREE.ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  496. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  497. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  498. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  499. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  500. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  501. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  502. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  503. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  504. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  505. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  506. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  507. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  508. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  509. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  510. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  511. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  512. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  513. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  514. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  515. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  516. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  517. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  518. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  519. // File:src/math/Quaternion.js
  520. /**
  521. * @author mikael emtinger / http://gomo.se/
  522. * @author alteredq / http://alteredqualia.com/
  523. * @author WestLangley / http://github.com/WestLangley
  524. * @author bhouston / http://clara.io
  525. */
  526. THREE.Quaternion = function ( x, y, z, w ) {
  527. this._x = x || 0;
  528. this._y = y || 0;
  529. this._z = z || 0;
  530. this._w = ( w !== undefined ) ? w : 1;
  531. };
  532. THREE.Quaternion.prototype = {
  533. constructor: THREE.Quaternion,
  534. get x () {
  535. return this._x;
  536. },
  537. set x ( value ) {
  538. this._x = value;
  539. this.onChangeCallback();
  540. },
  541. get y () {
  542. return this._y;
  543. },
  544. set y ( value ) {
  545. this._y = value;
  546. this.onChangeCallback();
  547. },
  548. get z () {
  549. return this._z;
  550. },
  551. set z ( value ) {
  552. this._z = value;
  553. this.onChangeCallback();
  554. },
  555. get w () {
  556. return this._w;
  557. },
  558. set w ( value ) {
  559. this._w = value;
  560. this.onChangeCallback();
  561. },
  562. set: function ( x, y, z, w ) {
  563. this._x = x;
  564. this._y = y;
  565. this._z = z;
  566. this._w = w;
  567. this.onChangeCallback();
  568. return this;
  569. },
  570. clone: function () {
  571. return new this.constructor( this._x, this._y, this._z, this._w );
  572. },
  573. copy: function ( quaternion ) {
  574. this._x = quaternion.x;
  575. this._y = quaternion.y;
  576. this._z = quaternion.z;
  577. this._w = quaternion.w;
  578. this.onChangeCallback();
  579. return this;
  580. },
  581. setFromEuler: function ( euler, update ) {
  582. if ( euler instanceof THREE.Euler === false ) {
  583. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  584. }
  585. // http://www.mathworks.com/matlabcentral/fileexchange/
  586. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  587. // content/SpinCalc.m
  588. var c1 = Math.cos( euler._x / 2 );
  589. var c2 = Math.cos( euler._y / 2 );
  590. var c3 = Math.cos( euler._z / 2 );
  591. var s1 = Math.sin( euler._x / 2 );
  592. var s2 = Math.sin( euler._y / 2 );
  593. var s3 = Math.sin( euler._z / 2 );
  594. var order = euler.order;
  595. if ( order === 'XYZ' ) {
  596. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  597. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  598. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  599. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  600. } else if ( order === 'YXZ' ) {
  601. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  602. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  603. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  604. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  605. } else if ( order === 'ZXY' ) {
  606. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  607. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  608. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  609. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  610. } else if ( order === 'ZYX' ) {
  611. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  612. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  613. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  614. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  615. } else if ( order === 'YZX' ) {
  616. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  617. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  618. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  619. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  620. } else if ( order === 'XZY' ) {
  621. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  622. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  623. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  624. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  625. }
  626. if ( update !== false ) this.onChangeCallback();
  627. return this;
  628. },
  629. setFromAxisAngle: function ( axis, angle ) {
  630. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  631. // assumes axis is normalized
  632. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  633. this._x = axis.x * s;
  634. this._y = axis.y * s;
  635. this._z = axis.z * s;
  636. this._w = Math.cos( halfAngle );
  637. this.onChangeCallback();
  638. return this;
  639. },
  640. setFromRotationMatrix: function ( m ) {
  641. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  642. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  643. var te = m.elements,
  644. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  645. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  646. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  647. trace = m11 + m22 + m33,
  648. s;
  649. if ( trace > 0 ) {
  650. s = 0.5 / Math.sqrt( trace + 1.0 );
  651. this._w = 0.25 / s;
  652. this._x = ( m32 - m23 ) * s;
  653. this._y = ( m13 - m31 ) * s;
  654. this._z = ( m21 - m12 ) * s;
  655. } else if ( m11 > m22 && m11 > m33 ) {
  656. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  657. this._w = ( m32 - m23 ) / s;
  658. this._x = 0.25 * s;
  659. this._y = ( m12 + m21 ) / s;
  660. this._z = ( m13 + m31 ) / s;
  661. } else if ( m22 > m33 ) {
  662. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  663. this._w = ( m13 - m31 ) / s;
  664. this._x = ( m12 + m21 ) / s;
  665. this._y = 0.25 * s;
  666. this._z = ( m23 + m32 ) / s;
  667. } else {
  668. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  669. this._w = ( m21 - m12 ) / s;
  670. this._x = ( m13 + m31 ) / s;
  671. this._y = ( m23 + m32 ) / s;
  672. this._z = 0.25 * s;
  673. }
  674. this.onChangeCallback();
  675. return this;
  676. },
  677. setFromUnitVectors: function () {
  678. // http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final
  679. // assumes direction vectors vFrom and vTo are normalized
  680. var v1, r;
  681. var EPS = 0.000001;
  682. return function ( vFrom, vTo ) {
  683. if ( v1 === undefined ) v1 = new THREE.Vector3();
  684. r = vFrom.dot( vTo ) + 1;
  685. if ( r < EPS ) {
  686. r = 0;
  687. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  688. v1.set( - vFrom.y, vFrom.x, 0 );
  689. } else {
  690. v1.set( 0, - vFrom.z, vFrom.y );
  691. }
  692. } else {
  693. v1.crossVectors( vFrom, vTo );
  694. }
  695. this._x = v1.x;
  696. this._y = v1.y;
  697. this._z = v1.z;
  698. this._w = r;
  699. this.normalize();
  700. return this;
  701. };
  702. }(),
  703. inverse: function () {
  704. this.conjugate().normalize();
  705. return this;
  706. },
  707. conjugate: function () {
  708. this._x *= - 1;
  709. this._y *= - 1;
  710. this._z *= - 1;
  711. this.onChangeCallback();
  712. return this;
  713. },
  714. dot: function ( v ) {
  715. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  716. },
  717. lengthSq: function () {
  718. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  719. },
  720. length: function () {
  721. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  722. },
  723. normalize: function () {
  724. var l = this.length();
  725. if ( l === 0 ) {
  726. this._x = 0;
  727. this._y = 0;
  728. this._z = 0;
  729. this._w = 1;
  730. } else {
  731. l = 1 / l;
  732. this._x = this._x * l;
  733. this._y = this._y * l;
  734. this._z = this._z * l;
  735. this._w = this._w * l;
  736. }
  737. this.onChangeCallback();
  738. return this;
  739. },
  740. multiply: function ( q, p ) {
  741. if ( p !== undefined ) {
  742. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  743. return this.multiplyQuaternions( q, p );
  744. }
  745. return this.multiplyQuaternions( this, q );
  746. },
  747. multiplyQuaternions: function ( a, b ) {
  748. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  749. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  750. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  751. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  752. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  753. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  754. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  755. this.onChangeCallback();
  756. return this;
  757. },
  758. slerp: function ( qb, t ) {
  759. if ( t === 0 ) return this;
  760. if ( t === 1 ) return this.copy( qb );
  761. var x = this._x, y = this._y, z = this._z, w = this._w;
  762. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  763. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  764. if ( cosHalfTheta < 0 ) {
  765. this._w = - qb._w;
  766. this._x = - qb._x;
  767. this._y = - qb._y;
  768. this._z = - qb._z;
  769. cosHalfTheta = - cosHalfTheta;
  770. } else {
  771. this.copy( qb );
  772. }
  773. if ( cosHalfTheta >= 1.0 ) {
  774. this._w = w;
  775. this._x = x;
  776. this._y = y;
  777. this._z = z;
  778. return this;
  779. }
  780. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  781. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  782. this._w = 0.5 * ( w + this._w );
  783. this._x = 0.5 * ( x + this._x );
  784. this._y = 0.5 * ( y + this._y );
  785. this._z = 0.5 * ( z + this._z );
  786. return this;
  787. }
  788. var halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  789. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  790. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  791. this._w = ( w * ratioA + this._w * ratioB );
  792. this._x = ( x * ratioA + this._x * ratioB );
  793. this._y = ( y * ratioA + this._y * ratioB );
  794. this._z = ( z * ratioA + this._z * ratioB );
  795. this.onChangeCallback();
  796. return this;
  797. },
  798. equals: function ( quaternion ) {
  799. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  800. },
  801. fromArray: function ( array, offset ) {
  802. if ( offset === undefined ) offset = 0;
  803. this._x = array[ offset ];
  804. this._y = array[ offset + 1 ];
  805. this._z = array[ offset + 2 ];
  806. this._w = array[ offset + 3 ];
  807. this.onChangeCallback();
  808. return this;
  809. },
  810. toArray: function ( array, offset ) {
  811. if ( array === undefined ) array = [];
  812. if ( offset === undefined ) offset = 0;
  813. array[ offset ] = this._x;
  814. array[ offset + 1 ] = this._y;
  815. array[ offset + 2 ] = this._z;
  816. array[ offset + 3 ] = this._w;
  817. return array;
  818. },
  819. onChange: function ( callback ) {
  820. this.onChangeCallback = callback;
  821. return this;
  822. },
  823. onChangeCallback: function () {}
  824. };
  825. Object.assign( THREE.Quaternion, {
  826. slerp: function( qa, qb, qm, t ) {
  827. return qm.copy( qa ).slerp( qb, t );
  828. },
  829. slerpFlat: function(
  830. dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  831. // fuzz-free, array-based Quaternion SLERP operation
  832. var x0 = src0[ srcOffset0 + 0 ],
  833. y0 = src0[ srcOffset0 + 1 ],
  834. z0 = src0[ srcOffset0 + 2 ],
  835. w0 = src0[ srcOffset0 + 3 ],
  836. x1 = src1[ srcOffset1 + 0 ],
  837. y1 = src1[ srcOffset1 + 1 ],
  838. z1 = src1[ srcOffset1 + 2 ],
  839. w1 = src1[ srcOffset1 + 3 ];
  840. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  841. var s = 1 - t,
  842. cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  843. dir = ( cos >= 0 ? 1 : - 1 ),
  844. sqrSin = 1 - cos * cos;
  845. // Skip the Slerp for tiny steps to avoid numeric problems:
  846. if ( sqrSin > Number.EPSILON ) {
  847. var sin = Math.sqrt( sqrSin ),
  848. len = Math.atan2( sin, cos * dir );
  849. s = Math.sin( s * len ) / sin;
  850. t = Math.sin( t * len ) / sin;
  851. }
  852. var tDir = t * dir;
  853. x0 = x0 * s + x1 * tDir;
  854. y0 = y0 * s + y1 * tDir;
  855. z0 = z0 * s + z1 * tDir;
  856. w0 = w0 * s + w1 * tDir;
  857. // Normalize in case we just did a lerp:
  858. if ( s === 1 - t ) {
  859. var f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  860. x0 *= f;
  861. y0 *= f;
  862. z0 *= f;
  863. w0 *= f;
  864. }
  865. }
  866. dst[ dstOffset ] = x0;
  867. dst[ dstOffset + 1 ] = y0;
  868. dst[ dstOffset + 2 ] = z0;
  869. dst[ dstOffset + 3 ] = w0;
  870. }
  871. } );
  872. // File:src/math/Vector2.js
  873. /**
  874. * @author mrdoob / http://mrdoob.com/
  875. * @author philogb / http://blog.thejit.org/
  876. * @author egraether / http://egraether.com/
  877. * @author zz85 / http://www.lab4games.net/zz85/blog
  878. */
  879. THREE.Vector2 = function ( x, y ) {
  880. this.x = x || 0;
  881. this.y = y || 0;
  882. };
  883. THREE.Vector2.prototype = {
  884. constructor: THREE.Vector2,
  885. get width() {
  886. return this.x;
  887. },
  888. set width( value ) {
  889. this.x = value;
  890. },
  891. get height() {
  892. return this.y;
  893. },
  894. set height( value ) {
  895. this.y = value;
  896. },
  897. //
  898. set: function ( x, y ) {
  899. this.x = x;
  900. this.y = y;
  901. return this;
  902. },
  903. setScalar: function ( scalar ) {
  904. this.x = scalar;
  905. this.y = scalar;
  906. return this;
  907. },
  908. setX: function ( x ) {
  909. this.x = x;
  910. return this;
  911. },
  912. setY: function ( y ) {
  913. this.y = y;
  914. return this;
  915. },
  916. setComponent: function ( index, value ) {
  917. switch ( index ) {
  918. case 0: this.x = value; break;
  919. case 1: this.y = value; break;
  920. default: throw new Error( 'index is out of range: ' + index );
  921. }
  922. },
  923. getComponent: function ( index ) {
  924. switch ( index ) {
  925. case 0: return this.x;
  926. case 1: return this.y;
  927. default: throw new Error( 'index is out of range: ' + index );
  928. }
  929. },
  930. clone: function () {
  931. return new this.constructor( this.x, this.y );
  932. },
  933. copy: function ( v ) {
  934. this.x = v.x;
  935. this.y = v.y;
  936. return this;
  937. },
  938. add: function ( v, w ) {
  939. if ( w !== undefined ) {
  940. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  941. return this.addVectors( v, w );
  942. }
  943. this.x += v.x;
  944. this.y += v.y;
  945. return this;
  946. },
  947. addScalar: function ( s ) {
  948. this.x += s;
  949. this.y += s;
  950. return this;
  951. },
  952. addVectors: function ( a, b ) {
  953. this.x = a.x + b.x;
  954. this.y = a.y + b.y;
  955. return this;
  956. },
  957. addScaledVector: function ( v, s ) {
  958. this.x += v.x * s;
  959. this.y += v.y * s;
  960. return this;
  961. },
  962. sub: function ( v, w ) {
  963. if ( w !== undefined ) {
  964. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  965. return this.subVectors( v, w );
  966. }
  967. this.x -= v.x;
  968. this.y -= v.y;
  969. return this;
  970. },
  971. subScalar: function ( s ) {
  972. this.x -= s;
  973. this.y -= s;
  974. return this;
  975. },
  976. subVectors: function ( a, b ) {
  977. this.x = a.x - b.x;
  978. this.y = a.y - b.y;
  979. return this;
  980. },
  981. multiply: function ( v ) {
  982. this.x *= v.x;
  983. this.y *= v.y;
  984. return this;
  985. },
  986. multiplyScalar: function ( scalar ) {
  987. if ( isFinite( scalar ) ) {
  988. this.x *= scalar;
  989. this.y *= scalar;
  990. } else {
  991. this.x = 0;
  992. this.y = 0;
  993. }
  994. return this;
  995. },
  996. divide: function ( v ) {
  997. this.x /= v.x;
  998. this.y /= v.y;
  999. return this;
  1000. },
  1001. divideScalar: function ( scalar ) {
  1002. return this.multiplyScalar( 1 / scalar );
  1003. },
  1004. min: function ( v ) {
  1005. this.x = Math.min( this.x, v.x );
  1006. this.y = Math.min( this.y, v.y );
  1007. return this;
  1008. },
  1009. max: function ( v ) {
  1010. this.x = Math.max( this.x, v.x );
  1011. this.y = Math.max( this.y, v.y );
  1012. return this;
  1013. },
  1014. clamp: function ( min, max ) {
  1015. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1016. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1017. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1018. return this;
  1019. },
  1020. clampScalar: function () {
  1021. var min, max;
  1022. return function clampScalar( minVal, maxVal ) {
  1023. if ( min === undefined ) {
  1024. min = new THREE.Vector2();
  1025. max = new THREE.Vector2();
  1026. }
  1027. min.set( minVal, minVal );
  1028. max.set( maxVal, maxVal );
  1029. return this.clamp( min, max );
  1030. };
  1031. }(),
  1032. clampLength: function ( min, max ) {
  1033. var length = this.length();
  1034. this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length );
  1035. return this;
  1036. },
  1037. floor: function () {
  1038. this.x = Math.floor( this.x );
  1039. this.y = Math.floor( this.y );
  1040. return this;
  1041. },
  1042. ceil: function () {
  1043. this.x = Math.ceil( this.x );
  1044. this.y = Math.ceil( this.y );
  1045. return this;
  1046. },
  1047. round: function () {
  1048. this.x = Math.round( this.x );
  1049. this.y = Math.round( this.y );
  1050. return this;
  1051. },
  1052. roundToZero: function () {
  1053. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1054. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1055. return this;
  1056. },
  1057. negate: function () {
  1058. this.x = - this.x;
  1059. this.y = - this.y;
  1060. return this;
  1061. },
  1062. dot: function ( v ) {
  1063. return this.x * v.x + this.y * v.y;
  1064. },
  1065. lengthSq: function () {
  1066. return this.x * this.x + this.y * this.y;
  1067. },
  1068. length: function () {
  1069. return Math.sqrt( this.x * this.x + this.y * this.y );
  1070. },
  1071. lengthManhattan: function() {
  1072. return Math.abs( this.x ) + Math.abs( this.y );
  1073. },
  1074. normalize: function () {
  1075. return this.divideScalar( this.length() );
  1076. },
  1077. angle: function () {
  1078. // computes the angle in radians with respect to the positive x-axis
  1079. var angle = Math.atan2( this.y, this.x );
  1080. if ( angle < 0 ) angle += 2 * Math.PI;
  1081. return angle;
  1082. },
  1083. distanceTo: function ( v ) {
  1084. return Math.sqrt( this.distanceToSquared( v ) );
  1085. },
  1086. distanceToSquared: function ( v ) {
  1087. var dx = this.x - v.x, dy = this.y - v.y;
  1088. return dx * dx + dy * dy;
  1089. },
  1090. setLength: function ( length ) {
  1091. return this.multiplyScalar( length / this.length() );
  1092. },
  1093. lerp: function ( v, alpha ) {
  1094. this.x += ( v.x - this.x ) * alpha;
  1095. this.y += ( v.y - this.y ) * alpha;
  1096. return this;
  1097. },
  1098. lerpVectors: function ( v1, v2, alpha ) {
  1099. this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1100. return this;
  1101. },
  1102. equals: function ( v ) {
  1103. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  1104. },
  1105. fromArray: function ( array, offset ) {
  1106. if ( offset === undefined ) offset = 0;
  1107. this.x = array[ offset ];
  1108. this.y = array[ offset + 1 ];
  1109. return this;
  1110. },
  1111. toArray: function ( array, offset ) {
  1112. if ( array === undefined ) array = [];
  1113. if ( offset === undefined ) offset = 0;
  1114. array[ offset ] = this.x;
  1115. array[ offset + 1 ] = this.y;
  1116. return array;
  1117. },
  1118. fromAttribute: function ( attribute, index, offset ) {
  1119. if ( offset === undefined ) offset = 0;
  1120. index = index * attribute.itemSize + offset;
  1121. this.x = attribute.array[ index ];
  1122. this.y = attribute.array[ index + 1 ];
  1123. return this;
  1124. },
  1125. rotateAround: function ( center, angle ) {
  1126. var c = Math.cos( angle ), s = Math.sin( angle );
  1127. var x = this.x - center.x;
  1128. var y = this.y - center.y;
  1129. this.x = x * c - y * s + center.x;
  1130. this.y = x * s + y * c + center.y;
  1131. return this;
  1132. }
  1133. };
  1134. // File:src/math/Vector3.js
  1135. /**
  1136. * @author mrdoob / http://mrdoob.com/
  1137. * @author *kile / http://kile.stravaganza.org/
  1138. * @author philogb / http://blog.thejit.org/
  1139. * @author mikael emtinger / http://gomo.se/
  1140. * @author egraether / http://egraether.com/
  1141. * @author WestLangley / http://github.com/WestLangley
  1142. */
  1143. THREE.Vector3 = function ( x, y, z ) {
  1144. this.x = x || 0;
  1145. this.y = y || 0;
  1146. this.z = z || 0;
  1147. };
  1148. THREE.Vector3.prototype = {
  1149. constructor: THREE.Vector3,
  1150. set: function ( x, y, z ) {
  1151. this.x = x;
  1152. this.y = y;
  1153. this.z = z;
  1154. return this;
  1155. },
  1156. setScalar: function ( scalar ) {
  1157. this.x = scalar;
  1158. this.y = scalar;
  1159. this.z = scalar;
  1160. return this;
  1161. },
  1162. setX: function ( x ) {
  1163. this.x = x;
  1164. return this;
  1165. },
  1166. setY: function ( y ) {
  1167. this.y = y;
  1168. return this;
  1169. },
  1170. setZ: function ( z ) {
  1171. this.z = z;
  1172. return this;
  1173. },
  1174. setComponent: function ( index, value ) {
  1175. switch ( index ) {
  1176. case 0: this.x = value; break;
  1177. case 1: this.y = value; break;
  1178. case 2: this.z = value; break;
  1179. default: throw new Error( 'index is out of range: ' + index );
  1180. }
  1181. },
  1182. getComponent: function ( index ) {
  1183. switch ( index ) {
  1184. case 0: return this.x;
  1185. case 1: return this.y;
  1186. case 2: return this.z;
  1187. default: throw new Error( 'index is out of range: ' + index );
  1188. }
  1189. },
  1190. clone: function () {
  1191. return new this.constructor( this.x, this.y, this.z );
  1192. },
  1193. copy: function ( v ) {
  1194. this.x = v.x;
  1195. this.y = v.y;
  1196. this.z = v.z;
  1197. return this;
  1198. },
  1199. add: function ( v, w ) {
  1200. if ( w !== undefined ) {
  1201. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1202. return this.addVectors( v, w );
  1203. }
  1204. this.x += v.x;
  1205. this.y += v.y;
  1206. this.z += v.z;
  1207. return this;
  1208. },
  1209. addScalar: function ( s ) {
  1210. this.x += s;
  1211. this.y += s;
  1212. this.z += s;
  1213. return this;
  1214. },
  1215. addVectors: function ( a, b ) {
  1216. this.x = a.x + b.x;
  1217. this.y = a.y + b.y;
  1218. this.z = a.z + b.z;
  1219. return this;
  1220. },
  1221. addScaledVector: function ( v, s ) {
  1222. this.x += v.x * s;
  1223. this.y += v.y * s;
  1224. this.z += v.z * s;
  1225. return this;
  1226. },
  1227. sub: function ( v, w ) {
  1228. if ( w !== undefined ) {
  1229. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1230. return this.subVectors( v, w );
  1231. }
  1232. this.x -= v.x;
  1233. this.y -= v.y;
  1234. this.z -= v.z;
  1235. return this;
  1236. },
  1237. subScalar: function ( s ) {
  1238. this.x -= s;
  1239. this.y -= s;
  1240. this.z -= s;
  1241. return this;
  1242. },
  1243. subVectors: function ( a, b ) {
  1244. this.x = a.x - b.x;
  1245. this.y = a.y - b.y;
  1246. this.z = a.z - b.z;
  1247. return this;
  1248. },
  1249. multiply: function ( v, w ) {
  1250. if ( w !== undefined ) {
  1251. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  1252. return this.multiplyVectors( v, w );
  1253. }
  1254. this.x *= v.x;
  1255. this.y *= v.y;
  1256. this.z *= v.z;
  1257. return this;
  1258. },
  1259. multiplyScalar: function ( scalar ) {
  1260. if ( isFinite( scalar ) ) {
  1261. this.x *= scalar;
  1262. this.y *= scalar;
  1263. this.z *= scalar;
  1264. } else {
  1265. this.x = 0;
  1266. this.y = 0;
  1267. this.z = 0;
  1268. }
  1269. return this;
  1270. },
  1271. multiplyVectors: function ( a, b ) {
  1272. this.x = a.x * b.x;
  1273. this.y = a.y * b.y;
  1274. this.z = a.z * b.z;
  1275. return this;
  1276. },
  1277. applyEuler: function () {
  1278. var quaternion;
  1279. return function applyEuler( euler ) {
  1280. if ( euler instanceof THREE.Euler === false ) {
  1281. console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  1282. }
  1283. if ( quaternion === undefined ) quaternion = new THREE.Quaternion();
  1284. this.applyQuaternion( quaternion.setFromEuler( euler ) );
  1285. return this;
  1286. };
  1287. }(),
  1288. applyAxisAngle: function () {
  1289. var quaternion;
  1290. return function applyAxisAngle( axis, angle ) {
  1291. if ( quaternion === undefined ) quaternion = new THREE.Quaternion();
  1292. this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  1293. return this;
  1294. };
  1295. }(),
  1296. applyMatrix3: function ( m ) {
  1297. var x = this.x;
  1298. var y = this.y;
  1299. var z = this.z;
  1300. var e = m.elements;
  1301. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  1302. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  1303. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  1304. return this;
  1305. },
  1306. applyMatrix4: function ( m ) {
  1307. // input: THREE.Matrix4 affine matrix
  1308. var x = this.x, y = this.y, z = this.z;
  1309. var e = m.elements;
  1310. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ];
  1311. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ];
  1312. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ];
  1313. return this;
  1314. },
  1315. applyProjection: function ( m ) {
  1316. // input: THREE.Matrix4 projection matrix
  1317. var x = this.x, y = this.y, z = this.z;
  1318. var e = m.elements;
  1319. var d = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] ); // perspective divide
  1320. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * d;
  1321. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * d;
  1322. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * d;
  1323. return this;
  1324. },
  1325. applyQuaternion: function ( q ) {
  1326. var x = this.x;
  1327. var y = this.y;
  1328. var z = this.z;
  1329. var qx = q.x;
  1330. var qy = q.y;
  1331. var qz = q.z;
  1332. var qw = q.w;
  1333. // calculate quat * vector
  1334. var ix = qw * x + qy * z - qz * y;
  1335. var iy = qw * y + qz * x - qx * z;
  1336. var iz = qw * z + qx * y - qy * x;
  1337. var iw = - qx * x - qy * y - qz * z;
  1338. // calculate result * inverse quat
  1339. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  1340. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  1341. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  1342. return this;
  1343. },
  1344. project: function () {
  1345. var matrix;
  1346. return function project( camera ) {
  1347. if ( matrix === undefined ) matrix = new THREE.Matrix4();
  1348. matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) );
  1349. return this.applyProjection( matrix );
  1350. };
  1351. }(),
  1352. unproject: function () {
  1353. var matrix;
  1354. return function unproject( camera ) {
  1355. if ( matrix === undefined ) matrix = new THREE.Matrix4();
  1356. matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) );
  1357. return this.applyProjection( matrix );
  1358. };
  1359. }(),
  1360. transformDirection: function ( m ) {
  1361. // input: THREE.Matrix4 affine matrix
  1362. // vector interpreted as a direction
  1363. var x = this.x, y = this.y, z = this.z;
  1364. var e = m.elements;
  1365. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  1366. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  1367. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  1368. this.normalize();
  1369. return this;
  1370. },
  1371. divide: function ( v ) {
  1372. this.x /= v.x;
  1373. this.y /= v.y;
  1374. this.z /= v.z;
  1375. return this;
  1376. },
  1377. divideScalar: function ( scalar ) {
  1378. return this.multiplyScalar( 1 / scalar );
  1379. },
  1380. min: function ( v ) {
  1381. this.x = Math.min( this.x, v.x );
  1382. this.y = Math.min( this.y, v.y );
  1383. this.z = Math.min( this.z, v.z );
  1384. return this;
  1385. },
  1386. max: function ( v ) {
  1387. this.x = Math.max( this.x, v.x );
  1388. this.y = Math.max( this.y, v.y );
  1389. this.z = Math.max( this.z, v.z );
  1390. return this;
  1391. },
  1392. clamp: function ( min, max ) {
  1393. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1394. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1395. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1396. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1397. return this;
  1398. },
  1399. clampScalar: function () {
  1400. var min, max;
  1401. return function clampScalar( minVal, maxVal ) {
  1402. if ( min === undefined ) {
  1403. min = new THREE.Vector3();
  1404. max = new THREE.Vector3();
  1405. }
  1406. min.set( minVal, minVal, minVal );
  1407. max.set( maxVal, maxVal, maxVal );
  1408. return this.clamp( min, max );
  1409. };
  1410. }(),
  1411. clampLength: function ( min, max ) {
  1412. var length = this.length();
  1413. this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length );
  1414. return this;
  1415. },
  1416. floor: function () {
  1417. this.x = Math.floor( this.x );
  1418. this.y = Math.floor( this.y );
  1419. this.z = Math.floor( this.z );
  1420. return this;
  1421. },
  1422. ceil: function () {
  1423. this.x = Math.ceil( this.x );
  1424. this.y = Math.ceil( this.y );
  1425. this.z = Math.ceil( this.z );
  1426. return this;
  1427. },
  1428. round: function () {
  1429. this.x = Math.round( this.x );
  1430. this.y = Math.round( this.y );
  1431. this.z = Math.round( this.z );
  1432. return this;
  1433. },
  1434. roundToZero: function () {
  1435. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1436. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1437. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1438. return this;
  1439. },
  1440. negate: function () {
  1441. this.x = - this.x;
  1442. this.y = - this.y;
  1443. this.z = - this.z;
  1444. return this;
  1445. },
  1446. dot: function ( v ) {
  1447. return this.x * v.x + this.y * v.y + this.z * v.z;
  1448. },
  1449. lengthSq: function () {
  1450. return this.x * this.x + this.y * this.y + this.z * this.z;
  1451. },
  1452. length: function () {
  1453. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1454. },
  1455. lengthManhattan: function () {
  1456. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1457. },
  1458. normalize: function () {
  1459. return this.divideScalar( this.length() );
  1460. },
  1461. setLength: function ( length ) {
  1462. return this.multiplyScalar( length / this.length() );
  1463. },
  1464. lerp: function ( v, alpha ) {
  1465. this.x += ( v.x - this.x ) * alpha;
  1466. this.y += ( v.y - this.y ) * alpha;
  1467. this.z += ( v.z - this.z ) * alpha;
  1468. return this;
  1469. },
  1470. lerpVectors: function ( v1, v2, alpha ) {
  1471. this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1472. return this;
  1473. },
  1474. cross: function ( v, w ) {
  1475. if ( w !== undefined ) {
  1476. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1477. return this.crossVectors( v, w );
  1478. }
  1479. var x = this.x, y = this.y, z = this.z;
  1480. this.x = y * v.z - z * v.y;
  1481. this.y = z * v.x - x * v.z;
  1482. this.z = x * v.y - y * v.x;
  1483. return this;
  1484. },
  1485. crossVectors: function ( a, b ) {
  1486. var ax = a.x, ay = a.y, az = a.z;
  1487. var bx = b.x, by = b.y, bz = b.z;
  1488. this.x = ay * bz - az * by;
  1489. this.y = az * bx - ax * bz;
  1490. this.z = ax * by - ay * bx;
  1491. return this;
  1492. },
  1493. projectOnVector: function () {
  1494. var v1, dot;
  1495. return function projectOnVector( vector ) {
  1496. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1497. v1.copy( vector ).normalize();
  1498. dot = this.dot( v1 );
  1499. return this.copy( v1 ).multiplyScalar( dot );
  1500. };
  1501. }(),
  1502. projectOnPlane: function () {
  1503. var v1;
  1504. return function projectOnPlane( planeNormal ) {
  1505. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1506. v1.copy( this ).projectOnVector( planeNormal );
  1507. return this.sub( v1 );
  1508. };
  1509. }(),
  1510. reflect: function () {
  1511. // reflect incident vector off plane orthogonal to normal
  1512. // normal is assumed to have unit length
  1513. var v1;
  1514. return function reflect( normal ) {
  1515. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1516. return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  1517. };
  1518. }(),
  1519. angleTo: function ( v ) {
  1520. var theta = this.dot( v ) / ( Math.sqrt( this.lengthSq() * v.lengthSq() ) );
  1521. // clamp, to handle numerical problems
  1522. return Math.acos( THREE.Math.clamp( theta, - 1, 1 ) );
  1523. },
  1524. distanceTo: function ( v ) {
  1525. return Math.sqrt( this.distanceToSquared( v ) );
  1526. },
  1527. distanceToSquared: function ( v ) {
  1528. var dx = this.x - v.x;
  1529. var dy = this.y - v.y;
  1530. var dz = this.z - v.z;
  1531. return dx * dx + dy * dy + dz * dz;
  1532. },
  1533. setFromSpherical: function( s ) {
  1534. var sinPhiRadius = Math.sin( s.phi ) * s.radius;
  1535. this.x = sinPhiRadius * Math.sin( s.theta );
  1536. this.y = Math.cos( s.phi ) * s.radius;
  1537. this.z = sinPhiRadius * Math.cos( s.theta );
  1538. return this;
  1539. },
  1540. setFromMatrixPosition: function ( m ) {
  1541. return this.setFromMatrixColumn( m, 3 );
  1542. },
  1543. setFromMatrixScale: function ( m ) {
  1544. var sx = this.setFromMatrixColumn( m, 0 ).length();
  1545. var sy = this.setFromMatrixColumn( m, 1 ).length();
  1546. var sz = this.setFromMatrixColumn( m, 2 ).length();
  1547. this.x = sx;
  1548. this.y = sy;
  1549. this.z = sz;
  1550. return this;
  1551. },
  1552. setFromMatrixColumn: function ( m, index ) {
  1553. if ( typeof m === 'number' ) {
  1554. console.warn( 'THREE.Vector3: setFromMatrixColumn now expects ( matrix, index ).' );
  1555. m = arguments[ 1 ];
  1556. index = arguments[ 0 ];
  1557. }
  1558. return this.fromArray( m.elements, index * 4 );
  1559. },
  1560. equals: function ( v ) {
  1561. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1562. },
  1563. fromArray: function ( array, offset ) {
  1564. if ( offset === undefined ) offset = 0;
  1565. this.x = array[ offset ];
  1566. this.y = array[ offset + 1 ];
  1567. this.z = array[ offset + 2 ];
  1568. return this;
  1569. },
  1570. toArray: function ( array, offset ) {
  1571. if ( array === undefined ) array = [];
  1572. if ( offset === undefined ) offset = 0;
  1573. array[ offset ] = this.x;
  1574. array[ offset + 1 ] = this.y;
  1575. array[ offset + 2 ] = this.z;
  1576. return array;
  1577. },
  1578. fromAttribute: function ( attribute, index, offset ) {
  1579. if ( offset === undefined ) offset = 0;
  1580. index = index * attribute.itemSize + offset;
  1581. this.x = attribute.array[ index ];
  1582. this.y = attribute.array[ index + 1 ];
  1583. this.z = attribute.array[ index + 2 ];
  1584. return this;
  1585. }
  1586. };
  1587. // File:src/math/Vector4.js
  1588. /**
  1589. * @author supereggbert / http://www.paulbrunt.co.uk/
  1590. * @author philogb / http://blog.thejit.org/
  1591. * @author mikael emtinger / http://gomo.se/
  1592. * @author egraether / http://egraether.com/
  1593. * @author WestLangley / http://github.com/WestLangley
  1594. */
  1595. THREE.Vector4 = function ( x, y, z, w ) {
  1596. this.x = x || 0;
  1597. this.y = y || 0;
  1598. this.z = z || 0;
  1599. this.w = ( w !== undefined ) ? w : 1;
  1600. };
  1601. THREE.Vector4.prototype = {
  1602. constructor: THREE.Vector4,
  1603. set: function ( x, y, z, w ) {
  1604. this.x = x;
  1605. this.y = y;
  1606. this.z = z;
  1607. this.w = w;
  1608. return this;
  1609. },
  1610. setScalar: function ( scalar ) {
  1611. this.x = scalar;
  1612. this.y = scalar;
  1613. this.z = scalar;
  1614. this.w = scalar;
  1615. return this;
  1616. },
  1617. setX: function ( x ) {
  1618. this.x = x;
  1619. return this;
  1620. },
  1621. setY: function ( y ) {
  1622. this.y = y;
  1623. return this;
  1624. },
  1625. setZ: function ( z ) {
  1626. this.z = z;
  1627. return this;
  1628. },
  1629. setW: function ( w ) {
  1630. this.w = w;
  1631. return this;
  1632. },
  1633. setComponent: function ( index, value ) {
  1634. switch ( index ) {
  1635. case 0: this.x = value; break;
  1636. case 1: this.y = value; break;
  1637. case 2: this.z = value; break;
  1638. case 3: this.w = value; break;
  1639. default: throw new Error( 'index is out of range: ' + index );
  1640. }
  1641. },
  1642. getComponent: function ( index ) {
  1643. switch ( index ) {
  1644. case 0: return this.x;
  1645. case 1: return this.y;
  1646. case 2: return this.z;
  1647. case 3: return this.w;
  1648. default: throw new Error( 'index is out of range: ' + index );
  1649. }
  1650. },
  1651. clone: function () {
  1652. return new this.constructor( this.x, this.y, this.z, this.w );
  1653. },
  1654. copy: function ( v ) {
  1655. this.x = v.x;
  1656. this.y = v.y;
  1657. this.z = v.z;
  1658. this.w = ( v.w !== undefined ) ? v.w : 1;
  1659. return this;
  1660. },
  1661. add: function ( v, w ) {
  1662. if ( w !== undefined ) {
  1663. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1664. return this.addVectors( v, w );
  1665. }
  1666. this.x += v.x;
  1667. this.y += v.y;
  1668. this.z += v.z;
  1669. this.w += v.w;
  1670. return this;
  1671. },
  1672. addScalar: function ( s ) {
  1673. this.x += s;
  1674. this.y += s;
  1675. this.z += s;
  1676. this.w += s;
  1677. return this;
  1678. },
  1679. addVectors: function ( a, b ) {
  1680. this.x = a.x + b.x;
  1681. this.y = a.y + b.y;
  1682. this.z = a.z + b.z;
  1683. this.w = a.w + b.w;
  1684. return this;
  1685. },
  1686. addScaledVector: function ( v, s ) {
  1687. this.x += v.x * s;
  1688. this.y += v.y * s;
  1689. this.z += v.z * s;
  1690. this.w += v.w * s;
  1691. return this;
  1692. },
  1693. sub: function ( v, w ) {
  1694. if ( w !== undefined ) {
  1695. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1696. return this.subVectors( v, w );
  1697. }
  1698. this.x -= v.x;
  1699. this.y -= v.y;
  1700. this.z -= v.z;
  1701. this.w -= v.w;
  1702. return this;
  1703. },
  1704. subScalar: function ( s ) {
  1705. this.x -= s;
  1706. this.y -= s;
  1707. this.z -= s;
  1708. this.w -= s;
  1709. return this;
  1710. },
  1711. subVectors: function ( a, b ) {
  1712. this.x = a.x - b.x;
  1713. this.y = a.y - b.y;
  1714. this.z = a.z - b.z;
  1715. this.w = a.w - b.w;
  1716. return this;
  1717. },
  1718. multiplyScalar: function ( scalar ) {
  1719. if ( isFinite( scalar ) ) {
  1720. this.x *= scalar;
  1721. this.y *= scalar;
  1722. this.z *= scalar;
  1723. this.w *= scalar;
  1724. } else {
  1725. this.x = 0;
  1726. this.y = 0;
  1727. this.z = 0;
  1728. this.w = 0;
  1729. }
  1730. return this;
  1731. },
  1732. applyMatrix4: function ( m ) {
  1733. var x = this.x;
  1734. var y = this.y;
  1735. var z = this.z;
  1736. var w = this.w;
  1737. var e = m.elements;
  1738. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1739. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1740. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1741. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1742. return this;
  1743. },
  1744. divideScalar: function ( scalar ) {
  1745. return this.multiplyScalar( 1 / scalar );
  1746. },
  1747. setAxisAngleFromQuaternion: function ( q ) {
  1748. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1749. // q is assumed to be normalized
  1750. this.w = 2 * Math.acos( q.w );
  1751. var s = Math.sqrt( 1 - q.w * q.w );
  1752. if ( s < 0.0001 ) {
  1753. this.x = 1;
  1754. this.y = 0;
  1755. this.z = 0;
  1756. } else {
  1757. this.x = q.x / s;
  1758. this.y = q.y / s;
  1759. this.z = q.z / s;
  1760. }
  1761. return this;
  1762. },
  1763. setAxisAngleFromRotationMatrix: function ( m ) {
  1764. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1765. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1766. var angle, x, y, z, // variables for result
  1767. epsilon = 0.01, // margin to allow for rounding errors
  1768. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1769. te = m.elements,
  1770. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1771. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1772. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1773. if ( ( Math.abs( m12 - m21 ) < epsilon )
  1774. && ( Math.abs( m13 - m31 ) < epsilon )
  1775. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1776. // singularity found
  1777. // first check for identity matrix which must have +1 for all terms
  1778. // in leading diagonal and zero in other terms
  1779. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  1780. && ( Math.abs( m13 + m31 ) < epsilon2 )
  1781. && ( Math.abs( m23 + m32 ) < epsilon2 )
  1782. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1783. // this singularity is identity matrix so angle = 0
  1784. this.set( 1, 0, 0, 0 );
  1785. return this; // zero angle, arbitrary axis
  1786. }
  1787. // otherwise this singularity is angle = 180
  1788. angle = Math.PI;
  1789. var xx = ( m11 + 1 ) / 2;
  1790. var yy = ( m22 + 1 ) / 2;
  1791. var zz = ( m33 + 1 ) / 2;
  1792. var xy = ( m12 + m21 ) / 4;
  1793. var xz = ( m13 + m31 ) / 4;
  1794. var yz = ( m23 + m32 ) / 4;
  1795. if ( ( xx > yy ) && ( xx > zz ) ) {
  1796. // m11 is the largest diagonal term
  1797. if ( xx < epsilon ) {
  1798. x = 0;
  1799. y = 0.707106781;
  1800. z = 0.707106781;
  1801. } else {
  1802. x = Math.sqrt( xx );
  1803. y = xy / x;
  1804. z = xz / x;
  1805. }
  1806. } else if ( yy > zz ) {
  1807. // m22 is the largest diagonal term
  1808. if ( yy < epsilon ) {
  1809. x = 0.707106781;
  1810. y = 0;
  1811. z = 0.707106781;
  1812. } else {
  1813. y = Math.sqrt( yy );
  1814. x = xy / y;
  1815. z = yz / y;
  1816. }
  1817. } else {
  1818. // m33 is the largest diagonal term so base result on this
  1819. if ( zz < epsilon ) {
  1820. x = 0.707106781;
  1821. y = 0.707106781;
  1822. z = 0;
  1823. } else {
  1824. z = Math.sqrt( zz );
  1825. x = xz / z;
  1826. y = yz / z;
  1827. }
  1828. }
  1829. this.set( x, y, z, angle );
  1830. return this; // return 180 deg rotation
  1831. }
  1832. // as we have reached here there are no singularities so we can handle normally
  1833. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  1834. + ( m13 - m31 ) * ( m13 - m31 )
  1835. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1836. if ( Math.abs( s ) < 0.001 ) s = 1;
  1837. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1838. // caught by singularity test above, but I've left it in just in case
  1839. this.x = ( m32 - m23 ) / s;
  1840. this.y = ( m13 - m31 ) / s;
  1841. this.z = ( m21 - m12 ) / s;
  1842. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1843. return this;
  1844. },
  1845. min: function ( v ) {
  1846. this.x = Math.min( this.x, v.x );
  1847. this.y = Math.min( this.y, v.y );
  1848. this.z = Math.min( this.z, v.z );
  1849. this.w = Math.min( this.w, v.w );
  1850. return this;
  1851. },
  1852. max: function ( v ) {
  1853. this.x = Math.max( this.x, v.x );
  1854. this.y = Math.max( this.y, v.y );
  1855. this.z = Math.max( this.z, v.z );
  1856. this.w = Math.max( this.w, v.w );
  1857. return this;
  1858. },
  1859. clamp: function ( min, max ) {
  1860. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1861. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1862. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1863. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1864. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1865. return this;
  1866. },
  1867. clampScalar: function () {
  1868. var min, max;
  1869. return function clampScalar( minVal, maxVal ) {
  1870. if ( min === undefined ) {
  1871. min = new THREE.Vector4();
  1872. max = new THREE.Vector4();
  1873. }
  1874. min.set( minVal, minVal, minVal, minVal );
  1875. max.set( maxVal, maxVal, maxVal, maxVal );
  1876. return this.clamp( min, max );
  1877. };
  1878. }(),
  1879. floor: function () {
  1880. this.x = Math.floor( this.x );
  1881. this.y = Math.floor( this.y );
  1882. this.z = Math.floor( this.z );
  1883. this.w = Math.floor( this.w );
  1884. return this;
  1885. },
  1886. ceil: function () {
  1887. this.x = Math.ceil( this.x );
  1888. this.y = Math.ceil( this.y );
  1889. this.z = Math.ceil( this.z );
  1890. this.w = Math.ceil( this.w );
  1891. return this;
  1892. },
  1893. round: function () {
  1894. this.x = Math.round( this.x );
  1895. this.y = Math.round( this.y );
  1896. this.z = Math.round( this.z );
  1897. this.w = Math.round( this.w );
  1898. return this;
  1899. },
  1900. roundToZero: function () {
  1901. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1902. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1903. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1904. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1905. return this;
  1906. },
  1907. negate: function () {
  1908. this.x = - this.x;
  1909. this.y = - this.y;
  1910. this.z = - this.z;
  1911. this.w = - this.w;
  1912. return this;
  1913. },
  1914. dot: function ( v ) {
  1915. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1916. },
  1917. lengthSq: function () {
  1918. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1919. },
  1920. length: function () {
  1921. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1922. },
  1923. lengthManhattan: function () {
  1924. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1925. },
  1926. normalize: function () {
  1927. return this.divideScalar( this.length() );
  1928. },
  1929. setLength: function ( length ) {
  1930. return this.multiplyScalar( length / this.length() );
  1931. },
  1932. lerp: function ( v, alpha ) {
  1933. this.x += ( v.x - this.x ) * alpha;
  1934. this.y += ( v.y - this.y ) * alpha;
  1935. this.z += ( v.z - this.z ) * alpha;
  1936. this.w += ( v.w - this.w ) * alpha;
  1937. return this;
  1938. },
  1939. lerpVectors: function ( v1, v2, alpha ) {
  1940. this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1941. return this;
  1942. },
  1943. equals: function ( v ) {
  1944. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1945. },
  1946. fromArray: function ( array, offset ) {
  1947. if ( offset === undefined ) offset = 0;
  1948. this.x = array[ offset ];
  1949. this.y = array[ offset + 1 ];
  1950. this.z = array[ offset + 2 ];
  1951. this.w = array[ offset + 3 ];
  1952. return this;
  1953. },
  1954. toArray: function ( array, offset ) {
  1955. if ( array === undefined ) array = [];
  1956. if ( offset === undefined ) offset = 0;
  1957. array[ offset ] = this.x;
  1958. array[ offset + 1 ] = this.y;
  1959. array[ offset + 2 ] = this.z;
  1960. array[ offset + 3 ] = this.w;
  1961. return array;
  1962. },
  1963. fromAttribute: function ( attribute, index, offset ) {
  1964. if ( offset === undefined ) offset = 0;
  1965. index = index * attribute.itemSize + offset;
  1966. this.x = attribute.array[ index ];
  1967. this.y = attribute.array[ index + 1 ];
  1968. this.z = attribute.array[ index + 2 ];
  1969. this.w = attribute.array[ index + 3 ];
  1970. return this;
  1971. }
  1972. };
  1973. // File:src/math/Euler.js
  1974. /**
  1975. * @author mrdoob / http://mrdoob.com/
  1976. * @author WestLangley / http://github.com/WestLangley
  1977. * @author bhouston / http://clara.io
  1978. */
  1979. THREE.Euler = function ( x, y, z, order ) {
  1980. this._x = x || 0;
  1981. this._y = y || 0;
  1982. this._z = z || 0;
  1983. this._order = order || THREE.Euler.DefaultOrder;
  1984. };
  1985. THREE.Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  1986. THREE.Euler.DefaultOrder = 'XYZ';
  1987. THREE.Euler.prototype = {
  1988. constructor: THREE.Euler,
  1989. get x () {
  1990. return this._x;
  1991. },
  1992. set x ( value ) {
  1993. this._x = value;
  1994. this.onChangeCallback();
  1995. },
  1996. get y () {
  1997. return this._y;
  1998. },
  1999. set y ( value ) {
  2000. this._y = value;
  2001. this.onChangeCallback();
  2002. },
  2003. get z () {
  2004. return this._z;
  2005. },
  2006. set z ( value ) {
  2007. this._z = value;
  2008. this.onChangeCallback();
  2009. },
  2010. get order () {
  2011. return this._order;
  2012. },
  2013. set order ( value ) {
  2014. this._order = value;
  2015. this.onChangeCallback();
  2016. },
  2017. set: function ( x, y, z, order ) {
  2018. this._x = x;
  2019. this._y = y;
  2020. this._z = z;
  2021. this._order = order || this._order;
  2022. this.onChangeCallback();
  2023. return this;
  2024. },
  2025. clone: function () {
  2026. return new this.constructor( this._x, this._y, this._z, this._order );
  2027. },
  2028. copy: function ( euler ) {
  2029. this._x = euler._x;
  2030. this._y = euler._y;
  2031. this._z = euler._z;
  2032. this._order = euler._order;
  2033. this.onChangeCallback();
  2034. return this;
  2035. },
  2036. setFromRotationMatrix: function ( m, order, update ) {
  2037. var clamp = THREE.Math.clamp;
  2038. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2039. var te = m.elements;
  2040. var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  2041. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  2042. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  2043. order = order || this._order;
  2044. if ( order === 'XYZ' ) {
  2045. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  2046. if ( Math.abs( m13 ) < 0.99999 ) {
  2047. this._x = Math.atan2( - m23, m33 );
  2048. this._z = Math.atan2( - m12, m11 );
  2049. } else {
  2050. this._x = Math.atan2( m32, m22 );
  2051. this._z = 0;
  2052. }
  2053. } else if ( order === 'YXZ' ) {
  2054. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  2055. if ( Math.abs( m23 ) < 0.99999 ) {
  2056. this._y = Math.atan2( m13, m33 );
  2057. this._z = Math.atan2( m21, m22 );
  2058. } else {
  2059. this._y = Math.atan2( - m31, m11 );
  2060. this._z = 0;
  2061. }
  2062. } else if ( order === 'ZXY' ) {
  2063. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  2064. if ( Math.abs( m32 ) < 0.99999 ) {
  2065. this._y = Math.atan2( - m31, m33 );
  2066. this._z = Math.atan2( - m12, m22 );
  2067. } else {
  2068. this._y = 0;
  2069. this._z = Math.atan2( m21, m11 );
  2070. }
  2071. } else if ( order === 'ZYX' ) {
  2072. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  2073. if ( Math.abs( m31 ) < 0.99999 ) {
  2074. this._x = Math.atan2( m32, m33 );
  2075. this._z = Math.atan2( m21, m11 );
  2076. } else {
  2077. this._x = 0;
  2078. this._z = Math.atan2( - m12, m22 );
  2079. }
  2080. } else if ( order === 'YZX' ) {
  2081. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  2082. if ( Math.abs( m21 ) < 0.99999 ) {
  2083. this._x = Math.atan2( - m23, m22 );
  2084. this._y = Math.atan2( - m31, m11 );
  2085. } else {
  2086. this._x = 0;
  2087. this._y = Math.atan2( m13, m33 );
  2088. }
  2089. } else if ( order === 'XZY' ) {
  2090. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  2091. if ( Math.abs( m12 ) < 0.99999 ) {
  2092. this._x = Math.atan2( m32, m22 );
  2093. this._y = Math.atan2( m13, m11 );
  2094. } else {
  2095. this._x = Math.atan2( - m23, m33 );
  2096. this._y = 0;
  2097. }
  2098. } else {
  2099. console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order )
  2100. }
  2101. this._order = order;
  2102. if ( update !== false ) this.onChangeCallback();
  2103. return this;
  2104. },
  2105. setFromQuaternion: function () {
  2106. var matrix;
  2107. return function ( q, order, update ) {
  2108. if ( matrix === undefined ) matrix = new THREE.Matrix4();
  2109. matrix.makeRotationFromQuaternion( q );
  2110. this.setFromRotationMatrix( matrix, order, update );
  2111. return this;
  2112. };
  2113. }(),
  2114. setFromVector3: function ( v, order ) {
  2115. return this.set( v.x, v.y, v.z, order || this._order );
  2116. },
  2117. reorder: function () {
  2118. // WARNING: this discards revolution information -bhouston
  2119. var q = new THREE.Quaternion();
  2120. return function ( newOrder ) {
  2121. q.setFromEuler( this );
  2122. this.setFromQuaternion( q, newOrder );
  2123. };
  2124. }(),
  2125. equals: function ( euler ) {
  2126. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  2127. },
  2128. fromArray: function ( array ) {
  2129. this._x = array[ 0 ];
  2130. this._y = array[ 1 ];
  2131. this._z = array[ 2 ];
  2132. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  2133. this.onChangeCallback();
  2134. return this;
  2135. },
  2136. toArray: function ( array, offset ) {
  2137. if ( array === undefined ) array = [];
  2138. if ( offset === undefined ) offset = 0;
  2139. array[ offset ] = this._x;
  2140. array[ offset + 1 ] = this._y;
  2141. array[ offset + 2 ] = this._z;
  2142. array[ offset + 3 ] = this._order;
  2143. return array;
  2144. },
  2145. toVector3: function ( optionalResult ) {
  2146. if ( optionalResult ) {
  2147. return optionalResult.set( this._x, this._y, this._z );
  2148. } else {
  2149. return new THREE.Vector3( this._x, this._y, this._z );
  2150. }
  2151. },
  2152. onChange: function ( callback ) {
  2153. this.onChangeCallback = callback;
  2154. return this;
  2155. },
  2156. onChangeCallback: function () {}
  2157. };
  2158. // File:src/math/Line3.js
  2159. /**
  2160. * @author bhouston / http://clara.io
  2161. */
  2162. THREE.Line3 = function ( start, end ) {
  2163. this.start = ( start !== undefined ) ? start : new THREE.Vector3();
  2164. this.end = ( end !== undefined ) ? end : new THREE.Vector3();
  2165. };
  2166. THREE.Line3.prototype = {
  2167. constructor: THREE.Line3,
  2168. set: function ( start, end ) {
  2169. this.start.copy( start );
  2170. this.end.copy( end );
  2171. return this;
  2172. },
  2173. clone: function () {
  2174. return new this.constructor().copy( this );
  2175. },
  2176. copy: function ( line ) {
  2177. this.start.copy( line.start );
  2178. this.end.copy( line.end );
  2179. return this;
  2180. },
  2181. center: function ( optionalTarget ) {
  2182. var result = optionalTarget || new THREE.Vector3();
  2183. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  2184. },
  2185. delta: function ( optionalTarget ) {
  2186. var result = optionalTarget || new THREE.Vector3();
  2187. return result.subVectors( this.end, this.start );
  2188. },
  2189. distanceSq: function () {
  2190. return this.start.distanceToSquared( this.end );
  2191. },
  2192. distance: function () {
  2193. return this.start.distanceTo( this.end );
  2194. },
  2195. at: function ( t, optionalTarget ) {
  2196. var result = optionalTarget || new THREE.Vector3();
  2197. return this.delta( result ).multiplyScalar( t ).add( this.start );
  2198. },
  2199. closestPointToPointParameter: function () {
  2200. var startP = new THREE.Vector3();
  2201. var startEnd = new THREE.Vector3();
  2202. return function ( point, clampToLine ) {
  2203. startP.subVectors( point, this.start );
  2204. startEnd.subVectors( this.end, this.start );
  2205. var startEnd2 = startEnd.dot( startEnd );
  2206. var startEnd_startP = startEnd.dot( startP );
  2207. var t = startEnd_startP / startEnd2;
  2208. if ( clampToLine ) {
  2209. t = THREE.Math.clamp( t, 0, 1 );
  2210. }
  2211. return t;
  2212. };
  2213. }(),
  2214. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  2215. var t = this.closestPointToPointParameter( point, clampToLine );
  2216. var result = optionalTarget || new THREE.Vector3();
  2217. return this.delta( result ).multiplyScalar( t ).add( this.start );
  2218. },
  2219. applyMatrix4: function ( matrix ) {
  2220. this.start.applyMatrix4( matrix );
  2221. this.end.applyMatrix4( matrix );
  2222. return this;
  2223. },
  2224. equals: function ( line ) {
  2225. return line.start.equals( this.start ) && line.end.equals( this.end );
  2226. }
  2227. };
  2228. // File:src/math/Box2.js
  2229. /**
  2230. * @author bhouston / http://clara.io
  2231. */
  2232. THREE.Box2 = function ( min, max ) {
  2233. this.min = ( min !== undefined ) ? min : new THREE.Vector2( + Infinity, + Infinity );
  2234. this.max = ( max !== undefined ) ? max : new THREE.Vector2( - Infinity, - Infinity );
  2235. };
  2236. THREE.Box2.prototype = {
  2237. constructor: THREE.Box2,
  2238. set: function ( min, max ) {
  2239. this.min.copy( min );
  2240. this.max.copy( max );
  2241. return this;
  2242. },
  2243. setFromPoints: function ( points ) {
  2244. this.makeEmpty();
  2245. for ( var i = 0, il = points.length; i < il; i ++ ) {
  2246. this.expandByPoint( points[ i ] );
  2247. }
  2248. return this;
  2249. },
  2250. setFromCenterAndSize: function () {
  2251. var v1 = new THREE.Vector2();
  2252. return function ( center, size ) {
  2253. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2254. this.min.copy( center ).sub( halfSize );
  2255. this.max.copy( center ).add( halfSize );
  2256. return this;
  2257. };
  2258. }(),
  2259. clone: function () {
  2260. return new this.constructor().copy( this );
  2261. },
  2262. copy: function ( box ) {
  2263. this.min.copy( box.min );
  2264. this.max.copy( box.max );
  2265. return this;
  2266. },
  2267. makeEmpty: function () {
  2268. this.min.x = this.min.y = + Infinity;
  2269. this.max.x = this.max.y = - Infinity;
  2270. return this;
  2271. },
  2272. isEmpty: function () {
  2273. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2274. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  2275. },
  2276. center: function ( optionalTarget ) {
  2277. var result = optionalTarget || new THREE.Vector2();
  2278. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2279. },
  2280. size: function ( optionalTarget ) {
  2281. var result = optionalTarget || new THREE.Vector2();
  2282. return result.subVectors( this.max, this.min );
  2283. },
  2284. expandByPoint: function ( point ) {
  2285. this.min.min( point );
  2286. this.max.max( point );
  2287. return this;
  2288. },
  2289. expandByVector: function ( vector ) {
  2290. this.min.sub( vector );
  2291. this.max.add( vector );
  2292. return this;
  2293. },
  2294. expandByScalar: function ( scalar ) {
  2295. this.min.addScalar( - scalar );
  2296. this.max.addScalar( scalar );
  2297. return this;
  2298. },
  2299. containsPoint: function ( point ) {
  2300. if ( point.x < this.min.x || point.x > this.max.x ||
  2301. point.y < this.min.y || point.y > this.max.y ) {
  2302. return false;
  2303. }
  2304. return true;
  2305. },
  2306. containsBox: function ( box ) {
  2307. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2308. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  2309. return true;
  2310. }
  2311. return false;
  2312. },
  2313. getParameter: function ( point, optionalTarget ) {
  2314. // This can potentially have a divide by zero if the box
  2315. // has a size dimension of 0.
  2316. var result = optionalTarget || new THREE.Vector2();
  2317. return result.set(
  2318. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2319. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  2320. );
  2321. },
  2322. intersectsBox: function ( box ) {
  2323. // using 6 splitting planes to rule out intersections.
  2324. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2325. box.max.y < this.min.y || box.min.y > this.max.y ) {
  2326. return false;
  2327. }
  2328. return true;
  2329. },
  2330. clampPoint: function ( point, optionalTarget ) {
  2331. var result = optionalTarget || new THREE.Vector2();
  2332. return result.copy( point ).clamp( this.min, this.max );
  2333. },
  2334. distanceToPoint: function () {
  2335. var v1 = new THREE.Vector2();
  2336. return function ( point ) {
  2337. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2338. return clampedPoint.sub( point ).length();
  2339. };
  2340. }(),
  2341. intersect: function ( box ) {
  2342. this.min.max( box.min );
  2343. this.max.min( box.max );
  2344. return this;
  2345. },
  2346. union: function ( box ) {
  2347. this.min.min( box.min );
  2348. this.max.max( box.max );
  2349. return this;
  2350. },
  2351. translate: function ( offset ) {
  2352. this.min.add( offset );
  2353. this.max.add( offset );
  2354. return this;
  2355. },
  2356. equals: function ( box ) {
  2357. return box.min.equals( this.min ) && box.max.equals( this.max );
  2358. }
  2359. };
  2360. // File:src/math/Box3.js
  2361. /**
  2362. * @author bhouston / http://clara.io
  2363. * @author WestLangley / http://github.com/WestLangley
  2364. */
  2365. THREE.Box3 = function ( min, max ) {
  2366. this.min = ( min !== undefined ) ? min : new THREE.Vector3( + Infinity, + Infinity, + Infinity );
  2367. this.max = ( max !== undefined ) ? max : new THREE.Vector3( - Infinity, - Infinity, - Infinity );
  2368. };
  2369. THREE.Box3.prototype = {
  2370. constructor: THREE.Box3,
  2371. set: function ( min, max ) {
  2372. this.min.copy( min );
  2373. this.max.copy( max );
  2374. return this;
  2375. },
  2376. setFromArray: function ( array ) {
  2377. this.makeEmpty();
  2378. var minX = + Infinity;
  2379. var minY = + Infinity;
  2380. var minZ = + Infinity;
  2381. var maxX = - Infinity;
  2382. var maxY = - Infinity;
  2383. var maxZ = - Infinity;
  2384. for ( var i = 0, il = array.length; i < il; i += 3 ) {
  2385. var x = array[ i ];
  2386. var y = array[ i + 1 ];
  2387. var z = array[ i + 2 ];
  2388. if ( x < minX ) minX = x;
  2389. if ( y < minY ) minY = y;
  2390. if ( z < minZ ) minZ = z;
  2391. if ( x > maxX ) maxX = x;
  2392. if ( y > maxY ) maxY = y;
  2393. if ( z > maxZ ) maxZ = z;
  2394. }
  2395. this.min.set( minX, minY, minZ );
  2396. this.max.set( maxX, maxY, maxZ );
  2397. },
  2398. setFromPoints: function ( points ) {
  2399. this.makeEmpty();
  2400. for ( var i = 0, il = points.length; i < il; i ++ ) {
  2401. this.expandByPoint( points[ i ] );
  2402. }
  2403. return this;
  2404. },
  2405. setFromCenterAndSize: function () {
  2406. var v1 = new THREE.Vector3();
  2407. return function ( center, size ) {
  2408. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2409. this.min.copy( center ).sub( halfSize );
  2410. this.max.copy( center ).add( halfSize );
  2411. return this;
  2412. };
  2413. }(),
  2414. setFromObject: function () {
  2415. // Computes the world-axis-aligned bounding box of an object (including its children),
  2416. // accounting for both the object's, and children's, world transforms
  2417. var v1 = new THREE.Vector3();
  2418. return function ( object ) {
  2419. var scope = this;
  2420. object.updateMatrixWorld( true );
  2421. this.makeEmpty();
  2422. object.traverse( function ( node ) {
  2423. var geometry = node.geometry;
  2424. if ( geometry !== undefined ) {
  2425. if ( geometry instanceof THREE.Geometry ) {
  2426. var vertices = geometry.vertices;
  2427. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  2428. v1.copy( vertices[ i ] );
  2429. v1.applyMatrix4( node.matrixWorld );
  2430. scope.expandByPoint( v1 );
  2431. }
  2432. } else if ( geometry instanceof THREE.BufferGeometry && geometry.attributes[ 'position' ] !== undefined ) {
  2433. var positions = geometry.attributes[ 'position' ].array;
  2434. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  2435. v1.fromArray( positions, i );
  2436. v1.applyMatrix4( node.matrixWorld );
  2437. scope.expandByPoint( v1 );
  2438. }
  2439. }
  2440. }
  2441. } );
  2442. return this;
  2443. };
  2444. }(),
  2445. clone: function () {
  2446. return new this.constructor().copy( this );
  2447. },
  2448. copy: function ( box ) {
  2449. this.min.copy( box.min );
  2450. this.max.copy( box.max );
  2451. return this;
  2452. },
  2453. makeEmpty: function () {
  2454. this.min.x = this.min.y = this.min.z = + Infinity;
  2455. this.max.x = this.max.y = this.max.z = - Infinity;
  2456. return this;
  2457. },
  2458. isEmpty: function () {
  2459. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2460. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2461. },
  2462. center: function ( optionalTarget ) {
  2463. var result = optionalTarget || new THREE.Vector3();
  2464. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2465. },
  2466. size: function ( optionalTarget ) {
  2467. var result = optionalTarget || new THREE.Vector3();
  2468. return result.subVectors( this.max, this.min );
  2469. },
  2470. expandByPoint: function ( point ) {
  2471. this.min.min( point );
  2472. this.max.max( point );
  2473. return this;
  2474. },
  2475. expandByVector: function ( vector ) {
  2476. this.min.sub( vector );
  2477. this.max.add( vector );
  2478. return this;
  2479. },
  2480. expandByScalar: function ( scalar ) {
  2481. this.min.addScalar( - scalar );
  2482. this.max.addScalar( scalar );
  2483. return this;
  2484. },
  2485. containsPoint: function ( point ) {
  2486. if ( point.x < this.min.x || point.x > this.max.x ||
  2487. point.y < this.min.y || point.y > this.max.y ||
  2488. point.z < this.min.z || point.z > this.max.z ) {
  2489. return false;
  2490. }
  2491. return true;
  2492. },
  2493. containsBox: function ( box ) {
  2494. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2495. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  2496. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  2497. return true;
  2498. }
  2499. return false;
  2500. },
  2501. getParameter: function ( point, optionalTarget ) {
  2502. // This can potentially have a divide by zero if the box
  2503. // has a size dimension of 0.
  2504. var result = optionalTarget || new THREE.Vector3();
  2505. return result.set(
  2506. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2507. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2508. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2509. );
  2510. },
  2511. intersectsBox: function ( box ) {
  2512. // using 6 splitting planes to rule out intersections.
  2513. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2514. box.max.y < this.min.y || box.min.y > this.max.y ||
  2515. box.max.z < this.min.z || box.min.z > this.max.z ) {
  2516. return false;
  2517. }
  2518. return true;
  2519. },
  2520. intersectsSphere: ( function () {
  2521. var closestPoint;
  2522. return function intersectsSphere( sphere ) {
  2523. if ( closestPoint === undefined ) closestPoint = new THREE.Vector3();
  2524. // Find the point on the AABB closest to the sphere center.
  2525. this.clampPoint( sphere.center, closestPoint );
  2526. // If that point is inside the sphere, the AABB and sphere intersect.
  2527. return closestPoint.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  2528. };
  2529. } )(),
  2530. intersectsPlane: function ( plane ) {
  2531. // We compute the minimum and maximum dot product values. If those values
  2532. // are on the same side (back or front) of the plane, then there is no intersection.
  2533. var min, max;
  2534. if ( plane.normal.x > 0 ) {
  2535. min = plane.normal.x * this.min.x;
  2536. max = plane.normal.x * this.max.x;
  2537. } else {
  2538. min = plane.normal.x * this.max.x;
  2539. max = plane.normal.x * this.min.x;
  2540. }
  2541. if ( plane.normal.y > 0 ) {
  2542. min += plane.normal.y * this.min.y;
  2543. max += plane.normal.y * this.max.y;
  2544. } else {
  2545. min += plane.normal.y * this.max.y;
  2546. max += plane.normal.y * this.min.y;
  2547. }
  2548. if ( plane.normal.z > 0 ) {
  2549. min += plane.normal.z * this.min.z;
  2550. max += plane.normal.z * this.max.z;
  2551. } else {
  2552. min += plane.normal.z * this.max.z;
  2553. max += plane.normal.z * this.min.z;
  2554. }
  2555. return ( min <= plane.constant && max >= plane.constant );
  2556. },
  2557. clampPoint: function ( point, optionalTarget ) {
  2558. var result = optionalTarget || new THREE.Vector3();
  2559. return result.copy( point ).clamp( this.min, this.max );
  2560. },
  2561. distanceToPoint: function () {
  2562. var v1 = new THREE.Vector3();
  2563. return function ( point ) {
  2564. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2565. return clampedPoint.sub( point ).length();
  2566. };
  2567. }(),
  2568. getBoundingSphere: function () {
  2569. var v1 = new THREE.Vector3();
  2570. return function ( optionalTarget ) {
  2571. var result = optionalTarget || new THREE.Sphere();
  2572. result.center = this.center();
  2573. result.radius = this.size( v1 ).length() * 0.5;
  2574. return result;
  2575. };
  2576. }(),
  2577. intersect: function ( box ) {
  2578. this.min.max( box.min );
  2579. this.max.min( box.max );
  2580. return this;
  2581. },
  2582. union: function ( box ) {
  2583. this.min.min( box.min );
  2584. this.max.max( box.max );
  2585. return this;
  2586. },
  2587. applyMatrix4: function () {
  2588. var points = [
  2589. new THREE.Vector3(),
  2590. new THREE.Vector3(),
  2591. new THREE.Vector3(),
  2592. new THREE.Vector3(),
  2593. new THREE.Vector3(),
  2594. new THREE.Vector3(),
  2595. new THREE.Vector3(),
  2596. new THREE.Vector3()
  2597. ];
  2598. return function ( matrix ) {
  2599. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2600. points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2601. points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2602. points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2603. points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2604. points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2605. points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2606. points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2607. points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2608. this.makeEmpty();
  2609. this.setFromPoints( points );
  2610. return this;
  2611. };
  2612. }(),
  2613. translate: function ( offset ) {
  2614. this.min.add( offset );
  2615. this.max.add( offset );
  2616. return this;
  2617. },
  2618. equals: function ( box ) {
  2619. return box.min.equals( this.min ) && box.max.equals( this.max );
  2620. }
  2621. };
  2622. // File:src/math/Matrix3.js
  2623. /**
  2624. * @author alteredq / http://alteredqualia.com/
  2625. * @author WestLangley / http://github.com/WestLangley
  2626. * @author bhouston / http://clara.io
  2627. * @author tschw
  2628. */
  2629. THREE.Matrix3 = function () {
  2630. this.elements = new Float32Array( [
  2631. 1, 0, 0,
  2632. 0, 1, 0,
  2633. 0, 0, 1
  2634. ] );
  2635. if ( arguments.length > 0 ) {
  2636. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  2637. }
  2638. };
  2639. THREE.Matrix3.prototype = {
  2640. constructor: THREE.Matrix3,
  2641. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2642. var te = this.elements;
  2643. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  2644. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  2645. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  2646. return this;
  2647. },
  2648. identity: function () {
  2649. this.set(
  2650. 1, 0, 0,
  2651. 0, 1, 0,
  2652. 0, 0, 1
  2653. );
  2654. return this;
  2655. },
  2656. clone: function () {
  2657. return new this.constructor().fromArray( this.elements );
  2658. },
  2659. copy: function ( m ) {
  2660. var me = m.elements;
  2661. this.set(
  2662. me[ 0 ], me[ 3 ], me[ 6 ],
  2663. me[ 1 ], me[ 4 ], me[ 7 ],
  2664. me[ 2 ], me[ 5 ], me[ 8 ]
  2665. );
  2666. return this;
  2667. },
  2668. setFromMatrix4: function( m ) {
  2669. var me = m.elements;
  2670. this.set(
  2671. me[ 0 ], me[ 4 ], me[ 8 ],
  2672. me[ 1 ], me[ 5 ], me[ 9 ],
  2673. me[ 2 ], me[ 6 ], me[ 10 ]
  2674. );
  2675. return this;
  2676. },
  2677. applyToVector3Array: function () {
  2678. var v1;
  2679. return function ( array, offset, length ) {
  2680. if ( v1 === undefined ) v1 = new THREE.Vector3();
  2681. if ( offset === undefined ) offset = 0;
  2682. if ( length === undefined ) length = array.length;
  2683. for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) {
  2684. v1.fromArray( array, j );
  2685. v1.applyMatrix3( this );
  2686. v1.toArray( array, j );
  2687. }
  2688. return array;
  2689. };
  2690. }(),
  2691. applyToBuffer: function () {
  2692. var v1;
  2693. return function applyToBuffer( buffer, offset, length ) {
  2694. if ( v1 === undefined ) v1 = new THREE.Vector3();
  2695. if ( offset === undefined ) offset = 0;
  2696. if ( length === undefined ) length = buffer.length / buffer.itemSize;
  2697. for ( var i = 0, j = offset; i < length; i ++, j ++ ) {
  2698. v1.x = buffer.getX( j );
  2699. v1.y = buffer.getY( j );
  2700. v1.z = buffer.getZ( j );
  2701. v1.applyMatrix3( this );
  2702. buffer.setXYZ( v1.x, v1.y, v1.z );
  2703. }
  2704. return buffer;
  2705. };
  2706. }(),
  2707. multiplyScalar: function ( s ) {
  2708. var te = this.elements;
  2709. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  2710. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  2711. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  2712. return this;
  2713. },
  2714. determinant: function () {
  2715. var te = this.elements;
  2716. var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  2717. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  2718. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  2719. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  2720. },
  2721. getInverse: function ( matrix, throwOnDegenerate ) {
  2722. if ( matrix instanceof THREE.Matrix4 ) {
  2723. console.error( "THREE.Matrix3.getInverse no longer takes a Matrix4 argument." );
  2724. }
  2725. var me = matrix.elements,
  2726. te = this.elements,
  2727. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ],
  2728. n12 = me[ 3 ], n22 = me[ 4 ], n32 = me[ 5 ],
  2729. n13 = me[ 6 ], n23 = me[ 7 ], n33 = me[ 8 ],
  2730. t11 = n33 * n22 - n32 * n23,
  2731. t12 = n32 * n13 - n33 * n12,
  2732. t13 = n23 * n12 - n22 * n13,
  2733. det = n11 * t11 + n21 * t12 + n31 * t13;
  2734. if ( det === 0 ) {
  2735. var msg = "THREE.Matrix3.getInverse(): can't invert matrix, determinant is 0";
  2736. if ( throwOnDegenerate || false ) {
  2737. throw new Error( msg );
  2738. } else {
  2739. console.warn( msg );
  2740. }
  2741. return this.identity();
  2742. }
  2743. te[ 0 ] = t11;
  2744. te[ 1 ] = n31 * n23 - n33 * n21;
  2745. te[ 2 ] = n32 * n21 - n31 * n22;
  2746. te[ 3 ] = t12;
  2747. te[ 4 ] = n33 * n11 - n31 * n13;
  2748. te[ 5 ] = n31 * n12 - n32 * n11;
  2749. te[ 6 ] = t13;
  2750. te[ 7 ] = n21 * n13 - n23 * n11;
  2751. te[ 8 ] = n22 * n11 - n21 * n12;
  2752. return this.multiplyScalar( 1 / det );
  2753. },
  2754. transpose: function () {
  2755. var tmp, m = this.elements;
  2756. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  2757. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  2758. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  2759. return this;
  2760. },
  2761. flattenToArrayOffset: function ( array, offset ) {
  2762. var te = this.elements;
  2763. array[ offset ] = te[ 0 ];
  2764. array[ offset + 1 ] = te[ 1 ];
  2765. array[ offset + 2 ] = te[ 2 ];
  2766. array[ offset + 3 ] = te[ 3 ];
  2767. array[ offset + 4 ] = te[ 4 ];
  2768. array[ offset + 5 ] = te[ 5 ];
  2769. array[ offset + 6 ] = te[ 6 ];
  2770. array[ offset + 7 ] = te[ 7 ];
  2771. array[ offset + 8 ] = te[ 8 ];
  2772. return array;
  2773. },
  2774. getNormalMatrix: function ( matrix4 ) {
  2775. return this.setFromMatrix4( matrix4 ).getInverse( this ).transpose();
  2776. },
  2777. transposeIntoArray: function ( r ) {
  2778. var m = this.elements;
  2779. r[ 0 ] = m[ 0 ];
  2780. r[ 1 ] = m[ 3 ];
  2781. r[ 2 ] = m[ 6 ];
  2782. r[ 3 ] = m[ 1 ];
  2783. r[ 4 ] = m[ 4 ];
  2784. r[ 5 ] = m[ 7 ];
  2785. r[ 6 ] = m[ 2 ];
  2786. r[ 7 ] = m[ 5 ];
  2787. r[ 8 ] = m[ 8 ];
  2788. return this;
  2789. },
  2790. fromArray: function ( array ) {
  2791. this.elements.set( array );
  2792. return this;
  2793. },
  2794. toArray: function () {
  2795. var te = this.elements;
  2796. return [
  2797. te[ 0 ], te[ 1 ], te[ 2 ],
  2798. te[ 3 ], te[ 4 ], te[ 5 ],
  2799. te[ 6 ], te[ 7 ], te[ 8 ]
  2800. ];
  2801. }
  2802. };
  2803. // File:src/math/Matrix4.js
  2804. /**
  2805. * @author mrdoob / http://mrdoob.com/
  2806. * @author supereggbert / http://www.paulbrunt.co.uk/
  2807. * @author philogb / http://blog.thejit.org/
  2808. * @author jordi_ros / http://plattsoft.com
  2809. * @author D1plo1d / http://github.com/D1plo1d
  2810. * @author alteredq / http://alteredqualia.com/
  2811. * @author mikael emtinger / http://gomo.se/
  2812. * @author timknip / http://www.floorplanner.com/
  2813. * @author bhouston / http://clara.io
  2814. * @author WestLangley / http://github.com/WestLangley
  2815. */
  2816. THREE.Matrix4 = function () {
  2817. this.elements = new Float32Array( [
  2818. 1, 0, 0, 0,
  2819. 0, 1, 0, 0,
  2820. 0, 0, 1, 0,
  2821. 0, 0, 0, 1
  2822. ] );
  2823. if ( arguments.length > 0 ) {
  2824. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  2825. }
  2826. };
  2827. THREE.Matrix4.prototype = {
  2828. constructor: THREE.Matrix4,
  2829. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2830. var te = this.elements;
  2831. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  2832. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  2833. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  2834. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  2835. return this;
  2836. },
  2837. identity: function () {
  2838. this.set(
  2839. 1, 0, 0, 0,
  2840. 0, 1, 0, 0,
  2841. 0, 0, 1, 0,
  2842. 0, 0, 0, 1
  2843. );
  2844. return this;
  2845. },
  2846. clone: function () {
  2847. return new THREE.Matrix4().fromArray( this.elements );
  2848. },
  2849. copy: function ( m ) {
  2850. this.elements.set( m.elements );
  2851. return this;
  2852. },
  2853. copyPosition: function ( m ) {
  2854. var te = this.elements;
  2855. var me = m.elements;
  2856. te[ 12 ] = me[ 12 ];
  2857. te[ 13 ] = me[ 13 ];
  2858. te[ 14 ] = me[ 14 ];
  2859. return this;
  2860. },
  2861. extractBasis: function ( xAxis, yAxis, zAxis ) {
  2862. xAxis.setFromMatrixColumn( this, 0 );
  2863. yAxis.setFromMatrixColumn( this, 1 );
  2864. zAxis.setFromMatrixColumn( this, 2 );
  2865. return this;
  2866. },
  2867. makeBasis: function ( xAxis, yAxis, zAxis ) {
  2868. this.set(
  2869. xAxis.x, yAxis.x, zAxis.x, 0,
  2870. xAxis.y, yAxis.y, zAxis.y, 0,
  2871. xAxis.z, yAxis.z, zAxis.z, 0,
  2872. 0, 0, 0, 1
  2873. );
  2874. return this;
  2875. },
  2876. extractRotation: function () {
  2877. var v1;
  2878. return function ( m ) {
  2879. if ( v1 === undefined ) v1 = new THREE.Vector3();
  2880. var te = this.elements;
  2881. var me = m.elements;
  2882. var scaleX = 1 / v1.setFromMatrixColumn( m, 0 ).length();
  2883. var scaleY = 1 / v1.setFromMatrixColumn( m, 1 ).length();
  2884. var scaleZ = 1 / v1.setFromMatrixColumn( m, 2 ).length();
  2885. te[ 0 ] = me[ 0 ] * scaleX;
  2886. te[ 1 ] = me[ 1 ] * scaleX;
  2887. te[ 2 ] = me[ 2 ] * scaleX;
  2888. te[ 4 ] = me[ 4 ] * scaleY;
  2889. te[ 5 ] = me[ 5 ] * scaleY;
  2890. te[ 6 ] = me[ 6 ] * scaleY;
  2891. te[ 8 ] = me[ 8 ] * scaleZ;
  2892. te[ 9 ] = me[ 9 ] * scaleZ;
  2893. te[ 10 ] = me[ 10 ] * scaleZ;
  2894. return this;
  2895. };
  2896. }(),
  2897. makeRotationFromEuler: function ( euler ) {
  2898. if ( euler instanceof THREE.Euler === false ) {
  2899. console.error( 'THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  2900. }
  2901. var te = this.elements;
  2902. var x = euler.x, y = euler.y, z = euler.z;
  2903. var a = Math.cos( x ), b = Math.sin( x );
  2904. var c = Math.cos( y ), d = Math.sin( y );
  2905. var e = Math.cos( z ), f = Math.sin( z );
  2906. if ( euler.order === 'XYZ' ) {
  2907. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2908. te[ 0 ] = c * e;
  2909. te[ 4 ] = - c * f;
  2910. te[ 8 ] = d;
  2911. te[ 1 ] = af + be * d;
  2912. te[ 5 ] = ae - bf * d;
  2913. te[ 9 ] = - b * c;
  2914. te[ 2 ] = bf - ae * d;
  2915. te[ 6 ] = be + af * d;
  2916. te[ 10 ] = a * c;
  2917. } else if ( euler.order === 'YXZ' ) {
  2918. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2919. te[ 0 ] = ce + df * b;
  2920. te[ 4 ] = de * b - cf;
  2921. te[ 8 ] = a * d;
  2922. te[ 1 ] = a * f;
  2923. te[ 5 ] = a * e;
  2924. te[ 9 ] = - b;
  2925. te[ 2 ] = cf * b - de;
  2926. te[ 6 ] = df + ce * b;
  2927. te[ 10 ] = a * c;
  2928. } else if ( euler.order === 'ZXY' ) {
  2929. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2930. te[ 0 ] = ce - df * b;
  2931. te[ 4 ] = - a * f;
  2932. te[ 8 ] = de + cf * b;
  2933. te[ 1 ] = cf + de * b;
  2934. te[ 5 ] = a * e;
  2935. te[ 9 ] = df - ce * b;
  2936. te[ 2 ] = - a * d;
  2937. te[ 6 ] = b;
  2938. te[ 10 ] = a * c;
  2939. } else if ( euler.order === 'ZYX' ) {
  2940. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2941. te[ 0 ] = c * e;
  2942. te[ 4 ] = be * d - af;
  2943. te[ 8 ] = ae * d + bf;
  2944. te[ 1 ] = c * f;
  2945. te[ 5 ] = bf * d + ae;
  2946. te[ 9 ] = af * d - be;
  2947. te[ 2 ] = - d;
  2948. te[ 6 ] = b * c;
  2949. te[ 10 ] = a * c;
  2950. } else if ( euler.order === 'YZX' ) {
  2951. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2952. te[ 0 ] = c * e;
  2953. te[ 4 ] = bd - ac * f;
  2954. te[ 8 ] = bc * f + ad;
  2955. te[ 1 ] = f;
  2956. te[ 5 ] = a * e;
  2957. te[ 9 ] = - b * e;
  2958. te[ 2 ] = - d * e;
  2959. te[ 6 ] = ad * f + bc;
  2960. te[ 10 ] = ac - bd * f;
  2961. } else if ( euler.order === 'XZY' ) {
  2962. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2963. te[ 0 ] = c * e;
  2964. te[ 4 ] = - f;
  2965. te[ 8 ] = d * e;
  2966. te[ 1 ] = ac * f + bd;
  2967. te[ 5 ] = a * e;
  2968. te[ 9 ] = ad * f - bc;
  2969. te[ 2 ] = bc * f - ad;
  2970. te[ 6 ] = b * e;
  2971. te[ 10 ] = bd * f + ac;
  2972. }
  2973. // last column
  2974. te[ 3 ] = 0;
  2975. te[ 7 ] = 0;
  2976. te[ 11 ] = 0;
  2977. // bottom row
  2978. te[ 12 ] = 0;
  2979. te[ 13 ] = 0;
  2980. te[ 14 ] = 0;
  2981. te[ 15 ] = 1;
  2982. return this;
  2983. },
  2984. makeRotationFromQuaternion: function ( q ) {
  2985. var te = this.elements;
  2986. var x = q.x, y = q.y, z = q.z, w = q.w;
  2987. var x2 = x + x, y2 = y + y, z2 = z + z;
  2988. var xx = x * x2, xy = x * y2, xz = x * z2;
  2989. var yy = y * y2, yz = y * z2, zz = z * z2;
  2990. var wx = w * x2, wy = w * y2, wz = w * z2;
  2991. te[ 0 ] = 1 - ( yy + zz );
  2992. te[ 4 ] = xy - wz;
  2993. te[ 8 ] = xz + wy;
  2994. te[ 1 ] = xy + wz;
  2995. te[ 5 ] = 1 - ( xx + zz );
  2996. te[ 9 ] = yz - wx;
  2997. te[ 2 ] = xz - wy;
  2998. te[ 6 ] = yz + wx;
  2999. te[ 10 ] = 1 - ( xx + yy );
  3000. // last column
  3001. te[ 3 ] = 0;
  3002. te[ 7 ] = 0;
  3003. te[ 11 ] = 0;
  3004. // bottom row
  3005. te[ 12 ] = 0;
  3006. te[ 13 ] = 0;
  3007. te[ 14 ] = 0;
  3008. te[ 15 ] = 1;
  3009. return this;
  3010. },
  3011. lookAt: function () {
  3012. var x, y, z;
  3013. return function ( eye, target, up ) {
  3014. if ( x === undefined ) x = new THREE.Vector3();
  3015. if ( y === undefined ) y = new THREE.Vector3();
  3016. if ( z === undefined ) z = new THREE.Vector3();
  3017. var te = this.elements;
  3018. z.subVectors( eye, target ).normalize();
  3019. if ( z.lengthSq() === 0 ) {
  3020. z.z = 1;
  3021. }
  3022. x.crossVectors( up, z ).normalize();
  3023. if ( x.lengthSq() === 0 ) {
  3024. z.x += 0.0001;
  3025. x.crossVectors( up, z ).normalize();
  3026. }
  3027. y.crossVectors( z, x );
  3028. te[ 0 ] = x.x; te[ 4 ] = y.x; te[ 8 ] = z.x;
  3029. te[ 1 ] = x.y; te[ 5 ] = y.y; te[ 9 ] = z.y;
  3030. te[ 2 ] = x.z; te[ 6 ] = y.z; te[ 10 ] = z.z;
  3031. return this;
  3032. };
  3033. }(),
  3034. multiply: function ( m, n ) {
  3035. if ( n !== undefined ) {
  3036. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  3037. return this.multiplyMatrices( m, n );
  3038. }
  3039. return this.multiplyMatrices( this, m );
  3040. },
  3041. premultiply: function ( m ) {
  3042. return this.multiplyMatrices( m, this );
  3043. },
  3044. multiplyMatrices: function ( a, b ) {
  3045. var ae = a.elements;
  3046. var be = b.elements;
  3047. var te = this.elements;
  3048. var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  3049. var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  3050. var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  3051. var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  3052. var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  3053. var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  3054. var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  3055. var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  3056. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3057. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3058. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3059. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3060. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3061. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3062. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3063. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3064. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3065. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3066. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3067. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3068. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3069. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3070. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3071. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3072. return this;
  3073. },
  3074. multiplyToArray: function ( a, b, r ) {
  3075. var te = this.elements;
  3076. this.multiplyMatrices( a, b );
  3077. r[ 0 ] = te[ 0 ]; r[ 1 ] = te[ 1 ]; r[ 2 ] = te[ 2 ]; r[ 3 ] = te[ 3 ];
  3078. r[ 4 ] = te[ 4 ]; r[ 5 ] = te[ 5 ]; r[ 6 ] = te[ 6 ]; r[ 7 ] = te[ 7 ];
  3079. r[ 8 ] = te[ 8 ]; r[ 9 ] = te[ 9 ]; r[ 10 ] = te[ 10 ]; r[ 11 ] = te[ 11 ];
  3080. r[ 12 ] = te[ 12 ]; r[ 13 ] = te[ 13 ]; r[ 14 ] = te[ 14 ]; r[ 15 ] = te[ 15 ];
  3081. return this;
  3082. },
  3083. multiplyScalar: function ( s ) {
  3084. var te = this.elements;
  3085. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  3086. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  3087. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  3088. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  3089. return this;
  3090. },
  3091. applyToVector3Array: function () {
  3092. var v1;
  3093. return function ( array, offset, length ) {
  3094. if ( v1 === undefined ) v1 = new THREE.Vector3();
  3095. if ( offset === undefined ) offset = 0;
  3096. if ( length === undefined ) length = array.length;
  3097. for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) {
  3098. v1.fromArray( array, j );
  3099. v1.applyMatrix4( this );
  3100. v1.toArray( array, j );
  3101. }
  3102. return array;
  3103. };
  3104. }(),
  3105. applyToBuffer: function () {
  3106. var v1;
  3107. return function applyToBuffer( buffer, offset, length ) {
  3108. if ( v1 === undefined ) v1 = new THREE.Vector3();
  3109. if ( offset === undefined ) offset = 0;
  3110. if ( length === undefined ) length = buffer.length / buffer.itemSize;
  3111. for ( var i = 0, j = offset; i < length; i ++, j ++ ) {
  3112. v1.x = buffer.getX( j );
  3113. v1.y = buffer.getY( j );
  3114. v1.z = buffer.getZ( j );
  3115. v1.applyMatrix4( this );
  3116. buffer.setXYZ( v1.x, v1.y, v1.z );
  3117. }
  3118. return buffer;
  3119. };
  3120. }(),
  3121. determinant: function () {
  3122. var te = this.elements;
  3123. var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  3124. var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  3125. var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  3126. var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  3127. //TODO: make this more efficient
  3128. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3129. return (
  3130. n41 * (
  3131. + n14 * n23 * n32
  3132. - n13 * n24 * n32
  3133. - n14 * n22 * n33
  3134. + n12 * n24 * n33
  3135. + n13 * n22 * n34
  3136. - n12 * n23 * n34
  3137. ) +
  3138. n42 * (
  3139. + n11 * n23 * n34
  3140. - n11 * n24 * n33
  3141. + n14 * n21 * n33
  3142. - n13 * n21 * n34
  3143. + n13 * n24 * n31
  3144. - n14 * n23 * n31
  3145. ) +
  3146. n43 * (
  3147. + n11 * n24 * n32
  3148. - n11 * n22 * n34
  3149. - n14 * n21 * n32
  3150. + n12 * n21 * n34
  3151. + n14 * n22 * n31
  3152. - n12 * n24 * n31
  3153. ) +
  3154. n44 * (
  3155. - n13 * n22 * n31
  3156. - n11 * n23 * n32
  3157. + n11 * n22 * n33
  3158. + n13 * n21 * n32
  3159. - n12 * n21 * n33
  3160. + n12 * n23 * n31
  3161. )
  3162. );
  3163. },
  3164. transpose: function () {
  3165. var te = this.elements;
  3166. var tmp;
  3167. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  3168. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  3169. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  3170. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  3171. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  3172. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  3173. return this;
  3174. },
  3175. flattenToArrayOffset: function ( array, offset ) {
  3176. var te = this.elements;
  3177. array[ offset ] = te[ 0 ];
  3178. array[ offset + 1 ] = te[ 1 ];
  3179. array[ offset + 2 ] = te[ 2 ];
  3180. array[ offset + 3 ] = te[ 3 ];
  3181. array[ offset + 4 ] = te[ 4 ];
  3182. array[ offset + 5 ] = te[ 5 ];
  3183. array[ offset + 6 ] = te[ 6 ];
  3184. array[ offset + 7 ] = te[ 7 ];
  3185. array[ offset + 8 ] = te[ 8 ];
  3186. array[ offset + 9 ] = te[ 9 ];
  3187. array[ offset + 10 ] = te[ 10 ];
  3188. array[ offset + 11 ] = te[ 11 ];
  3189. array[ offset + 12 ] = te[ 12 ];
  3190. array[ offset + 13 ] = te[ 13 ];
  3191. array[ offset + 14 ] = te[ 14 ];
  3192. array[ offset + 15 ] = te[ 15 ];
  3193. return array;
  3194. },
  3195. getPosition: function () {
  3196. var v1;
  3197. return function () {
  3198. if ( v1 === undefined ) v1 = new THREE.Vector3();
  3199. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  3200. return v1.setFromMatrixColumn( this, 3 );
  3201. };
  3202. }(),
  3203. setPosition: function ( v ) {
  3204. var te = this.elements;
  3205. te[ 12 ] = v.x;
  3206. te[ 13 ] = v.y;
  3207. te[ 14 ] = v.z;
  3208. return this;
  3209. },
  3210. getInverse: function ( m, throwOnDegenerate ) {
  3211. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3212. var te = this.elements,
  3213. me = m.elements,
  3214. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], n41 = me[ 3 ],
  3215. n12 = me[ 4 ], n22 = me[ 5 ], n32 = me[ 6 ], n42 = me[ 7 ],
  3216. n13 = me[ 8 ], n23 = me[ 9 ], n33 = me[ 10 ], n43 = me[ 11 ],
  3217. n14 = me[ 12 ], n24 = me[ 13 ], n34 = me[ 14 ], n44 = me[ 15 ],
  3218. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3219. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3220. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3221. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3222. var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3223. if ( det === 0 ) {
  3224. var msg = "THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0";
  3225. if ( throwOnDegenerate || false ) {
  3226. throw new Error( msg );
  3227. } else {
  3228. console.warn( msg );
  3229. }
  3230. return this.identity();
  3231. }
  3232. te[ 0 ] = t11;
  3233. te[ 1 ] = n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44;
  3234. te[ 2 ] = n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44;
  3235. te[ 3 ] = n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43;
  3236. te[ 4 ] = t12;
  3237. te[ 5 ] = n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44;
  3238. te[ 6 ] = n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44;
  3239. te[ 7 ] = n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43;
  3240. te[ 8 ] = t13;
  3241. te[ 9 ] = n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44;
  3242. te[ 10 ] = n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44;
  3243. te[ 11 ] = n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43;
  3244. te[ 12 ] = t14;
  3245. te[ 13 ] = n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34;
  3246. te[ 14 ] = n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34;
  3247. te[ 15 ] = n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33;
  3248. return this.multiplyScalar( 1 / det );
  3249. },
  3250. scale: function ( v ) {
  3251. var te = this.elements;
  3252. var x = v.x, y = v.y, z = v.z;
  3253. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  3254. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  3255. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  3256. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  3257. return this;
  3258. },
  3259. getMaxScaleOnAxis: function () {
  3260. var te = this.elements;
  3261. var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  3262. var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  3263. var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  3264. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  3265. },
  3266. makeTranslation: function ( x, y, z ) {
  3267. this.set(
  3268. 1, 0, 0, x,
  3269. 0, 1, 0, y,
  3270. 0, 0, 1, z,
  3271. 0, 0, 0, 1
  3272. );
  3273. return this;
  3274. },
  3275. makeRotationX: function ( theta ) {
  3276. var c = Math.cos( theta ), s = Math.sin( theta );
  3277. this.set(
  3278. 1, 0, 0, 0,
  3279. 0, c, - s, 0,
  3280. 0, s, c, 0,
  3281. 0, 0, 0, 1
  3282. );
  3283. return this;
  3284. },
  3285. makeRotationY: function ( theta ) {
  3286. var c = Math.cos( theta ), s = Math.sin( theta );
  3287. this.set(
  3288. c, 0, s, 0,
  3289. 0, 1, 0, 0,
  3290. - s, 0, c, 0,
  3291. 0, 0, 0, 1
  3292. );
  3293. return this;
  3294. },
  3295. makeRotationZ: function ( theta ) {
  3296. var c = Math.cos( theta ), s = Math.sin( theta );
  3297. this.set(
  3298. c, - s, 0, 0,
  3299. s, c, 0, 0,
  3300. 0, 0, 1, 0,
  3301. 0, 0, 0, 1
  3302. );
  3303. return this;
  3304. },
  3305. makeRotationAxis: function ( axis, angle ) {
  3306. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3307. var c = Math.cos( angle );
  3308. var s = Math.sin( angle );
  3309. var t = 1 - c;
  3310. var x = axis.x, y = axis.y, z = axis.z;
  3311. var tx = t * x, ty = t * y;
  3312. this.set(
  3313. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  3314. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3315. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3316. 0, 0, 0, 1
  3317. );
  3318. return this;
  3319. },
  3320. makeScale: function ( x, y, z ) {
  3321. this.set(
  3322. x, 0, 0, 0,
  3323. 0, y, 0, 0,
  3324. 0, 0, z, 0,
  3325. 0, 0, 0, 1
  3326. );
  3327. return this;
  3328. },
  3329. compose: function ( position, quaternion, scale ) {
  3330. this.makeRotationFromQuaternion( quaternion );
  3331. this.scale( scale );
  3332. this.setPosition( position );
  3333. return this;
  3334. },
  3335. decompose: function () {
  3336. var vector, matrix;
  3337. return function ( position, quaternion, scale ) {
  3338. if ( vector === undefined ) vector = new THREE.Vector3();
  3339. if ( matrix === undefined ) matrix = new THREE.Matrix4();
  3340. var te = this.elements;
  3341. var sx = vector.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  3342. var sy = vector.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  3343. var sz = vector.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  3344. // if determine is negative, we need to invert one scale
  3345. var det = this.determinant();
  3346. if ( det < 0 ) {
  3347. sx = - sx;
  3348. }
  3349. position.x = te[ 12 ];
  3350. position.y = te[ 13 ];
  3351. position.z = te[ 14 ];
  3352. // scale the rotation part
  3353. matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy()
  3354. var invSX = 1 / sx;
  3355. var invSY = 1 / sy;
  3356. var invSZ = 1 / sz;
  3357. matrix.elements[ 0 ] *= invSX;
  3358. matrix.elements[ 1 ] *= invSX;
  3359. matrix.elements[ 2 ] *= invSX;
  3360. matrix.elements[ 4 ] *= invSY;
  3361. matrix.elements[ 5 ] *= invSY;
  3362. matrix.elements[ 6 ] *= invSY;
  3363. matrix.elements[ 8 ] *= invSZ;
  3364. matrix.elements[ 9 ] *= invSZ;
  3365. matrix.elements[ 10 ] *= invSZ;
  3366. quaternion.setFromRotationMatrix( matrix );
  3367. scale.x = sx;
  3368. scale.y = sy;
  3369. scale.z = sz;
  3370. return this;
  3371. };
  3372. }(),
  3373. makeFrustum: function ( left, right, bottom, top, near, far ) {
  3374. var te = this.elements;
  3375. var x = 2 * near / ( right - left );
  3376. var y = 2 * near / ( top - bottom );
  3377. var a = ( right + left ) / ( right - left );
  3378. var b = ( top + bottom ) / ( top - bottom );
  3379. var c = - ( far + near ) / ( far - near );
  3380. var d = - 2 * far * near / ( far - near );
  3381. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  3382. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  3383. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  3384. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  3385. return this;
  3386. },
  3387. makePerspective: function ( fov, aspect, near, far ) {
  3388. var ymax = near * Math.tan( THREE.Math.DEG2RAD * fov * 0.5 );
  3389. var ymin = - ymax;
  3390. var xmin = ymin * aspect;
  3391. var xmax = ymax * aspect;
  3392. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  3393. },
  3394. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  3395. var te = this.elements;
  3396. var w = 1.0 / ( right - left );
  3397. var h = 1.0 / ( top - bottom );
  3398. var p = 1.0 / ( far - near );
  3399. var x = ( right + left ) * w;
  3400. var y = ( top + bottom ) * h;
  3401. var z = ( far + near ) * p;
  3402. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  3403. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  3404. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  3405. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  3406. return this;
  3407. },
  3408. equals: function ( matrix ) {
  3409. var te = this.elements;
  3410. var me = matrix.elements;
  3411. for ( var i = 0; i < 16; i ++ ) {
  3412. if ( te[ i ] !== me[ i ] ) return false;
  3413. }
  3414. return true;
  3415. },
  3416. fromArray: function ( array ) {
  3417. this.elements.set( array );
  3418. return this;
  3419. },
  3420. toArray: function () {
  3421. var te = this.elements;
  3422. return [
  3423. te[ 0 ], te[ 1 ], te[ 2 ], te[ 3 ],
  3424. te[ 4 ], te[ 5 ], te[ 6 ], te[ 7 ],
  3425. te[ 8 ], te[ 9 ], te[ 10 ], te[ 11 ],
  3426. te[ 12 ], te[ 13 ], te[ 14 ], te[ 15 ]
  3427. ];
  3428. }
  3429. };
  3430. // File:src/math/Ray.js
  3431. /**
  3432. * @author bhouston / http://clara.io
  3433. */
  3434. THREE.Ray = function ( origin, direction ) {
  3435. this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3();
  3436. this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3();
  3437. };
  3438. THREE.Ray.prototype = {
  3439. constructor: THREE.Ray,
  3440. set: function ( origin, direction ) {
  3441. this.origin.copy( origin );
  3442. this.direction.copy( direction );
  3443. return this;
  3444. },
  3445. clone: function () {
  3446. return new this.constructor().copy( this );
  3447. },
  3448. copy: function ( ray ) {
  3449. this.origin.copy( ray.origin );
  3450. this.direction.copy( ray.direction );
  3451. return this;
  3452. },
  3453. at: function ( t, optionalTarget ) {
  3454. var result = optionalTarget || new THREE.Vector3();
  3455. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  3456. },
  3457. lookAt: function ( v ) {
  3458. this.direction.copy( v ).sub( this.origin ).normalize();
  3459. },
  3460. recast: function () {
  3461. var v1 = new THREE.Vector3();
  3462. return function ( t ) {
  3463. this.origin.copy( this.at( t, v1 ) );
  3464. return this;
  3465. };
  3466. }(),
  3467. closestPointToPoint: function ( point, optionalTarget ) {
  3468. var result = optionalTarget || new THREE.Vector3();
  3469. result.subVectors( point, this.origin );
  3470. var directionDistance = result.dot( this.direction );
  3471. if ( directionDistance < 0 ) {
  3472. return result.copy( this.origin );
  3473. }
  3474. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3475. },
  3476. distanceToPoint: function ( point ) {
  3477. return Math.sqrt( this.distanceSqToPoint( point ) );
  3478. },
  3479. distanceSqToPoint: function () {
  3480. var v1 = new THREE.Vector3();
  3481. return function ( point ) {
  3482. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  3483. // point behind the ray
  3484. if ( directionDistance < 0 ) {
  3485. return this.origin.distanceToSquared( point );
  3486. }
  3487. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3488. return v1.distanceToSquared( point );
  3489. };
  3490. }(),
  3491. distanceSqToSegment: function () {
  3492. var segCenter = new THREE.Vector3();
  3493. var segDir = new THREE.Vector3();
  3494. var diff = new THREE.Vector3();
  3495. return function ( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3496. // from http://www.geometrictools.com/LibMathematics/Distance/Wm5DistRay3Segment3.cpp
  3497. // It returns the min distance between the ray and the segment
  3498. // defined by v0 and v1
  3499. // It can also set two optional targets :
  3500. // - The closest point on the ray
  3501. // - The closest point on the segment
  3502. segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3503. segDir.copy( v1 ).sub( v0 ).normalize();
  3504. diff.copy( this.origin ).sub( segCenter );
  3505. var segExtent = v0.distanceTo( v1 ) * 0.5;
  3506. var a01 = - this.direction.dot( segDir );
  3507. var b0 = diff.dot( this.direction );
  3508. var b1 = - diff.dot( segDir );
  3509. var c = diff.lengthSq();
  3510. var det = Math.abs( 1 - a01 * a01 );
  3511. var s0, s1, sqrDist, extDet;
  3512. if ( det > 0 ) {
  3513. // The ray and segment are not parallel.
  3514. s0 = a01 * b1 - b0;
  3515. s1 = a01 * b0 - b1;
  3516. extDet = segExtent * det;
  3517. if ( s0 >= 0 ) {
  3518. if ( s1 >= - extDet ) {
  3519. if ( s1 <= extDet ) {
  3520. // region 0
  3521. // Minimum at interior points of ray and segment.
  3522. var invDet = 1 / det;
  3523. s0 *= invDet;
  3524. s1 *= invDet;
  3525. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3526. } else {
  3527. // region 1
  3528. s1 = segExtent;
  3529. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3530. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3531. }
  3532. } else {
  3533. // region 5
  3534. s1 = - segExtent;
  3535. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3536. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3537. }
  3538. } else {
  3539. if ( s1 <= - extDet ) {
  3540. // region 4
  3541. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3542. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3543. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3544. } else if ( s1 <= extDet ) {
  3545. // region 3
  3546. s0 = 0;
  3547. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3548. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3549. } else {
  3550. // region 2
  3551. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3552. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3553. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3554. }
  3555. }
  3556. } else {
  3557. // Ray and segment are parallel.
  3558. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3559. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3560. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3561. }
  3562. if ( optionalPointOnRay ) {
  3563. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  3564. }
  3565. if ( optionalPointOnSegment ) {
  3566. optionalPointOnSegment.copy( segDir ).multiplyScalar( s1 ).add( segCenter );
  3567. }
  3568. return sqrDist;
  3569. };
  3570. }(),
  3571. intersectSphere: function () {
  3572. var v1 = new THREE.Vector3();
  3573. return function ( sphere, optionalTarget ) {
  3574. v1.subVectors( sphere.center, this.origin );
  3575. var tca = v1.dot( this.direction );
  3576. var d2 = v1.dot( v1 ) - tca * tca;
  3577. var radius2 = sphere.radius * sphere.radius;
  3578. if ( d2 > radius2 ) return null;
  3579. var thc = Math.sqrt( radius2 - d2 );
  3580. // t0 = first intersect point - entrance on front of sphere
  3581. var t0 = tca - thc;
  3582. // t1 = second intersect point - exit point on back of sphere
  3583. var t1 = tca + thc;
  3584. // test to see if both t0 and t1 are behind the ray - if so, return null
  3585. if ( t0 < 0 && t1 < 0 ) return null;
  3586. // test to see if t0 is behind the ray:
  3587. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3588. // in order to always return an intersect point that is in front of the ray.
  3589. if ( t0 < 0 ) return this.at( t1, optionalTarget );
  3590. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3591. return this.at( t0, optionalTarget );
  3592. }
  3593. }(),
  3594. intersectsSphere: function ( sphere ) {
  3595. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  3596. },
  3597. distanceToPlane: function ( plane ) {
  3598. var denominator = plane.normal.dot( this.direction );
  3599. if ( denominator === 0 ) {
  3600. // line is coplanar, return origin
  3601. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3602. return 0;
  3603. }
  3604. // Null is preferable to undefined since undefined means.... it is undefined
  3605. return null;
  3606. }
  3607. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3608. // Return if the ray never intersects the plane
  3609. return t >= 0 ? t : null;
  3610. },
  3611. intersectPlane: function ( plane, optionalTarget ) {
  3612. var t = this.distanceToPlane( plane );
  3613. if ( t === null ) {
  3614. return null;
  3615. }
  3616. return this.at( t, optionalTarget );
  3617. },
  3618. intersectsPlane: function ( plane ) {
  3619. // check if the ray lies on the plane first
  3620. var distToPoint = plane.distanceToPoint( this.origin );
  3621. if ( distToPoint === 0 ) {
  3622. return true;
  3623. }
  3624. var denominator = plane.normal.dot( this.direction );
  3625. if ( denominator * distToPoint < 0 ) {
  3626. return true;
  3627. }
  3628. // ray origin is behind the plane (and is pointing behind it)
  3629. return false;
  3630. },
  3631. intersectBox: function ( box, optionalTarget ) {
  3632. var tmin, tmax, tymin, tymax, tzmin, tzmax;
  3633. var invdirx = 1 / this.direction.x,
  3634. invdiry = 1 / this.direction.y,
  3635. invdirz = 1 / this.direction.z;
  3636. var origin = this.origin;
  3637. if ( invdirx >= 0 ) {
  3638. tmin = ( box.min.x - origin.x ) * invdirx;
  3639. tmax = ( box.max.x - origin.x ) * invdirx;
  3640. } else {
  3641. tmin = ( box.max.x - origin.x ) * invdirx;
  3642. tmax = ( box.min.x - origin.x ) * invdirx;
  3643. }
  3644. if ( invdiry >= 0 ) {
  3645. tymin = ( box.min.y - origin.y ) * invdiry;
  3646. tymax = ( box.max.y - origin.y ) * invdiry;
  3647. } else {
  3648. tymin = ( box.max.y - origin.y ) * invdiry;
  3649. tymax = ( box.min.y - origin.y ) * invdiry;
  3650. }
  3651. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3652. // These lines also handle the case where tmin or tmax is NaN
  3653. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3654. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  3655. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  3656. if ( invdirz >= 0 ) {
  3657. tzmin = ( box.min.z - origin.z ) * invdirz;
  3658. tzmax = ( box.max.z - origin.z ) * invdirz;
  3659. } else {
  3660. tzmin = ( box.max.z - origin.z ) * invdirz;
  3661. tzmax = ( box.min.z - origin.z ) * invdirz;
  3662. }
  3663. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3664. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3665. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3666. //return point closest to the ray (positive side)
  3667. if ( tmax < 0 ) return null;
  3668. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  3669. },
  3670. intersectsBox: ( function () {
  3671. var v = new THREE.Vector3();
  3672. return function ( box ) {
  3673. return this.intersectBox( box, v ) !== null;
  3674. };
  3675. } )(),
  3676. intersectTriangle: function () {
  3677. // Compute the offset origin, edges, and normal.
  3678. var diff = new THREE.Vector3();
  3679. var edge1 = new THREE.Vector3();
  3680. var edge2 = new THREE.Vector3();
  3681. var normal = new THREE.Vector3();
  3682. return function ( a, b, c, backfaceCulling, optionalTarget ) {
  3683. // from http://www.geometrictools.com/LibMathematics/Intersection/Wm5IntrRay3Triangle3.cpp
  3684. edge1.subVectors( b, a );
  3685. edge2.subVectors( c, a );
  3686. normal.crossVectors( edge1, edge2 );
  3687. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3688. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3689. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3690. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3691. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3692. var DdN = this.direction.dot( normal );
  3693. var sign;
  3694. if ( DdN > 0 ) {
  3695. if ( backfaceCulling ) return null;
  3696. sign = 1;
  3697. } else if ( DdN < 0 ) {
  3698. sign = - 1;
  3699. DdN = - DdN;
  3700. } else {
  3701. return null;
  3702. }
  3703. diff.subVectors( this.origin, a );
  3704. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  3705. // b1 < 0, no intersection
  3706. if ( DdQxE2 < 0 ) {
  3707. return null;
  3708. }
  3709. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  3710. // b2 < 0, no intersection
  3711. if ( DdE1xQ < 0 ) {
  3712. return null;
  3713. }
  3714. // b1+b2 > 1, no intersection
  3715. if ( DdQxE2 + DdE1xQ > DdN ) {
  3716. return null;
  3717. }
  3718. // Line intersects triangle, check if ray does.
  3719. var QdN = - sign * diff.dot( normal );
  3720. // t < 0, no intersection
  3721. if ( QdN < 0 ) {
  3722. return null;
  3723. }
  3724. // Ray intersects triangle.
  3725. return this.at( QdN / DdN, optionalTarget );
  3726. };
  3727. }(),
  3728. applyMatrix4: function ( matrix4 ) {
  3729. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  3730. this.origin.applyMatrix4( matrix4 );
  3731. this.direction.sub( this.origin );
  3732. this.direction.normalize();
  3733. return this;
  3734. },
  3735. equals: function ( ray ) {
  3736. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3737. }
  3738. };
  3739. // File:src/math/Sphere.js
  3740. /**
  3741. * @author bhouston / http://clara.io
  3742. * @author mrdoob / http://mrdoob.com/
  3743. */
  3744. THREE.Sphere = function ( center, radius ) {
  3745. this.center = ( center !== undefined ) ? center : new THREE.Vector3();
  3746. this.radius = ( radius !== undefined ) ? radius : 0;
  3747. };
  3748. THREE.Sphere.prototype = {
  3749. constructor: THREE.Sphere,
  3750. set: function ( center, radius ) {
  3751. this.center.copy( center );
  3752. this.radius = radius;
  3753. return this;
  3754. },
  3755. setFromPoints: function () {
  3756. var box = new THREE.Box3();
  3757. return function ( points, optionalCenter ) {
  3758. var center = this.center;
  3759. if ( optionalCenter !== undefined ) {
  3760. center.copy( optionalCenter );
  3761. } else {
  3762. box.setFromPoints( points ).center( center );
  3763. }
  3764. var maxRadiusSq = 0;
  3765. for ( var i = 0, il = points.length; i < il; i ++ ) {
  3766. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3767. }
  3768. this.radius = Math.sqrt( maxRadiusSq );
  3769. return this;
  3770. };
  3771. }(),
  3772. clone: function () {
  3773. return new this.constructor().copy( this );
  3774. },
  3775. copy: function ( sphere ) {
  3776. this.center.copy( sphere.center );
  3777. this.radius = sphere.radius;
  3778. return this;
  3779. },
  3780. empty: function () {
  3781. return ( this.radius <= 0 );
  3782. },
  3783. containsPoint: function ( point ) {
  3784. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3785. },
  3786. distanceToPoint: function ( point ) {
  3787. return ( point.distanceTo( this.center ) - this.radius );
  3788. },
  3789. intersectsSphere: function ( sphere ) {
  3790. var radiusSum = this.radius + sphere.radius;
  3791. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3792. },
  3793. intersectsBox: function ( box ) {
  3794. return box.intersectsSphere( this );
  3795. },
  3796. intersectsPlane: function ( plane ) {
  3797. // We use the following equation to compute the signed distance from
  3798. // the center of the sphere to the plane.
  3799. //
  3800. // distance = q * n - d
  3801. //
  3802. // If this distance is greater than the radius of the sphere,
  3803. // then there is no intersection.
  3804. return Math.abs( this.center.dot( plane.normal ) - plane.constant ) <= this.radius;
  3805. },
  3806. clampPoint: function ( point, optionalTarget ) {
  3807. var deltaLengthSq = this.center.distanceToSquared( point );
  3808. var result = optionalTarget || new THREE.Vector3();
  3809. result.copy( point );
  3810. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3811. result.sub( this.center ).normalize();
  3812. result.multiplyScalar( this.radius ).add( this.center );
  3813. }
  3814. return result;
  3815. },
  3816. getBoundingBox: function ( optionalTarget ) {
  3817. var box = optionalTarget || new THREE.Box3();
  3818. box.set( this.center, this.center );
  3819. box.expandByScalar( this.radius );
  3820. return box;
  3821. },
  3822. applyMatrix4: function ( matrix ) {
  3823. this.center.applyMatrix4( matrix );
  3824. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3825. return this;
  3826. },
  3827. translate: function ( offset ) {
  3828. this.center.add( offset );
  3829. return this;
  3830. },
  3831. equals: function ( sphere ) {
  3832. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3833. }
  3834. };
  3835. // File:src/math/Frustum.js
  3836. /**
  3837. * @author mrdoob / http://mrdoob.com/
  3838. * @author alteredq / http://alteredqualia.com/
  3839. * @author bhouston / http://clara.io
  3840. */
  3841. THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) {
  3842. this.planes = [
  3843. ( p0 !== undefined ) ? p0 : new THREE.Plane(),
  3844. ( p1 !== undefined ) ? p1 : new THREE.Plane(),
  3845. ( p2 !== undefined ) ? p2 : new THREE.Plane(),
  3846. ( p3 !== undefined ) ? p3 : new THREE.Plane(),
  3847. ( p4 !== undefined ) ? p4 : new THREE.Plane(),
  3848. ( p5 !== undefined ) ? p5 : new THREE.Plane()
  3849. ];
  3850. };
  3851. THREE.Frustum.prototype = {
  3852. constructor: THREE.Frustum,
  3853. set: function ( p0, p1, p2, p3, p4, p5 ) {
  3854. var planes = this.planes;
  3855. planes[ 0 ].copy( p0 );
  3856. planes[ 1 ].copy( p1 );
  3857. planes[ 2 ].copy( p2 );
  3858. planes[ 3 ].copy( p3 );
  3859. planes[ 4 ].copy( p4 );
  3860. planes[ 5 ].copy( p5 );
  3861. return this;
  3862. },
  3863. clone: function () {
  3864. return new this.constructor().copy( this );
  3865. },
  3866. copy: function ( frustum ) {
  3867. var planes = this.planes;
  3868. for ( var i = 0; i < 6; i ++ ) {
  3869. planes[ i ].copy( frustum.planes[ i ] );
  3870. }
  3871. return this;
  3872. },
  3873. setFromMatrix: function ( m ) {
  3874. var planes = this.planes;
  3875. var me = m.elements;
  3876. var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  3877. var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  3878. var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  3879. var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  3880. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  3881. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  3882. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  3883. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  3884. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  3885. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  3886. return this;
  3887. },
  3888. intersectsObject: function () {
  3889. var sphere = new THREE.Sphere();
  3890. return function ( object ) {
  3891. var geometry = object.geometry;
  3892. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  3893. sphere.copy( geometry.boundingSphere );
  3894. sphere.applyMatrix4( object.matrixWorld );
  3895. return this.intersectsSphere( sphere );
  3896. };
  3897. }(),
  3898. intersectsSphere: function ( sphere ) {
  3899. var planes = this.planes;
  3900. var center = sphere.center;
  3901. var negRadius = - sphere.radius;
  3902. for ( var i = 0; i < 6; i ++ ) {
  3903. var distance = planes[ i ].distanceToPoint( center );
  3904. if ( distance < negRadius ) {
  3905. return false;
  3906. }
  3907. }
  3908. return true;
  3909. },
  3910. intersectsBox: function () {
  3911. var p1 = new THREE.Vector3(),
  3912. p2 = new THREE.Vector3();
  3913. return function ( box ) {
  3914. var planes = this.planes;
  3915. for ( var i = 0; i < 6 ; i ++ ) {
  3916. var plane = planes[ i ];
  3917. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  3918. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  3919. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  3920. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  3921. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  3922. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  3923. var d1 = plane.distanceToPoint( p1 );
  3924. var d2 = plane.distanceToPoint( p2 );
  3925. // if both outside plane, no intersection
  3926. if ( d1 < 0 && d2 < 0 ) {
  3927. return false;
  3928. }
  3929. }
  3930. return true;
  3931. };
  3932. }(),
  3933. containsPoint: function ( point ) {
  3934. var planes = this.planes;
  3935. for ( var i = 0; i < 6; i ++ ) {
  3936. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  3937. return false;
  3938. }
  3939. }
  3940. return true;
  3941. }
  3942. };
  3943. // File:src/math/Plane.js
  3944. /**
  3945. * @author bhouston / http://clara.io
  3946. */
  3947. THREE.Plane = function ( normal, constant ) {
  3948. this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 );
  3949. this.constant = ( constant !== undefined ) ? constant : 0;
  3950. };
  3951. THREE.Plane.prototype = {
  3952. constructor: THREE.Plane,
  3953. set: function ( normal, constant ) {
  3954. this.normal.copy( normal );
  3955. this.constant = constant;
  3956. return this;
  3957. },
  3958. setComponents: function ( x, y, z, w ) {
  3959. this.normal.set( x, y, z );
  3960. this.constant = w;
  3961. return this;
  3962. },
  3963. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  3964. this.normal.copy( normal );
  3965. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  3966. return this;
  3967. },
  3968. setFromCoplanarPoints: function () {
  3969. var v1 = new THREE.Vector3();
  3970. var v2 = new THREE.Vector3();
  3971. return function ( a, b, c ) {
  3972. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  3973. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  3974. this.setFromNormalAndCoplanarPoint( normal, a );
  3975. return this;
  3976. };
  3977. }(),
  3978. clone: function () {
  3979. return new this.constructor().copy( this );
  3980. },
  3981. copy: function ( plane ) {
  3982. this.normal.copy( plane.normal );
  3983. this.constant = plane.constant;
  3984. return this;
  3985. },
  3986. normalize: function () {
  3987. // Note: will lead to a divide by zero if the plane is invalid.
  3988. var inverseNormalLength = 1.0 / this.normal.length();
  3989. this.normal.multiplyScalar( inverseNormalLength );
  3990. this.constant *= inverseNormalLength;
  3991. return this;
  3992. },
  3993. negate: function () {
  3994. this.constant *= - 1;
  3995. this.normal.negate();
  3996. return this;
  3997. },
  3998. distanceToPoint: function ( point ) {
  3999. return this.normal.dot( point ) + this.constant;
  4000. },
  4001. distanceToSphere: function ( sphere ) {
  4002. return this.distanceToPoint( sphere.center ) - sphere.radius;
  4003. },
  4004. projectPoint: function ( point, optionalTarget ) {
  4005. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  4006. },
  4007. orthoPoint: function ( point, optionalTarget ) {
  4008. var perpendicularMagnitude = this.distanceToPoint( point );
  4009. var result = optionalTarget || new THREE.Vector3();
  4010. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  4011. },
  4012. intersectLine: function () {
  4013. var v1 = new THREE.Vector3();
  4014. return function ( line, optionalTarget ) {
  4015. var result = optionalTarget || new THREE.Vector3();
  4016. var direction = line.delta( v1 );
  4017. var denominator = this.normal.dot( direction );
  4018. if ( denominator === 0 ) {
  4019. // line is coplanar, return origin
  4020. if ( this.distanceToPoint( line.start ) === 0 ) {
  4021. return result.copy( line.start );
  4022. }
  4023. // Unsure if this is the correct method to handle this case.
  4024. return undefined;
  4025. }
  4026. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  4027. if ( t < 0 || t > 1 ) {
  4028. return undefined;
  4029. }
  4030. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  4031. };
  4032. }(),
  4033. intersectsLine: function ( line ) {
  4034. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  4035. var startSign = this.distanceToPoint( line.start );
  4036. var endSign = this.distanceToPoint( line.end );
  4037. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  4038. },
  4039. intersectsBox: function ( box ) {
  4040. return box.intersectsPlane( this );
  4041. },
  4042. intersectsSphere: function ( sphere ) {
  4043. return sphere.intersectsPlane( this );
  4044. },
  4045. coplanarPoint: function ( optionalTarget ) {
  4046. var result = optionalTarget || new THREE.Vector3();
  4047. return result.copy( this.normal ).multiplyScalar( - this.constant );
  4048. },
  4049. applyMatrix4: function () {
  4050. var v1 = new THREE.Vector3();
  4051. var v2 = new THREE.Vector3();
  4052. var m1 = new THREE.Matrix3();
  4053. return function ( matrix, optionalNormalMatrix ) {
  4054. // compute new normal based on theory here:
  4055. // http://www.songho.ca/opengl/gl_normaltransform.html
  4056. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  4057. var newNormal = v1.copy( this.normal ).applyMatrix3( normalMatrix );
  4058. var newCoplanarPoint = this.coplanarPoint( v2 );
  4059. newCoplanarPoint.applyMatrix4( matrix );
  4060. this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint );
  4061. return this;
  4062. };
  4063. }(),
  4064. translate: function ( offset ) {
  4065. this.constant = this.constant - offset.dot( this.normal );
  4066. return this;
  4067. },
  4068. equals: function ( plane ) {
  4069. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  4070. }
  4071. };
  4072. // File:src/math/Spherical.js
  4073. /**
  4074. * @author bhouston / http://clara.io
  4075. * @author WestLangley / http://github.com/WestLangley
  4076. *
  4077. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  4078. *
  4079. * The poles (phi) are at the positive and negative y axis.
  4080. * The equator starts at positive z.
  4081. */
  4082. THREE.Spherical = function ( radius, phi, theta ) {
  4083. this.radius = ( radius !== undefined ) ? radius : 1.0;
  4084. this.phi = ( phi !== undefined ) ? phi : 0; // up / down towards top and bottom pole
  4085. this.theta = ( theta !== undefined ) ? theta : 0; // around the equator of the sphere
  4086. return this;
  4087. };
  4088. THREE.Spherical.prototype = {
  4089. constructor: THREE.Spherical,
  4090. set: function ( radius, phi, theta ) {
  4091. this.radius = radius;
  4092. this.phi = phi;
  4093. this.theta = theta;
  4094. },
  4095. clone: function () {
  4096. return new this.constructor().copy( this );
  4097. },
  4098. copy: function ( other ) {
  4099. this.radius.copy( other.radius );
  4100. this.phi.copy( other.phi );
  4101. this.theta.copy( other.theta );
  4102. return this;
  4103. },
  4104. // restrict phi to be betwee EPS and PI-EPS
  4105. makeSafe: function() {
  4106. var EPS = 0.000001;
  4107. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  4108. },
  4109. setFromVector3: function( vec3 ) {
  4110. this.radius = vec3.length();
  4111. if ( this.radius === 0 ) {
  4112. this.theta = 0;
  4113. this.phi = 0;
  4114. } else {
  4115. this.theta = Math.atan2( vec3.x, vec3.z ); // equator angle around y-up axis
  4116. this.phi = Math.acos( THREE.Math.clamp( vec3.y / this.radius, - 1, 1 ) ); // polar angle
  4117. }
  4118. return this;
  4119. },
  4120. };
  4121. // File:src/math/Math.js
  4122. /**
  4123. * @author alteredq / http://alteredqualia.com/
  4124. * @author mrdoob / http://mrdoob.com/
  4125. */
  4126. THREE.Math = {
  4127. DEG2RAD: Math.PI / 180,
  4128. RAD2DEG: 180 / Math.PI,
  4129. generateUUID: function () {
  4130. // http://www.broofa.com/Tools/Math.uuid.htm
  4131. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split( '' );
  4132. var uuid = new Array( 36 );
  4133. var rnd = 0, r;
  4134. return function () {
  4135. for ( var i = 0; i < 36; i ++ ) {
  4136. if ( i === 8 || i === 13 || i === 18 || i === 23 ) {
  4137. uuid[ i ] = '-';
  4138. } else if ( i === 14 ) {
  4139. uuid[ i ] = '4';
  4140. } else {
  4141. if ( rnd <= 0x02 ) rnd = 0x2000000 + ( Math.random() * 0x1000000 ) | 0;
  4142. r = rnd & 0xf;
  4143. rnd = rnd >> 4;
  4144. uuid[ i ] = chars[ ( i === 19 ) ? ( r & 0x3 ) | 0x8 : r ];
  4145. }
  4146. }
  4147. return uuid.join( '' );
  4148. };
  4149. }(),
  4150. clamp: function ( value, min, max ) {
  4151. return Math.max( min, Math.min( max, value ) );
  4152. },
  4153. // compute euclidian modulo of m % n
  4154. // https://en.wikipedia.org/wiki/Modulo_operation
  4155. euclideanModulo: function ( n, m ) {
  4156. return ( ( n % m ) + m ) % m;
  4157. },
  4158. // Linear mapping from range <a1, a2> to range <b1, b2>
  4159. mapLinear: function ( x, a1, a2, b1, b2 ) {
  4160. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  4161. },
  4162. // http://en.wikipedia.org/wiki/Smoothstep
  4163. smoothstep: function ( x, min, max ) {
  4164. if ( x <= min ) return 0;
  4165. if ( x >= max ) return 1;
  4166. x = ( x - min ) / ( max - min );
  4167. return x * x * ( 3 - 2 * x );
  4168. },
  4169. smootherstep: function ( x, min, max ) {
  4170. if ( x <= min ) return 0;
  4171. if ( x >= max ) return 1;
  4172. x = ( x - min ) / ( max - min );
  4173. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  4174. },
  4175. random16: function () {
  4176. console.warn( 'THREE.Math.random16() has been deprecated. Use Math.random() instead.' );
  4177. return Math.random();
  4178. },
  4179. // Random integer from <low, high> interval
  4180. randInt: function ( low, high ) {
  4181. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  4182. },
  4183. // Random float from <low, high> interval
  4184. randFloat: function ( low, high ) {
  4185. return low + Math.random() * ( high - low );
  4186. },
  4187. // Random float from <-range/2, range/2> interval
  4188. randFloatSpread: function ( range ) {
  4189. return range * ( 0.5 - Math.random() );
  4190. },
  4191. degToRad: function ( degrees ) {
  4192. return degrees * THREE.Math.DEG2RAD;
  4193. },
  4194. radToDeg: function ( radians ) {
  4195. return radians * THREE.Math.RAD2DEG;
  4196. },
  4197. isPowerOfTwo: function ( value ) {
  4198. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  4199. },
  4200. nearestPowerOfTwo: function ( value ) {
  4201. return Math.pow( 2, Math.round( Math.log( value ) / Math.LN2 ) );
  4202. },
  4203. nextPowerOfTwo: function ( value ) {
  4204. value --;
  4205. value |= value >> 1;
  4206. value |= value >> 2;
  4207. value |= value >> 4;
  4208. value |= value >> 8;
  4209. value |= value >> 16;
  4210. value ++;
  4211. return value;
  4212. }
  4213. };
  4214. // File:src/math/Spline.js
  4215. /**
  4216. * Spline from Tween.js, slightly optimized (and trashed)
  4217. * http://sole.github.com/tween.js/examples/05_spline.html
  4218. *
  4219. * @author mrdoob / http://mrdoob.com/
  4220. * @author alteredq / http://alteredqualia.com/
  4221. */
  4222. THREE.Spline = function ( points ) {
  4223. this.points = points;
  4224. var c = [], v3 = { x: 0, y: 0, z: 0 },
  4225. point, intPoint, weight, w2, w3,
  4226. pa, pb, pc, pd;
  4227. this.initFromArray = function ( a ) {
  4228. this.points = [];
  4229. for ( var i = 0; i < a.length; i ++ ) {
  4230. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  4231. }
  4232. };
  4233. this.getPoint = function ( k ) {
  4234. point = ( this.points.length - 1 ) * k;
  4235. intPoint = Math.floor( point );
  4236. weight = point - intPoint;
  4237. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  4238. c[ 1 ] = intPoint;
  4239. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  4240. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  4241. pa = this.points[ c[ 0 ] ];
  4242. pb = this.points[ c[ 1 ] ];
  4243. pc = this.points[ c[ 2 ] ];
  4244. pd = this.points[ c[ 3 ] ];
  4245. w2 = weight * weight;
  4246. w3 = weight * w2;
  4247. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  4248. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  4249. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  4250. return v3;
  4251. };
  4252. this.getControlPointsArray = function () {
  4253. var i, p, l = this.points.length,
  4254. coords = [];
  4255. for ( i = 0; i < l; i ++ ) {
  4256. p = this.points[ i ];
  4257. coords[ i ] = [ p.x, p.y, p.z ];
  4258. }
  4259. return coords;
  4260. };
  4261. // approximate length by summing linear segments
  4262. this.getLength = function ( nSubDivisions ) {
  4263. var i, index, nSamples, position,
  4264. point = 0, intPoint = 0, oldIntPoint = 0,
  4265. oldPosition = new THREE.Vector3(),
  4266. tmpVec = new THREE.Vector3(),
  4267. chunkLengths = [],
  4268. totalLength = 0;
  4269. // first point has 0 length
  4270. chunkLengths[ 0 ] = 0;
  4271. if ( ! nSubDivisions ) nSubDivisions = 100;
  4272. nSamples = this.points.length * nSubDivisions;
  4273. oldPosition.copy( this.points[ 0 ] );
  4274. for ( i = 1; i < nSamples; i ++ ) {
  4275. index = i / nSamples;
  4276. position = this.getPoint( index );
  4277. tmpVec.copy( position );
  4278. totalLength += tmpVec.distanceTo( oldPosition );
  4279. oldPosition.copy( position );
  4280. point = ( this.points.length - 1 ) * index;
  4281. intPoint = Math.floor( point );
  4282. if ( intPoint !== oldIntPoint ) {
  4283. chunkLengths[ intPoint ] = totalLength;
  4284. oldIntPoint = intPoint;
  4285. }
  4286. }
  4287. // last point ends with total length
  4288. chunkLengths[ chunkLengths.length ] = totalLength;
  4289. return { chunks: chunkLengths, total: totalLength };
  4290. };
  4291. this.reparametrizeByArcLength = function ( samplingCoef ) {
  4292. var i, j,
  4293. index, indexCurrent, indexNext,
  4294. realDistance,
  4295. sampling, position,
  4296. newpoints = [],
  4297. tmpVec = new THREE.Vector3(),
  4298. sl = this.getLength();
  4299. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  4300. for ( i = 1; i < this.points.length; i ++ ) {
  4301. //tmpVec.copy( this.points[ i - 1 ] );
  4302. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  4303. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  4304. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  4305. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  4306. indexNext = i / ( this.points.length - 1 );
  4307. for ( j = 1; j < sampling - 1; j ++ ) {
  4308. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  4309. position = this.getPoint( index );
  4310. newpoints.push( tmpVec.copy( position ).clone() );
  4311. }
  4312. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  4313. }
  4314. this.points = newpoints;
  4315. };
  4316. // Catmull-Rom
  4317. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  4318. var v0 = ( p2 - p0 ) * 0.5,
  4319. v1 = ( p3 - p1 ) * 0.5;
  4320. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  4321. }
  4322. };
  4323. // File:src/math/Triangle.js
  4324. /**
  4325. * @author bhouston / http://clara.io
  4326. * @author mrdoob / http://mrdoob.com/
  4327. */
  4328. THREE.Triangle = function ( a, b, c ) {
  4329. this.a = ( a !== undefined ) ? a : new THREE.Vector3();
  4330. this.b = ( b !== undefined ) ? b : new THREE.Vector3();
  4331. this.c = ( c !== undefined ) ? c : new THREE.Vector3();
  4332. };
  4333. THREE.Triangle.normal = function () {
  4334. var v0 = new THREE.Vector3();
  4335. return function ( a, b, c, optionalTarget ) {
  4336. var result = optionalTarget || new THREE.Vector3();
  4337. result.subVectors( c, b );
  4338. v0.subVectors( a, b );
  4339. result.cross( v0 );
  4340. var resultLengthSq = result.lengthSq();
  4341. if ( resultLengthSq > 0 ) {
  4342. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  4343. }
  4344. return result.set( 0, 0, 0 );
  4345. };
  4346. }();
  4347. // static/instance method to calculate barycentric coordinates
  4348. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4349. THREE.Triangle.barycoordFromPoint = function () {
  4350. var v0 = new THREE.Vector3();
  4351. var v1 = new THREE.Vector3();
  4352. var v2 = new THREE.Vector3();
  4353. return function ( point, a, b, c, optionalTarget ) {
  4354. v0.subVectors( c, a );
  4355. v1.subVectors( b, a );
  4356. v2.subVectors( point, a );
  4357. var dot00 = v0.dot( v0 );
  4358. var dot01 = v0.dot( v1 );
  4359. var dot02 = v0.dot( v2 );
  4360. var dot11 = v1.dot( v1 );
  4361. var dot12 = v1.dot( v2 );
  4362. var denom = ( dot00 * dot11 - dot01 * dot01 );
  4363. var result = optionalTarget || new THREE.Vector3();
  4364. // collinear or singular triangle
  4365. if ( denom === 0 ) {
  4366. // arbitrary location outside of triangle?
  4367. // not sure if this is the best idea, maybe should be returning undefined
  4368. return result.set( - 2, - 1, - 1 );
  4369. }
  4370. var invDenom = 1 / denom;
  4371. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  4372. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  4373. // barycentric coordinates must always sum to 1
  4374. return result.set( 1 - u - v, v, u );
  4375. };
  4376. }();
  4377. THREE.Triangle.containsPoint = function () {
  4378. var v1 = new THREE.Vector3();
  4379. return function ( point, a, b, c ) {
  4380. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 );
  4381. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  4382. };
  4383. }();
  4384. THREE.Triangle.prototype = {
  4385. constructor: THREE.Triangle,
  4386. set: function ( a, b, c ) {
  4387. this.a.copy( a );
  4388. this.b.copy( b );
  4389. this.c.copy( c );
  4390. return this;
  4391. },
  4392. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  4393. this.a.copy( points[ i0 ] );
  4394. this.b.copy( points[ i1 ] );
  4395. this.c.copy( points[ i2 ] );
  4396. return this;
  4397. },
  4398. clone: function () {
  4399. return new this.constructor().copy( this );
  4400. },
  4401. copy: function ( triangle ) {
  4402. this.a.copy( triangle.a );
  4403. this.b.copy( triangle.b );
  4404. this.c.copy( triangle.c );
  4405. return this;
  4406. },
  4407. area: function () {
  4408. var v0 = new THREE.Vector3();
  4409. var v1 = new THREE.Vector3();
  4410. return function () {
  4411. v0.subVectors( this.c, this.b );
  4412. v1.subVectors( this.a, this.b );
  4413. return v0.cross( v1 ).length() * 0.5;
  4414. };
  4415. }(),
  4416. midpoint: function ( optionalTarget ) {
  4417. var result = optionalTarget || new THREE.Vector3();
  4418. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  4419. },
  4420. normal: function ( optionalTarget ) {
  4421. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  4422. },
  4423. plane: function ( optionalTarget ) {
  4424. var result = optionalTarget || new THREE.Plane();
  4425. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  4426. },
  4427. barycoordFromPoint: function ( point, optionalTarget ) {
  4428. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  4429. },
  4430. containsPoint: function ( point ) {
  4431. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  4432. },
  4433. closestPointToPoint: function () {
  4434. var plane, edgeList, projectedPoint, closestPoint;
  4435. return function closestPointToPoint( point, optionalTarget ) {
  4436. if ( plane === undefined ) {
  4437. plane = new THREE.Plane();
  4438. edgeList = [ new THREE.Line3(), new THREE.Line3(), new THREE.Line3() ];
  4439. projectedPoint = new THREE.Vector3();
  4440. closestPoint = new THREE.Vector3();
  4441. }
  4442. var result = optionalTarget || new THREE.Vector3();
  4443. var minDistance = Infinity;
  4444. // project the point onto the plane of the triangle
  4445. plane.setFromCoplanarPoints( this.a, this.b, this.c );
  4446. plane.projectPoint( point, projectedPoint );
  4447. // check if the projection lies within the triangle
  4448. if( this.containsPoint( projectedPoint ) === true ) {
  4449. // if so, this is the closest point
  4450. result.copy( projectedPoint );
  4451. } else {
  4452. // if not, the point falls outside the triangle. the result is the closest point to the triangle's edges or vertices
  4453. edgeList[ 0 ].set( this.a, this.b );
  4454. edgeList[ 1 ].set( this.b, this.c );
  4455. edgeList[ 2 ].set( this.c, this.a );
  4456. for( var i = 0; i < edgeList.length; i ++ ) {
  4457. edgeList[ i ].closestPointToPoint( projectedPoint, true, closestPoint );
  4458. var distance = projectedPoint.distanceToSquared( closestPoint );
  4459. if( distance < minDistance ) {
  4460. minDistance = distance;
  4461. result.copy( closestPoint );
  4462. }
  4463. }
  4464. }
  4465. return result;
  4466. };
  4467. }(),
  4468. equals: function ( triangle ) {
  4469. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  4470. }
  4471. };
  4472. // File:src/math/Interpolant.js
  4473. /**
  4474. * Abstract base class of interpolants over parametric samples.
  4475. *
  4476. * The parameter domain is one dimensional, typically the time or a path
  4477. * along a curve defined by the data.
  4478. *
  4479. * The sample values can have any dimensionality and derived classes may
  4480. * apply special interpretations to the data.
  4481. *
  4482. * This class provides the interval seek in a Template Method, deferring
  4483. * the actual interpolation to derived classes.
  4484. *
  4485. * Time complexity is O(1) for linear access crossing at most two points
  4486. * and O(log N) for random access, where N is the number of positions.
  4487. *
  4488. * References:
  4489. *
  4490. * http://www.oodesign.com/template-method-pattern.html
  4491. *
  4492. * @author tschw
  4493. */
  4494. THREE.Interpolant = function(
  4495. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  4496. this.parameterPositions = parameterPositions;
  4497. this._cachedIndex = 0;
  4498. this.resultBuffer = resultBuffer !== undefined ?
  4499. resultBuffer : new sampleValues.constructor( sampleSize );
  4500. this.sampleValues = sampleValues;
  4501. this.valueSize = sampleSize;
  4502. };
  4503. THREE.Interpolant.prototype = {
  4504. constructor: THREE.Interpolant,
  4505. evaluate: function( t ) {
  4506. var pp = this.parameterPositions,
  4507. i1 = this._cachedIndex,
  4508. t1 = pp[ i1 ],
  4509. t0 = pp[ i1 - 1 ];
  4510. validate_interval: {
  4511. seek: {
  4512. var right;
  4513. linear_scan: {
  4514. //- See http://jsperf.com/comparison-to-undefined/3
  4515. //- slower code:
  4516. //-
  4517. //- if ( t >= t1 || t1 === undefined ) {
  4518. forward_scan: if ( ! ( t < t1 ) ) {
  4519. for ( var giveUpAt = i1 + 2; ;) {
  4520. if ( t1 === undefined ) {
  4521. if ( t < t0 ) break forward_scan;
  4522. // after end
  4523. i1 = pp.length;
  4524. this._cachedIndex = i1;
  4525. return this.afterEnd_( i1 - 1, t, t0 );
  4526. }
  4527. if ( i1 === giveUpAt ) break; // this loop
  4528. t0 = t1;
  4529. t1 = pp[ ++ i1 ];
  4530. if ( t < t1 ) {
  4531. // we have arrived at the sought interval
  4532. break seek;
  4533. }
  4534. }
  4535. // prepare binary search on the right side of the index
  4536. right = pp.length;
  4537. break linear_scan;
  4538. }
  4539. //- slower code:
  4540. //- if ( t < t0 || t0 === undefined ) {
  4541. if ( ! ( t >= t0 ) ) {
  4542. // looping?
  4543. var t1global = pp[ 1 ];
  4544. if ( t < t1global ) {
  4545. i1 = 2; // + 1, using the scan for the details
  4546. t0 = t1global;
  4547. }
  4548. // linear reverse scan
  4549. for ( var giveUpAt = i1 - 2; ;) {
  4550. if ( t0 === undefined ) {
  4551. // before start
  4552. this._cachedIndex = 0;
  4553. return this.beforeStart_( 0, t, t1 );
  4554. }
  4555. if ( i1 === giveUpAt ) break; // this loop
  4556. t1 = t0;
  4557. t0 = pp[ -- i1 - 1 ];
  4558. if ( t >= t0 ) {
  4559. // we have arrived at the sought interval
  4560. break seek;
  4561. }
  4562. }
  4563. // prepare binary search on the left side of the index
  4564. right = i1;
  4565. i1 = 0;
  4566. break linear_scan;
  4567. }
  4568. // the interval is valid
  4569. break validate_interval;
  4570. } // linear scan
  4571. // binary search
  4572. while ( i1 < right ) {
  4573. var mid = ( i1 + right ) >>> 1;
  4574. if ( t < pp[ mid ] ) {
  4575. right = mid;
  4576. } else {
  4577. i1 = mid + 1;
  4578. }
  4579. }
  4580. t1 = pp[ i1 ];
  4581. t0 = pp[ i1 - 1 ];
  4582. // check boundary cases, again
  4583. if ( t0 === undefined ) {
  4584. this._cachedIndex = 0;
  4585. return this.beforeStart_( 0, t, t1 );
  4586. }
  4587. if ( t1 === undefined ) {
  4588. i1 = pp.length;
  4589. this._cachedIndex = i1;
  4590. return this.afterEnd_( i1 - 1, t0, t );
  4591. }
  4592. } // seek
  4593. this._cachedIndex = i1;
  4594. this.intervalChanged_( i1, t0, t1 );
  4595. } // validate_interval
  4596. return this.interpolate_( i1, t0, t, t1 );
  4597. },
  4598. settings: null, // optional, subclass-specific settings structure
  4599. // Note: The indirection allows central control of many interpolants.
  4600. // --- Protected interface
  4601. DefaultSettings_: {},
  4602. getSettings_: function() {
  4603. return this.settings || this.DefaultSettings_;
  4604. },
  4605. copySampleValue_: function( index ) {
  4606. // copies a sample value to the result buffer
  4607. var result = this.resultBuffer,
  4608. values = this.sampleValues,
  4609. stride = this.valueSize,
  4610. offset = index * stride;
  4611. for ( var i = 0; i !== stride; ++ i ) {
  4612. result[ i ] = values[ offset + i ];
  4613. }
  4614. return result;
  4615. },
  4616. // Template methods for derived classes:
  4617. interpolate_: function( i1, t0, t, t1 ) {
  4618. throw new Error( "call to abstract method" );
  4619. // implementations shall return this.resultBuffer
  4620. },
  4621. intervalChanged_: function( i1, t0, t1 ) {
  4622. // empty
  4623. }
  4624. };
  4625. Object.assign( THREE.Interpolant.prototype, {
  4626. beforeStart_: //( 0, t, t0 ), returns this.resultBuffer
  4627. THREE.Interpolant.prototype.copySampleValue_,
  4628. afterEnd_: //( N-1, tN-1, t ), returns this.resultBuffer
  4629. THREE.Interpolant.prototype.copySampleValue_
  4630. } );
  4631. // File:src/math/interpolants/CubicInterpolant.js
  4632. /**
  4633. * Fast and simple cubic spline interpolant.
  4634. *
  4635. * It was derived from a Hermitian construction setting the first derivative
  4636. * at each sample position to the linear slope between neighboring positions
  4637. * over their parameter interval.
  4638. *
  4639. * @author tschw
  4640. */
  4641. THREE.CubicInterpolant = function(
  4642. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  4643. THREE.Interpolant.call(
  4644. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  4645. this._weightPrev = -0;
  4646. this._offsetPrev = -0;
  4647. this._weightNext = -0;
  4648. this._offsetNext = -0;
  4649. };
  4650. THREE.CubicInterpolant.prototype =
  4651. Object.assign( Object.create( THREE.Interpolant.prototype ), {
  4652. constructor: THREE.CubicInterpolant,
  4653. DefaultSettings_: {
  4654. endingStart: THREE.ZeroCurvatureEnding,
  4655. endingEnd: THREE.ZeroCurvatureEnding
  4656. },
  4657. intervalChanged_: function( i1, t0, t1 ) {
  4658. var pp = this.parameterPositions,
  4659. iPrev = i1 - 2,
  4660. iNext = i1 + 1,
  4661. tPrev = pp[ iPrev ],
  4662. tNext = pp[ iNext ];
  4663. if ( tPrev === undefined ) {
  4664. switch ( this.getSettings_().endingStart ) {
  4665. case THREE.ZeroSlopeEnding:
  4666. // f'(t0) = 0
  4667. iPrev = i1;
  4668. tPrev = 2 * t0 - t1;
  4669. break;
  4670. case THREE.WrapAroundEnding:
  4671. // use the other end of the curve
  4672. iPrev = pp.length - 2;
  4673. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  4674. break;
  4675. default: // ZeroCurvatureEnding
  4676. // f''(t0) = 0 a.k.a. Natural Spline
  4677. iPrev = i1;
  4678. tPrev = t1;
  4679. }
  4680. }
  4681. if ( tNext === undefined ) {
  4682. switch ( this.getSettings_().endingEnd ) {
  4683. case THREE.ZeroSlopeEnding:
  4684. // f'(tN) = 0
  4685. iNext = i1;
  4686. tNext = 2 * t1 - t0;
  4687. break;
  4688. case THREE.WrapAroundEnding:
  4689. // use the other end of the curve
  4690. iNext = 1;
  4691. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  4692. break;
  4693. default: // ZeroCurvatureEnding
  4694. // f''(tN) = 0, a.k.a. Natural Spline
  4695. iNext = i1 - 1;
  4696. tNext = t0;
  4697. }
  4698. }
  4699. var halfDt = ( t1 - t0 ) * 0.5,
  4700. stride = this.valueSize;
  4701. this._weightPrev = halfDt / ( t0 - tPrev );
  4702. this._weightNext = halfDt / ( tNext - t1 );
  4703. this._offsetPrev = iPrev * stride;
  4704. this._offsetNext = iNext * stride;
  4705. },
  4706. interpolate_: function( i1, t0, t, t1 ) {
  4707. var result = this.resultBuffer,
  4708. values = this.sampleValues,
  4709. stride = this.valueSize,
  4710. o1 = i1 * stride, o0 = o1 - stride,
  4711. oP = this._offsetPrev, oN = this._offsetNext,
  4712. wP = this._weightPrev, wN = this._weightNext,
  4713. p = ( t - t0 ) / ( t1 - t0 ),
  4714. pp = p * p,
  4715. ppp = pp * p;
  4716. // evaluate polynomials
  4717. var sP = - wP * ppp + 2 * wP * pp - wP * p;
  4718. var s0 = ( 1 + wP ) * ppp + (-1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  4719. var s1 = (-1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  4720. var sN = wN * ppp - wN * pp;
  4721. // combine data linearly
  4722. for ( var i = 0; i !== stride; ++ i ) {
  4723. result[ i ] =
  4724. sP * values[ oP + i ] +
  4725. s0 * values[ o0 + i ] +
  4726. s1 * values[ o1 + i ] +
  4727. sN * values[ oN + i ];
  4728. }
  4729. return result;
  4730. }
  4731. } );
  4732. // File:src/math/interpolants/DiscreteInterpolant.js
  4733. /**
  4734. *
  4735. * Interpolant that evaluates to the sample value at the position preceeding
  4736. * the parameter.
  4737. *
  4738. * @author tschw
  4739. */
  4740. THREE.DiscreteInterpolant = function(
  4741. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  4742. THREE.Interpolant.call(
  4743. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  4744. };
  4745. THREE.DiscreteInterpolant.prototype =
  4746. Object.assign( Object.create( THREE.Interpolant.prototype ), {
  4747. constructor: THREE.DiscreteInterpolant,
  4748. interpolate_: function( i1, t0, t, t1 ) {
  4749. return this.copySampleValue_( i1 - 1 );
  4750. }
  4751. } );
  4752. // File:src/math/interpolants/LinearInterpolant.js
  4753. /**
  4754. * @author tschw
  4755. */
  4756. THREE.LinearInterpolant = function(
  4757. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  4758. THREE.Interpolant.call(
  4759. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  4760. };
  4761. THREE.LinearInterpolant.prototype =
  4762. Object.assign( Object.create( THREE.Interpolant.prototype ), {
  4763. constructor: THREE.LinearInterpolant,
  4764. interpolate_: function( i1, t0, t, t1 ) {
  4765. var result = this.resultBuffer,
  4766. values = this.sampleValues,
  4767. stride = this.valueSize,
  4768. offset1 = i1 * stride,
  4769. offset0 = offset1 - stride,
  4770. weight1 = ( t - t0 ) / ( t1 - t0 ),
  4771. weight0 = 1 - weight1;
  4772. for ( var i = 0; i !== stride; ++ i ) {
  4773. result[ i ] =
  4774. values[ offset0 + i ] * weight0 +
  4775. values[ offset1 + i ] * weight1;
  4776. }
  4777. return result;
  4778. }
  4779. } );
  4780. // File:src/math/interpolants/QuaternionLinearInterpolant.js
  4781. /**
  4782. * Spherical linear unit quaternion interpolant.
  4783. *
  4784. * @author tschw
  4785. */
  4786. THREE.QuaternionLinearInterpolant = function(
  4787. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  4788. THREE.Interpolant.call(
  4789. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  4790. };
  4791. THREE.QuaternionLinearInterpolant.prototype =
  4792. Object.assign( Object.create( THREE.Interpolant.prototype ), {
  4793. constructor: THREE.QuaternionLinearInterpolant,
  4794. interpolate_: function( i1, t0, t, t1 ) {
  4795. var result = this.resultBuffer,
  4796. values = this.sampleValues,
  4797. stride = this.valueSize,
  4798. offset = i1 * stride,
  4799. alpha = ( t - t0 ) / ( t1 - t0 );
  4800. for ( var end = offset + stride; offset !== end; offset += 4 ) {
  4801. THREE.Quaternion.slerpFlat( result, 0,
  4802. values, offset - stride, values, offset, alpha );
  4803. }
  4804. return result;
  4805. }
  4806. } );
  4807. // File:src/core/Clock.js
  4808. /**
  4809. * @author alteredq / http://alteredqualia.com/
  4810. */
  4811. THREE.Clock = function ( autoStart ) {
  4812. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  4813. this.startTime = 0;
  4814. this.oldTime = 0;
  4815. this.elapsedTime = 0;
  4816. this.running = false;
  4817. };
  4818. THREE.Clock.prototype = {
  4819. constructor: THREE.Clock,
  4820. start: function () {
  4821. this.startTime = performance.now();
  4822. this.oldTime = this.startTime;
  4823. this.running = true;
  4824. },
  4825. stop: function () {
  4826. this.getElapsedTime();
  4827. this.running = false;
  4828. },
  4829. getElapsedTime: function () {
  4830. this.getDelta();
  4831. return this.elapsedTime;
  4832. },
  4833. getDelta: function () {
  4834. var diff = 0;
  4835. if ( this.autoStart && ! this.running ) {
  4836. this.start();
  4837. }
  4838. if ( this.running ) {
  4839. var newTime = performance.now();
  4840. diff = 0.001 * ( newTime - this.oldTime );
  4841. this.oldTime = newTime;
  4842. this.elapsedTime += diff;
  4843. }
  4844. return diff;
  4845. }
  4846. };
  4847. // File:src/core/EventDispatcher.js
  4848. /**
  4849. * https://github.com/mrdoob/eventdispatcher.js/
  4850. */
  4851. THREE.EventDispatcher = function () {};
  4852. THREE.EventDispatcher.prototype = {
  4853. constructor: THREE.EventDispatcher,
  4854. apply: function ( object ) {
  4855. object.addEventListener = THREE.EventDispatcher.prototype.addEventListener;
  4856. object.hasEventListener = THREE.EventDispatcher.prototype.hasEventListener;
  4857. object.removeEventListener = THREE.EventDispatcher.prototype.removeEventListener;
  4858. object.dispatchEvent = THREE.EventDispatcher.prototype.dispatchEvent;
  4859. },
  4860. addEventListener: function ( type, listener ) {
  4861. if ( this._listeners === undefined ) this._listeners = {};
  4862. var listeners = this._listeners;
  4863. if ( listeners[ type ] === undefined ) {
  4864. listeners[ type ] = [];
  4865. }
  4866. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  4867. listeners[ type ].push( listener );
  4868. }
  4869. },
  4870. hasEventListener: function ( type, listener ) {
  4871. if ( this._listeners === undefined ) return false;
  4872. var listeners = this._listeners;
  4873. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  4874. return true;
  4875. }
  4876. return false;
  4877. },
  4878. removeEventListener: function ( type, listener ) {
  4879. if ( this._listeners === undefined ) return;
  4880. var listeners = this._listeners;
  4881. var listenerArray = listeners[ type ];
  4882. if ( listenerArray !== undefined ) {
  4883. var index = listenerArray.indexOf( listener );
  4884. if ( index !== - 1 ) {
  4885. listenerArray.splice( index, 1 );
  4886. }
  4887. }
  4888. },
  4889. dispatchEvent: function ( event ) {
  4890. if ( this._listeners === undefined ) return;
  4891. var listeners = this._listeners;
  4892. var listenerArray = listeners[ event.type ];
  4893. if ( listenerArray !== undefined ) {
  4894. event.target = this;
  4895. var array = [];
  4896. var length = listenerArray.length;
  4897. for ( var i = 0; i < length; i ++ ) {
  4898. array[ i ] = listenerArray[ i ];
  4899. }
  4900. for ( var i = 0; i < length; i ++ ) {
  4901. array[ i ].call( this, event );
  4902. }
  4903. }
  4904. }
  4905. };
  4906. // File:src/core/Layers.js
  4907. /**
  4908. * @author mrdoob / http://mrdoob.com/
  4909. */
  4910. THREE.Layers = function () {
  4911. this.mask = 1;
  4912. };
  4913. THREE.Layers.prototype = {
  4914. constructor: THREE.Layers,
  4915. set: function ( channel ) {
  4916. this.mask = 1 << channel;
  4917. },
  4918. enable: function ( channel ) {
  4919. this.mask |= 1 << channel;
  4920. },
  4921. toggle: function ( channel ) {
  4922. this.mask ^= 1 << channel;
  4923. },
  4924. disable: function ( channel ) {
  4925. this.mask &= ~ ( 1 << channel );
  4926. },
  4927. test: function ( layers ) {
  4928. return ( this.mask & layers.mask ) !== 0;
  4929. }
  4930. };
  4931. // File:src/core/Raycaster.js
  4932. /**
  4933. * @author mrdoob / http://mrdoob.com/
  4934. * @author bhouston / http://clara.io/
  4935. * @author stephomi / http://stephaneginier.com/
  4936. */
  4937. ( function ( THREE ) {
  4938. THREE.Raycaster = function ( origin, direction, near, far ) {
  4939. this.ray = new THREE.Ray( origin, direction );
  4940. // direction is assumed to be normalized (for accurate distance calculations)
  4941. this.near = near || 0;
  4942. this.far = far || Infinity;
  4943. this.params = {
  4944. Mesh: {},
  4945. Line: {},
  4946. LOD: {},
  4947. Points: { threshold: 1 },
  4948. Sprite: {}
  4949. };
  4950. Object.defineProperties( this.params, {
  4951. PointCloud: {
  4952. get: function () {
  4953. console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' );
  4954. return this.Points;
  4955. }
  4956. }
  4957. } );
  4958. };
  4959. function ascSort( a, b ) {
  4960. return a.distance - b.distance;
  4961. }
  4962. function intersectObject( object, raycaster, intersects, recursive ) {
  4963. if ( object.visible === false ) return;
  4964. object.raycast( raycaster, intersects );
  4965. if ( recursive === true ) {
  4966. var children = object.children;
  4967. for ( var i = 0, l = children.length; i < l; i ++ ) {
  4968. intersectObject( children[ i ], raycaster, intersects, true );
  4969. }
  4970. }
  4971. }
  4972. //
  4973. THREE.Raycaster.prototype = {
  4974. constructor: THREE.Raycaster,
  4975. linePrecision: 1,
  4976. set: function ( origin, direction ) {
  4977. // direction is assumed to be normalized (for accurate distance calculations)
  4978. this.ray.set( origin, direction );
  4979. },
  4980. setFromCamera: function ( coords, camera ) {
  4981. if ( camera instanceof THREE.PerspectiveCamera ) {
  4982. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  4983. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  4984. } else if ( camera instanceof THREE.OrthographicCamera ) {
  4985. this.ray.origin.set( coords.x, coords.y, - 1 ).unproject( camera );
  4986. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  4987. } else {
  4988. console.error( 'THREE.Raycaster: Unsupported camera type.' );
  4989. }
  4990. },
  4991. intersectObject: function ( object, recursive ) {
  4992. var intersects = [];
  4993. intersectObject( object, this, intersects, recursive );
  4994. intersects.sort( ascSort );
  4995. return intersects;
  4996. },
  4997. intersectObjects: function ( objects, recursive ) {
  4998. var intersects = [];
  4999. if ( Array.isArray( objects ) === false ) {
  5000. console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
  5001. return intersects;
  5002. }
  5003. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  5004. intersectObject( objects[ i ], this, intersects, recursive );
  5005. }
  5006. intersects.sort( ascSort );
  5007. return intersects;
  5008. }
  5009. };
  5010. }( THREE ) );
  5011. // File:src/core/Object3D.js
  5012. /**
  5013. * @author mrdoob / http://mrdoob.com/
  5014. * @author mikael emtinger / http://gomo.se/
  5015. * @author alteredq / http://alteredqualia.com/
  5016. * @author WestLangley / http://github.com/WestLangley
  5017. * @author elephantatwork / www.elephantatwork.ch
  5018. */
  5019. THREE.Object3D = function () {
  5020. Object.defineProperty( this, 'id', { value: THREE.Object3DIdCount ++ } );
  5021. this.uuid = THREE.Math.generateUUID();
  5022. this.name = '';
  5023. this.type = 'Object3D';
  5024. this.parent = null;
  5025. this.children = [];
  5026. this.up = THREE.Object3D.DefaultUp.clone();
  5027. var position = new THREE.Vector3();
  5028. var rotation = new THREE.Euler();
  5029. var quaternion = new THREE.Quaternion();
  5030. var scale = new THREE.Vector3( 1, 1, 1 );
  5031. function onRotationChange() {
  5032. quaternion.setFromEuler( rotation, false );
  5033. }
  5034. function onQuaternionChange() {
  5035. rotation.setFromQuaternion( quaternion, undefined, false );
  5036. }
  5037. rotation.onChange( onRotationChange );
  5038. quaternion.onChange( onQuaternionChange );
  5039. Object.defineProperties( this, {
  5040. position: {
  5041. enumerable: true,
  5042. value: position
  5043. },
  5044. rotation: {
  5045. enumerable: true,
  5046. value: rotation
  5047. },
  5048. quaternion: {
  5049. enumerable: true,
  5050. value: quaternion
  5051. },
  5052. scale: {
  5053. enumerable: true,
  5054. value: scale
  5055. },
  5056. modelViewMatrix: {
  5057. value: new THREE.Matrix4()
  5058. },
  5059. normalMatrix: {
  5060. value: new THREE.Matrix3()
  5061. }
  5062. } );
  5063. this.rotationAutoUpdate = true;
  5064. this.matrix = new THREE.Matrix4();
  5065. this.matrixWorld = new THREE.Matrix4();
  5066. this.matrixAutoUpdate = THREE.Object3D.DefaultMatrixAutoUpdate;
  5067. this.matrixWorldNeedsUpdate = false;
  5068. this.layers = new THREE.Layers();
  5069. this.visible = true;
  5070. this.castShadow = false;
  5071. this.receiveShadow = false;
  5072. this.frustumCulled = true;
  5073. this.renderOrder = 0;
  5074. this.userData = {};
  5075. };
  5076. THREE.Object3D.DefaultUp = new THREE.Vector3( 0, 1, 0 );
  5077. THREE.Object3D.DefaultMatrixAutoUpdate = true;
  5078. THREE.Object3D.prototype = {
  5079. constructor: THREE.Object3D,
  5080. applyMatrix: function ( matrix ) {
  5081. this.matrix.multiplyMatrices( matrix, this.matrix );
  5082. this.matrix.decompose( this.position, this.quaternion, this.scale );
  5083. },
  5084. setRotationFromAxisAngle: function ( axis, angle ) {
  5085. // assumes axis is normalized
  5086. this.quaternion.setFromAxisAngle( axis, angle );
  5087. },
  5088. setRotationFromEuler: function ( euler ) {
  5089. this.quaternion.setFromEuler( euler, true );
  5090. },
  5091. setRotationFromMatrix: function ( m ) {
  5092. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  5093. this.quaternion.setFromRotationMatrix( m );
  5094. },
  5095. setRotationFromQuaternion: function ( q ) {
  5096. // assumes q is normalized
  5097. this.quaternion.copy( q );
  5098. },
  5099. rotateOnAxis: function () {
  5100. // rotate object on axis in object space
  5101. // axis is assumed to be normalized
  5102. var q1 = new THREE.Quaternion();
  5103. return function ( axis, angle ) {
  5104. q1.setFromAxisAngle( axis, angle );
  5105. this.quaternion.multiply( q1 );
  5106. return this;
  5107. };
  5108. }(),
  5109. rotateX: function () {
  5110. var v1 = new THREE.Vector3( 1, 0, 0 );
  5111. return function ( angle ) {
  5112. return this.rotateOnAxis( v1, angle );
  5113. };
  5114. }(),
  5115. rotateY: function () {
  5116. var v1 = new THREE.Vector3( 0, 1, 0 );
  5117. return function ( angle ) {
  5118. return this.rotateOnAxis( v1, angle );
  5119. };
  5120. }(),
  5121. rotateZ: function () {
  5122. var v1 = new THREE.Vector3( 0, 0, 1 );
  5123. return function ( angle ) {
  5124. return this.rotateOnAxis( v1, angle );
  5125. };
  5126. }(),
  5127. translateOnAxis: function () {
  5128. // translate object by distance along axis in object space
  5129. // axis is assumed to be normalized
  5130. var v1 = new THREE.Vector3();
  5131. return function ( axis, distance ) {
  5132. v1.copy( axis ).applyQuaternion( this.quaternion );
  5133. this.position.add( v1.multiplyScalar( distance ) );
  5134. return this;
  5135. };
  5136. }(),
  5137. translateX: function () {
  5138. var v1 = new THREE.Vector3( 1, 0, 0 );
  5139. return function ( distance ) {
  5140. return this.translateOnAxis( v1, distance );
  5141. };
  5142. }(),
  5143. translateY: function () {
  5144. var v1 = new THREE.Vector3( 0, 1, 0 );
  5145. return function ( distance ) {
  5146. return this.translateOnAxis( v1, distance );
  5147. };
  5148. }(),
  5149. translateZ: function () {
  5150. var v1 = new THREE.Vector3( 0, 0, 1 );
  5151. return function ( distance ) {
  5152. return this.translateOnAxis( v1, distance );
  5153. };
  5154. }(),
  5155. localToWorld: function ( vector ) {
  5156. return vector.applyMatrix4( this.matrixWorld );
  5157. },
  5158. worldToLocal: function () {
  5159. var m1 = new THREE.Matrix4();
  5160. return function ( vector ) {
  5161. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  5162. };
  5163. }(),
  5164. lookAt: function () {
  5165. // This routine does not support objects with rotated and/or translated parent(s)
  5166. var m1 = new THREE.Matrix4();
  5167. return function ( vector ) {
  5168. m1.lookAt( vector, this.position, this.up );
  5169. this.quaternion.setFromRotationMatrix( m1 );
  5170. };
  5171. }(),
  5172. add: function ( object ) {
  5173. if ( arguments.length > 1 ) {
  5174. for ( var i = 0; i < arguments.length; i ++ ) {
  5175. this.add( arguments[ i ] );
  5176. }
  5177. return this;
  5178. }
  5179. if ( object === this ) {
  5180. console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object );
  5181. return this;
  5182. }
  5183. if ( object instanceof THREE.Object3D ) {
  5184. if ( object.parent !== null ) {
  5185. object.parent.remove( object );
  5186. }
  5187. object.parent = this;
  5188. object.dispatchEvent( { type: 'added' } );
  5189. this.children.push( object );
  5190. } else {
  5191. console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object );
  5192. }
  5193. return this;
  5194. },
  5195. remove: function ( object ) {
  5196. if ( arguments.length > 1 ) {
  5197. for ( var i = 0; i < arguments.length; i ++ ) {
  5198. this.remove( arguments[ i ] );
  5199. }
  5200. }
  5201. var index = this.children.indexOf( object );
  5202. if ( index !== - 1 ) {
  5203. object.parent = null;
  5204. object.dispatchEvent( { type: 'removed' } );
  5205. this.children.splice( index, 1 );
  5206. }
  5207. },
  5208. getObjectById: function ( id ) {
  5209. return this.getObjectByProperty( 'id', id );
  5210. },
  5211. getObjectByName: function ( name ) {
  5212. return this.getObjectByProperty( 'name', name );
  5213. },
  5214. getObjectByProperty: function ( name, value ) {
  5215. if ( this[ name ] === value ) return this;
  5216. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  5217. var child = this.children[ i ];
  5218. var object = child.getObjectByProperty( name, value );
  5219. if ( object !== undefined ) {
  5220. return object;
  5221. }
  5222. }
  5223. return undefined;
  5224. },
  5225. getWorldPosition: function ( optionalTarget ) {
  5226. var result = optionalTarget || new THREE.Vector3();
  5227. this.updateMatrixWorld( true );
  5228. return result.setFromMatrixPosition( this.matrixWorld );
  5229. },
  5230. getWorldQuaternion: function () {
  5231. var position = new THREE.Vector3();
  5232. var scale = new THREE.Vector3();
  5233. return function ( optionalTarget ) {
  5234. var result = optionalTarget || new THREE.Quaternion();
  5235. this.updateMatrixWorld( true );
  5236. this.matrixWorld.decompose( position, result, scale );
  5237. return result;
  5238. };
  5239. }(),
  5240. getWorldRotation: function () {
  5241. var quaternion = new THREE.Quaternion();
  5242. return function ( optionalTarget ) {
  5243. var result = optionalTarget || new THREE.Euler();
  5244. this.getWorldQuaternion( quaternion );
  5245. return result.setFromQuaternion( quaternion, this.rotation.order, false );
  5246. };
  5247. }(),
  5248. getWorldScale: function () {
  5249. var position = new THREE.Vector3();
  5250. var quaternion = new THREE.Quaternion();
  5251. return function ( optionalTarget ) {
  5252. var result = optionalTarget || new THREE.Vector3();
  5253. this.updateMatrixWorld( true );
  5254. this.matrixWorld.decompose( position, quaternion, result );
  5255. return result;
  5256. };
  5257. }(),
  5258. getWorldDirection: function () {
  5259. var quaternion = new THREE.Quaternion();
  5260. return function ( optionalTarget ) {
  5261. var result = optionalTarget || new THREE.Vector3();
  5262. this.getWorldQuaternion( quaternion );
  5263. return result.set( 0, 0, 1 ).applyQuaternion( quaternion );
  5264. };
  5265. }(),
  5266. raycast: function () {},
  5267. traverse: function ( callback ) {
  5268. callback( this );
  5269. var children = this.children;
  5270. for ( var i = 0, l = children.length; i < l; i ++ ) {
  5271. children[ i ].traverse( callback );
  5272. }
  5273. },
  5274. traverseVisible: function ( callback ) {
  5275. if ( this.visible === false ) return;
  5276. callback( this );
  5277. var children = this.children;
  5278. for ( var i = 0, l = children.length; i < l; i ++ ) {
  5279. children[ i ].traverseVisible( callback );
  5280. }
  5281. },
  5282. traverseAncestors: function ( callback ) {
  5283. var parent = this.parent;
  5284. if ( parent !== null ) {
  5285. callback( parent );
  5286. parent.traverseAncestors( callback );
  5287. }
  5288. },
  5289. updateMatrix: function () {
  5290. this.matrix.compose( this.position, this.quaternion, this.scale );
  5291. this.matrixWorldNeedsUpdate = true;
  5292. },
  5293. updateMatrixWorld: function ( force ) {
  5294. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  5295. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  5296. if ( this.parent === null ) {
  5297. this.matrixWorld.copy( this.matrix );
  5298. } else {
  5299. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  5300. }
  5301. this.matrixWorldNeedsUpdate = false;
  5302. force = true;
  5303. }
  5304. // update children
  5305. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  5306. this.children[ i ].updateMatrixWorld( force );
  5307. }
  5308. },
  5309. toJSON: function ( meta ) {
  5310. // meta is '' when called from JSON.stringify
  5311. var isRootObject = ( meta === undefined || meta === '' );
  5312. var output = {};
  5313. // meta is a hash used to collect geometries, materials.
  5314. // not providing it implies that this is the root object
  5315. // being serialized.
  5316. if ( isRootObject ) {
  5317. // initialize meta obj
  5318. meta = {
  5319. geometries: {},
  5320. materials: {},
  5321. textures: {},
  5322. images: {}
  5323. };
  5324. output.metadata = {
  5325. version: 4.4,
  5326. type: 'Object',
  5327. generator: 'Object3D.toJSON'
  5328. };
  5329. }
  5330. // standard Object3D serialization
  5331. var object = {};
  5332. object.uuid = this.uuid;
  5333. object.type = this.type;
  5334. if ( this.name !== '' ) object.name = this.name;
  5335. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  5336. if ( this.castShadow === true ) object.castShadow = true;
  5337. if ( this.receiveShadow === true ) object.receiveShadow = true;
  5338. if ( this.visible === false ) object.visible = false;
  5339. object.matrix = this.matrix.toArray();
  5340. //
  5341. if ( this.geometry !== undefined ) {
  5342. if ( meta.geometries[ this.geometry.uuid ] === undefined ) {
  5343. meta.geometries[ this.geometry.uuid ] = this.geometry.toJSON( meta );
  5344. }
  5345. object.geometry = this.geometry.uuid;
  5346. }
  5347. if ( this.material !== undefined ) {
  5348. if ( meta.materials[ this.material.uuid ] === undefined ) {
  5349. meta.materials[ this.material.uuid ] = this.material.toJSON( meta );
  5350. }
  5351. object.material = this.material.uuid;
  5352. }
  5353. //
  5354. if ( this.children.length > 0 ) {
  5355. object.children = [];
  5356. for ( var i = 0; i < this.children.length; i ++ ) {
  5357. object.children.push( this.children[ i ].toJSON( meta ).object );
  5358. }
  5359. }
  5360. if ( isRootObject ) {
  5361. var geometries = extractFromCache( meta.geometries );
  5362. var materials = extractFromCache( meta.materials );
  5363. var textures = extractFromCache( meta.textures );
  5364. var images = extractFromCache( meta.images );
  5365. if ( geometries.length > 0 ) output.geometries = geometries;
  5366. if ( materials.length > 0 ) output.materials = materials;
  5367. if ( textures.length > 0 ) output.textures = textures;
  5368. if ( images.length > 0 ) output.images = images;
  5369. }
  5370. output.object = object;
  5371. return output;
  5372. // extract data from the cache hash
  5373. // remove metadata on each item
  5374. // and return as array
  5375. function extractFromCache ( cache ) {
  5376. var values = [];
  5377. for ( var key in cache ) {
  5378. var data = cache[ key ];
  5379. delete data.metadata;
  5380. values.push( data );
  5381. }
  5382. return values;
  5383. }
  5384. },
  5385. clone: function ( recursive ) {
  5386. return new this.constructor().copy( this, recursive );
  5387. },
  5388. copy: function ( source, recursive ) {
  5389. if ( recursive === undefined ) recursive = true;
  5390. this.name = source.name;
  5391. this.up.copy( source.up );
  5392. this.position.copy( source.position );
  5393. this.quaternion.copy( source.quaternion );
  5394. this.scale.copy( source.scale );
  5395. this.rotationAutoUpdate = source.rotationAutoUpdate;
  5396. this.matrix.copy( source.matrix );
  5397. this.matrixWorld.copy( source.matrixWorld );
  5398. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5399. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  5400. this.visible = source.visible;
  5401. this.castShadow = source.castShadow;
  5402. this.receiveShadow = source.receiveShadow;
  5403. this.frustumCulled = source.frustumCulled;
  5404. this.renderOrder = source.renderOrder;
  5405. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5406. if ( recursive === true ) {
  5407. for ( var i = 0; i < source.children.length; i ++ ) {
  5408. var child = source.children[ i ];
  5409. this.add( child.clone() );
  5410. }
  5411. }
  5412. return this;
  5413. }
  5414. };
  5415. THREE.EventDispatcher.prototype.apply( THREE.Object3D.prototype );
  5416. THREE.Object3DIdCount = 0;
  5417. // File:src/core/Face3.js
  5418. /**
  5419. * @author mrdoob / http://mrdoob.com/
  5420. * @author alteredq / http://alteredqualia.com/
  5421. */
  5422. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  5423. this.a = a;
  5424. this.b = b;
  5425. this.c = c;
  5426. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  5427. this.vertexNormals = Array.isArray( normal ) ? normal : [];
  5428. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  5429. this.vertexColors = Array.isArray( color ) ? color : [];
  5430. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  5431. };
  5432. THREE.Face3.prototype = {
  5433. constructor: THREE.Face3,
  5434. clone: function () {
  5435. return new this.constructor().copy( this );
  5436. },
  5437. copy: function ( source ) {
  5438. this.a = source.a;
  5439. this.b = source.b;
  5440. this.c = source.c;
  5441. this.normal.copy( source.normal );
  5442. this.color.copy( source.color );
  5443. this.materialIndex = source.materialIndex;
  5444. for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) {
  5445. this.vertexNormals[ i ] = source.vertexNormals[ i ].clone();
  5446. }
  5447. for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) {
  5448. this.vertexColors[ i ] = source.vertexColors[ i ].clone();
  5449. }
  5450. return this;
  5451. }
  5452. };
  5453. // File:src/core/BufferAttribute.js
  5454. /**
  5455. * @author mrdoob / http://mrdoob.com/
  5456. */
  5457. THREE.BufferAttribute = function ( array, itemSize ) {
  5458. this.uuid = THREE.Math.generateUUID();
  5459. this.array = array;
  5460. this.itemSize = itemSize;
  5461. this.dynamic = false;
  5462. this.updateRange = { offset: 0, count: - 1 };
  5463. this.version = 0;
  5464. };
  5465. THREE.BufferAttribute.prototype = {
  5466. constructor: THREE.BufferAttribute,
  5467. get count() {
  5468. return this.array.length / this.itemSize;
  5469. },
  5470. set needsUpdate( value ) {
  5471. if ( value === true ) this.version ++;
  5472. },
  5473. setDynamic: function ( value ) {
  5474. this.dynamic = value;
  5475. return this;
  5476. },
  5477. copy: function ( source ) {
  5478. this.array = new source.array.constructor( source.array );
  5479. this.itemSize = source.itemSize;
  5480. this.dynamic = source.dynamic;
  5481. return this;
  5482. },
  5483. copyAt: function ( index1, attribute, index2 ) {
  5484. index1 *= this.itemSize;
  5485. index2 *= attribute.itemSize;
  5486. for ( var i = 0, l = this.itemSize; i < l; i ++ ) {
  5487. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5488. }
  5489. return this;
  5490. },
  5491. copyArray: function ( array ) {
  5492. this.array.set( array );
  5493. return this;
  5494. },
  5495. copyColorsArray: function ( colors ) {
  5496. var array = this.array, offset = 0;
  5497. for ( var i = 0, l = colors.length; i < l; i ++ ) {
  5498. var color = colors[ i ];
  5499. if ( color === undefined ) {
  5500. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  5501. color = new THREE.Color();
  5502. }
  5503. array[ offset ++ ] = color.r;
  5504. array[ offset ++ ] = color.g;
  5505. array[ offset ++ ] = color.b;
  5506. }
  5507. return this;
  5508. },
  5509. copyIndicesArray: function ( indices ) {
  5510. var array = this.array, offset = 0;
  5511. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  5512. var index = indices[ i ];
  5513. array[ offset ++ ] = index.a;
  5514. array[ offset ++ ] = index.b;
  5515. array[ offset ++ ] = index.c;
  5516. }
  5517. return this;
  5518. },
  5519. copyVector2sArray: function ( vectors ) {
  5520. var array = this.array, offset = 0;
  5521. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  5522. var vector = vectors[ i ];
  5523. if ( vector === undefined ) {
  5524. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  5525. vector = new THREE.Vector2();
  5526. }
  5527. array[ offset ++ ] = vector.x;
  5528. array[ offset ++ ] = vector.y;
  5529. }
  5530. return this;
  5531. },
  5532. copyVector3sArray: function ( vectors ) {
  5533. var array = this.array, offset = 0;
  5534. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  5535. var vector = vectors[ i ];
  5536. if ( vector === undefined ) {
  5537. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  5538. vector = new THREE.Vector3();
  5539. }
  5540. array[ offset ++ ] = vector.x;
  5541. array[ offset ++ ] = vector.y;
  5542. array[ offset ++ ] = vector.z;
  5543. }
  5544. return this;
  5545. },
  5546. copyVector4sArray: function ( vectors ) {
  5547. var array = this.array, offset = 0;
  5548. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  5549. var vector = vectors[ i ];
  5550. if ( vector === undefined ) {
  5551. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  5552. vector = new THREE.Vector4();
  5553. }
  5554. array[ offset ++ ] = vector.x;
  5555. array[ offset ++ ] = vector.y;
  5556. array[ offset ++ ] = vector.z;
  5557. array[ offset ++ ] = vector.w;
  5558. }
  5559. return this;
  5560. },
  5561. set: function ( value, offset ) {
  5562. if ( offset === undefined ) offset = 0;
  5563. this.array.set( value, offset );
  5564. return this;
  5565. },
  5566. getX: function ( index ) {
  5567. return this.array[ index * this.itemSize ];
  5568. },
  5569. setX: function ( index, x ) {
  5570. this.array[ index * this.itemSize ] = x;
  5571. return this;
  5572. },
  5573. getY: function ( index ) {
  5574. return this.array[ index * this.itemSize + 1 ];
  5575. },
  5576. setY: function ( index, y ) {
  5577. this.array[ index * this.itemSize + 1 ] = y;
  5578. return this;
  5579. },
  5580. getZ: function ( index ) {
  5581. return this.array[ index * this.itemSize + 2 ];
  5582. },
  5583. setZ: function ( index, z ) {
  5584. this.array[ index * this.itemSize + 2 ] = z;
  5585. return this;
  5586. },
  5587. getW: function ( index ) {
  5588. return this.array[ index * this.itemSize + 3 ];
  5589. },
  5590. setW: function ( index, w ) {
  5591. this.array[ index * this.itemSize + 3 ] = w;
  5592. return this;
  5593. },
  5594. setXY: function ( index, x, y ) {
  5595. index *= this.itemSize;
  5596. this.array[ index + 0 ] = x;
  5597. this.array[ index + 1 ] = y;
  5598. return this;
  5599. },
  5600. setXYZ: function ( index, x, y, z ) {
  5601. index *= this.itemSize;
  5602. this.array[ index + 0 ] = x;
  5603. this.array[ index + 1 ] = y;
  5604. this.array[ index + 2 ] = z;
  5605. return this;
  5606. },
  5607. setXYZW: function ( index, x, y, z, w ) {
  5608. index *= this.itemSize;
  5609. this.array[ index + 0 ] = x;
  5610. this.array[ index + 1 ] = y;
  5611. this.array[ index + 2 ] = z;
  5612. this.array[ index + 3 ] = w;
  5613. return this;
  5614. },
  5615. clone: function () {
  5616. return new this.constructor().copy( this );
  5617. }
  5618. };
  5619. //
  5620. THREE.Int8Attribute = function ( array, itemSize ) {
  5621. return new THREE.BufferAttribute( new Int8Array( array ), itemSize );
  5622. };
  5623. THREE.Uint8Attribute = function ( array, itemSize ) {
  5624. return new THREE.BufferAttribute( new Uint8Array( array ), itemSize );
  5625. };
  5626. THREE.Uint8ClampedAttribute = function ( array, itemSize ) {
  5627. return new THREE.BufferAttribute( new Uint8ClampedArray( array ), itemSize );
  5628. };
  5629. THREE.Int16Attribute = function ( array, itemSize ) {
  5630. return new THREE.BufferAttribute( new Int16Array( array ), itemSize );
  5631. };
  5632. THREE.Uint16Attribute = function ( array, itemSize ) {
  5633. return new THREE.BufferAttribute( new Uint16Array( array ), itemSize );
  5634. };
  5635. THREE.Int32Attribute = function ( array, itemSize ) {
  5636. return new THREE.BufferAttribute( new Int32Array( array ), itemSize );
  5637. };
  5638. THREE.Uint32Attribute = function ( array, itemSize ) {
  5639. return new THREE.BufferAttribute( new Uint32Array( array ), itemSize );
  5640. };
  5641. THREE.Float32Attribute = function ( array, itemSize ) {
  5642. return new THREE.BufferAttribute( new Float32Array( array ), itemSize );
  5643. };
  5644. THREE.Float64Attribute = function ( array, itemSize ) {
  5645. return new THREE.BufferAttribute( new Float64Array( array ), itemSize );
  5646. };
  5647. // Deprecated
  5648. THREE.DynamicBufferAttribute = function ( array, itemSize ) {
  5649. console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.' );
  5650. return new THREE.BufferAttribute( array, itemSize ).setDynamic( true );
  5651. };
  5652. // File:src/core/InstancedBufferAttribute.js
  5653. /**
  5654. * @author benaadams / https://twitter.com/ben_a_adams
  5655. */
  5656. THREE.InstancedBufferAttribute = function ( array, itemSize, meshPerAttribute ) {
  5657. THREE.BufferAttribute.call( this, array, itemSize );
  5658. this.meshPerAttribute = meshPerAttribute || 1;
  5659. };
  5660. THREE.InstancedBufferAttribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5661. THREE.InstancedBufferAttribute.prototype.constructor = THREE.InstancedBufferAttribute;
  5662. THREE.InstancedBufferAttribute.prototype.copy = function ( source ) {
  5663. THREE.BufferAttribute.prototype.copy.call( this, source );
  5664. this.meshPerAttribute = source.meshPerAttribute;
  5665. return this;
  5666. };
  5667. // File:src/core/InterleavedBuffer.js
  5668. /**
  5669. * @author benaadams / https://twitter.com/ben_a_adams
  5670. */
  5671. THREE.InterleavedBuffer = function ( array, stride ) {
  5672. this.uuid = THREE.Math.generateUUID();
  5673. this.array = array;
  5674. this.stride = stride;
  5675. this.dynamic = false;
  5676. this.updateRange = { offset: 0, count: - 1 };
  5677. this.version = 0;
  5678. };
  5679. THREE.InterleavedBuffer.prototype = {
  5680. constructor: THREE.InterleavedBuffer,
  5681. get length () {
  5682. return this.array.length;
  5683. },
  5684. get count () {
  5685. return this.array.length / this.stride;
  5686. },
  5687. set needsUpdate( value ) {
  5688. if ( value === true ) this.version ++;
  5689. },
  5690. setDynamic: function ( value ) {
  5691. this.dynamic = value;
  5692. return this;
  5693. },
  5694. copy: function ( source ) {
  5695. this.array = new source.array.constructor( source.array );
  5696. this.stride = source.stride;
  5697. this.dynamic = source.dynamic;
  5698. return this;
  5699. },
  5700. copyAt: function ( index1, attribute, index2 ) {
  5701. index1 *= this.stride;
  5702. index2 *= attribute.stride;
  5703. for ( var i = 0, l = this.stride; i < l; i ++ ) {
  5704. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5705. }
  5706. return this;
  5707. },
  5708. set: function ( value, offset ) {
  5709. if ( offset === undefined ) offset = 0;
  5710. this.array.set( value, offset );
  5711. return this;
  5712. },
  5713. clone: function () {
  5714. return new this.constructor().copy( this );
  5715. }
  5716. };
  5717. // File:src/core/InstancedInterleavedBuffer.js
  5718. /**
  5719. * @author benaadams / https://twitter.com/ben_a_adams
  5720. */
  5721. THREE.InstancedInterleavedBuffer = function ( array, stride, meshPerAttribute ) {
  5722. THREE.InterleavedBuffer.call( this, array, stride );
  5723. this.meshPerAttribute = meshPerAttribute || 1;
  5724. };
  5725. THREE.InstancedInterleavedBuffer.prototype = Object.create( THREE.InterleavedBuffer.prototype );
  5726. THREE.InstancedInterleavedBuffer.prototype.constructor = THREE.InstancedInterleavedBuffer;
  5727. THREE.InstancedInterleavedBuffer.prototype.copy = function ( source ) {
  5728. THREE.InterleavedBuffer.prototype.copy.call( this, source );
  5729. this.meshPerAttribute = source.meshPerAttribute;
  5730. return this;
  5731. };
  5732. // File:src/core/InterleavedBufferAttribute.js
  5733. /**
  5734. * @author benaadams / https://twitter.com/ben_a_adams
  5735. */
  5736. THREE.InterleavedBufferAttribute = function ( interleavedBuffer, itemSize, offset ) {
  5737. this.uuid = THREE.Math.generateUUID();
  5738. this.data = interleavedBuffer;
  5739. this.itemSize = itemSize;
  5740. this.offset = offset;
  5741. };
  5742. THREE.InterleavedBufferAttribute.prototype = {
  5743. constructor: THREE.InterleavedBufferAttribute,
  5744. get length() {
  5745. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Please use .count.' );
  5746. return this.array.length;
  5747. },
  5748. get count() {
  5749. return this.data.count;
  5750. },
  5751. setX: function ( index, x ) {
  5752. this.data.array[ index * this.data.stride + this.offset ] = x;
  5753. return this;
  5754. },
  5755. setY: function ( index, y ) {
  5756. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  5757. return this;
  5758. },
  5759. setZ: function ( index, z ) {
  5760. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  5761. return this;
  5762. },
  5763. setW: function ( index, w ) {
  5764. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  5765. return this;
  5766. },
  5767. getX: function ( index ) {
  5768. return this.data.array[ index * this.data.stride + this.offset ];
  5769. },
  5770. getY: function ( index ) {
  5771. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  5772. },
  5773. getZ: function ( index ) {
  5774. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  5775. },
  5776. getW: function ( index ) {
  5777. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  5778. },
  5779. setXY: function ( index, x, y ) {
  5780. index = index * this.data.stride + this.offset;
  5781. this.data.array[ index + 0 ] = x;
  5782. this.data.array[ index + 1 ] = y;
  5783. return this;
  5784. },
  5785. setXYZ: function ( index, x, y, z ) {
  5786. index = index * this.data.stride + this.offset;
  5787. this.data.array[ index + 0 ] = x;
  5788. this.data.array[ index + 1 ] = y;
  5789. this.data.array[ index + 2 ] = z;
  5790. return this;
  5791. },
  5792. setXYZW: function ( index, x, y, z, w ) {
  5793. index = index * this.data.stride + this.offset;
  5794. this.data.array[ index + 0 ] = x;
  5795. this.data.array[ index + 1 ] = y;
  5796. this.data.array[ index + 2 ] = z;
  5797. this.data.array[ index + 3 ] = w;
  5798. return this;
  5799. }
  5800. };
  5801. // File:src/core/Geometry.js
  5802. /**
  5803. * @author mrdoob / http://mrdoob.com/
  5804. * @author kile / http://kile.stravaganza.org/
  5805. * @author alteredq / http://alteredqualia.com/
  5806. * @author mikael emtinger / http://gomo.se/
  5807. * @author zz85 / http://www.lab4games.net/zz85/blog
  5808. * @author bhouston / http://clara.io
  5809. */
  5810. THREE.Geometry = function () {
  5811. Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } );
  5812. this.uuid = THREE.Math.generateUUID();
  5813. this.name = '';
  5814. this.type = 'Geometry';
  5815. this.vertices = [];
  5816. this.colors = [];
  5817. this.faces = [];
  5818. this.faceVertexUvs = [ [] ];
  5819. this.morphTargets = [];
  5820. this.morphNormals = [];
  5821. this.skinWeights = [];
  5822. this.skinIndices = [];
  5823. this.lineDistances = [];
  5824. this.boundingBox = null;
  5825. this.boundingSphere = null;
  5826. // update flags
  5827. this.verticesNeedUpdate = false;
  5828. this.elementsNeedUpdate = false;
  5829. this.uvsNeedUpdate = false;
  5830. this.normalsNeedUpdate = false;
  5831. this.colorsNeedUpdate = false;
  5832. this.lineDistancesNeedUpdate = false;
  5833. this.groupsNeedUpdate = false;
  5834. };
  5835. THREE.Geometry.prototype = {
  5836. constructor: THREE.Geometry,
  5837. applyMatrix: function ( matrix ) {
  5838. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5839. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  5840. var vertex = this.vertices[ i ];
  5841. vertex.applyMatrix4( matrix );
  5842. }
  5843. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  5844. var face = this.faces[ i ];
  5845. face.normal.applyMatrix3( normalMatrix ).normalize();
  5846. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  5847. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  5848. }
  5849. }
  5850. if ( this.boundingBox !== null ) {
  5851. this.computeBoundingBox();
  5852. }
  5853. if ( this.boundingSphere !== null ) {
  5854. this.computeBoundingSphere();
  5855. }
  5856. this.verticesNeedUpdate = true;
  5857. this.normalsNeedUpdate = true;
  5858. return this;
  5859. },
  5860. rotateX: function () {
  5861. // rotate geometry around world x-axis
  5862. var m1;
  5863. return function rotateX( angle ) {
  5864. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  5865. m1.makeRotationX( angle );
  5866. this.applyMatrix( m1 );
  5867. return this;
  5868. };
  5869. }(),
  5870. rotateY: function () {
  5871. // rotate geometry around world y-axis
  5872. var m1;
  5873. return function rotateY( angle ) {
  5874. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  5875. m1.makeRotationY( angle );
  5876. this.applyMatrix( m1 );
  5877. return this;
  5878. };
  5879. }(),
  5880. rotateZ: function () {
  5881. // rotate geometry around world z-axis
  5882. var m1;
  5883. return function rotateZ( angle ) {
  5884. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  5885. m1.makeRotationZ( angle );
  5886. this.applyMatrix( m1 );
  5887. return this;
  5888. };
  5889. }(),
  5890. translate: function () {
  5891. // translate geometry
  5892. var m1;
  5893. return function translate( x, y, z ) {
  5894. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  5895. m1.makeTranslation( x, y, z );
  5896. this.applyMatrix( m1 );
  5897. return this;
  5898. };
  5899. }(),
  5900. scale: function () {
  5901. // scale geometry
  5902. var m1;
  5903. return function scale( x, y, z ) {
  5904. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  5905. m1.makeScale( x, y, z );
  5906. this.applyMatrix( m1 );
  5907. return this;
  5908. };
  5909. }(),
  5910. lookAt: function () {
  5911. var obj;
  5912. return function lookAt( vector ) {
  5913. if ( obj === undefined ) obj = new THREE.Object3D();
  5914. obj.lookAt( vector );
  5915. obj.updateMatrix();
  5916. this.applyMatrix( obj.matrix );
  5917. };
  5918. }(),
  5919. fromBufferGeometry: function ( geometry ) {
  5920. var scope = this;
  5921. var indices = geometry.index !== null ? geometry.index.array : undefined;
  5922. var attributes = geometry.attributes;
  5923. var positions = attributes.position.array;
  5924. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  5925. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  5926. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  5927. var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;
  5928. if ( uvs2 !== undefined ) this.faceVertexUvs[ 1 ] = [];
  5929. var tempNormals = [];
  5930. var tempUVs = [];
  5931. var tempUVs2 = [];
  5932. for ( var i = 0, j = 0; i < positions.length; i += 3, j += 2 ) {
  5933. scope.vertices.push( new THREE.Vector3( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ) );
  5934. if ( normals !== undefined ) {
  5935. tempNormals.push( new THREE.Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) );
  5936. }
  5937. if ( colors !== undefined ) {
  5938. scope.colors.push( new THREE.Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) );
  5939. }
  5940. if ( uvs !== undefined ) {
  5941. tempUVs.push( new THREE.Vector2( uvs[ j ], uvs[ j + 1 ] ) );
  5942. }
  5943. if ( uvs2 !== undefined ) {
  5944. tempUVs2.push( new THREE.Vector2( uvs2[ j ], uvs2[ j + 1 ] ) );
  5945. }
  5946. }
  5947. function addFace( a, b, c, materialIndex ) {
  5948. var vertexNormals = normals !== undefined ? [ tempNormals[ a ].clone(), tempNormals[ b ].clone(), tempNormals[ c ].clone() ] : [];
  5949. var vertexColors = colors !== undefined ? [ scope.colors[ a ].clone(), scope.colors[ b ].clone(), scope.colors[ c ].clone() ] : [];
  5950. var face = new THREE.Face3( a, b, c, vertexNormals, vertexColors, materialIndex );
  5951. scope.faces.push( face );
  5952. if ( uvs !== undefined ) {
  5953. scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] );
  5954. }
  5955. if ( uvs2 !== undefined ) {
  5956. scope.faceVertexUvs[ 1 ].push( [ tempUVs2[ a ].clone(), tempUVs2[ b ].clone(), tempUVs2[ c ].clone() ] );
  5957. }
  5958. }
  5959. if ( indices !== undefined ) {
  5960. var groups = geometry.groups;
  5961. if ( groups.length > 0 ) {
  5962. for ( var i = 0; i < groups.length; i ++ ) {
  5963. var group = groups[ i ];
  5964. var start = group.start;
  5965. var count = group.count;
  5966. for ( var j = start, jl = start + count; j < jl; j += 3 ) {
  5967. addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ], group.materialIndex );
  5968. }
  5969. }
  5970. } else {
  5971. for ( var i = 0; i < indices.length; i += 3 ) {
  5972. addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  5973. }
  5974. }
  5975. } else {
  5976. for ( var i = 0; i < positions.length / 3; i += 3 ) {
  5977. addFace( i, i + 1, i + 2 );
  5978. }
  5979. }
  5980. this.computeFaceNormals();
  5981. if ( geometry.boundingBox !== null ) {
  5982. this.boundingBox = geometry.boundingBox.clone();
  5983. }
  5984. if ( geometry.boundingSphere !== null ) {
  5985. this.boundingSphere = geometry.boundingSphere.clone();
  5986. }
  5987. return this;
  5988. },
  5989. center: function () {
  5990. this.computeBoundingBox();
  5991. var offset = this.boundingBox.center().negate();
  5992. this.translate( offset.x, offset.y, offset.z );
  5993. return offset;
  5994. },
  5995. normalize: function () {
  5996. this.computeBoundingSphere();
  5997. var center = this.boundingSphere.center;
  5998. var radius = this.boundingSphere.radius;
  5999. var s = radius === 0 ? 1 : 1.0 / radius;
  6000. var matrix = new THREE.Matrix4();
  6001. matrix.set(
  6002. s, 0, 0, - s * center.x,
  6003. 0, s, 0, - s * center.y,
  6004. 0, 0, s, - s * center.z,
  6005. 0, 0, 0, 1
  6006. );
  6007. this.applyMatrix( matrix );
  6008. return this;
  6009. },
  6010. computeFaceNormals: function () {
  6011. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  6012. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6013. var face = this.faces[ f ];
  6014. var vA = this.vertices[ face.a ];
  6015. var vB = this.vertices[ face.b ];
  6016. var vC = this.vertices[ face.c ];
  6017. cb.subVectors( vC, vB );
  6018. ab.subVectors( vA, vB );
  6019. cb.cross( ab );
  6020. cb.normalize();
  6021. face.normal.copy( cb );
  6022. }
  6023. },
  6024. computeVertexNormals: function ( areaWeighted ) {
  6025. if ( areaWeighted === undefined ) areaWeighted = true;
  6026. var v, vl, f, fl, face, vertices;
  6027. vertices = new Array( this.vertices.length );
  6028. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  6029. vertices[ v ] = new THREE.Vector3();
  6030. }
  6031. if ( areaWeighted ) {
  6032. // vertex normals weighted by triangle areas
  6033. // http://www.iquilezles.org/www/articles/normals/normals.htm
  6034. var vA, vB, vC;
  6035. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  6036. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6037. face = this.faces[ f ];
  6038. vA = this.vertices[ face.a ];
  6039. vB = this.vertices[ face.b ];
  6040. vC = this.vertices[ face.c ];
  6041. cb.subVectors( vC, vB );
  6042. ab.subVectors( vA, vB );
  6043. cb.cross( ab );
  6044. vertices[ face.a ].add( cb );
  6045. vertices[ face.b ].add( cb );
  6046. vertices[ face.c ].add( cb );
  6047. }
  6048. } else {
  6049. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6050. face = this.faces[ f ];
  6051. vertices[ face.a ].add( face.normal );
  6052. vertices[ face.b ].add( face.normal );
  6053. vertices[ face.c ].add( face.normal );
  6054. }
  6055. }
  6056. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  6057. vertices[ v ].normalize();
  6058. }
  6059. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6060. face = this.faces[ f ];
  6061. var vertexNormals = face.vertexNormals;
  6062. if ( vertexNormals.length === 3 ) {
  6063. vertexNormals[ 0 ].copy( vertices[ face.a ] );
  6064. vertexNormals[ 1 ].copy( vertices[ face.b ] );
  6065. vertexNormals[ 2 ].copy( vertices[ face.c ] );
  6066. } else {
  6067. vertexNormals[ 0 ] = vertices[ face.a ].clone();
  6068. vertexNormals[ 1 ] = vertices[ face.b ].clone();
  6069. vertexNormals[ 2 ] = vertices[ face.c ].clone();
  6070. }
  6071. }
  6072. if ( this.faces.length > 0 ) {
  6073. this.normalsNeedUpdate = true;
  6074. }
  6075. },
  6076. computeMorphNormals: function () {
  6077. var i, il, f, fl, face;
  6078. // save original normals
  6079. // - create temp variables on first access
  6080. // otherwise just copy (for faster repeated calls)
  6081. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6082. face = this.faces[ f ];
  6083. if ( ! face.__originalFaceNormal ) {
  6084. face.__originalFaceNormal = face.normal.clone();
  6085. } else {
  6086. face.__originalFaceNormal.copy( face.normal );
  6087. }
  6088. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  6089. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  6090. if ( ! face.__originalVertexNormals[ i ] ) {
  6091. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  6092. } else {
  6093. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  6094. }
  6095. }
  6096. }
  6097. // use temp geometry to compute face and vertex normals for each morph
  6098. var tmpGeo = new THREE.Geometry();
  6099. tmpGeo.faces = this.faces;
  6100. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  6101. // create on first access
  6102. if ( ! this.morphNormals[ i ] ) {
  6103. this.morphNormals[ i ] = {};
  6104. this.morphNormals[ i ].faceNormals = [];
  6105. this.morphNormals[ i ].vertexNormals = [];
  6106. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  6107. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  6108. var faceNormal, vertexNormals;
  6109. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6110. faceNormal = new THREE.Vector3();
  6111. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  6112. dstNormalsFace.push( faceNormal );
  6113. dstNormalsVertex.push( vertexNormals );
  6114. }
  6115. }
  6116. var morphNormals = this.morphNormals[ i ];
  6117. // set vertices to morph target
  6118. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  6119. // compute morph normals
  6120. tmpGeo.computeFaceNormals();
  6121. tmpGeo.computeVertexNormals();
  6122. // store morph normals
  6123. var faceNormal, vertexNormals;
  6124. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6125. face = this.faces[ f ];
  6126. faceNormal = morphNormals.faceNormals[ f ];
  6127. vertexNormals = morphNormals.vertexNormals[ f ];
  6128. faceNormal.copy( face.normal );
  6129. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  6130. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  6131. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  6132. }
  6133. }
  6134. // restore original normals
  6135. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6136. face = this.faces[ f ];
  6137. face.normal = face.__originalFaceNormal;
  6138. face.vertexNormals = face.__originalVertexNormals;
  6139. }
  6140. },
  6141. computeTangents: function () {
  6142. console.warn( 'THREE.Geometry: .computeTangents() has been removed.' );
  6143. },
  6144. computeLineDistances: function () {
  6145. var d = 0;
  6146. var vertices = this.vertices;
  6147. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  6148. if ( i > 0 ) {
  6149. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  6150. }
  6151. this.lineDistances[ i ] = d;
  6152. }
  6153. },
  6154. computeBoundingBox: function () {
  6155. if ( this.boundingBox === null ) {
  6156. this.boundingBox = new THREE.Box3();
  6157. }
  6158. this.boundingBox.setFromPoints( this.vertices );
  6159. },
  6160. computeBoundingSphere: function () {
  6161. if ( this.boundingSphere === null ) {
  6162. this.boundingSphere = new THREE.Sphere();
  6163. }
  6164. this.boundingSphere.setFromPoints( this.vertices );
  6165. },
  6166. merge: function ( geometry, matrix, materialIndexOffset ) {
  6167. if ( geometry instanceof THREE.Geometry === false ) {
  6168. console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  6169. return;
  6170. }
  6171. var normalMatrix,
  6172. vertexOffset = this.vertices.length,
  6173. vertices1 = this.vertices,
  6174. vertices2 = geometry.vertices,
  6175. faces1 = this.faces,
  6176. faces2 = geometry.faces,
  6177. uvs1 = this.faceVertexUvs[ 0 ],
  6178. uvs2 = geometry.faceVertexUvs[ 0 ];
  6179. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  6180. if ( matrix !== undefined ) {
  6181. normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  6182. }
  6183. // vertices
  6184. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  6185. var vertex = vertices2[ i ];
  6186. var vertexCopy = vertex.clone();
  6187. if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
  6188. vertices1.push( vertexCopy );
  6189. }
  6190. // faces
  6191. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  6192. var face = faces2[ i ], faceCopy, normal, color,
  6193. faceVertexNormals = face.vertexNormals,
  6194. faceVertexColors = face.vertexColors;
  6195. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  6196. faceCopy.normal.copy( face.normal );
  6197. if ( normalMatrix !== undefined ) {
  6198. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  6199. }
  6200. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  6201. normal = faceVertexNormals[ j ].clone();
  6202. if ( normalMatrix !== undefined ) {
  6203. normal.applyMatrix3( normalMatrix ).normalize();
  6204. }
  6205. faceCopy.vertexNormals.push( normal );
  6206. }
  6207. faceCopy.color.copy( face.color );
  6208. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  6209. color = faceVertexColors[ j ];
  6210. faceCopy.vertexColors.push( color.clone() );
  6211. }
  6212. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  6213. faces1.push( faceCopy );
  6214. }
  6215. // uvs
  6216. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  6217. var uv = uvs2[ i ], uvCopy = [];
  6218. if ( uv === undefined ) {
  6219. continue;
  6220. }
  6221. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  6222. uvCopy.push( uv[ j ].clone() );
  6223. }
  6224. uvs1.push( uvCopy );
  6225. }
  6226. },
  6227. mergeMesh: function ( mesh ) {
  6228. if ( mesh instanceof THREE.Mesh === false ) {
  6229. console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
  6230. return;
  6231. }
  6232. mesh.matrixAutoUpdate && mesh.updateMatrix();
  6233. this.merge( mesh.geometry, mesh.matrix );
  6234. },
  6235. /*
  6236. * Checks for duplicate vertices with hashmap.
  6237. * Duplicated vertices are removed
  6238. * and faces' vertices are updated.
  6239. */
  6240. mergeVertices: function () {
  6241. var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  6242. var unique = [], changes = [];
  6243. var v, key;
  6244. var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
  6245. var precision = Math.pow( 10, precisionPoints );
  6246. var i, il, face;
  6247. var indices, j, jl;
  6248. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  6249. v = this.vertices[ i ];
  6250. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  6251. if ( verticesMap[ key ] === undefined ) {
  6252. verticesMap[ key ] = i;
  6253. unique.push( this.vertices[ i ] );
  6254. changes[ i ] = unique.length - 1;
  6255. } else {
  6256. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  6257. changes[ i ] = changes[ verticesMap[ key ] ];
  6258. }
  6259. }
  6260. // if faces are completely degenerate after merging vertices, we
  6261. // have to remove them from the geometry.
  6262. var faceIndicesToRemove = [];
  6263. for ( i = 0, il = this.faces.length; i < il; i ++ ) {
  6264. face = this.faces[ i ];
  6265. face.a = changes[ face.a ];
  6266. face.b = changes[ face.b ];
  6267. face.c = changes[ face.c ];
  6268. indices = [ face.a, face.b, face.c ];
  6269. var dupIndex = - 1;
  6270. // if any duplicate vertices are found in a Face3
  6271. // we have to remove the face as nothing can be saved
  6272. for ( var n = 0; n < 3; n ++ ) {
  6273. if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) {
  6274. dupIndex = n;
  6275. faceIndicesToRemove.push( i );
  6276. break;
  6277. }
  6278. }
  6279. }
  6280. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  6281. var idx = faceIndicesToRemove[ i ];
  6282. this.faces.splice( idx, 1 );
  6283. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  6284. this.faceVertexUvs[ j ].splice( idx, 1 );
  6285. }
  6286. }
  6287. // Use unique set of vertices
  6288. var diff = this.vertices.length - unique.length;
  6289. this.vertices = unique;
  6290. return diff;
  6291. },
  6292. sortFacesByMaterialIndex: function () {
  6293. var faces = this.faces;
  6294. var length = faces.length;
  6295. // tag faces
  6296. for ( var i = 0; i < length; i ++ ) {
  6297. faces[ i ]._id = i;
  6298. }
  6299. // sort faces
  6300. function materialIndexSort( a, b ) {
  6301. return a.materialIndex - b.materialIndex;
  6302. }
  6303. faces.sort( materialIndexSort );
  6304. // sort uvs
  6305. var uvs1 = this.faceVertexUvs[ 0 ];
  6306. var uvs2 = this.faceVertexUvs[ 1 ];
  6307. var newUvs1, newUvs2;
  6308. if ( uvs1 && uvs1.length === length ) newUvs1 = [];
  6309. if ( uvs2 && uvs2.length === length ) newUvs2 = [];
  6310. for ( var i = 0; i < length; i ++ ) {
  6311. var id = faces[ i ]._id;
  6312. if ( newUvs1 ) newUvs1.push( uvs1[ id ] );
  6313. if ( newUvs2 ) newUvs2.push( uvs2[ id ] );
  6314. }
  6315. if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1;
  6316. if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2;
  6317. },
  6318. toJSON: function () {
  6319. var data = {
  6320. metadata: {
  6321. version: 4.4,
  6322. type: 'Geometry',
  6323. generator: 'Geometry.toJSON'
  6324. }
  6325. };
  6326. // standard Geometry serialization
  6327. data.uuid = this.uuid;
  6328. data.type = this.type;
  6329. if ( this.name !== '' ) data.name = this.name;
  6330. if ( this.parameters !== undefined ) {
  6331. var parameters = this.parameters;
  6332. for ( var key in parameters ) {
  6333. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6334. }
  6335. return data;
  6336. }
  6337. var vertices = [];
  6338. for ( var i = 0; i < this.vertices.length; i ++ ) {
  6339. var vertex = this.vertices[ i ];
  6340. vertices.push( vertex.x, vertex.y, vertex.z );
  6341. }
  6342. var faces = [];
  6343. var normals = [];
  6344. var normalsHash = {};
  6345. var colors = [];
  6346. var colorsHash = {};
  6347. var uvs = [];
  6348. var uvsHash = {};
  6349. for ( var i = 0; i < this.faces.length; i ++ ) {
  6350. var face = this.faces[ i ];
  6351. var hasMaterial = true;
  6352. var hasFaceUv = false; // deprecated
  6353. var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined;
  6354. var hasFaceNormal = face.normal.length() > 0;
  6355. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  6356. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  6357. var hasFaceVertexColor = face.vertexColors.length > 0;
  6358. var faceType = 0;
  6359. faceType = setBit( faceType, 0, 0 ); // isQuad
  6360. faceType = setBit( faceType, 1, hasMaterial );
  6361. faceType = setBit( faceType, 2, hasFaceUv );
  6362. faceType = setBit( faceType, 3, hasFaceVertexUv );
  6363. faceType = setBit( faceType, 4, hasFaceNormal );
  6364. faceType = setBit( faceType, 5, hasFaceVertexNormal );
  6365. faceType = setBit( faceType, 6, hasFaceColor );
  6366. faceType = setBit( faceType, 7, hasFaceVertexColor );
  6367. faces.push( faceType );
  6368. faces.push( face.a, face.b, face.c );
  6369. faces.push( face.materialIndex );
  6370. if ( hasFaceVertexUv ) {
  6371. var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ];
  6372. faces.push(
  6373. getUvIndex( faceVertexUvs[ 0 ] ),
  6374. getUvIndex( faceVertexUvs[ 1 ] ),
  6375. getUvIndex( faceVertexUvs[ 2 ] )
  6376. );
  6377. }
  6378. if ( hasFaceNormal ) {
  6379. faces.push( getNormalIndex( face.normal ) );
  6380. }
  6381. if ( hasFaceVertexNormal ) {
  6382. var vertexNormals = face.vertexNormals;
  6383. faces.push(
  6384. getNormalIndex( vertexNormals[ 0 ] ),
  6385. getNormalIndex( vertexNormals[ 1 ] ),
  6386. getNormalIndex( vertexNormals[ 2 ] )
  6387. );
  6388. }
  6389. if ( hasFaceColor ) {
  6390. faces.push( getColorIndex( face.color ) );
  6391. }
  6392. if ( hasFaceVertexColor ) {
  6393. var vertexColors = face.vertexColors;
  6394. faces.push(
  6395. getColorIndex( vertexColors[ 0 ] ),
  6396. getColorIndex( vertexColors[ 1 ] ),
  6397. getColorIndex( vertexColors[ 2 ] )
  6398. );
  6399. }
  6400. }
  6401. function setBit( value, position, enabled ) {
  6402. return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) );
  6403. }
  6404. function getNormalIndex( normal ) {
  6405. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  6406. if ( normalsHash[ hash ] !== undefined ) {
  6407. return normalsHash[ hash ];
  6408. }
  6409. normalsHash[ hash ] = normals.length / 3;
  6410. normals.push( normal.x, normal.y, normal.z );
  6411. return normalsHash[ hash ];
  6412. }
  6413. function getColorIndex( color ) {
  6414. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  6415. if ( colorsHash[ hash ] !== undefined ) {
  6416. return colorsHash[ hash ];
  6417. }
  6418. colorsHash[ hash ] = colors.length;
  6419. colors.push( color.getHex() );
  6420. return colorsHash[ hash ];
  6421. }
  6422. function getUvIndex( uv ) {
  6423. var hash = uv.x.toString() + uv.y.toString();
  6424. if ( uvsHash[ hash ] !== undefined ) {
  6425. return uvsHash[ hash ];
  6426. }
  6427. uvsHash[ hash ] = uvs.length / 2;
  6428. uvs.push( uv.x, uv.y );
  6429. return uvsHash[ hash ];
  6430. }
  6431. data.data = {};
  6432. data.data.vertices = vertices;
  6433. data.data.normals = normals;
  6434. if ( colors.length > 0 ) data.data.colors = colors;
  6435. if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility
  6436. data.data.faces = faces;
  6437. return data;
  6438. },
  6439. clone: function () {
  6440. /*
  6441. // Handle primitives
  6442. var parameters = this.parameters;
  6443. if ( parameters !== undefined ) {
  6444. var values = [];
  6445. for ( var key in parameters ) {
  6446. values.push( parameters[ key ] );
  6447. }
  6448. var geometry = Object.create( this.constructor.prototype );
  6449. this.constructor.apply( geometry, values );
  6450. return geometry;
  6451. }
  6452. return new this.constructor().copy( this );
  6453. */
  6454. return new THREE.Geometry().copy( this );
  6455. },
  6456. copy: function ( source ) {
  6457. this.vertices = [];
  6458. this.faces = [];
  6459. this.faceVertexUvs = [ [] ];
  6460. var vertices = source.vertices;
  6461. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  6462. this.vertices.push( vertices[ i ].clone() );
  6463. }
  6464. var faces = source.faces;
  6465. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  6466. this.faces.push( faces[ i ].clone() );
  6467. }
  6468. for ( var i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) {
  6469. var faceVertexUvs = source.faceVertexUvs[ i ];
  6470. if ( this.faceVertexUvs[ i ] === undefined ) {
  6471. this.faceVertexUvs[ i ] = [];
  6472. }
  6473. for ( var j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {
  6474. var uvs = faceVertexUvs[ j ], uvsCopy = [];
  6475. for ( var k = 0, kl = uvs.length; k < kl; k ++ ) {
  6476. var uv = uvs[ k ];
  6477. uvsCopy.push( uv.clone() );
  6478. }
  6479. this.faceVertexUvs[ i ].push( uvsCopy );
  6480. }
  6481. }
  6482. return this;
  6483. },
  6484. dispose: function () {
  6485. this.dispatchEvent( { type: 'dispose' } );
  6486. }
  6487. };
  6488. THREE.EventDispatcher.prototype.apply( THREE.Geometry.prototype );
  6489. THREE.GeometryIdCount = 0;
  6490. // File:src/core/DirectGeometry.js
  6491. /**
  6492. * @author mrdoob / http://mrdoob.com/
  6493. */
  6494. THREE.DirectGeometry = function () {
  6495. Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } );
  6496. this.uuid = THREE.Math.generateUUID();
  6497. this.name = '';
  6498. this.type = 'DirectGeometry';
  6499. this.indices = [];
  6500. this.vertices = [];
  6501. this.normals = [];
  6502. this.colors = [];
  6503. this.uvs = [];
  6504. this.uvs2 = [];
  6505. this.groups = [];
  6506. this.morphTargets = {};
  6507. this.skinWeights = [];
  6508. this.skinIndices = [];
  6509. // this.lineDistances = [];
  6510. this.boundingBox = null;
  6511. this.boundingSphere = null;
  6512. // update flags
  6513. this.verticesNeedUpdate = false;
  6514. this.normalsNeedUpdate = false;
  6515. this.colorsNeedUpdate = false;
  6516. this.uvsNeedUpdate = false;
  6517. this.groupsNeedUpdate = false;
  6518. };
  6519. THREE.DirectGeometry.prototype = {
  6520. constructor: THREE.DirectGeometry,
  6521. computeBoundingBox: THREE.Geometry.prototype.computeBoundingBox,
  6522. computeBoundingSphere: THREE.Geometry.prototype.computeBoundingSphere,
  6523. computeFaceNormals: function () {
  6524. console.warn( 'THREE.DirectGeometry: computeFaceNormals() is not a method of this type of geometry.' );
  6525. },
  6526. computeVertexNormals: function () {
  6527. console.warn( 'THREE.DirectGeometry: computeVertexNormals() is not a method of this type of geometry.' );
  6528. },
  6529. computeGroups: function ( geometry ) {
  6530. var group;
  6531. var groups = [];
  6532. var materialIndex;
  6533. var faces = geometry.faces;
  6534. for ( var i = 0; i < faces.length; i ++ ) {
  6535. var face = faces[ i ];
  6536. // materials
  6537. if ( face.materialIndex !== materialIndex ) {
  6538. materialIndex = face.materialIndex;
  6539. if ( group !== undefined ) {
  6540. group.count = ( i * 3 ) - group.start;
  6541. groups.push( group );
  6542. }
  6543. group = {
  6544. start: i * 3,
  6545. materialIndex: materialIndex
  6546. };
  6547. }
  6548. }
  6549. if ( group !== undefined ) {
  6550. group.count = ( i * 3 ) - group.start;
  6551. groups.push( group );
  6552. }
  6553. this.groups = groups;
  6554. },
  6555. fromGeometry: function ( geometry ) {
  6556. var faces = geometry.faces;
  6557. var vertices = geometry.vertices;
  6558. var faceVertexUvs = geometry.faceVertexUvs;
  6559. var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0;
  6560. var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0;
  6561. // morphs
  6562. var morphTargets = geometry.morphTargets;
  6563. var morphTargetsLength = morphTargets.length;
  6564. var morphTargetsPosition;
  6565. if ( morphTargetsLength > 0 ) {
  6566. morphTargetsPosition = [];
  6567. for ( var i = 0; i < morphTargetsLength; i ++ ) {
  6568. morphTargetsPosition[ i ] = [];
  6569. }
  6570. this.morphTargets.position = morphTargetsPosition;
  6571. }
  6572. var morphNormals = geometry.morphNormals;
  6573. var morphNormalsLength = morphNormals.length;
  6574. var morphTargetsNormal;
  6575. if ( morphNormalsLength > 0 ) {
  6576. morphTargetsNormal = [];
  6577. for ( var i = 0; i < morphNormalsLength; i ++ ) {
  6578. morphTargetsNormal[ i ] = [];
  6579. }
  6580. this.morphTargets.normal = morphTargetsNormal;
  6581. }
  6582. // skins
  6583. var skinIndices = geometry.skinIndices;
  6584. var skinWeights = geometry.skinWeights;
  6585. var hasSkinIndices = skinIndices.length === vertices.length;
  6586. var hasSkinWeights = skinWeights.length === vertices.length;
  6587. //
  6588. for ( var i = 0; i < faces.length; i ++ ) {
  6589. var face = faces[ i ];
  6590. this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] );
  6591. var vertexNormals = face.vertexNormals;
  6592. if ( vertexNormals.length === 3 ) {
  6593. this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] );
  6594. } else {
  6595. var normal = face.normal;
  6596. this.normals.push( normal, normal, normal );
  6597. }
  6598. var vertexColors = face.vertexColors;
  6599. if ( vertexColors.length === 3 ) {
  6600. this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] );
  6601. } else {
  6602. var color = face.color;
  6603. this.colors.push( color, color, color );
  6604. }
  6605. if ( hasFaceVertexUv === true ) {
  6606. var vertexUvs = faceVertexUvs[ 0 ][ i ];
  6607. if ( vertexUvs !== undefined ) {
  6608. this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  6609. } else {
  6610. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i );
  6611. this.uvs.push( new THREE.Vector2(), new THREE.Vector2(), new THREE.Vector2() );
  6612. }
  6613. }
  6614. if ( hasFaceVertexUv2 === true ) {
  6615. var vertexUvs = faceVertexUvs[ 1 ][ i ];
  6616. if ( vertexUvs !== undefined ) {
  6617. this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  6618. } else {
  6619. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i );
  6620. this.uvs2.push( new THREE.Vector2(), new THREE.Vector2(), new THREE.Vector2() );
  6621. }
  6622. }
  6623. // morphs
  6624. for ( var j = 0; j < morphTargetsLength; j ++ ) {
  6625. var morphTarget = morphTargets[ j ].vertices;
  6626. morphTargetsPosition[ j ].push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] );
  6627. }
  6628. for ( var j = 0; j < morphNormalsLength; j ++ ) {
  6629. var morphNormal = morphNormals[ j ].vertexNormals[ i ];
  6630. morphTargetsNormal[ j ].push( morphNormal.a, morphNormal.b, morphNormal.c );
  6631. }
  6632. // skins
  6633. if ( hasSkinIndices ) {
  6634. this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] );
  6635. }
  6636. if ( hasSkinWeights ) {
  6637. this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] );
  6638. }
  6639. }
  6640. this.computeGroups( geometry );
  6641. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  6642. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  6643. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  6644. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  6645. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  6646. return this;
  6647. },
  6648. dispose: function () {
  6649. this.dispatchEvent( { type: 'dispose' } );
  6650. }
  6651. };
  6652. THREE.EventDispatcher.prototype.apply( THREE.DirectGeometry.prototype );
  6653. // File:src/core/BufferGeometry.js
  6654. /**
  6655. * @author alteredq / http://alteredqualia.com/
  6656. * @author mrdoob / http://mrdoob.com/
  6657. */
  6658. THREE.BufferGeometry = function () {
  6659. Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } );
  6660. this.uuid = THREE.Math.generateUUID();
  6661. this.name = '';
  6662. this.type = 'BufferGeometry';
  6663. this.index = null;
  6664. this.attributes = {};
  6665. this.morphAttributes = {};
  6666. this.groups = [];
  6667. this.boundingBox = null;
  6668. this.boundingSphere = null;
  6669. this.drawRange = { start: 0, count: Infinity };
  6670. };
  6671. THREE.BufferGeometry.prototype = {
  6672. constructor: THREE.BufferGeometry,
  6673. getIndex: function () {
  6674. return this.index;
  6675. },
  6676. setIndex: function ( index ) {
  6677. this.index = index;
  6678. },
  6679. addAttribute: function ( name, attribute ) {
  6680. if ( attribute instanceof THREE.BufferAttribute === false && attribute instanceof THREE.InterleavedBufferAttribute === false ) {
  6681. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  6682. this.addAttribute( name, new THREE.BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  6683. return;
  6684. }
  6685. if ( name === 'index' ) {
  6686. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  6687. this.setIndex( attribute );
  6688. return;
  6689. }
  6690. this.attributes[ name ] = attribute;
  6691. return this;
  6692. },
  6693. getAttribute: function ( name ) {
  6694. return this.attributes[ name ];
  6695. },
  6696. removeAttribute: function ( name ) {
  6697. delete this.attributes[ name ];
  6698. return this;
  6699. },
  6700. addGroup: function ( start, count, materialIndex ) {
  6701. this.groups.push( {
  6702. start: start,
  6703. count: count,
  6704. materialIndex: materialIndex !== undefined ? materialIndex : 0
  6705. } );
  6706. },
  6707. clearGroups: function () {
  6708. this.groups = [];
  6709. },
  6710. setDrawRange: function ( start, count ) {
  6711. this.drawRange.start = start;
  6712. this.drawRange.count = count;
  6713. },
  6714. applyMatrix: function ( matrix ) {
  6715. var position = this.attributes.position;
  6716. if ( position !== undefined ) {
  6717. matrix.applyToVector3Array( position.array );
  6718. position.needsUpdate = true;
  6719. }
  6720. var normal = this.attributes.normal;
  6721. if ( normal !== undefined ) {
  6722. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  6723. normalMatrix.applyToVector3Array( normal.array );
  6724. normal.needsUpdate = true;
  6725. }
  6726. if ( this.boundingBox !== null ) {
  6727. this.computeBoundingBox();
  6728. }
  6729. if ( this.boundingSphere !== null ) {
  6730. this.computeBoundingSphere();
  6731. }
  6732. return this;
  6733. },
  6734. rotateX: function () {
  6735. // rotate geometry around world x-axis
  6736. var m1;
  6737. return function rotateX( angle ) {
  6738. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  6739. m1.makeRotationX( angle );
  6740. this.applyMatrix( m1 );
  6741. return this;
  6742. };
  6743. }(),
  6744. rotateY: function () {
  6745. // rotate geometry around world y-axis
  6746. var m1;
  6747. return function rotateY( angle ) {
  6748. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  6749. m1.makeRotationY( angle );
  6750. this.applyMatrix( m1 );
  6751. return this;
  6752. };
  6753. }(),
  6754. rotateZ: function () {
  6755. // rotate geometry around world z-axis
  6756. var m1;
  6757. return function rotateZ( angle ) {
  6758. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  6759. m1.makeRotationZ( angle );
  6760. this.applyMatrix( m1 );
  6761. return this;
  6762. };
  6763. }(),
  6764. translate: function () {
  6765. // translate geometry
  6766. var m1;
  6767. return function translate( x, y, z ) {
  6768. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  6769. m1.makeTranslation( x, y, z );
  6770. this.applyMatrix( m1 );
  6771. return this;
  6772. };
  6773. }(),
  6774. scale: function () {
  6775. // scale geometry
  6776. var m1;
  6777. return function scale( x, y, z ) {
  6778. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  6779. m1.makeScale( x, y, z );
  6780. this.applyMatrix( m1 );
  6781. return this;
  6782. };
  6783. }(),
  6784. lookAt: function () {
  6785. var obj;
  6786. return function lookAt( vector ) {
  6787. if ( obj === undefined ) obj = new THREE.Object3D();
  6788. obj.lookAt( vector );
  6789. obj.updateMatrix();
  6790. this.applyMatrix( obj.matrix );
  6791. };
  6792. }(),
  6793. center: function () {
  6794. this.computeBoundingBox();
  6795. var offset = this.boundingBox.center().negate();
  6796. this.translate( offset.x, offset.y, offset.z );
  6797. return offset;
  6798. },
  6799. setFromObject: function ( object ) {
  6800. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  6801. var geometry = object.geometry;
  6802. if ( object instanceof THREE.Points || object instanceof THREE.Line ) {
  6803. var positions = new THREE.Float32Attribute( geometry.vertices.length * 3, 3 );
  6804. var colors = new THREE.Float32Attribute( geometry.colors.length * 3, 3 );
  6805. this.addAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) );
  6806. this.addAttribute( 'color', colors.copyColorsArray( geometry.colors ) );
  6807. if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) {
  6808. var lineDistances = new THREE.Float32Attribute( geometry.lineDistances.length, 1 );
  6809. this.addAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) );
  6810. }
  6811. if ( geometry.boundingSphere !== null ) {
  6812. this.boundingSphere = geometry.boundingSphere.clone();
  6813. }
  6814. if ( geometry.boundingBox !== null ) {
  6815. this.boundingBox = geometry.boundingBox.clone();
  6816. }
  6817. } else if ( object instanceof THREE.Mesh ) {
  6818. if ( geometry instanceof THREE.Geometry ) {
  6819. this.fromGeometry( geometry );
  6820. }
  6821. }
  6822. return this;
  6823. },
  6824. updateFromObject: function ( object ) {
  6825. var geometry = object.geometry;
  6826. if ( object instanceof THREE.Mesh ) {
  6827. var direct = geometry.__directGeometry;
  6828. if ( direct === undefined ) {
  6829. return this.fromGeometry( geometry );
  6830. }
  6831. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  6832. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  6833. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  6834. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  6835. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  6836. geometry.verticesNeedUpdate = false;
  6837. geometry.normalsNeedUpdate = false;
  6838. geometry.colorsNeedUpdate = false;
  6839. geometry.uvsNeedUpdate = false;
  6840. geometry.groupsNeedUpdate = false;
  6841. geometry = direct;
  6842. }
  6843. if ( geometry.verticesNeedUpdate === true ) {
  6844. var attribute = this.attributes.position;
  6845. if ( attribute !== undefined ) {
  6846. attribute.copyVector3sArray( geometry.vertices );
  6847. attribute.needsUpdate = true;
  6848. }
  6849. geometry.verticesNeedUpdate = false;
  6850. }
  6851. if ( geometry.normalsNeedUpdate === true ) {
  6852. var attribute = this.attributes.normal;
  6853. if ( attribute !== undefined ) {
  6854. attribute.copyVector3sArray( geometry.normals );
  6855. attribute.needsUpdate = true;
  6856. }
  6857. geometry.normalsNeedUpdate = false;
  6858. }
  6859. if ( geometry.colorsNeedUpdate === true ) {
  6860. var attribute = this.attributes.color;
  6861. if ( attribute !== undefined ) {
  6862. attribute.copyColorsArray( geometry.colors );
  6863. attribute.needsUpdate = true;
  6864. }
  6865. geometry.colorsNeedUpdate = false;
  6866. }
  6867. if ( geometry.uvsNeedUpdate ) {
  6868. var attribute = this.attributes.uv;
  6869. if ( attribute !== undefined ) {
  6870. attribute.copyVector2sArray( geometry.uvs );
  6871. attribute.needsUpdate = true;
  6872. }
  6873. geometry.uvsNeedUpdate = false;
  6874. }
  6875. if ( geometry.lineDistancesNeedUpdate ) {
  6876. var attribute = this.attributes.lineDistance;
  6877. if ( attribute !== undefined ) {
  6878. attribute.copyArray( geometry.lineDistances );
  6879. attribute.needsUpdate = true;
  6880. }
  6881. geometry.lineDistancesNeedUpdate = false;
  6882. }
  6883. if ( geometry.groupsNeedUpdate ) {
  6884. geometry.computeGroups( object.geometry );
  6885. this.groups = geometry.groups;
  6886. geometry.groupsNeedUpdate = false;
  6887. }
  6888. return this;
  6889. },
  6890. fromGeometry: function ( geometry ) {
  6891. geometry.__directGeometry = new THREE.DirectGeometry().fromGeometry( geometry );
  6892. return this.fromDirectGeometry( geometry.__directGeometry );
  6893. },
  6894. fromDirectGeometry: function ( geometry ) {
  6895. var positions = new Float32Array( geometry.vertices.length * 3 );
  6896. this.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) );
  6897. if ( geometry.normals.length > 0 ) {
  6898. var normals = new Float32Array( geometry.normals.length * 3 );
  6899. this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) );
  6900. }
  6901. if ( geometry.colors.length > 0 ) {
  6902. var colors = new Float32Array( geometry.colors.length * 3 );
  6903. this.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) );
  6904. }
  6905. if ( geometry.uvs.length > 0 ) {
  6906. var uvs = new Float32Array( geometry.uvs.length * 2 );
  6907. this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) );
  6908. }
  6909. if ( geometry.uvs2.length > 0 ) {
  6910. var uvs2 = new Float32Array( geometry.uvs2.length * 2 );
  6911. this.addAttribute( 'uv2', new THREE.BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) );
  6912. }
  6913. if ( geometry.indices.length > 0 ) {
  6914. var TypeArray = geometry.vertices.length > 65535 ? Uint32Array : Uint16Array;
  6915. var indices = new TypeArray( geometry.indices.length * 3 );
  6916. this.setIndex( new THREE.BufferAttribute( indices, 1 ).copyIndicesArray( geometry.indices ) );
  6917. }
  6918. // groups
  6919. this.groups = geometry.groups;
  6920. // morphs
  6921. for ( var name in geometry.morphTargets ) {
  6922. var array = [];
  6923. var morphTargets = geometry.morphTargets[ name ];
  6924. for ( var i = 0, l = morphTargets.length; i < l; i ++ ) {
  6925. var morphTarget = morphTargets[ i ];
  6926. var attribute = new THREE.Float32Attribute( morphTarget.length * 3, 3 );
  6927. array.push( attribute.copyVector3sArray( morphTarget ) );
  6928. }
  6929. this.morphAttributes[ name ] = array;
  6930. }
  6931. // skinning
  6932. if ( geometry.skinIndices.length > 0 ) {
  6933. var skinIndices = new THREE.Float32Attribute( geometry.skinIndices.length * 4, 4 );
  6934. this.addAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) );
  6935. }
  6936. if ( geometry.skinWeights.length > 0 ) {
  6937. var skinWeights = new THREE.Float32Attribute( geometry.skinWeights.length * 4, 4 );
  6938. this.addAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) );
  6939. }
  6940. //
  6941. if ( geometry.boundingSphere !== null ) {
  6942. this.boundingSphere = geometry.boundingSphere.clone();
  6943. }
  6944. if ( geometry.boundingBox !== null ) {
  6945. this.boundingBox = geometry.boundingBox.clone();
  6946. }
  6947. return this;
  6948. },
  6949. computeBoundingBox: function () {
  6950. var vector = new THREE.Vector3();
  6951. return function () {
  6952. if ( this.boundingBox === null ) {
  6953. this.boundingBox = new THREE.Box3();
  6954. }
  6955. var positions = this.attributes.position.array;
  6956. if ( positions ) {
  6957. this.boundingBox.setFromArray( positions );
  6958. }
  6959. if ( positions === undefined || positions.length === 0 ) {
  6960. this.boundingBox.min.set( 0, 0, 0 );
  6961. this.boundingBox.max.set( 0, 0, 0 );
  6962. }
  6963. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  6964. console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6965. }
  6966. };
  6967. }(),
  6968. computeBoundingSphere: function () {
  6969. var box = new THREE.Box3();
  6970. var vector = new THREE.Vector3();
  6971. return function () {
  6972. if ( this.boundingSphere === null ) {
  6973. this.boundingSphere = new THREE.Sphere();
  6974. }
  6975. var positions = this.attributes.position.array;
  6976. if ( positions ) {
  6977. var center = this.boundingSphere.center;
  6978. box.setFromArray( positions );
  6979. box.center( center );
  6980. // hoping to find a boundingSphere with a radius smaller than the
  6981. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6982. var maxRadiusSq = 0;
  6983. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  6984. vector.fromArray( positions, i );
  6985. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  6986. }
  6987. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6988. if ( isNaN( this.boundingSphere.radius ) ) {
  6989. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6990. }
  6991. }
  6992. };
  6993. }(),
  6994. computeFaceNormals: function () {
  6995. // backwards compatibility
  6996. },
  6997. computeVertexNormals: function () {
  6998. var index = this.index;
  6999. var attributes = this.attributes;
  7000. var groups = this.groups;
  7001. if ( attributes.position ) {
  7002. var positions = attributes.position.array;
  7003. if ( attributes.normal === undefined ) {
  7004. this.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( positions.length ), 3 ) );
  7005. } else {
  7006. // reset existing normals to zero
  7007. var array = attributes.normal.array;
  7008. for ( var i = 0, il = array.length; i < il; i ++ ) {
  7009. array[ i ] = 0;
  7010. }
  7011. }
  7012. var normals = attributes.normal.array;
  7013. var vA, vB, vC,
  7014. pA = new THREE.Vector3(),
  7015. pB = new THREE.Vector3(),
  7016. pC = new THREE.Vector3(),
  7017. cb = new THREE.Vector3(),
  7018. ab = new THREE.Vector3();
  7019. // indexed elements
  7020. if ( index ) {
  7021. var indices = index.array;
  7022. if ( groups.length === 0 ) {
  7023. this.addGroup( 0, indices.length );
  7024. }
  7025. for ( var j = 0, jl = groups.length; j < jl; ++ j ) {
  7026. var group = groups[ j ];
  7027. var start = group.start;
  7028. var count = group.count;
  7029. for ( var i = start, il = start + count; i < il; i += 3 ) {
  7030. vA = indices[ i + 0 ] * 3;
  7031. vB = indices[ i + 1 ] * 3;
  7032. vC = indices[ i + 2 ] * 3;
  7033. pA.fromArray( positions, vA );
  7034. pB.fromArray( positions, vB );
  7035. pC.fromArray( positions, vC );
  7036. cb.subVectors( pC, pB );
  7037. ab.subVectors( pA, pB );
  7038. cb.cross( ab );
  7039. normals[ vA ] += cb.x;
  7040. normals[ vA + 1 ] += cb.y;
  7041. normals[ vA + 2 ] += cb.z;
  7042. normals[ vB ] += cb.x;
  7043. normals[ vB + 1 ] += cb.y;
  7044. normals[ vB + 2 ] += cb.z;
  7045. normals[ vC ] += cb.x;
  7046. normals[ vC + 1 ] += cb.y;
  7047. normals[ vC + 2 ] += cb.z;
  7048. }
  7049. }
  7050. } else {
  7051. // non-indexed elements (unconnected triangle soup)
  7052. for ( var i = 0, il = positions.length; i < il; i += 9 ) {
  7053. pA.fromArray( positions, i );
  7054. pB.fromArray( positions, i + 3 );
  7055. pC.fromArray( positions, i + 6 );
  7056. cb.subVectors( pC, pB );
  7057. ab.subVectors( pA, pB );
  7058. cb.cross( ab );
  7059. normals[ i ] = cb.x;
  7060. normals[ i + 1 ] = cb.y;
  7061. normals[ i + 2 ] = cb.z;
  7062. normals[ i + 3 ] = cb.x;
  7063. normals[ i + 4 ] = cb.y;
  7064. normals[ i + 5 ] = cb.z;
  7065. normals[ i + 6 ] = cb.x;
  7066. normals[ i + 7 ] = cb.y;
  7067. normals[ i + 8 ] = cb.z;
  7068. }
  7069. }
  7070. this.normalizeNormals();
  7071. attributes.normal.needsUpdate = true;
  7072. }
  7073. },
  7074. merge: function ( geometry, offset ) {
  7075. if ( geometry instanceof THREE.BufferGeometry === false ) {
  7076. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  7077. return;
  7078. }
  7079. if ( offset === undefined ) offset = 0;
  7080. var attributes = this.attributes;
  7081. for ( var key in attributes ) {
  7082. if ( geometry.attributes[ key ] === undefined ) continue;
  7083. var attribute1 = attributes[ key ];
  7084. var attributeArray1 = attribute1.array;
  7085. var attribute2 = geometry.attributes[ key ];
  7086. var attributeArray2 = attribute2.array;
  7087. var attributeSize = attribute2.itemSize;
  7088. for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) {
  7089. attributeArray1[ j ] = attributeArray2[ i ];
  7090. }
  7091. }
  7092. return this;
  7093. },
  7094. normalizeNormals: function () {
  7095. var normals = this.attributes.normal.array;
  7096. var x, y, z, n;
  7097. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  7098. x = normals[ i ];
  7099. y = normals[ i + 1 ];
  7100. z = normals[ i + 2 ];
  7101. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  7102. normals[ i ] *= n;
  7103. normals[ i + 1 ] *= n;
  7104. normals[ i + 2 ] *= n;
  7105. }
  7106. },
  7107. toNonIndexed: function () {
  7108. if ( this.index === null ) {
  7109. console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' );
  7110. return this;
  7111. }
  7112. var geometry2 = new THREE.BufferGeometry();
  7113. var indices = this.index.array;
  7114. var attributes = this.attributes;
  7115. for ( var name in attributes ) {
  7116. var attribute = attributes[ name ];
  7117. var array = attribute.array;
  7118. var itemSize = attribute.itemSize;
  7119. var array2 = new array.constructor( indices.length * itemSize );
  7120. var index = 0, index2 = 0;
  7121. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  7122. index = indices[ i ] * itemSize;
  7123. for ( var j = 0; j < itemSize; j ++ ) {
  7124. array2[ index2 ++ ] = array[ index ++ ];
  7125. }
  7126. }
  7127. geometry2.addAttribute( name, new THREE.BufferAttribute( array2, itemSize ) );
  7128. }
  7129. return geometry2;
  7130. },
  7131. toJSON: function () {
  7132. var data = {
  7133. metadata: {
  7134. version: 4.4,
  7135. type: 'BufferGeometry',
  7136. generator: 'BufferGeometry.toJSON'
  7137. }
  7138. };
  7139. // standard BufferGeometry serialization
  7140. data.uuid = this.uuid;
  7141. data.type = this.type;
  7142. if ( this.name !== '' ) data.name = this.name;
  7143. if ( this.parameters !== undefined ) {
  7144. var parameters = this.parameters;
  7145. for ( var key in parameters ) {
  7146. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  7147. }
  7148. return data;
  7149. }
  7150. data.data = { attributes: {} };
  7151. var index = this.index;
  7152. if ( index !== null ) {
  7153. var array = Array.prototype.slice.call( index.array );
  7154. data.data.index = {
  7155. type: index.array.constructor.name,
  7156. array: array
  7157. };
  7158. }
  7159. var attributes = this.attributes;
  7160. for ( var key in attributes ) {
  7161. var attribute = attributes[ key ];
  7162. var array = Array.prototype.slice.call( attribute.array );
  7163. data.data.attributes[ key ] = {
  7164. itemSize: attribute.itemSize,
  7165. type: attribute.array.constructor.name,
  7166. array: array
  7167. };
  7168. }
  7169. var groups = this.groups;
  7170. if ( groups.length > 0 ) {
  7171. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  7172. }
  7173. var boundingSphere = this.boundingSphere;
  7174. if ( boundingSphere !== null ) {
  7175. data.data.boundingSphere = {
  7176. center: boundingSphere.center.toArray(),
  7177. radius: boundingSphere.radius
  7178. };
  7179. }
  7180. return data;
  7181. },
  7182. clone: function () {
  7183. /*
  7184. // Handle primitives
  7185. var parameters = this.parameters;
  7186. if ( parameters !== undefined ) {
  7187. var values = [];
  7188. for ( var key in parameters ) {
  7189. values.push( parameters[ key ] );
  7190. }
  7191. var geometry = Object.create( this.constructor.prototype );
  7192. this.constructor.apply( geometry, values );
  7193. return geometry;
  7194. }
  7195. return new this.constructor().copy( this );
  7196. */
  7197. return new THREE.BufferGeometry().copy( this );
  7198. },
  7199. copy: function ( source ) {
  7200. var index = source.index;
  7201. if ( index !== null ) {
  7202. this.setIndex( index.clone() );
  7203. }
  7204. var attributes = source.attributes;
  7205. for ( var name in attributes ) {
  7206. var attribute = attributes[ name ];
  7207. this.addAttribute( name, attribute.clone() );
  7208. }
  7209. var groups = source.groups;
  7210. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  7211. var group = groups[ i ];
  7212. this.addGroup( group.start, group.count );
  7213. }
  7214. return this;
  7215. },
  7216. dispose: function () {
  7217. this.dispatchEvent( { type: 'dispose' } );
  7218. }
  7219. };
  7220. THREE.EventDispatcher.prototype.apply( THREE.BufferGeometry.prototype );
  7221. THREE.BufferGeometry.MaxIndex = 65535;
  7222. // File:src/core/InstancedBufferGeometry.js
  7223. /**
  7224. * @author benaadams / https://twitter.com/ben_a_adams
  7225. */
  7226. THREE.InstancedBufferGeometry = function () {
  7227. THREE.BufferGeometry.call( this );
  7228. this.type = 'InstancedBufferGeometry';
  7229. this.maxInstancedCount = undefined;
  7230. };
  7231. THREE.InstancedBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  7232. THREE.InstancedBufferGeometry.prototype.constructor = THREE.InstancedBufferGeometry;
  7233. THREE.InstancedBufferGeometry.prototype.addGroup = function ( start, count, instances ) {
  7234. this.groups.push( {
  7235. start: start,
  7236. count: count,
  7237. instances: instances
  7238. } );
  7239. };
  7240. THREE.InstancedBufferGeometry.prototype.copy = function ( source ) {
  7241. var index = source.index;
  7242. if ( index !== null ) {
  7243. this.setIndex( index.clone() );
  7244. }
  7245. var attributes = source.attributes;
  7246. for ( var name in attributes ) {
  7247. var attribute = attributes[ name ];
  7248. this.addAttribute( name, attribute.clone() );
  7249. }
  7250. var groups = source.groups;
  7251. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  7252. var group = groups[ i ];
  7253. this.addGroup( group.start, group.count, group.instances );
  7254. }
  7255. return this;
  7256. };
  7257. THREE.EventDispatcher.prototype.apply( THREE.InstancedBufferGeometry.prototype );
  7258. // File:src/core/Uniform.js
  7259. /**
  7260. * @author mrdoob / http://mrdoob.com/
  7261. */
  7262. THREE.Uniform = function ( type, value ) {
  7263. this.type = type;
  7264. this.value = value;
  7265. this.dynamic = false;
  7266. };
  7267. THREE.Uniform.prototype = {
  7268. constructor: THREE.Uniform,
  7269. onUpdate: function ( callback ) {
  7270. this.dynamic = true;
  7271. this.onUpdateCallback = callback;
  7272. return this;
  7273. }
  7274. };
  7275. // File:src/animation/AnimationClip.js
  7276. /**
  7277. *
  7278. * Reusable set of Tracks that represent an animation.
  7279. *
  7280. * @author Ben Houston / http://clara.io/
  7281. * @author David Sarno / http://lighthaus.us/
  7282. */
  7283. THREE.AnimationClip = function ( name, duration, tracks ) {
  7284. this.name = name || THREE.Math.generateUUID();
  7285. this.tracks = tracks;
  7286. this.duration = ( duration !== undefined ) ? duration : -1;
  7287. // this means it should figure out its duration by scanning the tracks
  7288. if ( this.duration < 0 ) {
  7289. this.resetDuration();
  7290. }
  7291. // maybe only do these on demand, as doing them here could potentially slow down loading
  7292. // but leaving these here during development as this ensures a lot of testing of these functions
  7293. this.trim();
  7294. this.optimize();
  7295. };
  7296. THREE.AnimationClip.prototype = {
  7297. constructor: THREE.AnimationClip,
  7298. resetDuration: function() {
  7299. var tracks = this.tracks,
  7300. duration = 0;
  7301. for ( var i = 0, n = tracks.length; i !== n; ++ i ) {
  7302. var track = this.tracks[ i ];
  7303. duration = Math.max(
  7304. duration, track.times[ track.times.length - 1 ] );
  7305. }
  7306. this.duration = duration;
  7307. },
  7308. trim: function() {
  7309. for ( var i = 0; i < this.tracks.length; i ++ ) {
  7310. this.tracks[ i ].trim( 0, this.duration );
  7311. }
  7312. return this;
  7313. },
  7314. optimize: function() {
  7315. for ( var i = 0; i < this.tracks.length; i ++ ) {
  7316. this.tracks[ i ].optimize();
  7317. }
  7318. return this;
  7319. }
  7320. };
  7321. // Static methods:
  7322. Object.assign( THREE.AnimationClip, {
  7323. parse: function( json ) {
  7324. var tracks = [],
  7325. jsonTracks = json.tracks,
  7326. frameTime = 1.0 / ( json.fps || 1.0 );
  7327. for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  7328. tracks.push( THREE.KeyframeTrack.parse( jsonTracks[ i ] ).scale( frameTime ) );
  7329. }
  7330. return new THREE.AnimationClip( json.name, json.duration, tracks );
  7331. },
  7332. toJSON: function( clip ) {
  7333. var tracks = [],
  7334. clipTracks = clip.tracks;
  7335. var json = {
  7336. 'name': clip.name,
  7337. 'duration': clip.duration,
  7338. 'tracks': tracks
  7339. };
  7340. for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) {
  7341. tracks.push( THREE.KeyframeTrack.toJSON( clipTracks[ i ] ) );
  7342. }
  7343. return json;
  7344. },
  7345. CreateFromMorphTargetSequence: function( name, morphTargetSequence, fps ) {
  7346. var numMorphTargets = morphTargetSequence.length;
  7347. var tracks = [];
  7348. for ( var i = 0; i < numMorphTargets; i ++ ) {
  7349. var times = [];
  7350. var values = [];
  7351. times.push(
  7352. ( i + numMorphTargets - 1 ) % numMorphTargets,
  7353. i,
  7354. ( i + 1 ) % numMorphTargets );
  7355. values.push( 0, 1, 0 );
  7356. var order = THREE.AnimationUtils.getKeyframeOrder( times );
  7357. times = THREE.AnimationUtils.sortedArray( times, 1, order );
  7358. values = THREE.AnimationUtils.sortedArray( values, 1, order );
  7359. // if there is a key at the first frame, duplicate it as the
  7360. // last frame as well for perfect loop.
  7361. if ( times[ 0 ] === 0 ) {
  7362. times.push( numMorphTargets );
  7363. values.push( values[ 0 ] );
  7364. }
  7365. tracks.push(
  7366. new THREE.NumberKeyframeTrack(
  7367. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  7368. times, values
  7369. ).scale( 1.0 / fps ) );
  7370. }
  7371. return new THREE.AnimationClip( name, -1, tracks );
  7372. },
  7373. findByName: function( clipArray, name ) {
  7374. for ( var i = 0; i < clipArray.length; i ++ ) {
  7375. if ( clipArray[ i ].name === name ) {
  7376. return clipArray[ i ];
  7377. }
  7378. }
  7379. return null;
  7380. },
  7381. CreateClipsFromMorphTargetSequences: function( morphTargets, fps ) {
  7382. var animationToMorphTargets = {};
  7383. // tested with https://regex101.com/ on trick sequences
  7384. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  7385. var pattern = /^([\w-]*?)([\d]+)$/;
  7386. // sort morph target names into animation groups based
  7387. // patterns like Walk_001, Walk_002, Run_001, Run_002
  7388. for ( var i = 0, il = morphTargets.length; i < il; i ++ ) {
  7389. var morphTarget = morphTargets[ i ];
  7390. var parts = morphTarget.name.match( pattern );
  7391. if ( parts && parts.length > 1 ) {
  7392. var name = parts[ 1 ];
  7393. var animationMorphTargets = animationToMorphTargets[ name ];
  7394. if ( ! animationMorphTargets ) {
  7395. animationToMorphTargets[ name ] = animationMorphTargets = [];
  7396. }
  7397. animationMorphTargets.push( morphTarget );
  7398. }
  7399. }
  7400. var clips = [];
  7401. for ( var name in animationToMorphTargets ) {
  7402. clips.push( THREE.AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps ) );
  7403. }
  7404. return clips;
  7405. },
  7406. // parse the animation.hierarchy format
  7407. parseAnimation: function( animation, bones, nodeName ) {
  7408. if ( ! animation ) {
  7409. console.error( " no animation in JSONLoader data" );
  7410. return null;
  7411. }
  7412. var addNonemptyTrack = function(
  7413. trackType, trackName, animationKeys, propertyName, destTracks ) {
  7414. // only return track if there are actually keys.
  7415. if ( animationKeys.length !== 0 ) {
  7416. var times = [];
  7417. var values = [];
  7418. THREE.AnimationUtils.flattenJSON(
  7419. animationKeys, times, values, propertyName );
  7420. // empty keys are filtered out, so check again
  7421. if ( times.length !== 0 ) {
  7422. destTracks.push( new trackType( trackName, times, values ) );
  7423. }
  7424. }
  7425. };
  7426. var tracks = [];
  7427. var clipName = animation.name || 'default';
  7428. // automatic length determination in AnimationClip.
  7429. var duration = animation.length || -1;
  7430. var fps = animation.fps || 30;
  7431. var hierarchyTracks = animation.hierarchy || [];
  7432. for ( var h = 0; h < hierarchyTracks.length; h ++ ) {
  7433. var animationKeys = hierarchyTracks[ h ].keys;
  7434. // skip empty tracks
  7435. if ( ! animationKeys || animationKeys.length == 0 ) continue;
  7436. // process morph targets in a way exactly compatible
  7437. // with AnimationHandler.init( animation )
  7438. if ( animationKeys[0].morphTargets ) {
  7439. // figure out all morph targets used in this track
  7440. var morphTargetNames = {};
  7441. for ( var k = 0; k < animationKeys.length; k ++ ) {
  7442. if ( animationKeys[k].morphTargets ) {
  7443. for ( var m = 0; m < animationKeys[k].morphTargets.length; m ++ ) {
  7444. morphTargetNames[ animationKeys[k].morphTargets[m] ] = -1;
  7445. }
  7446. }
  7447. }
  7448. // create a track for each morph target with all zero
  7449. // morphTargetInfluences except for the keys in which
  7450. // the morphTarget is named.
  7451. for ( var morphTargetName in morphTargetNames ) {
  7452. var times = [];
  7453. var values = [];
  7454. for ( var m = 0;
  7455. m !== animationKeys[k].morphTargets.length; ++ m ) {
  7456. var animationKey = animationKeys[k];
  7457. times.push( animationKey.time );
  7458. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 )
  7459. }
  7460. tracks.push( new THREE.NumberKeyframeTrack(
  7461. '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  7462. }
  7463. duration = morphTargetNames.length * ( fps || 1.0 );
  7464. } else {
  7465. // ...assume skeletal animation
  7466. var boneName = '.bones[' + bones[ h ].name + ']';
  7467. addNonemptyTrack(
  7468. THREE.VectorKeyframeTrack, boneName + '.position',
  7469. animationKeys, 'pos', tracks );
  7470. addNonemptyTrack(
  7471. THREE.QuaternionKeyframeTrack, boneName + '.quaternion',
  7472. animationKeys, 'rot', tracks );
  7473. addNonemptyTrack(
  7474. THREE.VectorKeyframeTrack, boneName + '.scale',
  7475. animationKeys, 'scl', tracks );
  7476. }
  7477. }
  7478. if ( tracks.length === 0 ) {
  7479. return null;
  7480. }
  7481. var clip = new THREE.AnimationClip( clipName, duration, tracks );
  7482. return clip;
  7483. }
  7484. } );
  7485. // File:src/animation/AnimationMixer.js
  7486. /**
  7487. *
  7488. * Player for AnimationClips.
  7489. *
  7490. *
  7491. * @author Ben Houston / http://clara.io/
  7492. * @author David Sarno / http://lighthaus.us/
  7493. * @author tschw
  7494. */
  7495. THREE.AnimationMixer = function( root ) {
  7496. this._root = root;
  7497. this._initMemoryManager();
  7498. this._accuIndex = 0;
  7499. this.time = 0;
  7500. this.timeScale = 1.0;
  7501. };
  7502. THREE.AnimationMixer.prototype = {
  7503. constructor: THREE.AnimationMixer,
  7504. // return an action for a clip optionally using a custom root target
  7505. // object (this method allocates a lot of dynamic memory in case a
  7506. // previously unknown clip/root combination is specified)
  7507. clipAction: function( clip, optionalRoot ) {
  7508. var root = optionalRoot || this._root,
  7509. rootUuid = root.uuid,
  7510. clipName = ( typeof clip === 'string' ) ? clip : clip.name,
  7511. clipObject = ( clip !== clipName ) ? clip : null,
  7512. actionsForClip = this._actionsByClip[ clipName ],
  7513. prototypeAction;
  7514. if ( actionsForClip !== undefined ) {
  7515. var existingAction =
  7516. actionsForClip.actionByRoot[ rootUuid ];
  7517. if ( existingAction !== undefined ) {
  7518. return existingAction;
  7519. }
  7520. // we know the clip, so we don't have to parse all
  7521. // the bindings again but can just copy
  7522. prototypeAction = actionsForClip.knownActions[ 0 ];
  7523. // also, take the clip from the prototype action
  7524. clipObject = prototypeAction._clip;
  7525. if ( clip !== clipName && clip !== clipObject ) {
  7526. throw new Error(
  7527. "Different clips with the same name detected!" );
  7528. }
  7529. }
  7530. // clip must be known when specified via string
  7531. if ( clipObject === null ) return null;
  7532. // allocate all resources required to run it
  7533. var newAction = new THREE.
  7534. AnimationMixer._Action( this, clipObject, optionalRoot );
  7535. this._bindAction( newAction, prototypeAction );
  7536. // and make the action known to the memory manager
  7537. this._addInactiveAction( newAction, clipName, rootUuid );
  7538. return newAction;
  7539. },
  7540. // get an existing action
  7541. existingAction: function( clip, optionalRoot ) {
  7542. var root = optionalRoot || this._root,
  7543. rootUuid = root.uuid,
  7544. clipName = ( typeof clip === 'string' ) ? clip : clip.name,
  7545. actionsForClip = this._actionsByClip[ clipName ];
  7546. if ( actionsForClip !== undefined ) {
  7547. return actionsForClip.actionByRoot[ rootUuid ] || null;
  7548. }
  7549. return null;
  7550. },
  7551. // deactivates all previously scheduled actions
  7552. stopAllAction: function() {
  7553. var actions = this._actions,
  7554. nActions = this._nActiveActions,
  7555. bindings = this._bindings,
  7556. nBindings = this._nActiveBindings;
  7557. this._nActiveActions = 0;
  7558. this._nActiveBindings = 0;
  7559. for ( var i = 0; i !== nActions; ++ i ) {
  7560. actions[ i ].reset();
  7561. }
  7562. for ( var i = 0; i !== nBindings; ++ i ) {
  7563. bindings[ i ].useCount = 0;
  7564. }
  7565. return this;
  7566. },
  7567. // advance the time and update apply the animation
  7568. update: function( deltaTime ) {
  7569. deltaTime *= this.timeScale;
  7570. var actions = this._actions,
  7571. nActions = this._nActiveActions,
  7572. time = this.time += deltaTime,
  7573. timeDirection = Math.sign( deltaTime ),
  7574. accuIndex = this._accuIndex ^= 1;
  7575. // run active actions
  7576. for ( var i = 0; i !== nActions; ++ i ) {
  7577. var action = actions[ i ];
  7578. if ( action.enabled ) {
  7579. action._update( time, deltaTime, timeDirection, accuIndex );
  7580. }
  7581. }
  7582. // update scene graph
  7583. var bindings = this._bindings,
  7584. nBindings = this._nActiveBindings;
  7585. for ( var i = 0; i !== nBindings; ++ i ) {
  7586. bindings[ i ].apply( accuIndex );
  7587. }
  7588. return this;
  7589. },
  7590. // return this mixer's root target object
  7591. getRoot: function() {
  7592. return this._root;
  7593. },
  7594. // free all resources specific to a particular clip
  7595. uncacheClip: function( clip ) {
  7596. var actions = this._actions,
  7597. clipName = clip.name,
  7598. actionsByClip = this._actionsByClip,
  7599. actionsForClip = actionsByClip[ clipName ];
  7600. if ( actionsForClip !== undefined ) {
  7601. // note: just calling _removeInactiveAction would mess up the
  7602. // iteration state and also require updating the state we can
  7603. // just throw away
  7604. var actionsToRemove = actionsForClip.knownActions;
  7605. for ( var i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  7606. var action = actionsToRemove[ i ];
  7607. this._deactivateAction( action );
  7608. var cacheIndex = action._cacheIndex,
  7609. lastInactiveAction = actions[ actions.length - 1 ];
  7610. action._cacheIndex = null;
  7611. action._byClipCacheIndex = null;
  7612. lastInactiveAction._cacheIndex = cacheIndex;
  7613. actions[ cacheIndex ] = lastInactiveAction;
  7614. actions.pop();
  7615. this._removeInactiveBindingsForAction( action );
  7616. }
  7617. delete actionsByClip[ clipName ];
  7618. }
  7619. },
  7620. // free all resources specific to a particular root target object
  7621. uncacheRoot: function( root ) {
  7622. var rootUuid = root.uuid,
  7623. actionsByClip = this._actionsByClip;
  7624. for ( var clipName in actionsByClip ) {
  7625. var actionByRoot = actionsByClip[ clipName ].actionByRoot,
  7626. action = actionByRoot[ rootUuid ];
  7627. if ( action !== undefined ) {
  7628. this._deactivateAction( action );
  7629. this._removeInactiveAction( action );
  7630. }
  7631. }
  7632. var bindingsByRoot = this._bindingsByRootAndName,
  7633. bindingByName = bindingsByRoot[ rootUuid ];
  7634. if ( bindingByName !== undefined ) {
  7635. for ( var trackName in bindingByName ) {
  7636. var binding = bindingByName[ trackName ];
  7637. binding.restoreOriginalState();
  7638. this._removeInactiveBinding( binding );
  7639. }
  7640. }
  7641. },
  7642. // remove a targeted clip from the cache
  7643. uncacheAction: function( clip, optionalRoot ) {
  7644. var action = this.existingAction( clip, optionalRoot );
  7645. if ( action !== null ) {
  7646. this._deactivateAction( action );
  7647. this._removeInactiveAction( action );
  7648. }
  7649. }
  7650. };
  7651. THREE.EventDispatcher.prototype.apply( THREE.AnimationMixer.prototype );
  7652. THREE.AnimationMixer._Action =
  7653. function( mixer, clip, localRoot ) {
  7654. this._mixer = mixer;
  7655. this._clip = clip;
  7656. this._localRoot = localRoot || null;
  7657. var tracks = clip.tracks,
  7658. nTracks = tracks.length,
  7659. interpolants = new Array( nTracks );
  7660. var interpolantSettings = {
  7661. endingStart: THREE.ZeroCurvatureEnding,
  7662. endingEnd: THREE.ZeroCurvatureEnding
  7663. };
  7664. for ( var i = 0; i !== nTracks; ++ i ) {
  7665. var interpolant = tracks[ i ].createInterpolant( null );
  7666. interpolants[ i ] = interpolant;
  7667. interpolant.settings = interpolantSettings
  7668. }
  7669. this._interpolantSettings = interpolantSettings;
  7670. this._interpolants = interpolants; // bound by the mixer
  7671. // inside: PropertyMixer (managed by the mixer)
  7672. this._propertyBindings = new Array( nTracks );
  7673. this._cacheIndex = null; // for the memory manager
  7674. this._byClipCacheIndex = null; // for the memory manager
  7675. this._timeScaleInterpolant = null;
  7676. this._weightInterpolant = null;
  7677. this.loop = THREE.LoopRepeat;
  7678. this._loopCount = -1;
  7679. // global mixer time when the action is to be started
  7680. // it's set back to 'null' upon start of the action
  7681. this._startTime = null;
  7682. // scaled local time of the action
  7683. // gets clamped or wrapped to 0..clip.duration according to loop
  7684. this.time = 0;
  7685. this.timeScale = 1;
  7686. this._effectiveTimeScale = 1;
  7687. this.weight = 1;
  7688. this._effectiveWeight = 1;
  7689. this.repetitions = Infinity; // no. of repetitions when looping
  7690. this.paused = false; // false -> zero effective time scale
  7691. this.enabled = true; // true -> zero effective weight
  7692. this.clampWhenFinished = false; // keep feeding the last frame?
  7693. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  7694. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  7695. };
  7696. THREE.AnimationMixer._Action.prototype = {
  7697. constructor: THREE.AnimationMixer._Action,
  7698. // State & Scheduling
  7699. play: function() {
  7700. this._mixer._activateAction( this );
  7701. return this;
  7702. },
  7703. stop: function() {
  7704. this._mixer._deactivateAction( this );
  7705. return this.reset();
  7706. },
  7707. reset: function() {
  7708. this.paused = false;
  7709. this.enabled = true;
  7710. this.time = 0; // restart clip
  7711. this._loopCount = -1; // forget previous loops
  7712. this._startTime = null; // forget scheduling
  7713. return this.stopFading().stopWarping();
  7714. },
  7715. isRunning: function() {
  7716. var start = this._startTime;
  7717. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  7718. this._startTime === null && this._mixer._isActiveAction( this )
  7719. },
  7720. // return true when play has been called
  7721. isScheduled: function() {
  7722. return this._mixer._isActiveAction( this );
  7723. },
  7724. startAt: function( time ) {
  7725. this._startTime = time;
  7726. return this;
  7727. },
  7728. setLoop: function( mode, repetitions ) {
  7729. this.loop = mode;
  7730. this.repetitions = repetitions;
  7731. return this;
  7732. },
  7733. // Weight
  7734. // set the weight stopping any scheduled fading
  7735. // although .enabled = false yields an effective weight of zero, this
  7736. // method does *not* change .enabled, because it would be confusing
  7737. setEffectiveWeight: function( weight ) {
  7738. this.weight = weight;
  7739. // note: same logic as when updated at runtime
  7740. this._effectiveWeight = this.enabled ? weight : 0;
  7741. return this.stopFading();
  7742. },
  7743. // return the weight considering fading and .enabled
  7744. getEffectiveWeight: function() {
  7745. return this._effectiveWeight;
  7746. },
  7747. fadeIn: function( duration ) {
  7748. return this._scheduleFading( duration, 0, 1 );
  7749. },
  7750. fadeOut: function( duration ) {
  7751. return this._scheduleFading( duration, 1, 0 );
  7752. },
  7753. crossFadeFrom: function( fadeOutAction, duration, warp ) {
  7754. var mixer = this._mixer;
  7755. fadeOutAction.fadeOut( duration );
  7756. this.fadeIn( duration );
  7757. if( warp ) {
  7758. var fadeInDuration = this._clip.duration,
  7759. fadeOutDuration = fadeOutAction._clip.duration,
  7760. startEndRatio = fadeOutDuration / fadeInDuration,
  7761. endStartRatio = fadeInDuration / fadeOutDuration;
  7762. fadeOutAction.warp( 1.0, startEndRatio, duration );
  7763. this.warp( endStartRatio, 1.0, duration );
  7764. }
  7765. return this;
  7766. },
  7767. crossFadeTo: function( fadeInAction, duration, warp ) {
  7768. return fadeInAction.crossFadeFrom( this, duration, warp );
  7769. },
  7770. stopFading: function() {
  7771. var weightInterpolant = this._weightInterpolant;
  7772. if ( weightInterpolant !== null ) {
  7773. this._weightInterpolant = null;
  7774. this._mixer._takeBackControlInterpolant( weightInterpolant );
  7775. }
  7776. return this;
  7777. },
  7778. // Time Scale Control
  7779. // set the weight stopping any scheduled warping
  7780. // although .paused = true yields an effective time scale of zero, this
  7781. // method does *not* change .paused, because it would be confusing
  7782. setEffectiveTimeScale: function( timeScale ) {
  7783. this.timeScale = timeScale;
  7784. this._effectiveTimeScale = this.paused ? 0 :timeScale;
  7785. return this.stopWarping();
  7786. },
  7787. // return the time scale considering warping and .paused
  7788. getEffectiveTimeScale: function() {
  7789. return this._effectiveTimeScale;
  7790. },
  7791. setDuration: function( duration ) {
  7792. this.timeScale = this._clip.duration / duration;
  7793. return this.stopWarping();
  7794. },
  7795. syncWith: function( action ) {
  7796. this.time = action.time;
  7797. this.timeScale = action.timeScale;
  7798. return this.stopWarping();
  7799. },
  7800. halt: function( duration ) {
  7801. return this.warp( this._currentTimeScale, 0, duration );
  7802. },
  7803. warp: function( startTimeScale, endTimeScale, duration ) {
  7804. var mixer = this._mixer, now = mixer.time,
  7805. interpolant = this._timeScaleInterpolant,
  7806. timeScale = this.timeScale;
  7807. if ( interpolant === null ) {
  7808. interpolant = mixer._lendControlInterpolant(),
  7809. this._timeScaleInterpolant = interpolant;
  7810. }
  7811. var times = interpolant.parameterPositions,
  7812. values = interpolant.sampleValues;
  7813. times[ 0 ] = now;
  7814. times[ 1 ] = now + duration;
  7815. values[ 0 ] = startTimeScale / timeScale;
  7816. values[ 1 ] = endTimeScale / timeScale;
  7817. return this;
  7818. },
  7819. stopWarping: function() {
  7820. var timeScaleInterpolant = this._timeScaleInterpolant;
  7821. if ( timeScaleInterpolant !== null ) {
  7822. this._timeScaleInterpolant = null;
  7823. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  7824. }
  7825. return this;
  7826. },
  7827. // Object Accessors
  7828. getMixer: function() {
  7829. return this._mixer;
  7830. },
  7831. getClip: function() {
  7832. return this._clip;
  7833. },
  7834. getRoot: function() {
  7835. return this._localRoot || this._mixer._root;
  7836. },
  7837. // Interna
  7838. _update: function( time, deltaTime, timeDirection, accuIndex ) {
  7839. // called by the mixer
  7840. var startTime = this._startTime;
  7841. if ( startTime !== null ) {
  7842. // check for scheduled start of action
  7843. var timeRunning = ( time - startTime ) * timeDirection;
  7844. if ( timeRunning < 0 || timeDirection === 0 ) {
  7845. return; // yet to come / don't decide when delta = 0
  7846. }
  7847. // start
  7848. this._startTime = null; // unschedule
  7849. deltaTime = timeDirection * timeRunning;
  7850. }
  7851. // apply time scale and advance time
  7852. deltaTime *= this._updateTimeScale( time );
  7853. var clipTime = this._updateTime( deltaTime );
  7854. // note: _updateTime may disable the action resulting in
  7855. // an effective weight of 0
  7856. var weight = this._updateWeight( time );
  7857. if ( weight > 0 ) {
  7858. var interpolants = this._interpolants;
  7859. var propertyMixers = this._propertyBindings;
  7860. for ( var j = 0, m = interpolants.length; j !== m; ++ j ) {
  7861. interpolants[ j ].evaluate( clipTime );
  7862. propertyMixers[ j ].accumulate( accuIndex, weight );
  7863. }
  7864. }
  7865. },
  7866. _updateWeight: function( time ) {
  7867. var weight = 0;
  7868. if ( this.enabled ) {
  7869. weight = this.weight;
  7870. var interpolant = this._weightInterpolant;
  7871. if ( interpolant !== null ) {
  7872. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  7873. weight *= interpolantValue;
  7874. if ( time > interpolant.parameterPositions[ 1 ] ) {
  7875. this.stopFading();
  7876. if ( interpolantValue === 0 ) {
  7877. // faded out, disable
  7878. this.enabled = false;
  7879. }
  7880. }
  7881. }
  7882. }
  7883. this._effectiveWeight = weight;
  7884. return weight;
  7885. },
  7886. _updateTimeScale: function( time ) {
  7887. var timeScale = 0;
  7888. if ( ! this.paused ) {
  7889. timeScale = this.timeScale;
  7890. var interpolant = this._timeScaleInterpolant;
  7891. if ( interpolant !== null ) {
  7892. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  7893. timeScale *= interpolantValue;
  7894. if ( time > interpolant.parameterPositions[ 1 ] ) {
  7895. this.stopWarping();
  7896. if ( timeScale === 0 ) {
  7897. // motion has halted, pause
  7898. this.pause = true;
  7899. } else {
  7900. // warp done - apply final time scale
  7901. this.timeScale = timeScale;
  7902. }
  7903. }
  7904. }
  7905. }
  7906. this._effectiveTimeScale = timeScale;
  7907. return timeScale;
  7908. },
  7909. _updateTime: function( deltaTime ) {
  7910. var time = this.time + deltaTime;
  7911. if ( deltaTime === 0 ) return time;
  7912. var duration = this._clip.duration,
  7913. loop = this.loop,
  7914. loopCount = this._loopCount,
  7915. pingPong = false;
  7916. switch ( loop ) {
  7917. case THREE.LoopOnce:
  7918. if ( loopCount === -1 ) {
  7919. // just started
  7920. this.loopCount = 0;
  7921. this._setEndings( true, true, false );
  7922. }
  7923. if ( time >= duration ) {
  7924. time = duration;
  7925. } else if ( time < 0 ) {
  7926. time = 0;
  7927. } else break;
  7928. // reached the end
  7929. if ( this.clampWhenFinished ) this.pause = true;
  7930. else this.enabled = false;
  7931. this._mixer.dispatchEvent( {
  7932. type: 'finished', action: this,
  7933. direction: deltaTime < 0 ? -1 : 1
  7934. } );
  7935. break;
  7936. case THREE.LoopPingPong:
  7937. pingPong = true;
  7938. case THREE.LoopRepeat:
  7939. if ( loopCount === -1 ) {
  7940. // just started
  7941. if ( deltaTime > 0 ) {
  7942. loopCount = 0;
  7943. this._setEndings(
  7944. true, this.repetitions === 0, pingPong );
  7945. } else {
  7946. // when looping in reverse direction, the initial
  7947. // transition through zero counts as a repetition,
  7948. // so leave loopCount at -1
  7949. this._setEndings(
  7950. this.repetitions === 0, true, pingPong );
  7951. }
  7952. }
  7953. if ( time >= duration || time < 0 ) {
  7954. // wrap around
  7955. var loopDelta = Math.floor( time / duration ); // signed
  7956. time -= duration * loopDelta;
  7957. loopCount += Math.abs( loopDelta );
  7958. var pending = this.repetitions - loopCount;
  7959. if ( pending < 0 ) {
  7960. // stop (switch state, clamp time, fire event)
  7961. if ( this.clampWhenFinished ) this.paused = true;
  7962. else this.enabled = false;
  7963. time = deltaTime > 0 ? duration : 0;
  7964. this._mixer.dispatchEvent( {
  7965. type: 'finished', action: this,
  7966. direction: deltaTime > 0 ? 1 : -1
  7967. } );
  7968. break;
  7969. } else if ( pending === 0 ) {
  7970. // transition to last round
  7971. var atStart = deltaTime < 0;
  7972. this._setEndings( atStart, ! atStart, pingPong );
  7973. } else {
  7974. this._setEndings( false, false, pingPong );
  7975. }
  7976. this._loopCount = loopCount;
  7977. this._mixer.dispatchEvent( {
  7978. type: 'loop', action: this, loopDelta: loopDelta
  7979. } );
  7980. }
  7981. if ( loop === THREE.LoopPingPong && ( loopCount & 1 ) === 1 ) {
  7982. // invert time for the "pong round"
  7983. this.time = time;
  7984. return duration - time;
  7985. }
  7986. break;
  7987. }
  7988. this.time = time;
  7989. return time;
  7990. },
  7991. _setEndings: function( atStart, atEnd, pingPong ) {
  7992. var settings = this._interpolantSettings;
  7993. if ( pingPong ) {
  7994. settings.endingStart = THREE.ZeroSlopeEnding;
  7995. settings.endingEnd = THREE.ZeroSlopeEnding;
  7996. } else {
  7997. // assuming for LoopOnce atStart == atEnd == true
  7998. if ( atStart ) {
  7999. settings.endingStart = this.zeroSlopeAtStart ?
  8000. THREE.ZeroSlopeEnding : THREE.ZeroCurvatureEnding;
  8001. } else {
  8002. settings.endingStart = THREE.WrapAroundEnding;
  8003. }
  8004. if ( atEnd ) {
  8005. settings.endingEnd = this.zeroSlopeAtEnd ?
  8006. THREE.ZeroSlopeEnding : THREE.ZeroCurvatureEnding;
  8007. } else {
  8008. settings.endingEnd = THREE.WrapAroundEnding;
  8009. }
  8010. }
  8011. },
  8012. _scheduleFading: function( duration, weightNow, weightThen ) {
  8013. var mixer = this._mixer, now = mixer.time,
  8014. interpolant = this._weightInterpolant;
  8015. if ( interpolant === null ) {
  8016. interpolant = mixer._lendControlInterpolant(),
  8017. this._weightInterpolant = interpolant;
  8018. }
  8019. var times = interpolant.parameterPositions,
  8020. values = interpolant.sampleValues;
  8021. times[ 0 ] = now; values[ 0 ] = weightNow;
  8022. times[ 1 ] = now + duration; values[ 1 ] = weightThen;
  8023. return this;
  8024. }
  8025. };
  8026. // Implementation details:
  8027. Object.assign( THREE.AnimationMixer.prototype, {
  8028. _bindAction: function( action, prototypeAction ) {
  8029. var root = action._localRoot || this._root,
  8030. tracks = action._clip.tracks,
  8031. nTracks = tracks.length,
  8032. bindings = action._propertyBindings,
  8033. interpolants = action._interpolants,
  8034. rootUuid = root.uuid,
  8035. bindingsByRoot = this._bindingsByRootAndName,
  8036. bindingsByName = bindingsByRoot[ rootUuid ];
  8037. if ( bindingsByName === undefined ) {
  8038. bindingsByName = {};
  8039. bindingsByRoot[ rootUuid ] = bindingsByName;
  8040. }
  8041. for ( var i = 0; i !== nTracks; ++ i ) {
  8042. var track = tracks[ i ],
  8043. trackName = track.name,
  8044. binding = bindingsByName[ trackName ];
  8045. if ( binding !== undefined ) {
  8046. bindings[ i ] = binding;
  8047. } else {
  8048. binding = bindings[ i ];
  8049. if ( binding !== undefined ) {
  8050. // existing binding, make sure the cache knows
  8051. if ( binding._cacheIndex === null ) {
  8052. ++ binding.referenceCount;
  8053. this._addInactiveBinding( binding, rootUuid, trackName );
  8054. }
  8055. continue;
  8056. }
  8057. var path = prototypeAction && prototypeAction.
  8058. _propertyBindings[ i ].binding.parsedPath;
  8059. binding = new THREE.PropertyMixer(
  8060. THREE.PropertyBinding.create( root, trackName, path ),
  8061. track.ValueTypeName, track.getValueSize() );
  8062. ++ binding.referenceCount;
  8063. this._addInactiveBinding( binding, rootUuid, trackName );
  8064. bindings[ i ] = binding;
  8065. }
  8066. interpolants[ i ].resultBuffer = binding.buffer;
  8067. }
  8068. },
  8069. _activateAction: function( action ) {
  8070. if ( ! this._isActiveAction( action ) ) {
  8071. if ( action._cacheIndex === null ) {
  8072. // this action has been forgotten by the cache, but the user
  8073. // appears to be still using it -> rebind
  8074. var rootUuid = ( action._localRoot || this._root ).uuid,
  8075. clipName = action._clip.name,
  8076. actionsForClip = this._actionsByClip[ clipName ];
  8077. this._bindAction( action,
  8078. actionsForClip && actionsForClip.knownActions[ 0 ] );
  8079. this._addInactiveAction( action, clipName, rootUuid );
  8080. }
  8081. var bindings = action._propertyBindings;
  8082. // increment reference counts / sort out state
  8083. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  8084. var binding = bindings[ i ];
  8085. if ( binding.useCount ++ === 0 ) {
  8086. this._lendBinding( binding );
  8087. binding.saveOriginalState();
  8088. }
  8089. }
  8090. this._lendAction( action );
  8091. }
  8092. },
  8093. _deactivateAction: function( action ) {
  8094. if ( this._isActiveAction( action ) ) {
  8095. var bindings = action._propertyBindings;
  8096. // decrement reference counts / sort out state
  8097. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  8098. var binding = bindings[ i ];
  8099. if ( -- binding.useCount === 0 ) {
  8100. binding.restoreOriginalState();
  8101. this._takeBackBinding( binding );
  8102. }
  8103. }
  8104. this._takeBackAction( action );
  8105. }
  8106. },
  8107. // Memory manager
  8108. _initMemoryManager: function() {
  8109. this._actions = []; // 'nActiveActions' followed by inactive ones
  8110. this._nActiveActions = 0;
  8111. this._actionsByClip = {};
  8112. // inside:
  8113. // {
  8114. // knownActions: Array< _Action > - used as prototypes
  8115. // actionByRoot: _Action - lookup
  8116. // }
  8117. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  8118. this._nActiveBindings = 0;
  8119. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  8120. this._controlInterpolants = []; // same game as above
  8121. this._nActiveControlInterpolants = 0;
  8122. var scope = this;
  8123. this.stats = {
  8124. actions: {
  8125. get total() { return scope._actions.length; },
  8126. get inUse() { return scope._nActiveActions; }
  8127. },
  8128. bindings: {
  8129. get total() { return scope._bindings.length; },
  8130. get inUse() { return scope._nActiveBindings; }
  8131. },
  8132. controlInterpolants: {
  8133. get total() { return scope._controlInterpolants.length; },
  8134. get inUse() { return scope._nActiveControlInterpolants; }
  8135. }
  8136. };
  8137. },
  8138. // Memory management for _Action objects
  8139. _isActiveAction: function( action ) {
  8140. var index = action._cacheIndex;
  8141. return index !== null && index < this._nActiveActions;
  8142. },
  8143. _addInactiveAction: function( action, clipName, rootUuid ) {
  8144. var actions = this._actions,
  8145. actionsByClip = this._actionsByClip,
  8146. actionsForClip = actionsByClip[ clipName ];
  8147. if ( actionsForClip === undefined ) {
  8148. actionsForClip = {
  8149. knownActions: [ action ],
  8150. actionByRoot: {}
  8151. };
  8152. action._byClipCacheIndex = 0;
  8153. actionsByClip[ clipName ] = actionsForClip;
  8154. } else {
  8155. var knownActions = actionsForClip.knownActions;
  8156. action._byClipCacheIndex = knownActions.length;
  8157. knownActions.push( action );
  8158. }
  8159. action._cacheIndex = actions.length;
  8160. actions.push( action );
  8161. actionsForClip.actionByRoot[ rootUuid ] = action;
  8162. },
  8163. _removeInactiveAction: function( action ) {
  8164. var actions = this._actions,
  8165. lastInactiveAction = actions[ actions.length - 1 ],
  8166. cacheIndex = action._cacheIndex;
  8167. lastInactiveAction._cacheIndex = cacheIndex;
  8168. actions[ cacheIndex ] = lastInactiveAction;
  8169. actions.pop();
  8170. action._cacheIndex = null;
  8171. var clipName = action._clip.name,
  8172. actionsByClip = this._actionsByClip,
  8173. actionsForClip = actionsByClip[ clipName ],
  8174. knownActionsForClip = actionsForClip.knownActions,
  8175. lastKnownAction =
  8176. knownActionsForClip[ knownActionsForClip.length - 1 ],
  8177. byClipCacheIndex = action._byClipCacheIndex;
  8178. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  8179. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  8180. knownActionsForClip.pop();
  8181. action._byClipCacheIndex = null;
  8182. var actionByRoot = actionsForClip.actionByRoot,
  8183. rootUuid = ( actions._localRoot || this._root ).uuid;
  8184. delete actionByRoot[ rootUuid ];
  8185. if ( knownActionsForClip.length === 0 ) {
  8186. delete actionsByClip[ clipName ];
  8187. }
  8188. this._removeInactiveBindingsForAction( action );
  8189. },
  8190. _removeInactiveBindingsForAction: function( action ) {
  8191. var bindings = action._propertyBindings;
  8192. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  8193. var binding = bindings[ i ];
  8194. if ( -- binding.referenceCount === 0 ) {
  8195. this._removeInactiveBinding( binding );
  8196. }
  8197. }
  8198. },
  8199. _lendAction: function( action ) {
  8200. // [ active actions | inactive actions ]
  8201. // [ active actions >| inactive actions ]
  8202. // s a
  8203. // <-swap->
  8204. // a s
  8205. var actions = this._actions,
  8206. prevIndex = action._cacheIndex,
  8207. lastActiveIndex = this._nActiveActions ++,
  8208. firstInactiveAction = actions[ lastActiveIndex ];
  8209. action._cacheIndex = lastActiveIndex;
  8210. actions[ lastActiveIndex ] = action;
  8211. firstInactiveAction._cacheIndex = prevIndex;
  8212. actions[ prevIndex ] = firstInactiveAction;
  8213. },
  8214. _takeBackAction: function( action ) {
  8215. // [ active actions | inactive actions ]
  8216. // [ active actions |< inactive actions ]
  8217. // a s
  8218. // <-swap->
  8219. // s a
  8220. var actions = this._actions,
  8221. prevIndex = action._cacheIndex,
  8222. firstInactiveIndex = -- this._nActiveActions,
  8223. lastActiveAction = actions[ firstInactiveIndex ];
  8224. action._cacheIndex = firstInactiveIndex;
  8225. actions[ firstInactiveIndex ] = action;
  8226. lastActiveAction._cacheIndex = prevIndex;
  8227. actions[ prevIndex ] = lastActiveAction;
  8228. },
  8229. // Memory management for PropertyMixer objects
  8230. _addInactiveBinding: function( binding, rootUuid, trackName ) {
  8231. var bindingsByRoot = this._bindingsByRootAndName,
  8232. bindingByName = bindingsByRoot[ rootUuid ],
  8233. bindings = this._bindings;
  8234. if ( bindingByName === undefined ) {
  8235. bindingByName = {};
  8236. bindingsByRoot[ rootUuid ] = bindingByName;
  8237. }
  8238. bindingByName[ trackName ] = binding;
  8239. binding._cacheIndex = bindings.length;
  8240. bindings.push( binding );
  8241. },
  8242. _removeInactiveBinding: function( binding ) {
  8243. var bindings = this._bindings,
  8244. propBinding = binding.binding,
  8245. rootUuid = propBinding.rootNode.uuid,
  8246. trackName = propBinding.path,
  8247. bindingsByRoot = this._bindingsByRootAndName,
  8248. bindingByName = bindingsByRoot[ rootUuid ],
  8249. lastInactiveBinding = bindings[ bindings.length - 1 ],
  8250. cacheIndex = binding._cacheIndex;
  8251. lastInactiveBinding._cacheIndex = cacheIndex;
  8252. bindings[ cacheIndex ] = lastInactiveBinding;
  8253. bindings.pop();
  8254. delete bindingByName[ trackName ];
  8255. remove_empty_map: {
  8256. for ( var _ in bindingByName ) break remove_empty_map;
  8257. delete bindingsByRoot[ rootUuid ];
  8258. }
  8259. },
  8260. _lendBinding: function( binding ) {
  8261. var bindings = this._bindings,
  8262. prevIndex = binding._cacheIndex,
  8263. lastActiveIndex = this._nActiveBindings ++,
  8264. firstInactiveBinding = bindings[ lastActiveIndex ];
  8265. binding._cacheIndex = lastActiveIndex;
  8266. bindings[ lastActiveIndex ] = binding;
  8267. firstInactiveBinding._cacheIndex = prevIndex;
  8268. bindings[ prevIndex ] = firstInactiveBinding;
  8269. },
  8270. _takeBackBinding: function( binding ) {
  8271. var bindings = this._bindings,
  8272. prevIndex = binding._cacheIndex,
  8273. firstInactiveIndex = -- this._nActiveBindings,
  8274. lastActiveBinding = bindings[ firstInactiveIndex ];
  8275. binding._cacheIndex = firstInactiveIndex;
  8276. bindings[ firstInactiveIndex ] = binding;
  8277. lastActiveBinding._cacheIndex = prevIndex;
  8278. bindings[ prevIndex ] = lastActiveBinding;
  8279. },
  8280. // Memory management of Interpolants for weight and time scale
  8281. _lendControlInterpolant: function() {
  8282. var interpolants = this._controlInterpolants,
  8283. lastActiveIndex = this._nActiveControlInterpolants ++,
  8284. interpolant = interpolants[ lastActiveIndex ];
  8285. if ( interpolant === undefined ) {
  8286. interpolant = new THREE.LinearInterpolant(
  8287. new Float32Array( 2 ), new Float32Array( 2 ),
  8288. 1, this._controlInterpolantsResultBuffer );
  8289. interpolant.__cacheIndex = lastActiveIndex;
  8290. interpolants[ lastActiveIndex ] = interpolant;
  8291. }
  8292. return interpolant;
  8293. },
  8294. _takeBackControlInterpolant: function( interpolant ) {
  8295. var interpolants = this._controlInterpolants,
  8296. prevIndex = interpolant.__cacheIndex,
  8297. firstInactiveIndex = -- this._nActiveControlInterpolants,
  8298. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  8299. interpolant.__cacheIndex = firstInactiveIndex;
  8300. interpolants[ firstInactiveIndex ] = interpolant;
  8301. lastActiveInterpolant.__cacheIndex = prevIndex;
  8302. interpolants[ prevIndex ] = lastActiveInterpolant;
  8303. },
  8304. _controlInterpolantsResultBuffer: new Float32Array( 1 )
  8305. } );
  8306. // File:src/animation/AnimationObjectGroup.js
  8307. /**
  8308. *
  8309. * A group of objects that receives a shared animation state.
  8310. *
  8311. * Usage:
  8312. *
  8313. * - Add objects you would otherwise pass as 'root' to the
  8314. * constructor or the .clipAction method of AnimationMixer.
  8315. *
  8316. * - Instead pass this object as 'root'.
  8317. *
  8318. * - You can also add and remove objects later when the mixer
  8319. * is running.
  8320. *
  8321. * Note:
  8322. *
  8323. * Objects of this class appear as one object to the mixer,
  8324. * so cache control of the individual objects must be done
  8325. * on the group.
  8326. *
  8327. * Limitation:
  8328. *
  8329. * - The animated properties must be compatible among the
  8330. * all objects in the group.
  8331. *
  8332. * - A single property can either be controlled through a
  8333. * target group or directly, but not both.
  8334. *
  8335. * @author tschw
  8336. */
  8337. THREE.AnimationObjectGroup = function( var_args ) {
  8338. this.uuid = THREE.Math.generateUUID();
  8339. // cached objects followed by the active ones
  8340. this._objects = Array.prototype.slice.call( arguments );
  8341. this.nCachedObjects_ = 0; // threshold
  8342. // note: read by PropertyBinding.Composite
  8343. var indices = {};
  8344. this._indicesByUUID = indices; // for bookkeeping
  8345. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  8346. indices[ arguments[ i ].uuid ] = i;
  8347. }
  8348. this._paths = []; // inside: string
  8349. this._parsedPaths = []; // inside: { we don't care, here }
  8350. this._bindings = []; // inside: Array< PropertyBinding >
  8351. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  8352. var scope = this;
  8353. this.stats = {
  8354. objects: {
  8355. get total() { return scope._objects.length; },
  8356. get inUse() { return this.total - scope.nCachedObjects_; }
  8357. },
  8358. get bindingsPerObject() { return scope._bindings.length; }
  8359. };
  8360. };
  8361. THREE.AnimationObjectGroup.prototype = {
  8362. constructor: THREE.AnimationObjectGroup,
  8363. add: function( var_args ) {
  8364. var objects = this._objects,
  8365. nObjects = objects.length,
  8366. nCachedObjects = this.nCachedObjects_,
  8367. indicesByUUID = this._indicesByUUID,
  8368. paths = this._paths,
  8369. parsedPaths = this._parsedPaths,
  8370. bindings = this._bindings,
  8371. nBindings = bindings.length;
  8372. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  8373. var object = arguments[ i ],
  8374. uuid = object.uuid,
  8375. index = indicesByUUID[ uuid ];
  8376. if ( index === undefined ) {
  8377. // unknown object -> add it to the ACTIVE region
  8378. index = nObjects ++;
  8379. indicesByUUID[ uuid ] = index;
  8380. objects.push( object );
  8381. // accounting is done, now do the same for all bindings
  8382. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  8383. bindings[ j ].push(
  8384. new THREE.PropertyBinding(
  8385. object, paths[ j ], parsedPaths[ j ] ) );
  8386. }
  8387. } else if ( index < nCachedObjects ) {
  8388. var knownObject = objects[ index ];
  8389. // move existing object to the ACTIVE region
  8390. var firstActiveIndex = -- nCachedObjects,
  8391. lastCachedObject = objects[ firstActiveIndex ];
  8392. indicesByUUID[ lastCachedObject.uuid ] = index;
  8393. objects[ index ] = lastCachedObject;
  8394. indicesByUUID[ uuid ] = firstActiveIndex;
  8395. objects[ firstActiveIndex ] = object;
  8396. // accounting is done, now do the same for all bindings
  8397. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  8398. var bindingsForPath = bindings[ j ],
  8399. lastCached = bindingsForPath[ firstActiveIndex ],
  8400. binding = bindingsForPath[ index ];
  8401. bindingsForPath[ index ] = lastCached;
  8402. if ( binding === undefined ) {
  8403. // since we do not bother to create new bindings
  8404. // for objects that are cached, the binding may
  8405. // or may not exist
  8406. binding = new THREE.PropertyBinding(
  8407. object, paths[ j ], parsedPaths[ j ] );
  8408. }
  8409. bindingsForPath[ firstActiveIndex ] = binding;
  8410. }
  8411. } else if ( objects[ index ] !== knownObject) {
  8412. console.error( "Different objects with the same UUID " +
  8413. "detected. Clean the caches or recreate your " +
  8414. "infrastructure when reloading scenes..." );
  8415. } // else the object is already where we want it to be
  8416. } // for arguments
  8417. this.nCachedObjects_ = nCachedObjects;
  8418. },
  8419. remove: function( var_args ) {
  8420. var objects = this._objects,
  8421. nObjects = objects.length,
  8422. nCachedObjects = this.nCachedObjects_,
  8423. indicesByUUID = this._indicesByUUID,
  8424. bindings = this._bindings,
  8425. nBindings = bindings.length;
  8426. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  8427. var object = arguments[ i ],
  8428. uuid = object.uuid,
  8429. index = indicesByUUID[ uuid ];
  8430. if ( index !== undefined && index >= nCachedObjects ) {
  8431. // move existing object into the CACHED region
  8432. var lastCachedIndex = nCachedObjects ++,
  8433. firstActiveObject = objects[ lastCachedIndex ];
  8434. indicesByUUID[ firstActiveObject.uuid ] = index;
  8435. objects[ index ] = firstActiveObject;
  8436. indicesByUUID[ uuid ] = lastCachedIndex;
  8437. objects[ lastCachedIndex ] = object;
  8438. // accounting is done, now do the same for all bindings
  8439. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  8440. var bindingsForPath = bindings[ j ],
  8441. firstActive = bindingsForPath[ lastCachedIndex ],
  8442. binding = bindingsForPath[ index ];
  8443. bindingsForPath[ index ] = firstActive;
  8444. bindingsForPath[ lastCachedIndex ] = binding;
  8445. }
  8446. }
  8447. } // for arguments
  8448. this.nCachedObjects_ = nCachedObjects;
  8449. },
  8450. // remove & forget
  8451. uncache: function( var_args ) {
  8452. var objects = this._objects,
  8453. nObjects = objects.length,
  8454. nCachedObjects = this.nCachedObjects_,
  8455. indicesByUUID = this._indicesByUUID,
  8456. bindings = this._bindings,
  8457. nBindings = bindings.length;
  8458. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  8459. var object = arguments[ i ],
  8460. uuid = object.uuid,
  8461. index = indicesByUUID[ uuid ];
  8462. if ( index !== undefined ) {
  8463. delete indicesByUUID[ uuid ];
  8464. if ( index < nCachedObjects ) {
  8465. // object is cached, shrink the CACHED region
  8466. var firstActiveIndex = -- nCachedObjects,
  8467. lastCachedObject = objects[ firstActiveIndex ],
  8468. lastIndex = -- nObjects,
  8469. lastObject = objects[ lastIndex ];
  8470. // last cached object takes this object's place
  8471. indicesByUUID[ lastCachedObject.uuid ] = index;
  8472. objects[ index ] = lastCachedObject;
  8473. // last object goes to the activated slot and pop
  8474. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  8475. objects[ firstActiveIndex ] = lastObject;
  8476. objects.pop();
  8477. // accounting is done, now do the same for all bindings
  8478. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  8479. var bindingsForPath = bindings[ j ],
  8480. lastCached = bindingsForPath[ firstActiveIndex ],
  8481. last = bindingsForPath[ lastIndex ];
  8482. bindingsForPath[ index ] = lastCached;
  8483. bindingsForPath[ firstActiveIndex ] = last;
  8484. bindingsForPath.pop();
  8485. }
  8486. } else {
  8487. // object is active, just swap with the last and pop
  8488. var lastIndex = -- nObjects,
  8489. lastObject = objects[ lastIndex ];
  8490. indicesByUUID[ lastObject.uuid ] = index;
  8491. objects[ index ] = lastObject;
  8492. objects.pop();
  8493. // accounting is done, now do the same for all bindings
  8494. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  8495. var bindingsForPath = bindings[ j ];
  8496. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  8497. bindingsForPath.pop();
  8498. }
  8499. } // cached or active
  8500. } // if object is known
  8501. } // for arguments
  8502. this.nCachedObjects_ = nCachedObjects;
  8503. },
  8504. // Internal interface used by befriended PropertyBinding.Composite:
  8505. subscribe_: function( path, parsedPath ) {
  8506. // returns an array of bindings for the given path that is changed
  8507. // according to the contained objects in the group
  8508. var indicesByPath = this._bindingsIndicesByPath,
  8509. index = indicesByPath[ path ],
  8510. bindings = this._bindings;
  8511. if ( index !== undefined ) return bindings[ index ];
  8512. var paths = this._paths,
  8513. parsedPaths = this._parsedPaths,
  8514. objects = this._objects,
  8515. nObjects = objects.length,
  8516. nCachedObjects = this.nCachedObjects_,
  8517. bindingsForPath = new Array( nObjects );
  8518. index = bindings.length;
  8519. indicesByPath[ path ] = index;
  8520. paths.push( path );
  8521. parsedPaths.push( parsedPath );
  8522. bindings.push( bindingsForPath );
  8523. for ( var i = nCachedObjects,
  8524. n = objects.length; i !== n; ++ i ) {
  8525. var object = objects[ i ];
  8526. bindingsForPath[ i ] =
  8527. new THREE.PropertyBinding( object, path, parsedPath );
  8528. }
  8529. return bindingsForPath;
  8530. },
  8531. unsubscribe_: function( path ) {
  8532. // tells the group to forget about a property path and no longer
  8533. // update the array previously obtained with 'subscribe_'
  8534. var indicesByPath = this._bindingsIndicesByPath,
  8535. index = indicesByPath[ path ];
  8536. if ( index !== undefined ) {
  8537. var paths = this._paths,
  8538. parsedPaths = this._parsedPaths,
  8539. bindings = this._bindings,
  8540. lastBindingsIndex = bindings.length - 1,
  8541. lastBindings = bindings[ lastBindingsIndex ],
  8542. lastBindingsPath = path[ lastBindingsIndex ];
  8543. indicesByPath[ lastBindingsPath ] = index;
  8544. bindings[ index ] = lastBindings;
  8545. bindings.pop();
  8546. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  8547. parsedPaths.pop();
  8548. paths[ index ] = paths[ lastBindingsIndex ];
  8549. paths.pop();
  8550. }
  8551. }
  8552. };
  8553. // File:src/animation/AnimationUtils.js
  8554. /**
  8555. * @author tschw
  8556. * @author Ben Houston / http://clara.io/
  8557. * @author David Sarno / http://lighthaus.us/
  8558. */
  8559. THREE.AnimationUtils = {
  8560. // same as Array.prototype.slice, but also works on typed arrays
  8561. arraySlice: function( array, from, to ) {
  8562. if ( THREE.AnimationUtils.isTypedArray( array ) ) {
  8563. return new array.constructor( array.subarray( from, to ) );
  8564. }
  8565. return array.slice( from, to );
  8566. },
  8567. // converts an array to a specific type
  8568. convertArray: function( array, type, forceClone ) {
  8569. if ( ! array || // let 'undefined' and 'null' pass
  8570. ! forceClone && array.constructor === type ) return array;
  8571. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  8572. return new type( array ); // create typed array
  8573. }
  8574. return Array.prototype.slice.call( array ); // create Array
  8575. },
  8576. isTypedArray: function( object ) {
  8577. return ArrayBuffer.isView( object ) &&
  8578. ! ( object instanceof DataView );
  8579. },
  8580. // returns an array by which times and values can be sorted
  8581. getKeyframeOrder: function( times ) {
  8582. function compareTime( i, j ) {
  8583. return times[ i ] - times[ j ];
  8584. }
  8585. var n = times.length;
  8586. var result = new Array( n );
  8587. for ( var i = 0; i !== n; ++ i ) result[ i ] = i;
  8588. result.sort( compareTime );
  8589. return result;
  8590. },
  8591. // uses the array previously returned by 'getKeyframeOrder' to sort data
  8592. sortedArray: function( values, stride, order ) {
  8593. var nValues = values.length;
  8594. var result = new values.constructor( nValues );
  8595. for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  8596. var srcOffset = order[ i ] * stride;
  8597. for ( var j = 0; j !== stride; ++ j ) {
  8598. result[ dstOffset ++ ] = values[ srcOffset + j ];
  8599. }
  8600. }
  8601. return result;
  8602. },
  8603. // function for parsing AOS keyframe formats
  8604. flattenJSON: function( jsonKeys, times, values, valuePropertyName ) {
  8605. var i = 1, key = jsonKeys[ 0 ];
  8606. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  8607. key = jsonKeys[ i ++ ];
  8608. }
  8609. if ( key === undefined ) return; // no data
  8610. var value = key[ valuePropertyName ];
  8611. if ( value === undefined ) return; // no data
  8612. if ( Array.isArray( value ) ) {
  8613. do {
  8614. value = key[ valuePropertyName ];
  8615. if ( value !== undefined ) {
  8616. times.push( key.time );
  8617. values.push.apply( values, value ); // push all elements
  8618. }
  8619. key = jsonKeys[ i ++ ];
  8620. } while ( key !== undefined );
  8621. } else if ( value.toArray !== undefined ) {
  8622. // ...assume THREE.Math-ish
  8623. do {
  8624. value = key[ valuePropertyName ];
  8625. if ( value !== undefined ) {
  8626. times.push( key.time );
  8627. value.toArray( values, values.length );
  8628. }
  8629. key = jsonKeys[ i ++ ];
  8630. } while ( key !== undefined );
  8631. } else {
  8632. // otherwise push as-is
  8633. do {
  8634. value = key[ valuePropertyName ];
  8635. if ( value !== undefined ) {
  8636. times.push( key.time );
  8637. values.push( value );
  8638. }
  8639. key = jsonKeys[ i ++ ];
  8640. } while ( key !== undefined );
  8641. }
  8642. }
  8643. };
  8644. // File:src/animation/KeyframeTrack.js
  8645. /**
  8646. *
  8647. * A timed sequence of keyframes for a specific property.
  8648. *
  8649. *
  8650. * @author Ben Houston / http://clara.io/
  8651. * @author David Sarno / http://lighthaus.us/
  8652. * @author tschw
  8653. */
  8654. THREE.KeyframeTrack = function ( name, times, values, interpolation ) {
  8655. if( name === undefined ) throw new Error( "track name is undefined" );
  8656. if( times === undefined || times.length === 0 ) {
  8657. throw new Error( "no keyframes in track named " + name );
  8658. }
  8659. this.name = name;
  8660. this.times = THREE.AnimationUtils.convertArray( times, this.TimeBufferType );
  8661. this.values = THREE.AnimationUtils.convertArray( values, this.ValueBufferType );
  8662. this.setInterpolation( interpolation || this.DefaultInterpolation );
  8663. this.validate();
  8664. this.optimize();
  8665. };
  8666. THREE.KeyframeTrack.prototype = {
  8667. constructor: THREE.KeyframeTrack,
  8668. TimeBufferType: Float32Array,
  8669. ValueBufferType: Float32Array,
  8670. DefaultInterpolation: THREE.InterpolateLinear,
  8671. InterpolantFactoryMethodDiscrete: function( result ) {
  8672. return new THREE.DiscreteInterpolant(
  8673. this.times, this.values, this.getValueSize(), result );
  8674. },
  8675. InterpolantFactoryMethodLinear: function( result ) {
  8676. return new THREE.LinearInterpolant(
  8677. this.times, this.values, this.getValueSize(), result );
  8678. },
  8679. InterpolantFactoryMethodSmooth: function( result ) {
  8680. return new THREE.CubicInterpolant(
  8681. this.times, this.values, this.getValueSize(), result );
  8682. },
  8683. setInterpolation: function( interpolation ) {
  8684. var factoryMethod = undefined;
  8685. switch ( interpolation ) {
  8686. case THREE.InterpolateDiscrete:
  8687. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  8688. break;
  8689. case THREE.InterpolateLinear:
  8690. factoryMethod = this.InterpolantFactoryMethodLinear;
  8691. break;
  8692. case THREE.InterpolateSmooth:
  8693. factoryMethod = this.InterpolantFactoryMethodSmooth;
  8694. break;
  8695. }
  8696. if ( factoryMethod === undefined ) {
  8697. var message = "unsupported interpolation for " +
  8698. this.ValueTypeName + " keyframe track named " + this.name;
  8699. if ( this.createInterpolant === undefined ) {
  8700. // fall back to default, unless the default itself is messed up
  8701. if ( interpolation !== this.DefaultInterpolation ) {
  8702. this.setInterpolation( this.DefaultInterpolation );
  8703. } else {
  8704. throw new Error( message ); // fatal, in this case
  8705. }
  8706. }
  8707. console.warn( message );
  8708. return;
  8709. }
  8710. this.createInterpolant = factoryMethod;
  8711. },
  8712. getInterpolation: function() {
  8713. switch ( this.createInterpolant ) {
  8714. case this.InterpolantFactoryMethodDiscrete:
  8715. return THREE.InterpolateDiscrete;
  8716. case this.InterpolantFactoryMethodLinear:
  8717. return THREE.InterpolateLinear;
  8718. case this.InterpolantFactoryMethodSmooth:
  8719. return THREE.InterpolateSmooth;
  8720. }
  8721. },
  8722. getValueSize: function() {
  8723. return this.values.length / this.times.length;
  8724. },
  8725. // move all keyframes either forwards or backwards in time
  8726. shift: function( timeOffset ) {
  8727. if( timeOffset !== 0.0 ) {
  8728. var times = this.times;
  8729. for( var i = 0, n = times.length; i !== n; ++ i ) {
  8730. times[ i ] += timeOffset;
  8731. }
  8732. }
  8733. return this;
  8734. },
  8735. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  8736. scale: function( timeScale ) {
  8737. if( timeScale !== 1.0 ) {
  8738. var times = this.times;
  8739. for( var i = 0, n = times.length; i !== n; ++ i ) {
  8740. times[ i ] *= timeScale;
  8741. }
  8742. }
  8743. return this;
  8744. },
  8745. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  8746. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  8747. trim: function( startTime, endTime ) {
  8748. var times = this.times,
  8749. nKeys = times.length,
  8750. from = 0,
  8751. to = nKeys - 1;
  8752. while ( from !== nKeys && times[ from ] < startTime ) ++ from;
  8753. while ( to !== -1 && times[ to ] > endTime ) -- to;
  8754. ++ to; // inclusive -> exclusive bound
  8755. if( from !== 0 || to !== nKeys ) {
  8756. // empty tracks are forbidden, so keep at least one keyframe
  8757. if ( from >= to ) to = Math.max( to , 1 ), from = to - 1;
  8758. var stride = this.getValueSize();
  8759. this.times = THREE.AnimationUtils.arraySlice( times, from, to );
  8760. this.values = THREE.AnimationUtils.
  8761. arraySlice( this.values, from * stride, to * stride );
  8762. }
  8763. return this;
  8764. },
  8765. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  8766. validate: function() {
  8767. var valid = true;
  8768. var valueSize = this.getValueSize();
  8769. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  8770. console.error( "invalid value size in track", this );
  8771. valid = false;
  8772. }
  8773. var times = this.times,
  8774. values = this.values,
  8775. nKeys = times.length;
  8776. if( nKeys === 0 ) {
  8777. console.error( "track is empty", this );
  8778. valid = false;
  8779. }
  8780. var prevTime = null;
  8781. for( var i = 0; i !== nKeys; i ++ ) {
  8782. var currTime = times[ i ];
  8783. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  8784. console.error( "time is not a valid number", this, i, currTime );
  8785. valid = false;
  8786. break;
  8787. }
  8788. if( prevTime !== null && prevTime > currTime ) {
  8789. console.error( "out of order keys", this, i, currTime, prevTime );
  8790. valid = false;
  8791. break;
  8792. }
  8793. prevTime = currTime;
  8794. }
  8795. if ( values !== undefined ) {
  8796. if ( THREE.AnimationUtils.isTypedArray( values ) ) {
  8797. for ( var i = 0, n = values.length; i !== n; ++ i ) {
  8798. var value = values[ i ];
  8799. if ( isNaN( value ) ) {
  8800. console.error( "value is not a valid number", this, i, value );
  8801. valid = false;
  8802. break;
  8803. }
  8804. }
  8805. }
  8806. }
  8807. return valid;
  8808. },
  8809. // removes equivalent sequential keys as common in morph target sequences
  8810. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  8811. optimize: function() {
  8812. var times = this.times,
  8813. values = this.values,
  8814. stride = this.getValueSize(),
  8815. writeIndex = 1;
  8816. for( var i = 1, n = times.length - 1; i <= n; ++ i ) {
  8817. var keep = false;
  8818. var time = times[ i ];
  8819. var timeNext = times[ i + 1 ];
  8820. // remove adjacent keyframes scheduled at the same time
  8821. if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) {
  8822. // remove unnecessary keyframes same as their neighbors
  8823. var offset = i * stride,
  8824. offsetP = offset - stride,
  8825. offsetN = offset + stride;
  8826. for ( var j = 0; j !== stride; ++ j ) {
  8827. var value = values[ offset + j ];
  8828. if ( value !== values[ offsetP + j ] ||
  8829. value !== values[ offsetN + j ] ) {
  8830. keep = true;
  8831. break;
  8832. }
  8833. }
  8834. }
  8835. // in-place compaction
  8836. if ( keep ) {
  8837. if ( i !== writeIndex ) {
  8838. times[ writeIndex ] = times[ i ];
  8839. var readOffset = i * stride,
  8840. writeOffset = writeIndex * stride;
  8841. for ( var j = 0; j !== stride; ++ j ) {
  8842. values[ writeOffset + j ] = values[ readOffset + j ];
  8843. }
  8844. }
  8845. ++ writeIndex;
  8846. }
  8847. }
  8848. if ( writeIndex !== times.length ) {
  8849. this.times = THREE.AnimationUtils.arraySlice( times, 0, writeIndex );
  8850. this.values = THREE.AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  8851. }
  8852. return this;
  8853. }
  8854. };
  8855. // Static methods:
  8856. Object.assign( THREE.KeyframeTrack, {
  8857. // Serialization (in static context, because of constructor invocation
  8858. // and automatic invocation of .toJSON):
  8859. parse: function( json ) {
  8860. if( json.type === undefined ) {
  8861. throw new Error( "track type undefined, can not parse" );
  8862. }
  8863. var trackType = THREE.KeyframeTrack._getTrackTypeForValueTypeName( json.type );
  8864. if ( json.times === undefined ) {
  8865. console.warn( "legacy JSON format detected, converting" );
  8866. var times = [], values = [];
  8867. THREE.AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  8868. json.times = times;
  8869. json.values = values;
  8870. }
  8871. // derived classes can define a static parse method
  8872. if ( trackType.parse !== undefined ) {
  8873. return trackType.parse( json );
  8874. } else {
  8875. // by default, we asssume a constructor compatible with the base
  8876. return new trackType(
  8877. json.name, json.times, json.values, json.interpolation );
  8878. }
  8879. },
  8880. toJSON: function( track ) {
  8881. var trackType = track.constructor;
  8882. var json;
  8883. // derived classes can define a static toJSON method
  8884. if ( trackType.toJSON !== undefined ) {
  8885. json = trackType.toJSON( track );
  8886. } else {
  8887. // by default, we assume the data can be serialized as-is
  8888. json = {
  8889. 'name': track.name,
  8890. 'times': THREE.AnimationUtils.convertArray( track.times, Array ),
  8891. 'values': THREE.AnimationUtils.convertArray( track.values, Array )
  8892. };
  8893. var interpolation = track.getInterpolation();
  8894. if ( interpolation !== track.DefaultInterpolation ) {
  8895. json.interpolation = interpolation;
  8896. }
  8897. }
  8898. json.type = track.ValueTypeName; // mandatory
  8899. return json;
  8900. },
  8901. _getTrackTypeForValueTypeName: function( typeName ) {
  8902. switch( typeName.toLowerCase() ) {
  8903. case "scalar":
  8904. case "double":
  8905. case "float":
  8906. case "number":
  8907. case "integer":
  8908. return THREE.NumberKeyframeTrack;
  8909. case "vector":
  8910. case "vector2":
  8911. case "vector3":
  8912. case "vector4":
  8913. return THREE.VectorKeyframeTrack;
  8914. case "color":
  8915. return THREE.ColorKeyframeTrack;
  8916. case "quaternion":
  8917. return THREE.QuaternionKeyframeTrack;
  8918. case "bool":
  8919. case "boolean":
  8920. return THREE.BooleanKeyframeTrack;
  8921. case "string":
  8922. return THREE.StringKeyframeTrack;
  8923. };
  8924. throw new Error( "Unsupported typeName: " + typeName );
  8925. }
  8926. } );
  8927. // File:src/animation/PropertyBinding.js
  8928. /**
  8929. *
  8930. * A reference to a real property in the scene graph.
  8931. *
  8932. *
  8933. * @author Ben Houston / http://clara.io/
  8934. * @author David Sarno / http://lighthaus.us/
  8935. * @author tschw
  8936. */
  8937. THREE.PropertyBinding = function ( rootNode, path, parsedPath ) {
  8938. this.path = path;
  8939. this.parsedPath = parsedPath ||
  8940. THREE.PropertyBinding.parseTrackName( path );
  8941. this.node = THREE.PropertyBinding.findNode(
  8942. rootNode, this.parsedPath.nodeName ) || rootNode;
  8943. this.rootNode = rootNode;
  8944. };
  8945. THREE.PropertyBinding.prototype = {
  8946. constructor: THREE.PropertyBinding,
  8947. getValue: function getValue_unbound( targetArray, offset ) {
  8948. this.bind();
  8949. this.getValue( targetArray, offset );
  8950. // Note: This class uses a State pattern on a per-method basis:
  8951. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  8952. // prototype version of these methods with one that represents
  8953. // the bound state. When the property is not found, the methods
  8954. // become no-ops.
  8955. },
  8956. setValue: function getValue_unbound( sourceArray, offset ) {
  8957. this.bind();
  8958. this.setValue( sourceArray, offset );
  8959. },
  8960. // create getter / setter pair for a property in the scene graph
  8961. bind: function() {
  8962. var targetObject = this.node,
  8963. parsedPath = this.parsedPath,
  8964. objectName = parsedPath.objectName,
  8965. propertyName = parsedPath.propertyName,
  8966. propertyIndex = parsedPath.propertyIndex;
  8967. if ( ! targetObject ) {
  8968. targetObject = THREE.PropertyBinding.findNode(
  8969. this.rootNode, parsedPath.nodeName ) || this.rootNode;
  8970. this.node = targetObject;
  8971. }
  8972. // set fail state so we can just 'return' on error
  8973. this.getValue = this._getValue_unavailable;
  8974. this.setValue = this._setValue_unavailable;
  8975. // ensure there is a value node
  8976. if ( ! targetObject ) {
  8977. console.error( " trying to update node for track: " + this.path + " but it wasn't found." );
  8978. return;
  8979. }
  8980. if( objectName ) {
  8981. var objectIndex = parsedPath.objectIndex;
  8982. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  8983. switch ( objectName ) {
  8984. case 'materials':
  8985. if( ! targetObject.material ) {
  8986. console.error( ' can not bind to material as node does not have a material', this );
  8987. return;
  8988. }
  8989. if( ! targetObject.material.materials ) {
  8990. console.error( ' can not bind to material.materials as node.material does not have a materials array', this );
  8991. return;
  8992. }
  8993. targetObject = targetObject.material.materials;
  8994. break;
  8995. case 'bones':
  8996. if( ! targetObject.skeleton ) {
  8997. console.error( ' can not bind to bones as node does not have a skeleton', this );
  8998. return;
  8999. }
  9000. // potential future optimization: skip this if propertyIndex is already an integer
  9001. // and convert the integer string to a true integer.
  9002. targetObject = targetObject.skeleton.bones;
  9003. // support resolving morphTarget names into indices.
  9004. for ( var i = 0; i < targetObject.length; i ++ ) {
  9005. if ( targetObject[i].name === objectIndex ) {
  9006. objectIndex = i;
  9007. break;
  9008. }
  9009. }
  9010. break;
  9011. default:
  9012. if ( targetObject[ objectName ] === undefined ) {
  9013. console.error( ' can not bind to objectName of node, undefined', this );
  9014. return;
  9015. }
  9016. targetObject = targetObject[ objectName ];
  9017. }
  9018. if ( objectIndex !== undefined ) {
  9019. if( targetObject[ objectIndex ] === undefined ) {
  9020. console.error( " trying to bind to objectIndex of objectName, but is undefined:", this, targetObject );
  9021. return;
  9022. }
  9023. targetObject = targetObject[ objectIndex ];
  9024. }
  9025. }
  9026. // resolve property
  9027. var nodeProperty = targetObject[ propertyName ];
  9028. if ( ! nodeProperty ) {
  9029. var nodeName = parsedPath.nodeName;
  9030. console.error( " trying to update property for track: " + nodeName +
  9031. '.' + propertyName + " but it wasn't found.", targetObject );
  9032. return;
  9033. }
  9034. // determine versioning scheme
  9035. var versioning = this.Versioning.None;
  9036. if ( targetObject.needsUpdate !== undefined ) { // material
  9037. versioning = this.Versioning.NeedsUpdate;
  9038. this.targetObject = targetObject;
  9039. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  9040. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  9041. this.targetObject = targetObject;
  9042. }
  9043. // determine how the property gets bound
  9044. var bindingType = this.BindingType.Direct;
  9045. if ( propertyIndex !== undefined ) {
  9046. // access a sub element of the property array (only primitives are supported right now)
  9047. if ( propertyName === "morphTargetInfluences" ) {
  9048. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  9049. // support resolving morphTarget names into indices.
  9050. if ( ! targetObject.geometry ) {
  9051. console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry', this );
  9052. return;
  9053. }
  9054. if ( ! targetObject.geometry.morphTargets ) {
  9055. console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry.morphTargets', this );
  9056. return;
  9057. }
  9058. for ( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) {
  9059. if ( targetObject.geometry.morphTargets[i].name === propertyIndex ) {
  9060. propertyIndex = i;
  9061. break;
  9062. }
  9063. }
  9064. }
  9065. bindingType = this.BindingType.ArrayElement;
  9066. this.resolvedProperty = nodeProperty;
  9067. this.propertyIndex = propertyIndex;
  9068. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  9069. // must use copy for Object3D.Euler/Quaternion
  9070. bindingType = this.BindingType.HasFromToArray;
  9071. this.resolvedProperty = nodeProperty;
  9072. } else if ( nodeProperty.length !== undefined ) {
  9073. bindingType = this.BindingType.EntireArray;
  9074. this.resolvedProperty = nodeProperty;
  9075. } else {
  9076. this.propertyName = propertyName;
  9077. }
  9078. // select getter / setter
  9079. this.getValue = this.GetterByBindingType[ bindingType ];
  9080. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  9081. },
  9082. unbind: function() {
  9083. this.node = null;
  9084. // back to the prototype version of getValue / setValue
  9085. // note: avoiding to mutate the shape of 'this' via 'delete'
  9086. this.getValue = this._getValue_unbound;
  9087. this.setValue = this._setValue_unbound;
  9088. }
  9089. };
  9090. Object.assign( THREE.PropertyBinding.prototype, { // prototype, continued
  9091. // these are used to "bind" a nonexistent property
  9092. _getValue_unavailable: function() {},
  9093. _setValue_unavailable: function() {},
  9094. // initial state of these methods that calls 'bind'
  9095. _getValue_unbound: THREE.PropertyBinding.prototype.getValue,
  9096. _setValue_unbound: THREE.PropertyBinding.prototype.setValue,
  9097. BindingType: {
  9098. Direct: 0,
  9099. EntireArray: 1,
  9100. ArrayElement: 2,
  9101. HasFromToArray: 3
  9102. },
  9103. Versioning: {
  9104. None: 0,
  9105. NeedsUpdate: 1,
  9106. MatrixWorldNeedsUpdate: 2
  9107. },
  9108. GetterByBindingType: [
  9109. function getValue_direct( buffer, offset ) {
  9110. buffer[ offset ] = this.node[ this.propertyName ];
  9111. },
  9112. function getValue_array( buffer, offset ) {
  9113. var source = this.resolvedProperty;
  9114. for ( var i = 0, n = source.length; i !== n; ++ i ) {
  9115. buffer[ offset ++ ] = source[ i ];
  9116. }
  9117. },
  9118. function getValue_arrayElement( buffer, offset ) {
  9119. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  9120. },
  9121. function getValue_toArray( buffer, offset ) {
  9122. this.resolvedProperty.toArray( buffer, offset );
  9123. }
  9124. ],
  9125. SetterByBindingTypeAndVersioning: [
  9126. [
  9127. // Direct
  9128. function setValue_direct( buffer, offset ) {
  9129. this.node[ this.propertyName ] = buffer[ offset ];
  9130. },
  9131. function setValue_direct_setNeedsUpdate( buffer, offset ) {
  9132. this.node[ this.propertyName ] = buffer[ offset ];
  9133. this.targetObject.needsUpdate = true;
  9134. },
  9135. function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  9136. this.node[ this.propertyName ] = buffer[ offset ];
  9137. this.targetObject.matrixWorldNeedsUpdate = true;
  9138. }
  9139. ], [
  9140. // EntireArray
  9141. function setValue_array( buffer, offset ) {
  9142. var dest = this.resolvedProperty;
  9143. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  9144. dest[ i ] = buffer[ offset ++ ];
  9145. }
  9146. },
  9147. function setValue_array_setNeedsUpdate( buffer, offset ) {
  9148. var dest = this.resolvedProperty;
  9149. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  9150. dest[ i ] = buffer[ offset ++ ];
  9151. }
  9152. this.targetObject.needsUpdate = true;
  9153. },
  9154. function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  9155. var dest = this.resolvedProperty;
  9156. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  9157. dest[ i ] = buffer[ offset ++ ];
  9158. }
  9159. this.targetObject.matrixWorldNeedsUpdate = true;
  9160. }
  9161. ], [
  9162. // ArrayElement
  9163. function setValue_arrayElement( buffer, offset ) {
  9164. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  9165. },
  9166. function setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  9167. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  9168. this.targetObject.needsUpdate = true;
  9169. },
  9170. function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  9171. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  9172. this.targetObject.matrixWorldNeedsUpdate = true;
  9173. }
  9174. ], [
  9175. // HasToFromArray
  9176. function setValue_fromArray( buffer, offset ) {
  9177. this.resolvedProperty.fromArray( buffer, offset );
  9178. },
  9179. function setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  9180. this.resolvedProperty.fromArray( buffer, offset );
  9181. this.targetObject.needsUpdate = true;
  9182. },
  9183. function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  9184. this.resolvedProperty.fromArray( buffer, offset );
  9185. this.targetObject.matrixWorldNeedsUpdate = true;
  9186. }
  9187. ]
  9188. ]
  9189. } );
  9190. THREE.PropertyBinding.Composite =
  9191. function( targetGroup, path, optionalParsedPath ) {
  9192. var parsedPath = optionalParsedPath ||
  9193. THREE.PropertyBinding.parseTrackName( path );
  9194. this._targetGroup = targetGroup;
  9195. this._bindings = targetGroup.subscribe_( path, parsedPath );
  9196. };
  9197. THREE.PropertyBinding.Composite.prototype = {
  9198. constructor: THREE.PropertyBinding.Composite,
  9199. getValue: function( array, offset ) {
  9200. this.bind(); // bind all binding
  9201. var firstValidIndex = this._targetGroup.nCachedObjects_,
  9202. binding = this._bindings[ firstValidIndex ];
  9203. // and only call .getValue on the first
  9204. if ( binding !== undefined ) binding.getValue( array, offset );
  9205. },
  9206. setValue: function( array, offset ) {
  9207. var bindings = this._bindings;
  9208. for ( var i = this._targetGroup.nCachedObjects_,
  9209. n = bindings.length; i !== n; ++ i ) {
  9210. bindings[ i ].setValue( array, offset );
  9211. }
  9212. },
  9213. bind: function() {
  9214. var bindings = this._bindings;
  9215. for ( var i = this._targetGroup.nCachedObjects_,
  9216. n = bindings.length; i !== n; ++ i ) {
  9217. bindings[ i ].bind();
  9218. }
  9219. },
  9220. unbind: function() {
  9221. var bindings = this._bindings;
  9222. for ( var i = this._targetGroup.nCachedObjects_,
  9223. n = bindings.length; i !== n; ++ i ) {
  9224. bindings[ i ].unbind();
  9225. }
  9226. }
  9227. };
  9228. THREE.PropertyBinding.create = function( root, path, parsedPath ) {
  9229. if ( ! ( root instanceof THREE.AnimationObjectGroup ) ) {
  9230. return new THREE.PropertyBinding( root, path, parsedPath );
  9231. } else {
  9232. return new THREE.PropertyBinding.Composite( root, path, parsedPath );
  9233. }
  9234. };
  9235. THREE.PropertyBinding.parseTrackName = function( trackName ) {
  9236. // matches strings in the form of:
  9237. // nodeName.property
  9238. // nodeName.property[accessor]
  9239. // nodeName.material.property[accessor]
  9240. // uuid.property[accessor]
  9241. // uuid.objectName[objectIndex].propertyName[propertyIndex]
  9242. // parentName/nodeName.property
  9243. // parentName/parentName/nodeName.property[index]
  9244. // .bone[Armature.DEF_cog].position
  9245. // created and tested via https://regex101.com/#javascript
  9246. var re = /^(([\w]+\/)*)([\w-\d]+)?(\.([\w]+)(\[([\w\d\[\]\_.:\- ]+)\])?)?(\.([\w.]+)(\[([\w\d\[\]\_. ]+)\])?)$/;
  9247. var matches = re.exec(trackName);
  9248. if( ! matches ) {
  9249. throw new Error( "cannot parse trackName at all: " + trackName );
  9250. }
  9251. if (matches.index === re.lastIndex) {
  9252. re.lastIndex++;
  9253. }
  9254. var results = {
  9255. // directoryName: matches[1], // (tschw) currently unused
  9256. nodeName: matches[3], // allowed to be null, specified root node.
  9257. objectName: matches[5],
  9258. objectIndex: matches[7],
  9259. propertyName: matches[9],
  9260. propertyIndex: matches[11] // allowed to be null, specifies that the whole property is set.
  9261. };
  9262. if( results.propertyName === null || results.propertyName.length === 0 ) {
  9263. throw new Error( "can not parse propertyName from trackName: " + trackName );
  9264. }
  9265. return results;
  9266. };
  9267. THREE.PropertyBinding.findNode = function( root, nodeName ) {
  9268. if( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  9269. return root;
  9270. }
  9271. // search into skeleton bones.
  9272. if( root.skeleton ) {
  9273. var searchSkeleton = function( skeleton ) {
  9274. for( var i = 0; i < skeleton.bones.length; i ++ ) {
  9275. var bone = skeleton.bones[i];
  9276. if( bone.name === nodeName ) {
  9277. return bone;
  9278. }
  9279. }
  9280. return null;
  9281. };
  9282. var bone = searchSkeleton( root.skeleton );
  9283. if( bone ) {
  9284. return bone;
  9285. }
  9286. }
  9287. // search into node subtree.
  9288. if( root.children ) {
  9289. var searchNodeSubtree = function( children ) {
  9290. for( var i = 0; i < children.length; i ++ ) {
  9291. var childNode = children[i];
  9292. if( childNode.name === nodeName || childNode.uuid === nodeName ) {
  9293. return childNode;
  9294. }
  9295. var result = searchNodeSubtree( childNode.children );
  9296. if( result ) return result;
  9297. }
  9298. return null;
  9299. };
  9300. var subTreeNode = searchNodeSubtree( root.children );
  9301. if( subTreeNode ) {
  9302. return subTreeNode;
  9303. }
  9304. }
  9305. return null;
  9306. }
  9307. // File:src/animation/PropertyMixer.js
  9308. /**
  9309. *
  9310. * Buffered scene graph property that allows weighted accumulation.
  9311. *
  9312. *
  9313. * @author Ben Houston / http://clara.io/
  9314. * @author David Sarno / http://lighthaus.us/
  9315. * @author tschw
  9316. */
  9317. THREE.PropertyMixer = function ( binding, typeName, valueSize ) {
  9318. this.binding = binding;
  9319. this.valueSize = valueSize;
  9320. var bufferType = Float64Array,
  9321. mixFunction;
  9322. switch ( typeName ) {
  9323. case 'quaternion': mixFunction = this._slerp; break;
  9324. case 'string':
  9325. case 'bool':
  9326. bufferType = Array, mixFunction = this._select; break;
  9327. default: mixFunction = this._lerp;
  9328. }
  9329. this.buffer = new bufferType( valueSize * 4 );
  9330. // layout: [ incoming | accu0 | accu1 | orig ]
  9331. //
  9332. // interpolators can use .buffer as their .result
  9333. // the data then goes to 'incoming'
  9334. //
  9335. // 'accu0' and 'accu1' are used frame-interleaved for
  9336. // the cumulative result and are compared to detect
  9337. // changes
  9338. //
  9339. // 'orig' stores the original state of the property
  9340. this._mixBufferRegion = mixFunction;
  9341. this.cumulativeWeight = 0;
  9342. this.useCount = 0;
  9343. this.referenceCount = 0;
  9344. };
  9345. THREE.PropertyMixer.prototype = {
  9346. constructor: THREE.PropertyMixer,
  9347. // accumulate data in the 'incoming' region into 'accu<i>'
  9348. accumulate: function( accuIndex, weight ) {
  9349. // note: happily accumulating nothing when weight = 0, the caller knows
  9350. // the weight and shouldn't have made the call in the first place
  9351. var buffer = this.buffer,
  9352. stride = this.valueSize,
  9353. offset = accuIndex * stride + stride,
  9354. currentWeight = this.cumulativeWeight;
  9355. if ( currentWeight === 0 ) {
  9356. // accuN := incoming * weight
  9357. for ( var i = 0; i !== stride; ++ i ) {
  9358. buffer[ offset + i ] = buffer[ i ];
  9359. }
  9360. currentWeight = weight;
  9361. } else {
  9362. // accuN := accuN + incoming * weight
  9363. currentWeight += weight;
  9364. var mix = weight / currentWeight;
  9365. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  9366. }
  9367. this.cumulativeWeight = currentWeight;
  9368. },
  9369. // apply the state of 'accu<i>' to the binding when accus differ
  9370. apply: function( accuIndex ) {
  9371. var stride = this.valueSize,
  9372. buffer = this.buffer,
  9373. offset = accuIndex * stride + stride,
  9374. weight = this.cumulativeWeight,
  9375. binding = this.binding;
  9376. this.cumulativeWeight = 0;
  9377. if ( weight < 1 ) {
  9378. // accuN := accuN + original * ( 1 - cumulativeWeight )
  9379. var originalValueOffset = stride * 3;
  9380. this._mixBufferRegion(
  9381. buffer, offset, originalValueOffset, 1 - weight, stride );
  9382. }
  9383. for ( var i = stride, e = stride + stride; i !== e; ++ i ) {
  9384. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  9385. // value has changed -> update scene graph
  9386. binding.setValue( buffer, offset );
  9387. break;
  9388. }
  9389. }
  9390. },
  9391. // remember the state of the bound property and copy it to both accus
  9392. saveOriginalState: function() {
  9393. var binding = this.binding;
  9394. var buffer = this.buffer,
  9395. stride = this.valueSize,
  9396. originalValueOffset = stride * 3;
  9397. binding.getValue( buffer, originalValueOffset );
  9398. // accu[0..1] := orig -- initially detect changes against the original
  9399. for ( var i = stride, e = originalValueOffset; i !== e; ++ i ) {
  9400. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  9401. }
  9402. this.cumulativeWeight = 0;
  9403. },
  9404. // apply the state previously taken via 'saveOriginalState' to the binding
  9405. restoreOriginalState: function() {
  9406. var originalValueOffset = this.valueSize * 3;
  9407. this.binding.setValue( this.buffer, originalValueOffset );
  9408. },
  9409. // mix functions
  9410. _select: function( buffer, dstOffset, srcOffset, t, stride ) {
  9411. if ( t >= 0.5 ) {
  9412. for ( var i = 0; i !== stride; ++ i ) {
  9413. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  9414. }
  9415. }
  9416. },
  9417. _slerp: function( buffer, dstOffset, srcOffset, t, stride ) {
  9418. THREE.Quaternion.slerpFlat( buffer, dstOffset,
  9419. buffer, dstOffset, buffer, srcOffset, t );
  9420. },
  9421. _lerp: function( buffer, dstOffset, srcOffset, t, stride ) {
  9422. var s = 1 - t;
  9423. for ( var i = 0; i !== stride; ++ i ) {
  9424. var j = dstOffset + i;
  9425. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  9426. }
  9427. }
  9428. };
  9429. // File:src/animation/tracks/BooleanKeyframeTrack.js
  9430. /**
  9431. *
  9432. * A Track of Boolean keyframe values.
  9433. *
  9434. *
  9435. * @author Ben Houston / http://clara.io/
  9436. * @author David Sarno / http://lighthaus.us/
  9437. * @author tschw
  9438. */
  9439. THREE.BooleanKeyframeTrack = function ( name, times, values ) {
  9440. THREE.KeyframeTrack.call( this, name, times, values );
  9441. };
  9442. THREE.BooleanKeyframeTrack.prototype =
  9443. Object.assign( Object.create( THREE.KeyframeTrack.prototype ), {
  9444. constructor: THREE.BooleanKeyframeTrack,
  9445. ValueTypeName: 'bool',
  9446. ValueBufferType: Array,
  9447. DefaultInterpolation: THREE.IntepolateDiscrete,
  9448. InterpolantFactoryMethodLinear: undefined,
  9449. InterpolantFactoryMethodSmooth: undefined
  9450. // Note: Actually this track could have a optimized / compressed
  9451. // representation of a single value and a custom interpolant that
  9452. // computes "firstValue ^ isOdd( index )".
  9453. } );
  9454. // File:src/animation/tracks/ColorKeyframeTrack.js
  9455. /**
  9456. *
  9457. * A Track of keyframe values that represent color.
  9458. *
  9459. *
  9460. * @author Ben Houston / http://clara.io/
  9461. * @author David Sarno / http://lighthaus.us/
  9462. * @author tschw
  9463. */
  9464. THREE.ColorKeyframeTrack = function ( name, times, values, interpolation ) {
  9465. THREE.KeyframeTrack.call( this, name, times, values, interpolation );
  9466. };
  9467. THREE.ColorKeyframeTrack.prototype =
  9468. Object.assign( Object.create( THREE.KeyframeTrack.prototype ), {
  9469. constructor: THREE.ColorKeyframeTrack,
  9470. ValueTypeName: 'color'
  9471. // ValueBufferType is inherited
  9472. // DefaultInterpolation is inherited
  9473. // Note: Very basic implementation and nothing special yet.
  9474. // However, this is the place for color space parameterization.
  9475. } );
  9476. // File:src/animation/tracks/NumberKeyframeTrack.js
  9477. /**
  9478. *
  9479. * A Track of numeric keyframe values.
  9480. *
  9481. * @author Ben Houston / http://clara.io/
  9482. * @author David Sarno / http://lighthaus.us/
  9483. * @author tschw
  9484. */
  9485. THREE.NumberKeyframeTrack = function ( name, times, values, interpolation ) {
  9486. THREE.KeyframeTrack.call( this, name, times, values, interpolation );
  9487. };
  9488. THREE.NumberKeyframeTrack.prototype =
  9489. Object.assign( Object.create( THREE.KeyframeTrack.prototype ), {
  9490. constructor: THREE.NumberKeyframeTrack,
  9491. ValueTypeName: 'number',
  9492. // ValueBufferType is inherited
  9493. // DefaultInterpolation is inherited
  9494. } );
  9495. // File:src/animation/tracks/QuaternionKeyframeTrack.js
  9496. /**
  9497. *
  9498. * A Track of quaternion keyframe values.
  9499. *
  9500. * @author Ben Houston / http://clara.io/
  9501. * @author David Sarno / http://lighthaus.us/
  9502. * @author tschw
  9503. */
  9504. THREE.QuaternionKeyframeTrack = function ( name, times, values, interpolation ) {
  9505. THREE.KeyframeTrack.call( this, name, times, values, interpolation );
  9506. };
  9507. THREE.QuaternionKeyframeTrack.prototype =
  9508. Object.assign( Object.create( THREE.KeyframeTrack.prototype ), {
  9509. constructor: THREE.QuaternionKeyframeTrack,
  9510. ValueTypeName: 'quaternion',
  9511. // ValueBufferType is inherited
  9512. DefaultInterpolation: THREE.InterpolateLinear,
  9513. InterpolantFactoryMethodLinear: function( result ) {
  9514. return new THREE.QuaternionLinearInterpolant(
  9515. this.times, this.values, this.getValueSize(), result );
  9516. },
  9517. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  9518. } );
  9519. // File:src/animation/tracks/StringKeyframeTrack.js
  9520. /**
  9521. *
  9522. * A Track that interpolates Strings
  9523. *
  9524. *
  9525. * @author Ben Houston / http://clara.io/
  9526. * @author David Sarno / http://lighthaus.us/
  9527. * @author tschw
  9528. */
  9529. THREE.StringKeyframeTrack = function ( name, times, values, interpolation ) {
  9530. THREE.KeyframeTrack.call( this, name, times, values, interpolation );
  9531. };
  9532. THREE.StringKeyframeTrack.prototype =
  9533. Object.assign( Object.create( THREE.KeyframeTrack.prototype ), {
  9534. constructor: THREE.StringKeyframeTrack,
  9535. ValueTypeName: 'string',
  9536. ValueBufferType: Array,
  9537. DefaultInterpolation: THREE.IntepolateDiscrete,
  9538. InterpolantFactoryMethodLinear: undefined,
  9539. InterpolantFactoryMethodSmooth: undefined
  9540. } );
  9541. // File:src/animation/tracks/VectorKeyframeTrack.js
  9542. /**
  9543. *
  9544. * A Track of vectored keyframe values.
  9545. *
  9546. *
  9547. * @author Ben Houston / http://clara.io/
  9548. * @author David Sarno / http://lighthaus.us/
  9549. * @author tschw
  9550. */
  9551. THREE.VectorKeyframeTrack = function ( name, times, values, interpolation ) {
  9552. THREE.KeyframeTrack.call( this, name, times, values, interpolation );
  9553. };
  9554. THREE.VectorKeyframeTrack.prototype =
  9555. Object.assign( Object.create( THREE.KeyframeTrack.prototype ), {
  9556. constructor: THREE.VectorKeyframeTrack,
  9557. ValueTypeName: 'vector'
  9558. // ValueBufferType is inherited
  9559. // DefaultInterpolation is inherited
  9560. } );
  9561. // File:src/audio/Audio.js
  9562. /**
  9563. * @author mrdoob / http://mrdoob.com/
  9564. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  9565. */
  9566. THREE.Audio = function ( listener ) {
  9567. THREE.Object3D.call( this );
  9568. this.type = 'Audio';
  9569. this.context = listener.context;
  9570. this.source = this.context.createBufferSource();
  9571. this.source.onended = this.onEnded.bind( this );
  9572. this.gain = this.context.createGain();
  9573. this.gain.connect( listener.getInput() );
  9574. this.autoplay = false;
  9575. this.startTime = 0;
  9576. this.playbackRate = 1;
  9577. this.isPlaying = false;
  9578. this.hasPlaybackControl = true;
  9579. this.sourceType = 'empty';
  9580. this.filter = null;
  9581. };
  9582. THREE.Audio.prototype = Object.create( THREE.Object3D.prototype );
  9583. THREE.Audio.prototype.constructor = THREE.Audio;
  9584. THREE.Audio.prototype.getOutput = function () {
  9585. return this.gain;
  9586. };
  9587. THREE.Audio.prototype.load = function ( file ) {
  9588. console.warn( 'THREE.Audio: .load has been deprecated. Please use THREE.AudioLoader.' );
  9589. var scope = this;
  9590. var audioLoader = new THREE.AudioLoader();
  9591. audioLoader.load( file, function ( buffer ) {
  9592. scope.setBuffer( buffer );
  9593. } );
  9594. return this;
  9595. };
  9596. THREE.Audio.prototype.setNodeSource = function ( audioNode ) {
  9597. this.hasPlaybackControl = false;
  9598. this.sourceType = 'audioNode';
  9599. this.source = audioNode;
  9600. this.connect();
  9601. return this;
  9602. };
  9603. THREE.Audio.prototype.setBuffer = function ( audioBuffer ) {
  9604. var scope = this;
  9605. scope.source.buffer = audioBuffer;
  9606. scope.sourceType = 'buffer';
  9607. if ( scope.autoplay ) scope.play();
  9608. return this;
  9609. };
  9610. THREE.Audio.prototype.play = function () {
  9611. if ( this.isPlaying === true ) {
  9612. console.warn( 'THREE.Audio: Audio is already playing.' );
  9613. return;
  9614. }
  9615. if ( this.hasPlaybackControl === false ) {
  9616. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  9617. return;
  9618. }
  9619. var source = this.context.createBufferSource();
  9620. source.buffer = this.source.buffer;
  9621. source.loop = this.source.loop;
  9622. source.onended = this.source.onended;
  9623. source.start( 0, this.startTime );
  9624. source.playbackRate.value = this.playbackRate;
  9625. this.isPlaying = true;
  9626. this.source = source;
  9627. this.connect();
  9628. };
  9629. THREE.Audio.prototype.pause = function () {
  9630. if ( this.hasPlaybackControl === false ) {
  9631. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  9632. return;
  9633. }
  9634. this.source.stop();
  9635. this.startTime = this.context.currentTime;
  9636. };
  9637. THREE.Audio.prototype.stop = function () {
  9638. if ( this.hasPlaybackControl === false ) {
  9639. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  9640. return;
  9641. }
  9642. this.source.stop();
  9643. this.startTime = 0;
  9644. };
  9645. THREE.Audio.prototype.connect = function () {
  9646. if ( this.filter !== null ) {
  9647. this.source.connect( this.filter );
  9648. this.filter.connect( this.getOutput() );
  9649. } else {
  9650. this.source.connect( this.getOutput() );
  9651. }
  9652. };
  9653. THREE.Audio.prototype.disconnect = function () {
  9654. if ( this.filter !== null ) {
  9655. this.source.disconnect( this.filter );
  9656. this.filter.disconnect( this.getOutput() );
  9657. } else {
  9658. this.source.disconnect( this.getOutput() );
  9659. }
  9660. };
  9661. THREE.Audio.prototype.getFilter = function () {
  9662. return this.filter;
  9663. };
  9664. THREE.Audio.prototype.setFilter = function ( value ) {
  9665. if ( value === undefined ) value = null;
  9666. if ( this.isPlaying === true ) {
  9667. this.disconnect();
  9668. this.filter = value;
  9669. this.connect();
  9670. } else {
  9671. this.filter = value;
  9672. }
  9673. };
  9674. THREE.Audio.prototype.setPlaybackRate = function ( value ) {
  9675. if ( this.hasPlaybackControl === false ) {
  9676. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  9677. return;
  9678. }
  9679. this.playbackRate = value;
  9680. if ( this.isPlaying === true ) {
  9681. this.source.playbackRate.value = this.playbackRate;
  9682. }
  9683. };
  9684. THREE.Audio.prototype.getPlaybackRate = function () {
  9685. return this.playbackRate;
  9686. };
  9687. THREE.Audio.prototype.onEnded = function () {
  9688. this.isPlaying = false;
  9689. };
  9690. THREE.Audio.prototype.setLoop = function ( value ) {
  9691. if ( this.hasPlaybackControl === false ) {
  9692. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  9693. return;
  9694. }
  9695. this.source.loop = value;
  9696. };
  9697. THREE.Audio.prototype.getLoop = function () {
  9698. if ( this.hasPlaybackControl === false ) {
  9699. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  9700. return false;
  9701. }
  9702. return this.source.loop;
  9703. };
  9704. THREE.Audio.prototype.setVolume = function ( value ) {
  9705. this.gain.gain.value = value;
  9706. };
  9707. THREE.Audio.prototype.getVolume = function () {
  9708. return this.gain.gain.value;
  9709. };
  9710. // File:src/audio/AudioAnalyser.js
  9711. /**
  9712. * @author mrdoob / http://mrdoob.com/
  9713. */
  9714. THREE.AudioAnalyser = function ( audio, fftSize ) {
  9715. this.analyser = audio.context.createAnalyser();
  9716. this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048;
  9717. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  9718. audio.getOutput().connect( this.analyser );
  9719. };
  9720. THREE.AudioAnalyser.prototype = {
  9721. constructor: THREE.AudioAnalyser,
  9722. getData: function () {
  9723. this.analyser.getByteFrequencyData( this.data );
  9724. return this.data;
  9725. }
  9726. };
  9727. // File:src/audio/AudioContext.js
  9728. /**
  9729. * @author mrdoob / http://mrdoob.com/
  9730. */
  9731. Object.defineProperty( THREE, 'AudioContext', {
  9732. get: ( function () {
  9733. var context;
  9734. return function () {
  9735. if ( context === undefined ) {
  9736. context = new ( window.AudioContext || window.webkitAudioContext )();
  9737. }
  9738. return context;
  9739. };
  9740. } )()
  9741. } );
  9742. // File:src/audio/PositionalAudio.js
  9743. /**
  9744. * @author mrdoob / http://mrdoob.com/
  9745. */
  9746. THREE.PositionalAudio = function ( listener ) {
  9747. THREE.Audio.call( this, listener );
  9748. this.panner = this.context.createPanner();
  9749. this.panner.connect( this.gain );
  9750. };
  9751. THREE.PositionalAudio.prototype = Object.create( THREE.Audio.prototype );
  9752. THREE.PositionalAudio.prototype.constructor = THREE.PositionalAudio;
  9753. THREE.PositionalAudio.prototype.getOutput = function () {
  9754. return this.panner;
  9755. };
  9756. THREE.PositionalAudio.prototype.setRefDistance = function ( value ) {
  9757. this.panner.refDistance = value;
  9758. };
  9759. THREE.PositionalAudio.prototype.getRefDistance = function () {
  9760. return this.panner.refDistance;
  9761. };
  9762. THREE.PositionalAudio.prototype.setRolloffFactor = function ( value ) {
  9763. this.panner.rolloffFactor = value;
  9764. };
  9765. THREE.PositionalAudio.prototype.getRolloffFactor = function () {
  9766. return this.panner.rolloffFactor;
  9767. };
  9768. THREE.PositionalAudio.prototype.setDistanceModel = function ( value ) {
  9769. this.panner.distanceModel = value;
  9770. };
  9771. THREE.PositionalAudio.prototype.getDistanceModel = function () {
  9772. return this.panner.distanceModel;
  9773. };
  9774. THREE.PositionalAudio.prototype.setMaxDistance = function ( value ) {
  9775. this.panner.maxDistance = value;
  9776. };
  9777. THREE.PositionalAudio.prototype.getMaxDistance = function () {
  9778. return this.panner.maxDistance;
  9779. };
  9780. THREE.PositionalAudio.prototype.updateMatrixWorld = ( function () {
  9781. var position = new THREE.Vector3();
  9782. return function updateMatrixWorld( force ) {
  9783. THREE.Object3D.prototype.updateMatrixWorld.call( this, force );
  9784. position.setFromMatrixPosition( this.matrixWorld );
  9785. this.panner.setPosition( position.x, position.y, position.z );
  9786. };
  9787. } )();
  9788. // File:src/audio/AudioListener.js
  9789. /**
  9790. * @author mrdoob / http://mrdoob.com/
  9791. */
  9792. THREE.AudioListener = function () {
  9793. THREE.Object3D.call( this );
  9794. this.type = 'AudioListener';
  9795. this.context = THREE.AudioContext;
  9796. this.gain = this.context.createGain();
  9797. this.gain.connect( this.context.destination );
  9798. this.filter = null;
  9799. };
  9800. THREE.AudioListener.prototype = Object.create( THREE.Object3D.prototype );
  9801. THREE.AudioListener.prototype.constructor = THREE.AudioListener;
  9802. THREE.AudioListener.prototype.getInput = function () {
  9803. return this.gain;
  9804. };
  9805. THREE.AudioListener.prototype.removeFilter = function ( ) {
  9806. if ( this.filter !== null ) {
  9807. this.gain.disconnect( this.filter );
  9808. this.filter.disconnect( this.context.destination );
  9809. this.gain.connect( this.context.destination );
  9810. this.filter = null;
  9811. }
  9812. };
  9813. THREE.AudioListener.prototype.setFilter = function ( value ) {
  9814. if ( this.filter !== null ) {
  9815. this.gain.disconnect( this.filter );
  9816. this.filter.disconnect( this.context.destination );
  9817. } else {
  9818. this.gain.disconnect( this.context.destination );
  9819. }
  9820. this.filter = value;
  9821. this.gain.connect( this.filter );
  9822. this.filter.connect( this.context.destination );
  9823. };
  9824. THREE.AudioListener.prototype.getFilter = function () {
  9825. return this.filter;
  9826. };
  9827. THREE.AudioListener.prototype.setMasterVolume = function ( value ) {
  9828. this.gain.gain.value = value;
  9829. };
  9830. THREE.AudioListener.prototype.getMasterVolume = function () {
  9831. return this.gain.gain.value;
  9832. };
  9833. THREE.AudioListener.prototype.updateMatrixWorld = ( function () {
  9834. var position = new THREE.Vector3();
  9835. var quaternion = new THREE.Quaternion();
  9836. var scale = new THREE.Vector3();
  9837. var orientation = new THREE.Vector3();
  9838. return function updateMatrixWorld( force ) {
  9839. THREE.Object3D.prototype.updateMatrixWorld.call( this, force );
  9840. var listener = this.context.listener;
  9841. var up = this.up;
  9842. this.matrixWorld.decompose( position, quaternion, scale );
  9843. orientation.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  9844. listener.setPosition( position.x, position.y, position.z );
  9845. listener.setOrientation( orientation.x, orientation.y, orientation.z, up.x, up.y, up.z );
  9846. };
  9847. } )();
  9848. // File:src/cameras/Camera.js
  9849. /**
  9850. * @author mrdoob / http://mrdoob.com/
  9851. * @author mikael emtinger / http://gomo.se/
  9852. * @author WestLangley / http://github.com/WestLangley
  9853. */
  9854. THREE.Camera = function () {
  9855. THREE.Object3D.call( this );
  9856. this.type = 'Camera';
  9857. this.matrixWorldInverse = new THREE.Matrix4();
  9858. this.projectionMatrix = new THREE.Matrix4();
  9859. };
  9860. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  9861. THREE.Camera.prototype.constructor = THREE.Camera;
  9862. THREE.Camera.prototype.getWorldDirection = function () {
  9863. var quaternion = new THREE.Quaternion();
  9864. return function ( optionalTarget ) {
  9865. var result = optionalTarget || new THREE.Vector3();
  9866. this.getWorldQuaternion( quaternion );
  9867. return result.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  9868. };
  9869. }();
  9870. THREE.Camera.prototype.lookAt = function () {
  9871. // This routine does not support cameras with rotated and/or translated parent(s)
  9872. var m1 = new THREE.Matrix4();
  9873. return function ( vector ) {
  9874. m1.lookAt( this.position, vector, this.up );
  9875. this.quaternion.setFromRotationMatrix( m1 );
  9876. };
  9877. }();
  9878. THREE.Camera.prototype.clone = function () {
  9879. return new this.constructor().copy( this );
  9880. };
  9881. THREE.Camera.prototype.copy = function ( source ) {
  9882. THREE.Object3D.prototype.copy.call( this, source );
  9883. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  9884. this.projectionMatrix.copy( source.projectionMatrix );
  9885. return this;
  9886. };
  9887. // File:src/cameras/CubeCamera.js
  9888. /**
  9889. * Camera for rendering cube maps
  9890. * - renders scene into axis-aligned cube
  9891. *
  9892. * @author alteredq / http://alteredqualia.com/
  9893. */
  9894. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  9895. THREE.Object3D.call( this );
  9896. this.type = 'CubeCamera';
  9897. var fov = 90, aspect = 1;
  9898. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  9899. cameraPX.up.set( 0, - 1, 0 );
  9900. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  9901. this.add( cameraPX );
  9902. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  9903. cameraNX.up.set( 0, - 1, 0 );
  9904. cameraNX.lookAt( new THREE.Vector3( - 1, 0, 0 ) );
  9905. this.add( cameraNX );
  9906. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  9907. cameraPY.up.set( 0, 0, 1 );
  9908. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  9909. this.add( cameraPY );
  9910. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  9911. cameraNY.up.set( 0, 0, - 1 );
  9912. cameraNY.lookAt( new THREE.Vector3( 0, - 1, 0 ) );
  9913. this.add( cameraNY );
  9914. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  9915. cameraPZ.up.set( 0, - 1, 0 );
  9916. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  9917. this.add( cameraPZ );
  9918. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  9919. cameraNZ.up.set( 0, - 1, 0 );
  9920. cameraNZ.lookAt( new THREE.Vector3( 0, 0, - 1 ) );
  9921. this.add( cameraNZ );
  9922. var options = { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter };
  9923. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, options );
  9924. this.updateCubeMap = function ( renderer, scene ) {
  9925. if ( this.parent === null ) this.updateMatrixWorld();
  9926. var renderTarget = this.renderTarget;
  9927. var generateMipmaps = renderTarget.texture.generateMipmaps;
  9928. renderTarget.texture.generateMipmaps = false;
  9929. renderTarget.activeCubeFace = 0;
  9930. renderer.render( scene, cameraPX, renderTarget );
  9931. renderTarget.activeCubeFace = 1;
  9932. renderer.render( scene, cameraNX, renderTarget );
  9933. renderTarget.activeCubeFace = 2;
  9934. renderer.render( scene, cameraPY, renderTarget );
  9935. renderTarget.activeCubeFace = 3;
  9936. renderer.render( scene, cameraNY, renderTarget );
  9937. renderTarget.activeCubeFace = 4;
  9938. renderer.render( scene, cameraPZ, renderTarget );
  9939. renderTarget.texture.generateMipmaps = generateMipmaps;
  9940. renderTarget.activeCubeFace = 5;
  9941. renderer.render( scene, cameraNZ, renderTarget );
  9942. renderer.setRenderTarget( null );
  9943. };
  9944. };
  9945. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  9946. THREE.CubeCamera.prototype.constructor = THREE.CubeCamera;
  9947. // File:src/cameras/OrthographicCamera.js
  9948. /**
  9949. * @author alteredq / http://alteredqualia.com/
  9950. */
  9951. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  9952. THREE.Camera.call( this );
  9953. this.type = 'OrthographicCamera';
  9954. this.zoom = 1;
  9955. this.left = left;
  9956. this.right = right;
  9957. this.top = top;
  9958. this.bottom = bottom;
  9959. this.near = ( near !== undefined ) ? near : 0.1;
  9960. this.far = ( far !== undefined ) ? far : 2000;
  9961. this.updateProjectionMatrix();
  9962. };
  9963. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  9964. THREE.OrthographicCamera.prototype.constructor = THREE.OrthographicCamera;
  9965. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  9966. var dx = ( this.right - this.left ) / ( 2 * this.zoom );
  9967. var dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  9968. var cx = ( this.right + this.left ) / 2;
  9969. var cy = ( this.top + this.bottom ) / 2;
  9970. this.projectionMatrix.makeOrthographic( cx - dx, cx + dx, cy + dy, cy - dy, this.near, this.far );
  9971. };
  9972. THREE.OrthographicCamera.prototype.copy = function ( source ) {
  9973. THREE.Camera.prototype.copy.call( this, source );
  9974. this.left = source.left;
  9975. this.right = source.right;
  9976. this.top = source.top;
  9977. this.bottom = source.bottom;
  9978. this.near = source.near;
  9979. this.far = source.far;
  9980. this.zoom = source.zoom;
  9981. return this;
  9982. };
  9983. THREE.OrthographicCamera.prototype.toJSON = function ( meta ) {
  9984. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  9985. data.object.zoom = this.zoom;
  9986. data.object.left = this.left;
  9987. data.object.right = this.right;
  9988. data.object.top = this.top;
  9989. data.object.bottom = this.bottom;
  9990. data.object.near = this.near;
  9991. data.object.far = this.far;
  9992. return data;
  9993. };
  9994. // File:src/cameras/PerspectiveCamera.js
  9995. /**
  9996. * @author mrdoob / http://mrdoob.com/
  9997. * @author greggman / http://games.greggman.com/
  9998. * @author zz85 / http://www.lab4games.net/zz85/blog
  9999. */
  10000. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  10001. THREE.Camera.call( this );
  10002. this.type = 'PerspectiveCamera';
  10003. this.focalLength = 10;
  10004. this.zoom = 1;
  10005. this.fov = fov !== undefined ? fov : 50;
  10006. this.aspect = aspect !== undefined ? aspect : 1;
  10007. this.near = near !== undefined ? near : 0.1;
  10008. this.far = far !== undefined ? far : 2000;
  10009. this.updateProjectionMatrix();
  10010. };
  10011. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  10012. THREE.PerspectiveCamera.prototype.constructor = THREE.PerspectiveCamera;
  10013. /**
  10014. * Uses Focal Length (in mm) to estimate and set FOV
  10015. * 35mm (full-frame) camera is used if frame size is not specified;
  10016. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  10017. */
  10018. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  10019. if ( frameHeight === undefined ) frameHeight = 24;
  10020. this.fov = 2 * THREE.Math.RAD2DEG * Math.atan( frameHeight / ( focalLength * 2 ) );
  10021. this.updateProjectionMatrix();
  10022. };
  10023. /**
  10024. * Sets an offset in a larger frustum. This is useful for multi-window or
  10025. * multi-monitor/multi-machine setups.
  10026. *
  10027. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  10028. * the monitors are in grid like this
  10029. *
  10030. * +---+---+---+
  10031. * | A | B | C |
  10032. * +---+---+---+
  10033. * | D | E | F |
  10034. * +---+---+---+
  10035. *
  10036. * then for each monitor you would call it like this
  10037. *
  10038. * var w = 1920;
  10039. * var h = 1080;
  10040. * var fullWidth = w * 3;
  10041. * var fullHeight = h * 2;
  10042. *
  10043. * --A--
  10044. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  10045. * --B--
  10046. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  10047. * --C--
  10048. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  10049. * --D--
  10050. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  10051. * --E--
  10052. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  10053. * --F--
  10054. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  10055. *
  10056. * Note there is no reason monitors have to be the same size or in a grid.
  10057. */
  10058. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  10059. this.fullWidth = fullWidth;
  10060. this.fullHeight = fullHeight;
  10061. this.x = x;
  10062. this.y = y;
  10063. this.width = width;
  10064. this.height = height;
  10065. this.updateProjectionMatrix();
  10066. };
  10067. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  10068. var fov = THREE.Math.RAD2DEG * ( 2 * Math.atan( Math.tan( THREE.Math.DEG2RAD * this.fov * 0.5 ) / this.zoom ) );
  10069. if ( this.fullWidth ) {
  10070. var aspect = this.fullWidth / this.fullHeight;
  10071. var top = Math.tan( THREE.Math.DEG2RAD * fov * 0.5 ) * this.near;
  10072. var bottom = - top;
  10073. var left = aspect * bottom;
  10074. var right = aspect * top;
  10075. var width = Math.abs( right - left );
  10076. var height = Math.abs( top - bottom );
  10077. this.projectionMatrix.makeFrustum(
  10078. left + this.x * width / this.fullWidth,
  10079. left + ( this.x + this.width ) * width / this.fullWidth,
  10080. top - ( this.y + this.height ) * height / this.fullHeight,
  10081. top - this.y * height / this.fullHeight,
  10082. this.near,
  10083. this.far
  10084. );
  10085. } else {
  10086. this.projectionMatrix.makePerspective( fov, this.aspect, this.near, this.far );
  10087. }
  10088. };
  10089. THREE.PerspectiveCamera.prototype.copy = function ( source ) {
  10090. THREE.Camera.prototype.copy.call( this, source );
  10091. this.focalLength = source.focalLength;
  10092. this.zoom = source.zoom;
  10093. this.fov = source.fov;
  10094. this.aspect = source.aspect;
  10095. this.near = source.near;
  10096. this.far = source.far;
  10097. return this;
  10098. };
  10099. THREE.PerspectiveCamera.prototype.toJSON = function ( meta ) {
  10100. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  10101. data.object.focalLength = this.focalLength;
  10102. data.object.zoom = this.zoom;
  10103. data.object.fov = this.fov;
  10104. data.object.aspect = this.aspect;
  10105. data.object.near = this.near;
  10106. data.object.far = this.far;
  10107. return data;
  10108. };
  10109. // File:src/cameras/StereoCamera.js
  10110. /**
  10111. * @author mrdoob / http://mrdoob.com/
  10112. */
  10113. THREE.StereoCamera = function () {
  10114. this.type = 'StereoCamera';
  10115. this.aspect = 1;
  10116. this.cameraL = new THREE.PerspectiveCamera();
  10117. this.cameraL.layers.enable( 1 );
  10118. this.cameraL.matrixAutoUpdate = false;
  10119. this.cameraR = new THREE.PerspectiveCamera();
  10120. this.cameraR.layers.enable( 2 );
  10121. this.cameraR.matrixAutoUpdate = false;
  10122. };
  10123. THREE.StereoCamera.prototype = {
  10124. constructor: THREE.StereoCamera,
  10125. update: ( function () {
  10126. var focalLength, fov, aspect, near, far;
  10127. var eyeRight = new THREE.Matrix4();
  10128. var eyeLeft = new THREE.Matrix4();
  10129. return function update ( camera ) {
  10130. var needsUpdate = focalLength !== camera.focalLength || fov !== camera.fov ||
  10131. aspect !== camera.aspect * this.aspect || near !== camera.near ||
  10132. far !== camera.far;
  10133. if ( needsUpdate ) {
  10134. focalLength = camera.focalLength;
  10135. fov = camera.fov;
  10136. aspect = camera.aspect * this.aspect;
  10137. near = camera.near;
  10138. far = camera.far;
  10139. // Off-axis stereoscopic effect based on
  10140. // http://paulbourke.net/stereographics/stereorender/
  10141. var projectionMatrix = camera.projectionMatrix.clone();
  10142. var eyeSep = 0.064 / 2;
  10143. var eyeSepOnProjection = eyeSep * near / focalLength;
  10144. var ymax = near * Math.tan( THREE.Math.DEG2RAD * fov * 0.5 );
  10145. var xmin, xmax;
  10146. // translate xOffset
  10147. eyeLeft.elements[ 12 ] = - eyeSep;
  10148. eyeRight.elements[ 12 ] = eyeSep;
  10149. // for left eye
  10150. xmin = - ymax * aspect + eyeSepOnProjection;
  10151. xmax = ymax * aspect + eyeSepOnProjection;
  10152. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  10153. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  10154. this.cameraL.projectionMatrix.copy( projectionMatrix );
  10155. // for right eye
  10156. xmin = - ymax * aspect - eyeSepOnProjection;
  10157. xmax = ymax * aspect - eyeSepOnProjection;
  10158. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  10159. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  10160. this.cameraR.projectionMatrix.copy( projectionMatrix );
  10161. }
  10162. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( eyeLeft );
  10163. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( eyeRight );
  10164. };
  10165. } )()
  10166. };
  10167. // File:src/lights/Light.js
  10168. /**
  10169. * @author mrdoob / http://mrdoob.com/
  10170. * @author alteredq / http://alteredqualia.com/
  10171. */
  10172. THREE.Light = function ( color, intensity ) {
  10173. THREE.Object3D.call( this );
  10174. this.type = 'Light';
  10175. this.color = new THREE.Color( color );
  10176. this.intensity = intensity !== undefined ? intensity : 1;
  10177. this.receiveShadow = undefined;
  10178. };
  10179. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  10180. THREE.Light.prototype.constructor = THREE.Light;
  10181. THREE.Light.prototype.copy = function ( source ) {
  10182. THREE.Object3D.prototype.copy.call( this, source );
  10183. this.color.copy( source.color );
  10184. this.intensity = source.intensity;
  10185. return this;
  10186. };
  10187. THREE.Light.prototype.toJSON = function ( meta ) {
  10188. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  10189. data.object.color = this.color.getHex();
  10190. data.object.intensity = this.intensity;
  10191. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  10192. if ( this.distance !== undefined ) data.object.distance = this.distance;
  10193. if ( this.angle !== undefined ) data.object.angle = this.angle;
  10194. if ( this.decay !== undefined ) data.object.decay = this.decay;
  10195. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  10196. return data;
  10197. };
  10198. // File:src/lights/LightShadow.js
  10199. /**
  10200. * @author mrdoob / http://mrdoob.com/
  10201. */
  10202. THREE.LightShadow = function ( camera ) {
  10203. this.camera = camera;
  10204. this.bias = 0;
  10205. this.radius = 1;
  10206. this.mapSize = new THREE.Vector2( 512, 512 );
  10207. this.map = null;
  10208. this.matrix = new THREE.Matrix4();
  10209. };
  10210. THREE.LightShadow.prototype = {
  10211. constructor: THREE.LightShadow,
  10212. copy: function ( source ) {
  10213. this.camera = source.camera.clone();
  10214. this.bias = source.bias;
  10215. this.radius = source.radius;
  10216. this.mapSize.copy( source.mapSize );
  10217. return this;
  10218. },
  10219. clone: function () {
  10220. return new this.constructor().copy( this );
  10221. }
  10222. };
  10223. // File:src/lights/AmbientLight.js
  10224. /**
  10225. * @author mrdoob / http://mrdoob.com/
  10226. */
  10227. THREE.AmbientLight = function ( color, intensity ) {
  10228. THREE.Light.call( this, color, intensity );
  10229. this.type = 'AmbientLight';
  10230. this.castShadow = undefined;
  10231. };
  10232. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  10233. THREE.AmbientLight.prototype.constructor = THREE.AmbientLight;
  10234. // File:src/lights/DirectionalLight.js
  10235. /**
  10236. * @author mrdoob / http://mrdoob.com/
  10237. * @author alteredq / http://alteredqualia.com/
  10238. */
  10239. THREE.DirectionalLight = function ( color, intensity ) {
  10240. THREE.Light.call( this, color, intensity );
  10241. this.type = 'DirectionalLight';
  10242. this.position.set( 0, 1, 0 );
  10243. this.updateMatrix();
  10244. this.target = new THREE.Object3D();
  10245. this.shadow = new THREE.DirectionalLightShadow();
  10246. };
  10247. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  10248. THREE.DirectionalLight.prototype.constructor = THREE.DirectionalLight;
  10249. THREE.DirectionalLight.prototype.copy = function ( source ) {
  10250. THREE.Light.prototype.copy.call( this, source );
  10251. this.target = source.target.clone();
  10252. this.shadow = source.shadow.clone();
  10253. return this;
  10254. };
  10255. // File:src/lights/DirectionalLightShadow.js
  10256. /**
  10257. * @author mrdoob / http://mrdoob.com/
  10258. */
  10259. THREE.DirectionalLightShadow = function ( light ) {
  10260. THREE.LightShadow.call( this, new THREE.OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  10261. };
  10262. THREE.DirectionalLightShadow.prototype = Object.create( THREE.LightShadow.prototype );
  10263. THREE.DirectionalLightShadow.prototype.constructor = THREE.DirectionalLightShadow;
  10264. // File:src/lights/HemisphereLight.js
  10265. /**
  10266. * @author alteredq / http://alteredqualia.com/
  10267. */
  10268. THREE.HemisphereLight = function ( skyColor, groundColor, intensity ) {
  10269. THREE.Light.call( this, skyColor, intensity );
  10270. this.type = 'HemisphereLight';
  10271. this.castShadow = undefined;
  10272. this.position.set( 0, 1, 0 );
  10273. this.updateMatrix();
  10274. this.groundColor = new THREE.Color( groundColor );
  10275. };
  10276. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  10277. THREE.HemisphereLight.prototype.constructor = THREE.HemisphereLight;
  10278. THREE.HemisphereLight.prototype.copy = function ( source ) {
  10279. THREE.Light.prototype.copy.call( this, source );
  10280. this.groundColor.copy( source.groundColor );
  10281. return this;
  10282. };
  10283. // File:src/lights/PointLight.js
  10284. /**
  10285. * @author mrdoob / http://mrdoob.com/
  10286. */
  10287. THREE.PointLight = function ( color, intensity, distance, decay ) {
  10288. THREE.Light.call( this, color, intensity );
  10289. this.type = 'PointLight';
  10290. this.distance = ( distance !== undefined ) ? distance : 0;
  10291. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  10292. this.shadow = new THREE.LightShadow( new THREE.PerspectiveCamera( 90, 1, 0.5, 500 ) );
  10293. };
  10294. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  10295. THREE.PointLight.prototype.constructor = THREE.PointLight;
  10296. Object.defineProperty( THREE.PointLight.prototype, "power", {
  10297. get: function () {
  10298. // intensity = power per solid angle.
  10299. // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  10300. return this.intensity * 4 * Math.PI;
  10301. },
  10302. set: function ( power ) {
  10303. // intensity = power per solid angle.
  10304. // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  10305. this.intensity = power / ( 4 * Math.PI );
  10306. }
  10307. } );
  10308. THREE.PointLight.prototype.copy = function ( source ) {
  10309. THREE.Light.prototype.copy.call( this, source );
  10310. this.distance = source.distance;
  10311. this.decay = source.decay;
  10312. this.shadow = source.shadow.clone();
  10313. return this;
  10314. };
  10315. // File:src/lights/SpotLight.js
  10316. /**
  10317. * @author alteredq / http://alteredqualia.com/
  10318. */
  10319. THREE.SpotLight = function ( color, intensity, distance, angle, penumbra, decay ) {
  10320. THREE.Light.call( this, color, intensity );
  10321. this.type = 'SpotLight';
  10322. this.position.set( 0, 1, 0 );
  10323. this.updateMatrix();
  10324. this.target = new THREE.Object3D();
  10325. this.distance = ( distance !== undefined ) ? distance : 0;
  10326. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  10327. this.penumbra = ( penumbra !== undefined ) ? penumbra : 0;
  10328. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  10329. this.shadow = new THREE.SpotLightShadow();
  10330. };
  10331. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  10332. THREE.SpotLight.prototype.constructor = THREE.SpotLight;
  10333. Object.defineProperty( THREE.SpotLight.prototype, "power", {
  10334. get: function () {
  10335. // intensity = power per solid angle.
  10336. // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  10337. return this.intensity * Math.PI;
  10338. },
  10339. set: function ( power ) {
  10340. // intensity = power per solid angle.
  10341. // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  10342. this.intensity = power / Math.PI;
  10343. }
  10344. } );
  10345. THREE.SpotLight.prototype.copy = function ( source ) {
  10346. THREE.Light.prototype.copy.call( this, source );
  10347. this.distance = source.distance;
  10348. this.angle = source.angle;
  10349. this.penumbra = source.penumbra;
  10350. this.decay = source.decay;
  10351. this.target = source.target.clone();
  10352. this.shadow = source.shadow.clone();
  10353. return this;
  10354. };
  10355. // File:src/lights/SpotLightShadow.js
  10356. /**
  10357. * @author mrdoob / http://mrdoob.com/
  10358. */
  10359. THREE.SpotLightShadow = function () {
  10360. THREE.LightShadow.call( this, new THREE.PerspectiveCamera( 50, 1, 0.5, 500 ) );
  10361. };
  10362. THREE.SpotLightShadow.prototype = Object.create( THREE.LightShadow.prototype );
  10363. THREE.SpotLightShadow.prototype.constructor = THREE.SpotLightShadow;
  10364. THREE.SpotLightShadow.prototype.update = function ( light ) {
  10365. var fov = THREE.Math.radToDeg( 2 * light.angle );
  10366. var aspect = this.mapSize.width / this.mapSize.height;
  10367. var far = light.distance || 500;
  10368. var camera = this.camera;
  10369. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  10370. camera.fov = fov;
  10371. camera.aspect = aspect;
  10372. camera.far = far;
  10373. camera.updateProjectionMatrix();
  10374. }
  10375. };
  10376. // File:src/loaders/AudioLoader.js
  10377. /**
  10378. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  10379. */
  10380. THREE.AudioLoader = function ( manager ) {
  10381. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  10382. };
  10383. THREE.AudioLoader.prototype = {
  10384. constructor: THREE.AudioLoader,
  10385. load: function ( url, onLoad, onProgress, onError ) {
  10386. var loader = new THREE.XHRLoader( this.manager );
  10387. loader.setResponseType( 'arraybuffer' );
  10388. loader.load( url, function ( buffer ) {
  10389. var context = THREE.AudioContext;
  10390. context.decodeAudioData( buffer, function ( audioBuffer ) {
  10391. onLoad( audioBuffer );
  10392. } );
  10393. }, onProgress, onError );
  10394. }
  10395. };
  10396. // File:src/loaders/Cache.js
  10397. /**
  10398. * @author mrdoob / http://mrdoob.com/
  10399. */
  10400. THREE.Cache = {
  10401. enabled: false,
  10402. files: {},
  10403. add: function ( key, file ) {
  10404. if ( this.enabled === false ) return;
  10405. // console.log( 'THREE.Cache', 'Adding key:', key );
  10406. this.files[ key ] = file;
  10407. },
  10408. get: function ( key ) {
  10409. if ( this.enabled === false ) return;
  10410. // console.log( 'THREE.Cache', 'Checking key:', key );
  10411. return this.files[ key ];
  10412. },
  10413. remove: function ( key ) {
  10414. delete this.files[ key ];
  10415. },
  10416. clear: function () {
  10417. this.files = {};
  10418. }
  10419. };
  10420. // File:src/loaders/Loader.js
  10421. /**
  10422. * @author alteredq / http://alteredqualia.com/
  10423. */
  10424. THREE.Loader = function () {
  10425. this.onLoadStart = function () {};
  10426. this.onLoadProgress = function () {};
  10427. this.onLoadComplete = function () {};
  10428. };
  10429. THREE.Loader.prototype = {
  10430. constructor: THREE.Loader,
  10431. crossOrigin: undefined,
  10432. extractUrlBase: function ( url ) {
  10433. var parts = url.split( '/' );
  10434. if ( parts.length === 1 ) return './';
  10435. parts.pop();
  10436. return parts.join( '/' ) + '/';
  10437. },
  10438. initMaterials: function ( materials, texturePath, crossOrigin ) {
  10439. var array = [];
  10440. for ( var i = 0; i < materials.length; ++ i ) {
  10441. array[ i ] = this.createMaterial( materials[ i ], texturePath, crossOrigin );
  10442. }
  10443. return array;
  10444. },
  10445. createMaterial: ( function () {
  10446. var color, textureLoader, materialLoader;
  10447. return function ( m, texturePath, crossOrigin ) {
  10448. if ( color === undefined ) color = new THREE.Color();
  10449. if ( textureLoader === undefined ) textureLoader = new THREE.TextureLoader();
  10450. if ( materialLoader === undefined ) materialLoader = new THREE.MaterialLoader();
  10451. // convert from old material format
  10452. var textures = {};
  10453. function loadTexture( path, repeat, offset, wrap, anisotropy ) {
  10454. var fullPath = texturePath + path;
  10455. var loader = THREE.Loader.Handlers.get( fullPath );
  10456. var texture;
  10457. if ( loader !== null ) {
  10458. texture = loader.load( fullPath );
  10459. } else {
  10460. textureLoader.setCrossOrigin( crossOrigin );
  10461. texture = textureLoader.load( fullPath );
  10462. }
  10463. if ( repeat !== undefined ) {
  10464. texture.repeat.fromArray( repeat );
  10465. if ( repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  10466. if ( repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  10467. }
  10468. if ( offset !== undefined ) {
  10469. texture.offset.fromArray( offset );
  10470. }
  10471. if ( wrap !== undefined ) {
  10472. if ( wrap[ 0 ] === 'repeat' ) texture.wrapS = THREE.RepeatWrapping;
  10473. if ( wrap[ 0 ] === 'mirror' ) texture.wrapS = THREE.MirroredRepeatWrapping;
  10474. if ( wrap[ 1 ] === 'repeat' ) texture.wrapT = THREE.RepeatWrapping;
  10475. if ( wrap[ 1 ] === 'mirror' ) texture.wrapT = THREE.MirroredRepeatWrapping;
  10476. }
  10477. if ( anisotropy !== undefined ) {
  10478. texture.anisotropy = anisotropy;
  10479. }
  10480. var uuid = THREE.Math.generateUUID();
  10481. textures[ uuid ] = texture;
  10482. return uuid;
  10483. }
  10484. //
  10485. var json = {
  10486. uuid: THREE.Math.generateUUID(),
  10487. type: 'MeshLambertMaterial'
  10488. };
  10489. for ( var name in m ) {
  10490. var value = m[ name ];
  10491. switch ( name ) {
  10492. case 'DbgColor':
  10493. case 'DbgIndex':
  10494. case 'opticalDensity':
  10495. case 'illumination':
  10496. break;
  10497. case 'DbgName':
  10498. json.name = value;
  10499. break;
  10500. case 'blending':
  10501. json.blending = THREE[ value ];
  10502. break;
  10503. case 'colorAmbient':
  10504. case 'mapAmbient':
  10505. console.warn( 'THREE.Loader.createMaterial:', name, 'is no longer supported.' );
  10506. break;
  10507. case 'colorDiffuse':
  10508. json.color = color.fromArray( value ).getHex();
  10509. break;
  10510. case 'colorSpecular':
  10511. json.specular = color.fromArray( value ).getHex();
  10512. break;
  10513. case 'colorEmissive':
  10514. json.emissive = color.fromArray( value ).getHex();
  10515. break;
  10516. case 'specularCoef':
  10517. json.shininess = value;
  10518. break;
  10519. case 'shading':
  10520. if ( value.toLowerCase() === 'basic' ) json.type = 'MeshBasicMaterial';
  10521. if ( value.toLowerCase() === 'phong' ) json.type = 'MeshPhongMaterial';
  10522. break;
  10523. case 'mapDiffuse':
  10524. json.map = loadTexture( value, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  10525. break;
  10526. case 'mapDiffuseRepeat':
  10527. case 'mapDiffuseOffset':
  10528. case 'mapDiffuseWrap':
  10529. case 'mapDiffuseAnisotropy':
  10530. break;
  10531. case 'mapLight':
  10532. json.lightMap = loadTexture( value, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  10533. break;
  10534. case 'mapLightRepeat':
  10535. case 'mapLightOffset':
  10536. case 'mapLightWrap':
  10537. case 'mapLightAnisotropy':
  10538. break;
  10539. case 'mapAO':
  10540. json.aoMap = loadTexture( value, m.mapAORepeat, m.mapAOOffset, m.mapAOWrap, m.mapAOAnisotropy );
  10541. break;
  10542. case 'mapAORepeat':
  10543. case 'mapAOOffset':
  10544. case 'mapAOWrap':
  10545. case 'mapAOAnisotropy':
  10546. break;
  10547. case 'mapBump':
  10548. json.bumpMap = loadTexture( value, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  10549. break;
  10550. case 'mapBumpScale':
  10551. json.bumpScale = value;
  10552. break;
  10553. case 'mapBumpRepeat':
  10554. case 'mapBumpOffset':
  10555. case 'mapBumpWrap':
  10556. case 'mapBumpAnisotropy':
  10557. break;
  10558. case 'mapNormal':
  10559. json.normalMap = loadTexture( value, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  10560. break;
  10561. case 'mapNormalFactor':
  10562. json.normalScale = [ value, value ];
  10563. break;
  10564. case 'mapNormalRepeat':
  10565. case 'mapNormalOffset':
  10566. case 'mapNormalWrap':
  10567. case 'mapNormalAnisotropy':
  10568. break;
  10569. case 'mapSpecular':
  10570. json.specularMap = loadTexture( value, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  10571. break;
  10572. case 'mapSpecularRepeat':
  10573. case 'mapSpecularOffset':
  10574. case 'mapSpecularWrap':
  10575. case 'mapSpecularAnisotropy':
  10576. break;
  10577. case 'mapAlpha':
  10578. json.alphaMap = loadTexture( value, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy );
  10579. break;
  10580. case 'mapAlphaRepeat':
  10581. case 'mapAlphaOffset':
  10582. case 'mapAlphaWrap':
  10583. case 'mapAlphaAnisotropy':
  10584. break;
  10585. case 'flipSided':
  10586. json.side = THREE.BackSide;
  10587. break;
  10588. case 'doubleSided':
  10589. json.side = THREE.DoubleSide;
  10590. break;
  10591. case 'transparency':
  10592. console.warn( 'THREE.Loader.createMaterial: transparency has been renamed to opacity' );
  10593. json.opacity = value;
  10594. break;
  10595. case 'depthTest':
  10596. case 'depthWrite':
  10597. case 'colorWrite':
  10598. case 'opacity':
  10599. case 'reflectivity':
  10600. case 'transparent':
  10601. case 'visible':
  10602. case 'wireframe':
  10603. json[ name ] = value;
  10604. break;
  10605. case 'vertexColors':
  10606. if ( value === true ) json.vertexColors = THREE.VertexColors;
  10607. if ( value === 'face' ) json.vertexColors = THREE.FaceColors;
  10608. break;
  10609. default:
  10610. console.error( 'THREE.Loader.createMaterial: Unsupported', name, value );
  10611. break;
  10612. }
  10613. }
  10614. if ( json.type === 'MeshBasicMaterial' ) delete json.emissive;
  10615. if ( json.type !== 'MeshPhongMaterial' ) delete json.specular;
  10616. if ( json.opacity < 1 ) json.transparent = true;
  10617. materialLoader.setTextures( textures );
  10618. return materialLoader.parse( json );
  10619. };
  10620. } )()
  10621. };
  10622. THREE.Loader.Handlers = {
  10623. handlers: [],
  10624. add: function ( regex, loader ) {
  10625. this.handlers.push( regex, loader );
  10626. },
  10627. get: function ( file ) {
  10628. var handlers = this.handlers;
  10629. for ( var i = 0, l = handlers.length; i < l; i += 2 ) {
  10630. var regex = handlers[ i ];
  10631. var loader = handlers[ i + 1 ];
  10632. if ( regex.test( file ) ) {
  10633. return loader;
  10634. }
  10635. }
  10636. return null;
  10637. }
  10638. };
  10639. // File:src/loaders/XHRLoader.js
  10640. /**
  10641. * @author mrdoob / http://mrdoob.com/
  10642. */
  10643. THREE.XHRLoader = function ( manager ) {
  10644. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  10645. };
  10646. THREE.XHRLoader.prototype = {
  10647. constructor: THREE.XHRLoader,
  10648. load: function ( url, onLoad, onProgress, onError ) {
  10649. if ( this.path !== undefined ) url = this.path + url;
  10650. var scope = this;
  10651. var cached = THREE.Cache.get( url );
  10652. if ( cached !== undefined ) {
  10653. if ( onLoad ) {
  10654. setTimeout( function () {
  10655. onLoad( cached );
  10656. }, 0 );
  10657. }
  10658. return cached;
  10659. }
  10660. var request = new XMLHttpRequest();
  10661. request.overrideMimeType( 'text/plain' );
  10662. request.open( 'GET', url, true );
  10663. request.addEventListener( 'load', function ( event ) {
  10664. var response = event.target.response;
  10665. THREE.Cache.add( url, response );
  10666. if ( this.status === 200 ) {
  10667. if ( onLoad ) onLoad( response );
  10668. scope.manager.itemEnd( url );
  10669. } else if ( this.status === 0 ) {
  10670. // Some browsers return HTTP Status 0 when using non-http protocol
  10671. // e.g. 'file://' or 'data://'. Handle as success.
  10672. console.warn( 'THREE.XHRLoader: HTTP Status 0 received.' );
  10673. if ( onLoad ) onLoad( response );
  10674. scope.manager.itemEnd( url );
  10675. } else {
  10676. if ( onError ) onError( event );
  10677. scope.manager.itemError( url );
  10678. }
  10679. }, false );
  10680. if ( onProgress !== undefined ) {
  10681. request.addEventListener( 'progress', function ( event ) {
  10682. onProgress( event );
  10683. }, false );
  10684. }
  10685. request.addEventListener( 'error', function ( event ) {
  10686. if ( onError ) onError( event );
  10687. scope.manager.itemError( url );
  10688. }, false );
  10689. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  10690. if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;
  10691. request.send( null );
  10692. scope.manager.itemStart( url );
  10693. return request;
  10694. },
  10695. setPath: function ( value ) {
  10696. this.path = value;
  10697. },
  10698. setResponseType: function ( value ) {
  10699. this.responseType = value;
  10700. },
  10701. setWithCredentials: function ( value ) {
  10702. this.withCredentials = value;
  10703. }
  10704. };
  10705. // File:src/loaders/FontLoader.js
  10706. /**
  10707. * @author mrdoob / http://mrdoob.com/
  10708. */
  10709. THREE.FontLoader = function ( manager ) {
  10710. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  10711. };
  10712. THREE.FontLoader.prototype = {
  10713. constructor: THREE.FontLoader,
  10714. load: function ( url, onLoad, onProgress, onError ) {
  10715. var loader = new THREE.XHRLoader( this.manager );
  10716. loader.load( url, function ( text ) {
  10717. onLoad( new THREE.Font( JSON.parse( text.substring( 65, text.length - 2 ) ) ) );
  10718. }, onProgress, onError );
  10719. }
  10720. };
  10721. // File:src/loaders/ImageLoader.js
  10722. /**
  10723. * @author mrdoob / http://mrdoob.com/
  10724. */
  10725. THREE.ImageLoader = function ( manager ) {
  10726. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  10727. };
  10728. THREE.ImageLoader.prototype = {
  10729. constructor: THREE.ImageLoader,
  10730. load: function ( url, onLoad, onProgress, onError ) {
  10731. if ( this.path !== undefined ) url = this.path + url;
  10732. var scope = this;
  10733. var cached = THREE.Cache.get( url );
  10734. if ( cached !== undefined ) {
  10735. scope.manager.itemStart( url );
  10736. if ( onLoad ) {
  10737. setTimeout( function () {
  10738. onLoad( cached );
  10739. scope.manager.itemEnd( url );
  10740. }, 0 );
  10741. } else {
  10742. scope.manager.itemEnd( url );
  10743. }
  10744. return cached;
  10745. }
  10746. var image = document.createElement( 'img' );
  10747. image.addEventListener( 'load', function ( event ) {
  10748. THREE.Cache.add( url, this );
  10749. if ( onLoad ) onLoad( this );
  10750. scope.manager.itemEnd( url );
  10751. }, false );
  10752. if ( onProgress !== undefined ) {
  10753. image.addEventListener( 'progress', function ( event ) {
  10754. onProgress( event );
  10755. }, false );
  10756. }
  10757. image.addEventListener( 'error', function ( event ) {
  10758. if ( onError ) onError( event );
  10759. scope.manager.itemError( url );
  10760. }, false );
  10761. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  10762. scope.manager.itemStart( url );
  10763. image.src = url;
  10764. return image;
  10765. },
  10766. setCrossOrigin: function ( value ) {
  10767. this.crossOrigin = value;
  10768. },
  10769. setPath: function ( value ) {
  10770. this.path = value;
  10771. }
  10772. };
  10773. // File:src/loaders/JSONLoader.js
  10774. /**
  10775. * @author mrdoob / http://mrdoob.com/
  10776. * @author alteredq / http://alteredqualia.com/
  10777. */
  10778. THREE.JSONLoader = function ( manager ) {
  10779. if ( typeof manager === 'boolean' ) {
  10780. console.warn( 'THREE.JSONLoader: showStatus parameter has been removed from constructor.' );
  10781. manager = undefined;
  10782. }
  10783. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  10784. this.withCredentials = false;
  10785. };
  10786. THREE.JSONLoader.prototype = {
  10787. constructor: THREE.JSONLoader,
  10788. // Deprecated
  10789. get statusDomElement () {
  10790. if ( this._statusDomElement === undefined ) {
  10791. this._statusDomElement = document.createElement( 'div' );
  10792. }
  10793. console.warn( 'THREE.JSONLoader: .statusDomElement has been removed.' );
  10794. return this._statusDomElement;
  10795. },
  10796. load: function( url, onLoad, onProgress, onError ) {
  10797. var scope = this;
  10798. var texturePath = this.texturePath && ( typeof this.texturePath === "string" ) ? this.texturePath : THREE.Loader.prototype.extractUrlBase( url );
  10799. var loader = new THREE.XHRLoader( this.manager );
  10800. loader.setWithCredentials( this.withCredentials );
  10801. loader.load( url, function ( text ) {
  10802. var json = JSON.parse( text );
  10803. var metadata = json.metadata;
  10804. if ( metadata !== undefined ) {
  10805. var type = metadata.type;
  10806. if ( type !== undefined ) {
  10807. if ( type.toLowerCase() === 'object' ) {
  10808. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' );
  10809. return;
  10810. }
  10811. if ( type.toLowerCase() === 'scene' ) {
  10812. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.SceneLoader instead.' );
  10813. return;
  10814. }
  10815. }
  10816. }
  10817. var object = scope.parse( json, texturePath );
  10818. onLoad( object.geometry, object.materials );
  10819. }, onProgress, onError );
  10820. },
  10821. setTexturePath: function ( value ) {
  10822. this.texturePath = value;
  10823. },
  10824. parse: function ( json, texturePath ) {
  10825. var geometry = new THREE.Geometry(),
  10826. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  10827. parseModel( scale );
  10828. parseSkin();
  10829. parseMorphing( scale );
  10830. parseAnimations();
  10831. geometry.computeFaceNormals();
  10832. geometry.computeBoundingSphere();
  10833. function parseModel( scale ) {
  10834. function isBitSet( value, position ) {
  10835. return value & ( 1 << position );
  10836. }
  10837. var i, j, fi,
  10838. offset, zLength,
  10839. colorIndex, normalIndex, uvIndex, materialIndex,
  10840. type,
  10841. isQuad,
  10842. hasMaterial,
  10843. hasFaceVertexUv,
  10844. hasFaceNormal, hasFaceVertexNormal,
  10845. hasFaceColor, hasFaceVertexColor,
  10846. vertex, face, faceA, faceB, hex, normal,
  10847. uvLayer, uv, u, v,
  10848. faces = json.faces,
  10849. vertices = json.vertices,
  10850. normals = json.normals,
  10851. colors = json.colors,
  10852. nUvLayers = 0;
  10853. if ( json.uvs !== undefined ) {
  10854. // disregard empty arrays
  10855. for ( i = 0; i < json.uvs.length; i ++ ) {
  10856. if ( json.uvs[ i ].length ) nUvLayers ++;
  10857. }
  10858. for ( i = 0; i < nUvLayers; i ++ ) {
  10859. geometry.faceVertexUvs[ i ] = [];
  10860. }
  10861. }
  10862. offset = 0;
  10863. zLength = vertices.length;
  10864. while ( offset < zLength ) {
  10865. vertex = new THREE.Vector3();
  10866. vertex.x = vertices[ offset ++ ] * scale;
  10867. vertex.y = vertices[ offset ++ ] * scale;
  10868. vertex.z = vertices[ offset ++ ] * scale;
  10869. geometry.vertices.push( vertex );
  10870. }
  10871. offset = 0;
  10872. zLength = faces.length;
  10873. while ( offset < zLength ) {
  10874. type = faces[ offset ++ ];
  10875. isQuad = isBitSet( type, 0 );
  10876. hasMaterial = isBitSet( type, 1 );
  10877. hasFaceVertexUv = isBitSet( type, 3 );
  10878. hasFaceNormal = isBitSet( type, 4 );
  10879. hasFaceVertexNormal = isBitSet( type, 5 );
  10880. hasFaceColor = isBitSet( type, 6 );
  10881. hasFaceVertexColor = isBitSet( type, 7 );
  10882. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  10883. if ( isQuad ) {
  10884. faceA = new THREE.Face3();
  10885. faceA.a = faces[ offset ];
  10886. faceA.b = faces[ offset + 1 ];
  10887. faceA.c = faces[ offset + 3 ];
  10888. faceB = new THREE.Face3();
  10889. faceB.a = faces[ offset + 1 ];
  10890. faceB.b = faces[ offset + 2 ];
  10891. faceB.c = faces[ offset + 3 ];
  10892. offset += 4;
  10893. if ( hasMaterial ) {
  10894. materialIndex = faces[ offset ++ ];
  10895. faceA.materialIndex = materialIndex;
  10896. faceB.materialIndex = materialIndex;
  10897. }
  10898. // to get face <=> uv index correspondence
  10899. fi = geometry.faces.length;
  10900. if ( hasFaceVertexUv ) {
  10901. for ( i = 0; i < nUvLayers; i ++ ) {
  10902. uvLayer = json.uvs[ i ];
  10903. geometry.faceVertexUvs[ i ][ fi ] = [];
  10904. geometry.faceVertexUvs[ i ][ fi + 1 ] = [];
  10905. for ( j = 0; j < 4; j ++ ) {
  10906. uvIndex = faces[ offset ++ ];
  10907. u = uvLayer[ uvIndex * 2 ];
  10908. v = uvLayer[ uvIndex * 2 + 1 ];
  10909. uv = new THREE.Vector2( u, v );
  10910. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  10911. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  10912. }
  10913. }
  10914. }
  10915. if ( hasFaceNormal ) {
  10916. normalIndex = faces[ offset ++ ] * 3;
  10917. faceA.normal.set(
  10918. normals[ normalIndex ++ ],
  10919. normals[ normalIndex ++ ],
  10920. normals[ normalIndex ]
  10921. );
  10922. faceB.normal.copy( faceA.normal );
  10923. }
  10924. if ( hasFaceVertexNormal ) {
  10925. for ( i = 0; i < 4; i ++ ) {
  10926. normalIndex = faces[ offset ++ ] * 3;
  10927. normal = new THREE.Vector3(
  10928. normals[ normalIndex ++ ],
  10929. normals[ normalIndex ++ ],
  10930. normals[ normalIndex ]
  10931. );
  10932. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  10933. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  10934. }
  10935. }
  10936. if ( hasFaceColor ) {
  10937. colorIndex = faces[ offset ++ ];
  10938. hex = colors[ colorIndex ];
  10939. faceA.color.setHex( hex );
  10940. faceB.color.setHex( hex );
  10941. }
  10942. if ( hasFaceVertexColor ) {
  10943. for ( i = 0; i < 4; i ++ ) {
  10944. colorIndex = faces[ offset ++ ];
  10945. hex = colors[ colorIndex ];
  10946. if ( i !== 2 ) faceA.vertexColors.push( new THREE.Color( hex ) );
  10947. if ( i !== 0 ) faceB.vertexColors.push( new THREE.Color( hex ) );
  10948. }
  10949. }
  10950. geometry.faces.push( faceA );
  10951. geometry.faces.push( faceB );
  10952. } else {
  10953. face = new THREE.Face3();
  10954. face.a = faces[ offset ++ ];
  10955. face.b = faces[ offset ++ ];
  10956. face.c = faces[ offset ++ ];
  10957. if ( hasMaterial ) {
  10958. materialIndex = faces[ offset ++ ];
  10959. face.materialIndex = materialIndex;
  10960. }
  10961. // to get face <=> uv index correspondence
  10962. fi = geometry.faces.length;
  10963. if ( hasFaceVertexUv ) {
  10964. for ( i = 0; i < nUvLayers; i ++ ) {
  10965. uvLayer = json.uvs[ i ];
  10966. geometry.faceVertexUvs[ i ][ fi ] = [];
  10967. for ( j = 0; j < 3; j ++ ) {
  10968. uvIndex = faces[ offset ++ ];
  10969. u = uvLayer[ uvIndex * 2 ];
  10970. v = uvLayer[ uvIndex * 2 + 1 ];
  10971. uv = new THREE.Vector2( u, v );
  10972. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  10973. }
  10974. }
  10975. }
  10976. if ( hasFaceNormal ) {
  10977. normalIndex = faces[ offset ++ ] * 3;
  10978. face.normal.set(
  10979. normals[ normalIndex ++ ],
  10980. normals[ normalIndex ++ ],
  10981. normals[ normalIndex ]
  10982. );
  10983. }
  10984. if ( hasFaceVertexNormal ) {
  10985. for ( i = 0; i < 3; i ++ ) {
  10986. normalIndex = faces[ offset ++ ] * 3;
  10987. normal = new THREE.Vector3(
  10988. normals[ normalIndex ++ ],
  10989. normals[ normalIndex ++ ],
  10990. normals[ normalIndex ]
  10991. );
  10992. face.vertexNormals.push( normal );
  10993. }
  10994. }
  10995. if ( hasFaceColor ) {
  10996. colorIndex = faces[ offset ++ ];
  10997. face.color.setHex( colors[ colorIndex ] );
  10998. }
  10999. if ( hasFaceVertexColor ) {
  11000. for ( i = 0; i < 3; i ++ ) {
  11001. colorIndex = faces[ offset ++ ];
  11002. face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) );
  11003. }
  11004. }
  11005. geometry.faces.push( face );
  11006. }
  11007. }
  11008. };
  11009. function parseSkin() {
  11010. var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2;
  11011. if ( json.skinWeights ) {
  11012. for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {
  11013. var x = json.skinWeights[ i ];
  11014. var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
  11015. var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
  11016. var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;
  11017. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  11018. }
  11019. }
  11020. if ( json.skinIndices ) {
  11021. for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {
  11022. var a = json.skinIndices[ i ];
  11023. var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
  11024. var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
  11025. var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;
  11026. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  11027. }
  11028. }
  11029. geometry.bones = json.bones;
  11030. if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {
  11031. console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
  11032. geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );
  11033. }
  11034. };
  11035. function parseMorphing( scale ) {
  11036. if ( json.morphTargets !== undefined ) {
  11037. for ( var i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  11038. geometry.morphTargets[ i ] = {};
  11039. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  11040. geometry.morphTargets[ i ].vertices = [];
  11041. var dstVertices = geometry.morphTargets[ i ].vertices;
  11042. var srcVertices = json.morphTargets[ i ].vertices;
  11043. for ( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  11044. var vertex = new THREE.Vector3();
  11045. vertex.x = srcVertices[ v ] * scale;
  11046. vertex.y = srcVertices[ v + 1 ] * scale;
  11047. vertex.z = srcVertices[ v + 2 ] * scale;
  11048. dstVertices.push( vertex );
  11049. }
  11050. }
  11051. }
  11052. if ( json.morphColors !== undefined && json.morphColors.length > 0 ) {
  11053. console.warn( 'THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.' );
  11054. var faces = geometry.faces;
  11055. var morphColors = json.morphColors[ 0 ].colors;
  11056. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  11057. faces[ i ].color.fromArray( morphColors, i * 3 );
  11058. }
  11059. }
  11060. }
  11061. function parseAnimations() {
  11062. var outputAnimations = [];
  11063. // parse old style Bone/Hierarchy animations
  11064. var animations = [];
  11065. if ( json.animation !== undefined ) {
  11066. animations.push( json.animation );
  11067. }
  11068. if ( json.animations !== undefined ) {
  11069. if ( json.animations.length ) {
  11070. animations = animations.concat( json.animations );
  11071. } else {
  11072. animations.push( json.animations );
  11073. }
  11074. }
  11075. for ( var i = 0; i < animations.length; i ++ ) {
  11076. var clip = THREE.AnimationClip.parseAnimation( animations[ i ], geometry.bones );
  11077. if ( clip ) outputAnimations.push( clip );
  11078. }
  11079. // parse implicit morph animations
  11080. if ( geometry.morphTargets ) {
  11081. // TODO: Figure out what an appropraite FPS is for morph target animations -- defaulting to 10, but really it is completely arbitrary.
  11082. var morphAnimationClips = THREE.AnimationClip.CreateClipsFromMorphTargetSequences( geometry.morphTargets, 10 );
  11083. outputAnimations = outputAnimations.concat( morphAnimationClips );
  11084. }
  11085. if ( outputAnimations.length > 0 ) geometry.animations = outputAnimations;
  11086. };
  11087. if ( json.materials === undefined || json.materials.length === 0 ) {
  11088. return { geometry: geometry };
  11089. } else {
  11090. var materials = THREE.Loader.prototype.initMaterials( json.materials, texturePath, this.crossOrigin );
  11091. return { geometry: geometry, materials: materials };
  11092. }
  11093. }
  11094. };
  11095. // File:src/loaders/LoadingManager.js
  11096. /**
  11097. * @author mrdoob / http://mrdoob.com/
  11098. */
  11099. THREE.LoadingManager = function ( onLoad, onProgress, onError ) {
  11100. var scope = this;
  11101. var isLoading = false, itemsLoaded = 0, itemsTotal = 0;
  11102. this.onStart = undefined;
  11103. this.onLoad = onLoad;
  11104. this.onProgress = onProgress;
  11105. this.onError = onError;
  11106. this.itemStart = function ( url ) {
  11107. itemsTotal ++;
  11108. if ( isLoading === false ) {
  11109. if ( scope.onStart !== undefined ) {
  11110. scope.onStart( url, itemsLoaded, itemsTotal );
  11111. }
  11112. }
  11113. isLoading = true;
  11114. };
  11115. this.itemEnd = function ( url ) {
  11116. itemsLoaded ++;
  11117. if ( scope.onProgress !== undefined ) {
  11118. scope.onProgress( url, itemsLoaded, itemsTotal );
  11119. }
  11120. if ( itemsLoaded === itemsTotal ) {
  11121. isLoading = false;
  11122. if ( scope.onLoad !== undefined ) {
  11123. scope.onLoad();
  11124. }
  11125. }
  11126. };
  11127. this.itemError = function ( url ) {
  11128. if ( scope.onError !== undefined ) {
  11129. scope.onError( url );
  11130. }
  11131. };
  11132. };
  11133. THREE.DefaultLoadingManager = new THREE.LoadingManager();
  11134. // File:src/loaders/BufferGeometryLoader.js
  11135. /**
  11136. * @author mrdoob / http://mrdoob.com/
  11137. */
  11138. THREE.BufferGeometryLoader = function ( manager ) {
  11139. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  11140. };
  11141. THREE.BufferGeometryLoader.prototype = {
  11142. constructor: THREE.BufferGeometryLoader,
  11143. load: function ( url, onLoad, onProgress, onError ) {
  11144. var scope = this;
  11145. var loader = new THREE.XHRLoader( scope.manager );
  11146. loader.load( url, function ( text ) {
  11147. onLoad( scope.parse( JSON.parse( text ) ) );
  11148. }, onProgress, onError );
  11149. },
  11150. parse: function ( json ) {
  11151. var geometry = new THREE.BufferGeometry();
  11152. var index = json.data.index;
  11153. var TYPED_ARRAYS = {
  11154. 'Int8Array': Int8Array,
  11155. 'Uint8Array': Uint8Array,
  11156. 'Uint8ClampedArray': Uint8ClampedArray,
  11157. 'Int16Array': Int16Array,
  11158. 'Uint16Array': Uint16Array,
  11159. 'Int32Array': Int32Array,
  11160. 'Uint32Array': Uint32Array,
  11161. 'Float32Array': Float32Array,
  11162. 'Float64Array': Float64Array
  11163. };
  11164. if ( index !== undefined ) {
  11165. var typedArray = new TYPED_ARRAYS[ index.type ]( index.array );
  11166. geometry.setIndex( new THREE.BufferAttribute( typedArray, 1 ) );
  11167. }
  11168. var attributes = json.data.attributes;
  11169. for ( var key in attributes ) {
  11170. var attribute = attributes[ key ];
  11171. var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array );
  11172. geometry.addAttribute( key, new THREE.BufferAttribute( typedArray, attribute.itemSize ) );
  11173. }
  11174. var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  11175. if ( groups !== undefined ) {
  11176. for ( var i = 0, n = groups.length; i !== n; ++ i ) {
  11177. var group = groups[ i ];
  11178. geometry.addGroup( group.start, group.count, group.materialIndex );
  11179. }
  11180. }
  11181. var boundingSphere = json.data.boundingSphere;
  11182. if ( boundingSphere !== undefined ) {
  11183. var center = new THREE.Vector3();
  11184. if ( boundingSphere.center !== undefined ) {
  11185. center.fromArray( boundingSphere.center );
  11186. }
  11187. geometry.boundingSphere = new THREE.Sphere( center, boundingSphere.radius );
  11188. }
  11189. return geometry;
  11190. }
  11191. };
  11192. // File:src/loaders/MaterialLoader.js
  11193. /**
  11194. * @author mrdoob / http://mrdoob.com/
  11195. */
  11196. THREE.MaterialLoader = function ( manager ) {
  11197. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  11198. this.textures = {};
  11199. };
  11200. THREE.MaterialLoader.prototype = {
  11201. constructor: THREE.MaterialLoader,
  11202. load: function ( url, onLoad, onProgress, onError ) {
  11203. var scope = this;
  11204. var loader = new THREE.XHRLoader( scope.manager );
  11205. loader.load( url, function ( text ) {
  11206. onLoad( scope.parse( JSON.parse( text ) ) );
  11207. }, onProgress, onError );
  11208. },
  11209. setTextures: function ( value ) {
  11210. this.textures = value;
  11211. },
  11212. getTexture: function ( name ) {
  11213. var textures = this.textures;
  11214. if ( textures[ name ] === undefined ) {
  11215. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  11216. }
  11217. return textures[ name ];
  11218. },
  11219. parse: function ( json ) {
  11220. var material = new THREE[ json.type ];
  11221. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  11222. if ( json.name !== undefined ) material.name = json.name;
  11223. if ( json.color !== undefined ) material.color.setHex( json.color );
  11224. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  11225. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  11226. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  11227. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  11228. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  11229. if ( json.uniforms !== undefined ) material.uniforms = json.uniforms;
  11230. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  11231. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  11232. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  11233. if ( json.shading !== undefined ) material.shading = json.shading;
  11234. if ( json.blending !== undefined ) material.blending = json.blending;
  11235. if ( json.side !== undefined ) material.side = json.side;
  11236. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  11237. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  11238. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  11239. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  11240. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  11241. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  11242. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  11243. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  11244. // for PointsMaterial
  11245. if ( json.size !== undefined ) material.size = json.size;
  11246. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  11247. // maps
  11248. if ( json.map !== undefined ) material.map = this.getTexture( json.map );
  11249. if ( json.alphaMap !== undefined ) {
  11250. material.alphaMap = this.getTexture( json.alphaMap );
  11251. material.transparent = true;
  11252. }
  11253. if ( json.bumpMap !== undefined ) material.bumpMap = this.getTexture( json.bumpMap );
  11254. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  11255. if ( json.normalMap !== undefined ) material.normalMap = this.getTexture( json.normalMap );
  11256. if ( json.normalScale !== undefined ) {
  11257. var normalScale = json.normalScale;
  11258. if ( Array.isArray( normalScale ) === false ) {
  11259. // Blender exporter used to export a scalar. See #7459
  11260. normalScale = [ normalScale, normalScale ];
  11261. }
  11262. material.normalScale = new THREE.Vector2().fromArray( normalScale );
  11263. }
  11264. if ( json.displacementMap !== undefined ) material.displacementMap = this.getTexture( json.displacementMap );
  11265. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  11266. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  11267. if ( json.roughnessMap !== undefined ) material.roughnessMap = this.getTexture( json.roughnessMap );
  11268. if ( json.metalnessMap !== undefined ) material.metalnessMap = this.getTexture( json.metalnessMap );
  11269. if ( json.emissiveMap !== undefined ) material.emissiveMap = this.getTexture( json.emissiveMap );
  11270. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  11271. if ( json.specularMap !== undefined ) material.specularMap = this.getTexture( json.specularMap );
  11272. if ( json.envMap !== undefined ) {
  11273. material.envMap = this.getTexture( json.envMap );
  11274. material.combine = THREE.MultiplyOperation;
  11275. }
  11276. if ( json.reflectivity ) material.reflectivity = json.reflectivity;
  11277. if ( json.lightMap !== undefined ) material.lightMap = this.getTexture( json.lightMap );
  11278. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  11279. if ( json.aoMap !== undefined ) material.aoMap = this.getTexture( json.aoMap );
  11280. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  11281. // MultiMaterial
  11282. if ( json.materials !== undefined ) {
  11283. for ( var i = 0, l = json.materials.length; i < l; i ++ ) {
  11284. material.materials.push( this.parse( json.materials[ i ] ) );
  11285. }
  11286. }
  11287. return material;
  11288. }
  11289. };
  11290. // File:src/loaders/ObjectLoader.js
  11291. /**
  11292. * @author mrdoob / http://mrdoob.com/
  11293. */
  11294. THREE.ObjectLoader = function ( manager ) {
  11295. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  11296. this.texturePath = '';
  11297. };
  11298. THREE.ObjectLoader.prototype = {
  11299. constructor: THREE.ObjectLoader,
  11300. load: function ( url, onLoad, onProgress, onError ) {
  11301. if ( this.texturePath === '' ) {
  11302. this.texturePath = url.substring( 0, url.lastIndexOf( '/' ) + 1 );
  11303. }
  11304. var scope = this;
  11305. var loader = new THREE.XHRLoader( scope.manager );
  11306. loader.load( url, function ( text ) {
  11307. scope.parse( JSON.parse( text ), onLoad );
  11308. }, onProgress, onError );
  11309. },
  11310. setTexturePath: function ( value ) {
  11311. this.texturePath = value;
  11312. },
  11313. setCrossOrigin: function ( value ) {
  11314. this.crossOrigin = value;
  11315. },
  11316. parse: function ( json, onLoad ) {
  11317. var geometries = this.parseGeometries( json.geometries );
  11318. var images = this.parseImages( json.images, function () {
  11319. if ( onLoad !== undefined ) onLoad( object );
  11320. } );
  11321. var textures = this.parseTextures( json.textures, images );
  11322. var materials = this.parseMaterials( json.materials, textures );
  11323. var object = this.parseObject( json.object, geometries, materials );
  11324. if ( json.animations ) {
  11325. object.animations = this.parseAnimations( json.animations );
  11326. }
  11327. if ( json.images === undefined || json.images.length === 0 ) {
  11328. if ( onLoad !== undefined ) onLoad( object );
  11329. }
  11330. return object;
  11331. },
  11332. parseGeometries: function ( json ) {
  11333. var geometries = {};
  11334. if ( json !== undefined ) {
  11335. var geometryLoader = new THREE.JSONLoader();
  11336. var bufferGeometryLoader = new THREE.BufferGeometryLoader();
  11337. for ( var i = 0, l = json.length; i < l; i ++ ) {
  11338. var geometry;
  11339. var data = json[ i ];
  11340. switch ( data.type ) {
  11341. case 'PlaneGeometry':
  11342. case 'PlaneBufferGeometry':
  11343. geometry = new THREE[ data.type ](
  11344. data.width,
  11345. data.height,
  11346. data.widthSegments,
  11347. data.heightSegments
  11348. );
  11349. break;
  11350. case 'BoxGeometry':
  11351. case 'BoxBufferGeometry':
  11352. case 'CubeGeometry': // backwards compatible
  11353. geometry = new THREE[ data.type ](
  11354. data.width,
  11355. data.height,
  11356. data.depth,
  11357. data.widthSegments,
  11358. data.heightSegments,
  11359. data.depthSegments
  11360. );
  11361. break;
  11362. case 'CircleGeometry':
  11363. case 'CircleBufferGeometry':
  11364. geometry = new THREE[ data.type ](
  11365. data.radius,
  11366. data.segments,
  11367. data.thetaStart,
  11368. data.thetaLength
  11369. );
  11370. break;
  11371. case 'CylinderGeometry':
  11372. case 'CylinderBufferGeometry':
  11373. geometry = new THREE[ data.type ](
  11374. data.radiusTop,
  11375. data.radiusBottom,
  11376. data.height,
  11377. data.radialSegments,
  11378. data.heightSegments,
  11379. data.openEnded,
  11380. data.thetaStart,
  11381. data.thetaLength
  11382. );
  11383. break;
  11384. case 'SphereGeometry':
  11385. case 'SphereBufferGeometry':
  11386. geometry = new THREE[ data.type ](
  11387. data.radius,
  11388. data.widthSegments,
  11389. data.heightSegments,
  11390. data.phiStart,
  11391. data.phiLength,
  11392. data.thetaStart,
  11393. data.thetaLength
  11394. );
  11395. break;
  11396. case 'DodecahedronGeometry':
  11397. geometry = new THREE.DodecahedronGeometry(
  11398. data.radius,
  11399. data.detail
  11400. );
  11401. break;
  11402. case 'IcosahedronGeometry':
  11403. geometry = new THREE.IcosahedronGeometry(
  11404. data.radius,
  11405. data.detail
  11406. );
  11407. break;
  11408. case 'OctahedronGeometry':
  11409. geometry = new THREE.OctahedronGeometry(
  11410. data.radius,
  11411. data.detail
  11412. );
  11413. break;
  11414. case 'TetrahedronGeometry':
  11415. geometry = new THREE.TetrahedronGeometry(
  11416. data.radius,
  11417. data.detail
  11418. );
  11419. break;
  11420. case 'RingGeometry':
  11421. case 'RingBufferGeometry':
  11422. geometry = new THREE[ data.type ](
  11423. data.innerRadius,
  11424. data.outerRadius,
  11425. data.thetaSegments,
  11426. data.phiSegments,
  11427. data.thetaStart,
  11428. data.thetaLength
  11429. );
  11430. break;
  11431. case 'TorusGeometry':
  11432. case 'TorusBufferGeometry':
  11433. geometry = new THREE[ data.type ](
  11434. data.radius,
  11435. data.tube,
  11436. data.radialSegments,
  11437. data.tubularSegments,
  11438. data.arc
  11439. );
  11440. break;
  11441. case 'TorusKnotGeometry':
  11442. case 'TorusKnotBufferGeometry':
  11443. geometry = new THREE[ data.type ](
  11444. data.radius,
  11445. data.tube,
  11446. data.tubularSegments,
  11447. data.radialSegments,
  11448. data.p,
  11449. data.q
  11450. );
  11451. break;
  11452. case 'LatheGeometry':
  11453. case 'LatheBufferGeometry':
  11454. geometry = new THREE[ data.type ](
  11455. data.points,
  11456. data.segments,
  11457. data.phiStart,
  11458. data.phiLength
  11459. );
  11460. break;
  11461. case 'BufferGeometry':
  11462. geometry = bufferGeometryLoader.parse( data );
  11463. break;
  11464. case 'Geometry':
  11465. geometry = geometryLoader.parse( data.data, this.texturePath ).geometry;
  11466. break;
  11467. default:
  11468. console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' );
  11469. continue;
  11470. }
  11471. geometry.uuid = data.uuid;
  11472. if ( data.name !== undefined ) geometry.name = data.name;
  11473. geometries[ data.uuid ] = geometry;
  11474. }
  11475. }
  11476. return geometries;
  11477. },
  11478. parseMaterials: function ( json, textures ) {
  11479. var materials = {};
  11480. if ( json !== undefined ) {
  11481. var loader = new THREE.MaterialLoader();
  11482. loader.setTextures( textures );
  11483. for ( var i = 0, l = json.length; i < l; i ++ ) {
  11484. var material = loader.parse( json[ i ] );
  11485. materials[ material.uuid ] = material;
  11486. }
  11487. }
  11488. return materials;
  11489. },
  11490. parseAnimations: function ( json ) {
  11491. var animations = [];
  11492. for ( var i = 0; i < json.length; i ++ ) {
  11493. var clip = THREE.AnimationClip.parse( json[ i ] );
  11494. animations.push( clip );
  11495. }
  11496. return animations;
  11497. },
  11498. parseImages: function ( json, onLoad ) {
  11499. var scope = this;
  11500. var images = {};
  11501. function loadImage( url ) {
  11502. scope.manager.itemStart( url );
  11503. return loader.load( url, function () {
  11504. scope.manager.itemEnd( url );
  11505. } );
  11506. }
  11507. if ( json !== undefined && json.length > 0 ) {
  11508. var manager = new THREE.LoadingManager( onLoad );
  11509. var loader = new THREE.ImageLoader( manager );
  11510. loader.setCrossOrigin( this.crossOrigin );
  11511. for ( var i = 0, l = json.length; i < l; i ++ ) {
  11512. var image = json[ i ];
  11513. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.texturePath + image.url;
  11514. images[ image.uuid ] = loadImage( path );
  11515. }
  11516. }
  11517. return images;
  11518. },
  11519. parseTextures: function ( json, images ) {
  11520. function parseConstant( value ) {
  11521. if ( typeof( value ) === 'number' ) return value;
  11522. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  11523. return THREE[ value ];
  11524. }
  11525. var textures = {};
  11526. if ( json !== undefined ) {
  11527. for ( var i = 0, l = json.length; i < l; i ++ ) {
  11528. var data = json[ i ];
  11529. if ( data.image === undefined ) {
  11530. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  11531. }
  11532. if ( images[ data.image ] === undefined ) {
  11533. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  11534. }
  11535. var texture = new THREE.Texture( images[ data.image ] );
  11536. texture.needsUpdate = true;
  11537. texture.uuid = data.uuid;
  11538. if ( data.name !== undefined ) texture.name = data.name;
  11539. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping );
  11540. if ( data.offset !== undefined ) texture.offset = new THREE.Vector2( data.offset[ 0 ], data.offset[ 1 ] );
  11541. if ( data.repeat !== undefined ) texture.repeat = new THREE.Vector2( data.repeat[ 0 ], data.repeat[ 1 ] );
  11542. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter );
  11543. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter );
  11544. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  11545. if ( Array.isArray( data.wrap ) ) {
  11546. texture.wrapS = parseConstant( data.wrap[ 0 ] );
  11547. texture.wrapT = parseConstant( data.wrap[ 1 ] );
  11548. }
  11549. textures[ data.uuid ] = texture;
  11550. }
  11551. }
  11552. return textures;
  11553. },
  11554. parseObject: function () {
  11555. var matrix = new THREE.Matrix4();
  11556. return function ( data, geometries, materials ) {
  11557. var object;
  11558. function getGeometry( name ) {
  11559. if ( geometries[ name ] === undefined ) {
  11560. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  11561. }
  11562. return geometries[ name ];
  11563. }
  11564. function getMaterial( name ) {
  11565. if ( name === undefined ) return undefined;
  11566. if ( materials[ name ] === undefined ) {
  11567. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  11568. }
  11569. return materials[ name ];
  11570. }
  11571. switch ( data.type ) {
  11572. case 'Scene':
  11573. object = new THREE.Scene();
  11574. break;
  11575. case 'PerspectiveCamera':
  11576. object = new THREE.PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  11577. break;
  11578. case 'OrthographicCamera':
  11579. object = new THREE.OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  11580. break;
  11581. case 'AmbientLight':
  11582. object = new THREE.AmbientLight( data.color, data.intensity );
  11583. break;
  11584. case 'DirectionalLight':
  11585. object = new THREE.DirectionalLight( data.color, data.intensity );
  11586. break;
  11587. case 'PointLight':
  11588. object = new THREE.PointLight( data.color, data.intensity, data.distance, data.decay );
  11589. break;
  11590. case 'SpotLight':
  11591. object = new THREE.SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  11592. break;
  11593. case 'HemisphereLight':
  11594. object = new THREE.HemisphereLight( data.color, data.groundColor, data.intensity );
  11595. break;
  11596. case 'Mesh':
  11597. var geometry = getGeometry( data.geometry );
  11598. var material = getMaterial( data.material );
  11599. if ( geometry.bones && geometry.bones.length > 0 ) {
  11600. object = new THREE.SkinnedMesh( geometry, material );
  11601. } else {
  11602. object = new THREE.Mesh( geometry, material );
  11603. }
  11604. break;
  11605. case 'LOD':
  11606. object = new THREE.LOD();
  11607. break;
  11608. case 'Line':
  11609. object = new THREE.Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode );
  11610. break;
  11611. case 'PointCloud':
  11612. case 'Points':
  11613. object = new THREE.Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  11614. break;
  11615. case 'Sprite':
  11616. object = new THREE.Sprite( getMaterial( data.material ) );
  11617. break;
  11618. case 'Group':
  11619. object = new THREE.Group();
  11620. break;
  11621. default:
  11622. object = new THREE.Object3D();
  11623. }
  11624. object.uuid = data.uuid;
  11625. if ( data.name !== undefined ) object.name = data.name;
  11626. if ( data.matrix !== undefined ) {
  11627. matrix.fromArray( data.matrix );
  11628. matrix.decompose( object.position, object.quaternion, object.scale );
  11629. } else {
  11630. if ( data.position !== undefined ) object.position.fromArray( data.position );
  11631. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  11632. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  11633. }
  11634. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  11635. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  11636. if ( data.visible !== undefined ) object.visible = data.visible;
  11637. if ( data.userData !== undefined ) object.userData = data.userData;
  11638. if ( data.children !== undefined ) {
  11639. for ( var child in data.children ) {
  11640. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  11641. }
  11642. }
  11643. if ( data.type === 'LOD' ) {
  11644. var levels = data.levels;
  11645. for ( var l = 0; l < levels.length; l ++ ) {
  11646. var level = levels[ l ];
  11647. var child = object.getObjectByProperty( 'uuid', level.object );
  11648. if ( child !== undefined ) {
  11649. object.addLevel( child, level.distance );
  11650. }
  11651. }
  11652. }
  11653. return object;
  11654. };
  11655. }()
  11656. };
  11657. // File:src/loaders/TextureLoader.js
  11658. /**
  11659. * @author mrdoob / http://mrdoob.com/
  11660. */
  11661. THREE.TextureLoader = function ( manager ) {
  11662. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  11663. };
  11664. THREE.TextureLoader.prototype = {
  11665. constructor: THREE.TextureLoader,
  11666. load: function ( url, onLoad, onProgress, onError ) {
  11667. var texture = new THREE.Texture();
  11668. var loader = new THREE.ImageLoader( this.manager );
  11669. loader.setCrossOrigin( this.crossOrigin );
  11670. loader.setPath( this.path );
  11671. loader.load( url, function ( image ) {
  11672. texture.image = image;
  11673. texture.needsUpdate = true;
  11674. if ( onLoad !== undefined ) {
  11675. onLoad( texture );
  11676. }
  11677. }, onProgress, onError );
  11678. return texture;
  11679. },
  11680. setCrossOrigin: function ( value ) {
  11681. this.crossOrigin = value;
  11682. },
  11683. setPath: function ( value ) {
  11684. this.path = value;
  11685. }
  11686. };
  11687. // File:src/loaders/CubeTextureLoader.js
  11688. /**
  11689. * @author mrdoob / http://mrdoob.com/
  11690. */
  11691. THREE.CubeTextureLoader = function ( manager ) {
  11692. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  11693. };
  11694. THREE.CubeTextureLoader.prototype = {
  11695. constructor: THREE.CubeTextureLoader,
  11696. load: function ( urls, onLoad, onProgress, onError ) {
  11697. var texture = new THREE.CubeTexture();
  11698. var loader = new THREE.ImageLoader( this.manager );
  11699. loader.setCrossOrigin( this.crossOrigin );
  11700. loader.setPath( this.path );
  11701. var loaded = 0;
  11702. function loadTexture( i ) {
  11703. loader.load( urls[ i ], function ( image ) {
  11704. texture.images[ i ] = image;
  11705. loaded ++;
  11706. if ( loaded === 6 ) {
  11707. texture.needsUpdate = true;
  11708. if ( onLoad ) onLoad( texture );
  11709. }
  11710. }, undefined, onError );
  11711. }
  11712. for ( var i = 0; i < urls.length; ++ i ) {
  11713. loadTexture( i );
  11714. }
  11715. return texture;
  11716. },
  11717. setCrossOrigin: function ( value ) {
  11718. this.crossOrigin = value;
  11719. },
  11720. setPath: function ( value ) {
  11721. this.path = value;
  11722. }
  11723. };
  11724. // File:src/loaders/BinaryTextureLoader.js
  11725. /**
  11726. * @author Nikos M. / https://github.com/foo123/
  11727. *
  11728. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  11729. */
  11730. THREE.DataTextureLoader = THREE.BinaryTextureLoader = function ( manager ) {
  11731. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  11732. // override in sub classes
  11733. this._parser = null;
  11734. };
  11735. THREE.BinaryTextureLoader.prototype = {
  11736. constructor: THREE.BinaryTextureLoader,
  11737. load: function ( url, onLoad, onProgress, onError ) {
  11738. var scope = this;
  11739. var texture = new THREE.DataTexture();
  11740. var loader = new THREE.XHRLoader( this.manager );
  11741. loader.setResponseType( 'arraybuffer' );
  11742. loader.load( url, function ( buffer ) {
  11743. var texData = scope._parser( buffer );
  11744. if ( ! texData ) return;
  11745. if ( undefined !== texData.image ) {
  11746. texture.image = texData.image;
  11747. } else if ( undefined !== texData.data ) {
  11748. texture.image.width = texData.width;
  11749. texture.image.height = texData.height;
  11750. texture.image.data = texData.data;
  11751. }
  11752. texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : THREE.ClampToEdgeWrapping;
  11753. texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : THREE.ClampToEdgeWrapping;
  11754. texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : THREE.LinearFilter;
  11755. texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : THREE.LinearMipMapLinearFilter;
  11756. texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1;
  11757. if ( undefined !== texData.format ) {
  11758. texture.format = texData.format;
  11759. }
  11760. if ( undefined !== texData.type ) {
  11761. texture.type = texData.type;
  11762. }
  11763. if ( undefined !== texData.mipmaps ) {
  11764. texture.mipmaps = texData.mipmaps;
  11765. }
  11766. if ( 1 === texData.mipmapCount ) {
  11767. texture.minFilter = THREE.LinearFilter;
  11768. }
  11769. texture.needsUpdate = true;
  11770. if ( onLoad ) onLoad( texture, texData );
  11771. }, onProgress, onError );
  11772. return texture;
  11773. }
  11774. };
  11775. // File:src/loaders/CompressedTextureLoader.js
  11776. /**
  11777. * @author mrdoob / http://mrdoob.com/
  11778. *
  11779. * Abstract Base class to block based textures loader (dds, pvr, ...)
  11780. */
  11781. THREE.CompressedTextureLoader = function ( manager ) {
  11782. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  11783. // override in sub classes
  11784. this._parser = null;
  11785. };
  11786. THREE.CompressedTextureLoader.prototype = {
  11787. constructor: THREE.CompressedTextureLoader,
  11788. load: function ( url, onLoad, onProgress, onError ) {
  11789. var scope = this;
  11790. var images = [];
  11791. var texture = new THREE.CompressedTexture();
  11792. texture.image = images;
  11793. var loader = new THREE.XHRLoader( this.manager );
  11794. loader.setPath( this.path );
  11795. loader.setResponseType( 'arraybuffer' );
  11796. function loadTexture( i ) {
  11797. loader.load( url[ i ], function ( buffer ) {
  11798. var texDatas = scope._parser( buffer, true );
  11799. images[ i ] = {
  11800. width: texDatas.width,
  11801. height: texDatas.height,
  11802. format: texDatas.format,
  11803. mipmaps: texDatas.mipmaps
  11804. };
  11805. loaded += 1;
  11806. if ( loaded === 6 ) {
  11807. if ( texDatas.mipmapCount === 1 )
  11808. texture.minFilter = THREE.LinearFilter;
  11809. texture.format = texDatas.format;
  11810. texture.needsUpdate = true;
  11811. if ( onLoad ) onLoad( texture );
  11812. }
  11813. }, onProgress, onError );
  11814. }
  11815. if ( Array.isArray( url ) ) {
  11816. var loaded = 0;
  11817. for ( var i = 0, il = url.length; i < il; ++ i ) {
  11818. loadTexture( i );
  11819. }
  11820. } else {
  11821. // compressed cubemap texture stored in a single DDS file
  11822. loader.load( url, function ( buffer ) {
  11823. var texDatas = scope._parser( buffer, true );
  11824. if ( texDatas.isCubemap ) {
  11825. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  11826. for ( var f = 0; f < faces; f ++ ) {
  11827. images[ f ] = { mipmaps : [] };
  11828. for ( var i = 0; i < texDatas.mipmapCount; i ++ ) {
  11829. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  11830. images[ f ].format = texDatas.format;
  11831. images[ f ].width = texDatas.width;
  11832. images[ f ].height = texDatas.height;
  11833. }
  11834. }
  11835. } else {
  11836. texture.image.width = texDatas.width;
  11837. texture.image.height = texDatas.height;
  11838. texture.mipmaps = texDatas.mipmaps;
  11839. }
  11840. if ( texDatas.mipmapCount === 1 ) {
  11841. texture.minFilter = THREE.LinearFilter;
  11842. }
  11843. texture.format = texDatas.format;
  11844. texture.needsUpdate = true;
  11845. if ( onLoad ) onLoad( texture );
  11846. }, onProgress, onError );
  11847. }
  11848. return texture;
  11849. },
  11850. setPath: function ( value ) {
  11851. this.path = value;
  11852. }
  11853. };
  11854. // File:src/materials/Material.js
  11855. /**
  11856. * @author mrdoob / http://mrdoob.com/
  11857. * @author alteredq / http://alteredqualia.com/
  11858. */
  11859. THREE.Material = function () {
  11860. Object.defineProperty( this, 'id', { value: THREE.MaterialIdCount ++ } );
  11861. this.uuid = THREE.Math.generateUUID();
  11862. this.name = '';
  11863. this.type = 'Material';
  11864. this.side = THREE.FrontSide;
  11865. this.opacity = 1;
  11866. this.transparent = false;
  11867. this.blending = THREE.NormalBlending;
  11868. this.blendSrc = THREE.SrcAlphaFactor;
  11869. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  11870. this.blendEquation = THREE.AddEquation;
  11871. this.blendSrcAlpha = null;
  11872. this.blendDstAlpha = null;
  11873. this.blendEquationAlpha = null;
  11874. this.depthFunc = THREE.LessEqualDepth;
  11875. this.depthTest = true;
  11876. this.depthWrite = true;
  11877. this.colorWrite = true;
  11878. this.precision = null; // override the renderer's default precision for this material
  11879. this.polygonOffset = false;
  11880. this.polygonOffsetFactor = 0;
  11881. this.polygonOffsetUnits = 0;
  11882. this.alphaTest = 0;
  11883. this.premultipliedAlpha = false;
  11884. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  11885. this.visible = true;
  11886. this._needsUpdate = true;
  11887. };
  11888. THREE.Material.prototype = {
  11889. constructor: THREE.Material,
  11890. get needsUpdate () {
  11891. return this._needsUpdate;
  11892. },
  11893. set needsUpdate ( value ) {
  11894. if ( value === true ) this.update();
  11895. this._needsUpdate = value;
  11896. },
  11897. setValues: function ( values ) {
  11898. if ( values === undefined ) return;
  11899. for ( var key in values ) {
  11900. var newValue = values[ key ];
  11901. if ( newValue === undefined ) {
  11902. console.warn( "THREE.Material: '" + key + "' parameter is undefined." );
  11903. continue;
  11904. }
  11905. var currentValue = this[ key ];
  11906. if ( currentValue === undefined ) {
  11907. console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." );
  11908. continue;
  11909. }
  11910. if ( currentValue instanceof THREE.Color ) {
  11911. currentValue.set( newValue );
  11912. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  11913. currentValue.copy( newValue );
  11914. } else if ( key === 'overdraw' ) {
  11915. // ensure overdraw is backwards-compatible with legacy boolean type
  11916. this[ key ] = Number( newValue );
  11917. } else {
  11918. this[ key ] = newValue;
  11919. }
  11920. }
  11921. },
  11922. toJSON: function ( meta ) {
  11923. var isRoot = meta === undefined;
  11924. if ( isRoot ) {
  11925. meta = {
  11926. textures: {},
  11927. images: {}
  11928. };
  11929. }
  11930. var data = {
  11931. metadata: {
  11932. version: 4.4,
  11933. type: 'Material',
  11934. generator: 'Material.toJSON'
  11935. }
  11936. };
  11937. // standard Material serialization
  11938. data.uuid = this.uuid;
  11939. data.type = this.type;
  11940. if ( this.name !== '' ) data.name = this.name;
  11941. if ( this.color instanceof THREE.Color ) data.color = this.color.getHex();
  11942. if ( this.roughness !== 0.5 ) data.roughness = this.roughness;
  11943. if ( this.metalness !== 0.5 ) data.metalness = this.metalness;
  11944. if ( this.emissive instanceof THREE.Color ) data.emissive = this.emissive.getHex();
  11945. if ( this.specular instanceof THREE.Color ) data.specular = this.specular.getHex();
  11946. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  11947. if ( this.map instanceof THREE.Texture ) data.map = this.map.toJSON( meta ).uuid;
  11948. if ( this.alphaMap instanceof THREE.Texture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  11949. if ( this.lightMap instanceof THREE.Texture ) data.lightMap = this.lightMap.toJSON( meta ).uuid;
  11950. if ( this.bumpMap instanceof THREE.Texture ) {
  11951. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  11952. data.bumpScale = this.bumpScale;
  11953. }
  11954. if ( this.normalMap instanceof THREE.Texture ) {
  11955. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  11956. data.normalScale = this.normalScale.toArray();
  11957. }
  11958. if ( this.displacementMap instanceof THREE.Texture ) {
  11959. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  11960. data.displacementScale = this.displacementScale;
  11961. data.displacementBias = this.displacementBias;
  11962. }
  11963. if ( this.roughnessMap instanceof THREE.Texture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  11964. if ( this.metalnessMap instanceof THREE.Texture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  11965. if ( this.emissiveMap instanceof THREE.Texture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  11966. if ( this.specularMap instanceof THREE.Texture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  11967. if ( this.envMap instanceof THREE.Texture ) {
  11968. data.envMap = this.envMap.toJSON( meta ).uuid;
  11969. data.reflectivity = this.reflectivity; // Scale behind envMap
  11970. }
  11971. if ( this.size !== undefined ) data.size = this.size;
  11972. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  11973. if ( this.vertexColors !== undefined && this.vertexColors !== THREE.NoColors ) data.vertexColors = this.vertexColors;
  11974. if ( this.shading !== undefined && this.shading !== THREE.SmoothShading ) data.shading = this.shading;
  11975. if ( this.blending !== undefined && this.blending !== THREE.NormalBlending ) data.blending = this.blending;
  11976. if ( this.side !== undefined && this.side !== THREE.FrontSide ) data.side = this.side;
  11977. if ( this.opacity < 1 ) data.opacity = this.opacity;
  11978. if ( this.transparent === true ) data.transparent = this.transparent;
  11979. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  11980. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  11981. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  11982. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  11983. // TODO: Copied from Object3D.toJSON
  11984. function extractFromCache ( cache ) {
  11985. var values = [];
  11986. for ( var key in cache ) {
  11987. var data = cache[ key ];
  11988. delete data.metadata;
  11989. values.push( data );
  11990. }
  11991. return values;
  11992. }
  11993. if ( isRoot ) {
  11994. var textures = extractFromCache( meta.textures );
  11995. var images = extractFromCache( meta.images );
  11996. if ( textures.length > 0 ) data.textures = textures;
  11997. if ( images.length > 0 ) data.images = images;
  11998. }
  11999. return data;
  12000. },
  12001. clone: function () {
  12002. return new this.constructor().copy( this );
  12003. },
  12004. copy: function ( source ) {
  12005. this.name = source.name;
  12006. this.side = source.side;
  12007. this.opacity = source.opacity;
  12008. this.transparent = source.transparent;
  12009. this.blending = source.blending;
  12010. this.blendSrc = source.blendSrc;
  12011. this.blendDst = source.blendDst;
  12012. this.blendEquation = source.blendEquation;
  12013. this.blendSrcAlpha = source.blendSrcAlpha;
  12014. this.blendDstAlpha = source.blendDstAlpha;
  12015. this.blendEquationAlpha = source.blendEquationAlpha;
  12016. this.depthFunc = source.depthFunc;
  12017. this.depthTest = source.depthTest;
  12018. this.depthWrite = source.depthWrite;
  12019. this.colorWrite = source.colorWrite;
  12020. this.precision = source.precision;
  12021. this.polygonOffset = source.polygonOffset;
  12022. this.polygonOffsetFactor = source.polygonOffsetFactor;
  12023. this.polygonOffsetUnits = source.polygonOffsetUnits;
  12024. this.alphaTest = source.alphaTest;
  12025. this.premultipliedAlpha = source.premultipliedAlpha;
  12026. this.overdraw = source.overdraw;
  12027. this.visible = source.visible;
  12028. return this;
  12029. },
  12030. update: function () {
  12031. this.dispatchEvent( { type: 'update' } );
  12032. },
  12033. dispose: function () {
  12034. this.dispatchEvent( { type: 'dispose' } );
  12035. }
  12036. };
  12037. THREE.EventDispatcher.prototype.apply( THREE.Material.prototype );
  12038. THREE.MaterialIdCount = 0;
  12039. // File:src/materials/LineBasicMaterial.js
  12040. /**
  12041. * @author mrdoob / http://mrdoob.com/
  12042. * @author alteredq / http://alteredqualia.com/
  12043. *
  12044. * parameters = {
  12045. * color: <hex>,
  12046. * opacity: <float>,
  12047. *
  12048. * linewidth: <float>,
  12049. * linecap: "round",
  12050. * linejoin: "round",
  12051. *
  12052. * blending: THREE.NormalBlending,
  12053. * depthTest: <bool>,
  12054. * depthWrite: <bool>,
  12055. *
  12056. * vertexColors: <bool>
  12057. *
  12058. * fog: <bool>
  12059. * }
  12060. */
  12061. THREE.LineBasicMaterial = function ( parameters ) {
  12062. THREE.Material.call( this );
  12063. this.type = 'LineBasicMaterial';
  12064. this.color = new THREE.Color( 0xffffff );
  12065. this.linewidth = 1;
  12066. this.linecap = 'round';
  12067. this.linejoin = 'round';
  12068. this.blending = THREE.NormalBlending;
  12069. this.vertexColors = THREE.NoColors;
  12070. this.fog = true;
  12071. this.setValues( parameters );
  12072. };
  12073. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  12074. THREE.LineBasicMaterial.prototype.constructor = THREE.LineBasicMaterial;
  12075. THREE.LineBasicMaterial.prototype.copy = function ( source ) {
  12076. THREE.Material.prototype.copy.call( this, source );
  12077. this.color.copy( source.color );
  12078. this.linewidth = source.linewidth;
  12079. this.linecap = source.linecap;
  12080. this.linejoin = source.linejoin;
  12081. this.vertexColors = source.vertexColors;
  12082. this.fog = source.fog;
  12083. return this;
  12084. };
  12085. // File:src/materials/LineDashedMaterial.js
  12086. /**
  12087. * @author alteredq / http://alteredqualia.com/
  12088. *
  12089. * parameters = {
  12090. * color: <hex>,
  12091. * opacity: <float>,
  12092. *
  12093. * linewidth: <float>,
  12094. *
  12095. * scale: <float>,
  12096. * dashSize: <float>,
  12097. * gapSize: <float>,
  12098. *
  12099. * blending: THREE.NormalBlending,
  12100. * depthTest: <bool>,
  12101. * depthWrite: <bool>,
  12102. *
  12103. * vertexColors: THREE.NoColors / THREE.FaceColors / THREE.VertexColors
  12104. *
  12105. * fog: <bool>
  12106. * }
  12107. */
  12108. THREE.LineDashedMaterial = function ( parameters ) {
  12109. THREE.Material.call( this );
  12110. this.type = 'LineDashedMaterial';
  12111. this.color = new THREE.Color( 0xffffff );
  12112. this.linewidth = 1;
  12113. this.scale = 1;
  12114. this.dashSize = 3;
  12115. this.gapSize = 1;
  12116. this.blending = THREE.NormalBlending;
  12117. this.vertexColors = THREE.NoColors;
  12118. this.fog = true;
  12119. this.setValues( parameters );
  12120. };
  12121. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  12122. THREE.LineDashedMaterial.prototype.constructor = THREE.LineDashedMaterial;
  12123. THREE.LineDashedMaterial.prototype.copy = function ( source ) {
  12124. THREE.Material.prototype.copy.call( this, source );
  12125. this.color.copy( source.color );
  12126. this.linewidth = source.linewidth;
  12127. this.scale = source.scale;
  12128. this.dashSize = source.dashSize;
  12129. this.gapSize = source.gapSize;
  12130. this.vertexColors = source.vertexColors;
  12131. this.fog = source.fog;
  12132. return this;
  12133. };
  12134. // File:src/materials/MeshBasicMaterial.js
  12135. /**
  12136. * @author mrdoob / http://mrdoob.com/
  12137. * @author alteredq / http://alteredqualia.com/
  12138. *
  12139. * parameters = {
  12140. * color: <hex>,
  12141. * opacity: <float>,
  12142. * map: new THREE.Texture( <Image> ),
  12143. *
  12144. * aoMap: new THREE.Texture( <Image> ),
  12145. * aoMapIntensity: <float>
  12146. *
  12147. * specularMap: new THREE.Texture( <Image> ),
  12148. *
  12149. * alphaMap: new THREE.Texture( <Image> ),
  12150. *
  12151. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  12152. * combine: THREE.Multiply,
  12153. * reflectivity: <float>,
  12154. * refractionRatio: <float>,
  12155. *
  12156. * shading: THREE.SmoothShading,
  12157. * blending: THREE.NormalBlending,
  12158. * depthTest: <bool>,
  12159. * depthWrite: <bool>,
  12160. *
  12161. * wireframe: <boolean>,
  12162. * wireframeLinewidth: <float>,
  12163. *
  12164. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  12165. *
  12166. * skinning: <bool>,
  12167. * morphTargets: <bool>,
  12168. *
  12169. * fog: <bool>
  12170. * }
  12171. */
  12172. THREE.MeshBasicMaterial = function ( parameters ) {
  12173. THREE.Material.call( this );
  12174. this.type = 'MeshBasicMaterial';
  12175. this.color = new THREE.Color( 0xffffff ); // emissive
  12176. this.map = null;
  12177. this.aoMap = null;
  12178. this.aoMapIntensity = 1.0;
  12179. this.specularMap = null;
  12180. this.alphaMap = null;
  12181. this.envMap = null;
  12182. this.combine = THREE.MultiplyOperation;
  12183. this.reflectivity = 1;
  12184. this.refractionRatio = 0.98;
  12185. this.fog = true;
  12186. this.shading = THREE.SmoothShading;
  12187. this.blending = THREE.NormalBlending;
  12188. this.wireframe = false;
  12189. this.wireframeLinewidth = 1;
  12190. this.wireframeLinecap = 'round';
  12191. this.wireframeLinejoin = 'round';
  12192. this.vertexColors = THREE.NoColors;
  12193. this.skinning = false;
  12194. this.morphTargets = false;
  12195. this.setValues( parameters );
  12196. };
  12197. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  12198. THREE.MeshBasicMaterial.prototype.constructor = THREE.MeshBasicMaterial;
  12199. THREE.MeshBasicMaterial.prototype.copy = function ( source ) {
  12200. THREE.Material.prototype.copy.call( this, source );
  12201. this.color.copy( source.color );
  12202. this.map = source.map;
  12203. this.aoMap = source.aoMap;
  12204. this.aoMapIntensity = source.aoMapIntensity;
  12205. this.specularMap = source.specularMap;
  12206. this.alphaMap = source.alphaMap;
  12207. this.envMap = source.envMap;
  12208. this.combine = source.combine;
  12209. this.reflectivity = source.reflectivity;
  12210. this.refractionRatio = source.refractionRatio;
  12211. this.fog = source.fog;
  12212. this.shading = source.shading;
  12213. this.wireframe = source.wireframe;
  12214. this.wireframeLinewidth = source.wireframeLinewidth;
  12215. this.wireframeLinecap = source.wireframeLinecap;
  12216. this.wireframeLinejoin = source.wireframeLinejoin;
  12217. this.vertexColors = source.vertexColors;
  12218. this.skinning = source.skinning;
  12219. this.morphTargets = source.morphTargets;
  12220. return this;
  12221. };
  12222. // File:src/materials/MeshLambertMaterial.js
  12223. /**
  12224. * @author mrdoob / http://mrdoob.com/
  12225. * @author alteredq / http://alteredqualia.com/
  12226. *
  12227. * parameters = {
  12228. * color: <hex>,
  12229. * opacity: <float>,
  12230. *
  12231. * map: new THREE.Texture( <Image> ),
  12232. *
  12233. * lightMap: new THREE.Texture( <Image> ),
  12234. * lightMapIntensity: <float>
  12235. *
  12236. * aoMap: new THREE.Texture( <Image> ),
  12237. * aoMapIntensity: <float>
  12238. *
  12239. * emissive: <hex>,
  12240. * emissiveIntensity: <float>
  12241. * emissiveMap: new THREE.Texture( <Image> ),
  12242. *
  12243. * specularMap: new THREE.Texture( <Image> ),
  12244. *
  12245. * alphaMap: new THREE.Texture( <Image> ),
  12246. *
  12247. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  12248. * combine: THREE.Multiply,
  12249. * reflectivity: <float>,
  12250. * refractionRatio: <float>,
  12251. *
  12252. * blending: THREE.NormalBlending,
  12253. * depthTest: <bool>,
  12254. * depthWrite: <bool>,
  12255. *
  12256. * wireframe: <boolean>,
  12257. * wireframeLinewidth: <float>,
  12258. *
  12259. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  12260. *
  12261. * skinning: <bool>,
  12262. * morphTargets: <bool>,
  12263. * morphNormals: <bool>,
  12264. *
  12265. * fog: <bool>
  12266. * }
  12267. */
  12268. THREE.MeshLambertMaterial = function ( parameters ) {
  12269. THREE.Material.call( this );
  12270. this.type = 'MeshLambertMaterial';
  12271. this.color = new THREE.Color( 0xffffff ); // diffuse
  12272. this.map = null;
  12273. this.lightMap = null;
  12274. this.lightMapIntensity = 1.0;
  12275. this.aoMap = null;
  12276. this.aoMapIntensity = 1.0;
  12277. this.emissive = new THREE.Color( 0x000000 );
  12278. this.emissiveIntensity = 1.0;
  12279. this.emissiveMap = null;
  12280. this.specularMap = null;
  12281. this.alphaMap = null;
  12282. this.envMap = null;
  12283. this.combine = THREE.MultiplyOperation;
  12284. this.reflectivity = 1;
  12285. this.refractionRatio = 0.98;
  12286. this.fog = true;
  12287. this.blending = THREE.NormalBlending;
  12288. this.wireframe = false;
  12289. this.wireframeLinewidth = 1;
  12290. this.wireframeLinecap = 'round';
  12291. this.wireframeLinejoin = 'round';
  12292. this.vertexColors = THREE.NoColors;
  12293. this.skinning = false;
  12294. this.morphTargets = false;
  12295. this.morphNormals = false;
  12296. this.setValues( parameters );
  12297. };
  12298. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  12299. THREE.MeshLambertMaterial.prototype.constructor = THREE.MeshLambertMaterial;
  12300. THREE.MeshLambertMaterial.prototype.copy = function ( source ) {
  12301. THREE.Material.prototype.copy.call( this, source );
  12302. this.color.copy( source.color );
  12303. this.map = source.map;
  12304. this.lightMap = source.lightMap;
  12305. this.lightMapIntensity = source.lightMapIntensity;
  12306. this.aoMap = source.aoMap;
  12307. this.aoMapIntensity = source.aoMapIntensity;
  12308. this.emissive.copy( source.emissive );
  12309. this.emissiveMap = source.emissiveMap;
  12310. this.emissiveIntensity = source.emissiveIntensity;
  12311. this.specularMap = source.specularMap;
  12312. this.alphaMap = source.alphaMap;
  12313. this.envMap = source.envMap;
  12314. this.combine = source.combine;
  12315. this.reflectivity = source.reflectivity;
  12316. this.refractionRatio = source.refractionRatio;
  12317. this.fog = source.fog;
  12318. this.wireframe = source.wireframe;
  12319. this.wireframeLinewidth = source.wireframeLinewidth;
  12320. this.wireframeLinecap = source.wireframeLinecap;
  12321. this.wireframeLinejoin = source.wireframeLinejoin;
  12322. this.vertexColors = source.vertexColors;
  12323. this.skinning = source.skinning;
  12324. this.morphTargets = source.morphTargets;
  12325. this.morphNormals = source.morphNormals;
  12326. return this;
  12327. };
  12328. // File:src/materials/MeshPhongMaterial.js
  12329. /**
  12330. * @author mrdoob / http://mrdoob.com/
  12331. * @author alteredq / http://alteredqualia.com/
  12332. *
  12333. * parameters = {
  12334. * color: <hex>,
  12335. * specular: <hex>,
  12336. * shininess: <float>,
  12337. * opacity: <float>,
  12338. *
  12339. * map: new THREE.Texture( <Image> ),
  12340. *
  12341. * lightMap: new THREE.Texture( <Image> ),
  12342. * lightMapIntensity: <float>
  12343. *
  12344. * aoMap: new THREE.Texture( <Image> ),
  12345. * aoMapIntensity: <float>
  12346. *
  12347. * emissive: <hex>,
  12348. * emissiveIntensity: <float>
  12349. * emissiveMap: new THREE.Texture( <Image> ),
  12350. *
  12351. * bumpMap: new THREE.Texture( <Image> ),
  12352. * bumpScale: <float>,
  12353. *
  12354. * normalMap: new THREE.Texture( <Image> ),
  12355. * normalScale: <Vector2>,
  12356. *
  12357. * displacementMap: new THREE.Texture( <Image> ),
  12358. * displacementScale: <float>,
  12359. * displacementBias: <float>,
  12360. *
  12361. * specularMap: new THREE.Texture( <Image> ),
  12362. *
  12363. * alphaMap: new THREE.Texture( <Image> ),
  12364. *
  12365. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  12366. * combine: THREE.Multiply,
  12367. * reflectivity: <float>,
  12368. * refractionRatio: <float>,
  12369. *
  12370. * shading: THREE.SmoothShading,
  12371. * blending: THREE.NormalBlending,
  12372. * depthTest: <bool>,
  12373. * depthWrite: <bool>,
  12374. *
  12375. * wireframe: <boolean>,
  12376. * wireframeLinewidth: <float>,
  12377. *
  12378. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  12379. *
  12380. * skinning: <bool>,
  12381. * morphTargets: <bool>,
  12382. * morphNormals: <bool>,
  12383. *
  12384. * fog: <bool>
  12385. * }
  12386. */
  12387. THREE.MeshPhongMaterial = function ( parameters ) {
  12388. THREE.Material.call( this );
  12389. this.type = 'MeshPhongMaterial';
  12390. this.color = new THREE.Color( 0xffffff ); // diffuse
  12391. this.specular = new THREE.Color( 0x111111 );
  12392. this.shininess = 30;
  12393. this.map = null;
  12394. this.lightMap = null;
  12395. this.lightMapIntensity = 1.0;
  12396. this.aoMap = null;
  12397. this.aoMapIntensity = 1.0;
  12398. this.emissive = new THREE.Color( 0x000000 );
  12399. this.emissiveIntensity = 1.0;
  12400. this.emissiveMap = null;
  12401. this.bumpMap = null;
  12402. this.bumpScale = 1;
  12403. this.normalMap = null;
  12404. this.normalScale = new THREE.Vector2( 1, 1 );
  12405. this.displacementMap = null;
  12406. this.displacementScale = 1;
  12407. this.displacementBias = 0;
  12408. this.specularMap = null;
  12409. this.alphaMap = null;
  12410. this.envMap = null;
  12411. this.combine = THREE.MultiplyOperation;
  12412. this.reflectivity = 1;
  12413. this.refractionRatio = 0.98;
  12414. this.fog = true;
  12415. this.shading = THREE.SmoothShading;
  12416. this.blending = THREE.NormalBlending;
  12417. this.wireframe = false;
  12418. this.wireframeLinewidth = 1;
  12419. this.wireframeLinecap = 'round';
  12420. this.wireframeLinejoin = 'round';
  12421. this.vertexColors = THREE.NoColors;
  12422. this.skinning = false;
  12423. this.morphTargets = false;
  12424. this.morphNormals = false;
  12425. this.setValues( parameters );
  12426. };
  12427. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  12428. THREE.MeshPhongMaterial.prototype.constructor = THREE.MeshPhongMaterial;
  12429. THREE.MeshPhongMaterial.prototype.copy = function ( source ) {
  12430. THREE.Material.prototype.copy.call( this, source );
  12431. this.color.copy( source.color );
  12432. this.specular.copy( source.specular );
  12433. this.shininess = source.shininess;
  12434. this.map = source.map;
  12435. this.lightMap = source.lightMap;
  12436. this.lightMapIntensity = source.lightMapIntensity;
  12437. this.aoMap = source.aoMap;
  12438. this.aoMapIntensity = source.aoMapIntensity;
  12439. this.emissive.copy( source.emissive );
  12440. this.emissiveMap = source.emissiveMap;
  12441. this.emissiveIntensity = source.emissiveIntensity;
  12442. this.bumpMap = source.bumpMap;
  12443. this.bumpScale = source.bumpScale;
  12444. this.normalMap = source.normalMap;
  12445. this.normalScale.copy( source.normalScale );
  12446. this.displacementMap = source.displacementMap;
  12447. this.displacementScale = source.displacementScale;
  12448. this.displacementBias = source.displacementBias;
  12449. this.specularMap = source.specularMap;
  12450. this.alphaMap = source.alphaMap;
  12451. this.envMap = source.envMap;
  12452. this.combine = source.combine;
  12453. this.reflectivity = source.reflectivity;
  12454. this.refractionRatio = source.refractionRatio;
  12455. this.fog = source.fog;
  12456. this.shading = source.shading;
  12457. this.wireframe = source.wireframe;
  12458. this.wireframeLinewidth = source.wireframeLinewidth;
  12459. this.wireframeLinecap = source.wireframeLinecap;
  12460. this.wireframeLinejoin = source.wireframeLinejoin;
  12461. this.vertexColors = source.vertexColors;
  12462. this.skinning = source.skinning;
  12463. this.morphTargets = source.morphTargets;
  12464. this.morphNormals = source.morphNormals;
  12465. return this;
  12466. };
  12467. // File:src/materials/MeshStandardMaterial.js
  12468. /**
  12469. * @author WestLangley / http://github.com/WestLangley
  12470. *
  12471. * parameters = {
  12472. * color: <hex>,
  12473. * roughness: <float>,
  12474. * metalness: <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. * roughnessMap: new THREE.Texture( <Image> ),
  12500. *
  12501. * metalnessMap: new THREE.Texture( <Image> ),
  12502. *
  12503. * alphaMap: new THREE.Texture( <Image> ),
  12504. *
  12505. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  12506. * envMapIntensity: <float>
  12507. *
  12508. * refractionRatio: <float>,
  12509. *
  12510. * shading: THREE.SmoothShading,
  12511. * blending: THREE.NormalBlending,
  12512. * depthTest: <bool>,
  12513. * depthWrite: <bool>,
  12514. *
  12515. * wireframe: <boolean>,
  12516. * wireframeLinewidth: <float>,
  12517. *
  12518. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  12519. *
  12520. * skinning: <bool>,
  12521. * morphTargets: <bool>,
  12522. * morphNormals: <bool>,
  12523. *
  12524. * fog: <bool>
  12525. * }
  12526. */
  12527. THREE.MeshStandardMaterial = function ( parameters ) {
  12528. THREE.Material.call( this );
  12529. this.type = 'MeshStandardMaterial';
  12530. this.color = new THREE.Color( 0xffffff ); // diffuse
  12531. this.roughness = 0.5;
  12532. this.metalness = 0.5;
  12533. this.map = null;
  12534. this.lightMap = null;
  12535. this.lightMapIntensity = 1.0;
  12536. this.aoMap = null;
  12537. this.aoMapIntensity = 1.0;
  12538. this.emissive = new THREE.Color( 0x000000 );
  12539. this.emissiveIntensity = 1.0;
  12540. this.emissiveMap = null;
  12541. this.bumpMap = null;
  12542. this.bumpScale = 1;
  12543. this.normalMap = null;
  12544. this.normalScale = new THREE.Vector2( 1, 1 );
  12545. this.displacementMap = null;
  12546. this.displacementScale = 1;
  12547. this.displacementBias = 0;
  12548. this.roughnessMap = null;
  12549. this.metalnessMap = null;
  12550. this.alphaMap = null;
  12551. this.envMap = null;
  12552. this.envMapIntensity = 1.0;
  12553. this.refractionRatio = 0.98;
  12554. this.fog = true;
  12555. this.shading = THREE.SmoothShading;
  12556. this.blending = THREE.NormalBlending;
  12557. this.wireframe = false;
  12558. this.wireframeLinewidth = 1;
  12559. this.wireframeLinecap = 'round';
  12560. this.wireframeLinejoin = 'round';
  12561. this.vertexColors = THREE.NoColors;
  12562. this.skinning = false;
  12563. this.morphTargets = false;
  12564. this.morphNormals = false;
  12565. this.setValues( parameters );
  12566. };
  12567. THREE.MeshStandardMaterial.prototype = Object.create( THREE.Material.prototype );
  12568. THREE.MeshStandardMaterial.prototype.constructor = THREE.MeshStandardMaterial;
  12569. THREE.MeshStandardMaterial.prototype.copy = function ( source ) {
  12570. THREE.Material.prototype.copy.call( this, source );
  12571. this.color.copy( source.color );
  12572. this.roughness = source.roughness;
  12573. this.metalness = source.metalness;
  12574. this.map = source.map;
  12575. this.lightMap = source.lightMap;
  12576. this.lightMapIntensity = source.lightMapIntensity;
  12577. this.aoMap = source.aoMap;
  12578. this.aoMapIntensity = source.aoMapIntensity;
  12579. this.emissive.copy( source.emissive );
  12580. this.emissiveMap = source.emissiveMap;
  12581. this.emissiveIntensity = source.emissiveIntensity;
  12582. this.bumpMap = source.bumpMap;
  12583. this.bumpScale = source.bumpScale;
  12584. this.normalMap = source.normalMap;
  12585. this.normalScale.copy( source.normalScale );
  12586. this.displacementMap = source.displacementMap;
  12587. this.displacementScale = source.displacementScale;
  12588. this.displacementBias = source.displacementBias;
  12589. this.roughnessMap = source.roughnessMap;
  12590. this.metalnessMap = source.metalnessMap;
  12591. this.alphaMap = source.alphaMap;
  12592. this.envMap = source.envMap;
  12593. this.envMapIntensity = source.envMapIntensity;
  12594. this.refractionRatio = source.refractionRatio;
  12595. this.fog = source.fog;
  12596. this.shading = source.shading;
  12597. this.wireframe = source.wireframe;
  12598. this.wireframeLinewidth = source.wireframeLinewidth;
  12599. this.wireframeLinecap = source.wireframeLinecap;
  12600. this.wireframeLinejoin = source.wireframeLinejoin;
  12601. this.vertexColors = source.vertexColors;
  12602. this.skinning = source.skinning;
  12603. this.morphTargets = source.morphTargets;
  12604. this.morphNormals = source.morphNormals;
  12605. return this;
  12606. };
  12607. // File:src/materials/MeshDepthMaterial.js
  12608. /**
  12609. * @author mrdoob / http://mrdoob.com/
  12610. * @author alteredq / http://alteredqualia.com/
  12611. *
  12612. * parameters = {
  12613. * opacity: <float>,
  12614. *
  12615. * wireframe: <boolean>,
  12616. * wireframeLinewidth: <float>
  12617. * }
  12618. */
  12619. THREE.MeshDepthMaterial = function ( parameters ) {
  12620. THREE.Material.call( this );
  12621. this.type = 'MeshDepthMaterial';
  12622. this.morphTargets = false;
  12623. this.wireframe = false;
  12624. this.wireframeLinewidth = 1;
  12625. this.setValues( parameters );
  12626. };
  12627. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  12628. THREE.MeshDepthMaterial.prototype.constructor = THREE.MeshDepthMaterial;
  12629. THREE.MeshDepthMaterial.prototype.copy = function ( source ) {
  12630. THREE.Material.prototype.copy.call( this, source );
  12631. this.wireframe = source.wireframe;
  12632. this.wireframeLinewidth = source.wireframeLinewidth;
  12633. return this;
  12634. };
  12635. // File:src/materials/MeshNormalMaterial.js
  12636. /**
  12637. * @author mrdoob / http://mrdoob.com/
  12638. *
  12639. * parameters = {
  12640. * opacity: <float>,
  12641. *
  12642. * wireframe: <boolean>,
  12643. * wireframeLinewidth: <float>
  12644. * }
  12645. */
  12646. THREE.MeshNormalMaterial = function ( parameters ) {
  12647. THREE.Material.call( this, parameters );
  12648. this.type = 'MeshNormalMaterial';
  12649. this.wireframe = false;
  12650. this.wireframeLinewidth = 1;
  12651. this.morphTargets = false;
  12652. this.setValues( parameters );
  12653. };
  12654. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  12655. THREE.MeshNormalMaterial.prototype.constructor = THREE.MeshNormalMaterial;
  12656. THREE.MeshNormalMaterial.prototype.copy = function ( source ) {
  12657. THREE.Material.prototype.copy.call( this, source );
  12658. this.wireframe = source.wireframe;
  12659. this.wireframeLinewidth = source.wireframeLinewidth;
  12660. return this;
  12661. };
  12662. // File:src/materials/MultiMaterial.js
  12663. /**
  12664. * @author mrdoob / http://mrdoob.com/
  12665. */
  12666. THREE.MultiMaterial = function ( materials ) {
  12667. this.uuid = THREE.Math.generateUUID();
  12668. this.type = 'MultiMaterial';
  12669. this.materials = materials instanceof Array ? materials : [];
  12670. this.visible = true;
  12671. };
  12672. THREE.MultiMaterial.prototype = {
  12673. constructor: THREE.MultiMaterial,
  12674. toJSON: function ( meta ) {
  12675. var output = {
  12676. metadata: {
  12677. version: 4.2,
  12678. type: 'material',
  12679. generator: 'MaterialExporter'
  12680. },
  12681. uuid: this.uuid,
  12682. type: this.type,
  12683. materials: []
  12684. };
  12685. var materials = this.materials;
  12686. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  12687. var material = materials[ i ].toJSON( meta );
  12688. delete material.metadata;
  12689. output.materials.push( material );
  12690. }
  12691. output.visible = this.visible;
  12692. return output;
  12693. },
  12694. clone: function () {
  12695. var material = new this.constructor();
  12696. for ( var i = 0; i < this.materials.length; i ++ ) {
  12697. material.materials.push( this.materials[ i ].clone() );
  12698. }
  12699. material.visible = this.visible;
  12700. return material;
  12701. }
  12702. };
  12703. // File:src/materials/PointsMaterial.js
  12704. /**
  12705. * @author mrdoob / http://mrdoob.com/
  12706. * @author alteredq / http://alteredqualia.com/
  12707. *
  12708. * parameters = {
  12709. * color: <hex>,
  12710. * opacity: <float>,
  12711. * map: new THREE.Texture( <Image> ),
  12712. *
  12713. * size: <float>,
  12714. * sizeAttenuation: <bool>,
  12715. *
  12716. * blending: THREE.NormalBlending,
  12717. * depthTest: <bool>,
  12718. * depthWrite: <bool>,
  12719. *
  12720. * vertexColors: <bool>,
  12721. *
  12722. * fog: <bool>
  12723. * }
  12724. */
  12725. THREE.PointsMaterial = function ( parameters ) {
  12726. THREE.Material.call( this );
  12727. this.type = 'PointsMaterial';
  12728. this.color = new THREE.Color( 0xffffff );
  12729. this.map = null;
  12730. this.size = 1;
  12731. this.sizeAttenuation = true;
  12732. this.blending = THREE.NormalBlending;
  12733. this.vertexColors = THREE.NoColors;
  12734. this.fog = true;
  12735. this.setValues( parameters );
  12736. };
  12737. THREE.PointsMaterial.prototype = Object.create( THREE.Material.prototype );
  12738. THREE.PointsMaterial.prototype.constructor = THREE.PointsMaterial;
  12739. THREE.PointsMaterial.prototype.copy = function ( source ) {
  12740. THREE.Material.prototype.copy.call( this, source );
  12741. this.color.copy( source.color );
  12742. this.map = source.map;
  12743. this.size = source.size;
  12744. this.sizeAttenuation = source.sizeAttenuation;
  12745. this.vertexColors = source.vertexColors;
  12746. this.fog = source.fog;
  12747. return this;
  12748. };
  12749. // File:src/materials/ShaderMaterial.js
  12750. /**
  12751. * @author alteredq / http://alteredqualia.com/
  12752. *
  12753. * parameters = {
  12754. * defines: { "label" : "value" },
  12755. * uniforms: { "parameter1": { type: "1f", value: 1.0 }, "parameter2": { type: "1i" value2: 2 } },
  12756. *
  12757. * fragmentShader: <string>,
  12758. * vertexShader: <string>,
  12759. *
  12760. * shading: THREE.SmoothShading,
  12761. *
  12762. * wireframe: <boolean>,
  12763. * wireframeLinewidth: <float>,
  12764. *
  12765. * lights: <bool>,
  12766. *
  12767. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  12768. *
  12769. * skinning: <bool>,
  12770. * morphTargets: <bool>,
  12771. * morphNormals: <bool>,
  12772. *
  12773. * fog: <bool>
  12774. * }
  12775. */
  12776. THREE.ShaderMaterial = function ( parameters ) {
  12777. THREE.Material.call( this );
  12778. this.type = 'ShaderMaterial';
  12779. this.defines = {};
  12780. this.uniforms = {};
  12781. this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}';
  12782. this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}';
  12783. this.shading = THREE.SmoothShading;
  12784. this.linewidth = 1;
  12785. this.wireframe = false;
  12786. this.wireframeLinewidth = 1;
  12787. this.fog = false; // set to use scene fog
  12788. this.lights = false; // set to use scene lights
  12789. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  12790. this.skinning = false; // set to use skinning attribute streams
  12791. this.morphTargets = false; // set to use morph targets
  12792. this.morphNormals = false; // set to use morph normals
  12793. this.extensions = {
  12794. derivatives: false, // set to use derivatives
  12795. fragDepth: false, // set to use fragment depth values
  12796. drawBuffers: false, // set to use draw buffers
  12797. shaderTextureLOD: false // set to use shader texture LOD
  12798. };
  12799. // When rendered geometry doesn't include these attributes but the material does,
  12800. // use these default values in WebGL. This avoids errors when buffer data is missing.
  12801. this.defaultAttributeValues = {
  12802. 'color': [ 1, 1, 1 ],
  12803. 'uv': [ 0, 0 ],
  12804. 'uv2': [ 0, 0 ]
  12805. };
  12806. this.index0AttributeName = undefined;
  12807. if ( parameters !== undefined ) {
  12808. if ( parameters.attributes !== undefined ) {
  12809. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  12810. }
  12811. this.setValues( parameters );
  12812. }
  12813. };
  12814. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  12815. THREE.ShaderMaterial.prototype.constructor = THREE.ShaderMaterial;
  12816. THREE.ShaderMaterial.prototype.copy = function ( source ) {
  12817. THREE.Material.prototype.copy.call( this, source );
  12818. this.fragmentShader = source.fragmentShader;
  12819. this.vertexShader = source.vertexShader;
  12820. this.uniforms = THREE.UniformsUtils.clone( source.uniforms );
  12821. this.defines = source.defines;
  12822. this.shading = source.shading;
  12823. this.wireframe = source.wireframe;
  12824. this.wireframeLinewidth = source.wireframeLinewidth;
  12825. this.fog = source.fog;
  12826. this.lights = source.lights;
  12827. this.vertexColors = source.vertexColors;
  12828. this.skinning = source.skinning;
  12829. this.morphTargets = source.morphTargets;
  12830. this.morphNormals = source.morphNormals;
  12831. this.extensions = source.extensions;
  12832. return this;
  12833. };
  12834. THREE.ShaderMaterial.prototype.toJSON = function ( meta ) {
  12835. var data = THREE.Material.prototype.toJSON.call( this, meta );
  12836. data.uniforms = this.uniforms;
  12837. data.vertexShader = this.vertexShader;
  12838. data.fragmentShader = this.fragmentShader;
  12839. return data;
  12840. };
  12841. // File:src/materials/RawShaderMaterial.js
  12842. /**
  12843. * @author mrdoob / http://mrdoob.com/
  12844. */
  12845. THREE.RawShaderMaterial = function ( parameters ) {
  12846. THREE.ShaderMaterial.call( this, parameters );
  12847. this.type = 'RawShaderMaterial';
  12848. };
  12849. THREE.RawShaderMaterial.prototype = Object.create( THREE.ShaderMaterial.prototype );
  12850. THREE.RawShaderMaterial.prototype.constructor = THREE.RawShaderMaterial;
  12851. // File:src/materials/SpriteMaterial.js
  12852. /**
  12853. * @author alteredq / http://alteredqualia.com/
  12854. *
  12855. * parameters = {
  12856. * color: <hex>,
  12857. * opacity: <float>,
  12858. * map: new THREE.Texture( <Image> ),
  12859. *
  12860. * uvOffset: new THREE.Vector2(),
  12861. * uvScale: new THREE.Vector2(),
  12862. *
  12863. * fog: <bool>
  12864. * }
  12865. */
  12866. THREE.SpriteMaterial = function ( parameters ) {
  12867. THREE.Material.call( this );
  12868. this.type = 'SpriteMaterial';
  12869. this.color = new THREE.Color( 0xffffff );
  12870. this.map = null;
  12871. this.rotation = 0;
  12872. this.fog = false;
  12873. // set parameters
  12874. this.setValues( parameters );
  12875. };
  12876. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  12877. THREE.SpriteMaterial.prototype.constructor = THREE.SpriteMaterial;
  12878. THREE.SpriteMaterial.prototype.copy = function ( source ) {
  12879. THREE.Material.prototype.copy.call( this, source );
  12880. this.color.copy( source.color );
  12881. this.map = source.map;
  12882. this.rotation = source.rotation;
  12883. this.fog = source.fog;
  12884. return this;
  12885. };
  12886. // File:src/textures/Texture.js
  12887. /**
  12888. * @author mrdoob / http://mrdoob.com/
  12889. * @author alteredq / http://alteredqualia.com/
  12890. * @author szimek / https://github.com/szimek/
  12891. */
  12892. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  12893. Object.defineProperty( this, 'id', { value: THREE.TextureIdCount ++ } );
  12894. this.uuid = THREE.Math.generateUUID();
  12895. this.name = '';
  12896. this.sourceFile = '';
  12897. this.image = image !== undefined ? image : THREE.Texture.DEFAULT_IMAGE;
  12898. this.mipmaps = [];
  12899. this.mapping = mapping !== undefined ? mapping : THREE.Texture.DEFAULT_MAPPING;
  12900. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  12901. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  12902. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  12903. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  12904. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  12905. this.format = format !== undefined ? format : THREE.RGBAFormat;
  12906. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  12907. this.offset = new THREE.Vector2( 0, 0 );
  12908. this.repeat = new THREE.Vector2( 1, 1 );
  12909. this.generateMipmaps = true;
  12910. this.premultiplyAlpha = false;
  12911. this.flipY = true;
  12912. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  12913. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  12914. //
  12915. // Also changing the encoding after already used by a Material will not automatically make the Material
  12916. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  12917. this.encoding = encoding !== undefined ? encoding : THREE.LinearEncoding;
  12918. this.version = 0;
  12919. this.onUpdate = null;
  12920. };
  12921. THREE.Texture.DEFAULT_IMAGE = undefined;
  12922. THREE.Texture.DEFAULT_MAPPING = THREE.UVMapping;
  12923. THREE.Texture.prototype = {
  12924. constructor: THREE.Texture,
  12925. set needsUpdate ( value ) {
  12926. if ( value === true ) this.version ++;
  12927. },
  12928. clone: function () {
  12929. return new this.constructor().copy( this );
  12930. },
  12931. copy: function ( source ) {
  12932. this.image = source.image;
  12933. this.mipmaps = source.mipmaps.slice( 0 );
  12934. this.mapping = source.mapping;
  12935. this.wrapS = source.wrapS;
  12936. this.wrapT = source.wrapT;
  12937. this.magFilter = source.magFilter;
  12938. this.minFilter = source.minFilter;
  12939. this.anisotropy = source.anisotropy;
  12940. this.format = source.format;
  12941. this.type = source.type;
  12942. this.offset.copy( source.offset );
  12943. this.repeat.copy( source.repeat );
  12944. this.generateMipmaps = source.generateMipmaps;
  12945. this.premultiplyAlpha = source.premultiplyAlpha;
  12946. this.flipY = source.flipY;
  12947. this.unpackAlignment = source.unpackAlignment;
  12948. this.encoding = source.encoding;
  12949. return this;
  12950. },
  12951. toJSON: function ( meta ) {
  12952. if ( meta.textures[ this.uuid ] !== undefined ) {
  12953. return meta.textures[ this.uuid ];
  12954. }
  12955. function getDataURL( image ) {
  12956. var canvas;
  12957. if ( image.toDataURL !== undefined ) {
  12958. canvas = image;
  12959. } else {
  12960. canvas = document.createElement( 'canvas' );
  12961. canvas.width = image.width;
  12962. canvas.height = image.height;
  12963. canvas.getContext( '2d' ).drawImage( image, 0, 0, image.width, image.height );
  12964. }
  12965. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  12966. return canvas.toDataURL( 'image/jpeg', 0.6 );
  12967. } else {
  12968. return canvas.toDataURL( 'image/png' );
  12969. }
  12970. }
  12971. var output = {
  12972. metadata: {
  12973. version: 4.4,
  12974. type: 'Texture',
  12975. generator: 'Texture.toJSON'
  12976. },
  12977. uuid: this.uuid,
  12978. name: this.name,
  12979. mapping: this.mapping,
  12980. repeat: [ this.repeat.x, this.repeat.y ],
  12981. offset: [ this.offset.x, this.offset.y ],
  12982. wrap: [ this.wrapS, this.wrapT ],
  12983. minFilter: this.minFilter,
  12984. magFilter: this.magFilter,
  12985. anisotropy: this.anisotropy
  12986. };
  12987. if ( this.image !== undefined ) {
  12988. // TODO: Move to THREE.Image
  12989. var image = this.image;
  12990. if ( image.uuid === undefined ) {
  12991. image.uuid = THREE.Math.generateUUID(); // UGH
  12992. }
  12993. if ( meta.images[ image.uuid ] === undefined ) {
  12994. meta.images[ image.uuid ] = {
  12995. uuid: image.uuid,
  12996. url: getDataURL( image )
  12997. };
  12998. }
  12999. output.image = image.uuid;
  13000. }
  13001. meta.textures[ this.uuid ] = output;
  13002. return output;
  13003. },
  13004. dispose: function () {
  13005. this.dispatchEvent( { type: 'dispose' } );
  13006. },
  13007. transformUv: function ( uv ) {
  13008. if ( this.mapping !== THREE.UVMapping ) return;
  13009. uv.multiply( this.repeat );
  13010. uv.add( this.offset );
  13011. if ( uv.x < 0 || uv.x > 1 ) {
  13012. switch ( this.wrapS ) {
  13013. case THREE.RepeatWrapping:
  13014. uv.x = uv.x - Math.floor( uv.x );
  13015. break;
  13016. case THREE.ClampToEdgeWrapping:
  13017. uv.x = uv.x < 0 ? 0 : 1;
  13018. break;
  13019. case THREE.MirroredRepeatWrapping:
  13020. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  13021. uv.x = Math.ceil( uv.x ) - uv.x;
  13022. } else {
  13023. uv.x = uv.x - Math.floor( uv.x );
  13024. }
  13025. break;
  13026. }
  13027. }
  13028. if ( uv.y < 0 || uv.y > 1 ) {
  13029. switch ( this.wrapT ) {
  13030. case THREE.RepeatWrapping:
  13031. uv.y = uv.y - Math.floor( uv.y );
  13032. break;
  13033. case THREE.ClampToEdgeWrapping:
  13034. uv.y = uv.y < 0 ? 0 : 1;
  13035. break;
  13036. case THREE.MirroredRepeatWrapping:
  13037. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  13038. uv.y = Math.ceil( uv.y ) - uv.y;
  13039. } else {
  13040. uv.y = uv.y - Math.floor( uv.y );
  13041. }
  13042. break;
  13043. }
  13044. }
  13045. if ( this.flipY ) {
  13046. uv.y = 1 - uv.y;
  13047. }
  13048. }
  13049. };
  13050. THREE.EventDispatcher.prototype.apply( THREE.Texture.prototype );
  13051. THREE.TextureIdCount = 0;
  13052. // File:src/textures/CanvasTexture.js
  13053. /**
  13054. * @author mrdoob / http://mrdoob.com/
  13055. */
  13056. THREE.CanvasTexture = function ( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  13057. THREE.Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  13058. this.needsUpdate = true;
  13059. };
  13060. THREE.CanvasTexture.prototype = Object.create( THREE.Texture.prototype );
  13061. THREE.CanvasTexture.prototype.constructor = THREE.CanvasTexture;
  13062. // File:src/textures/CubeTexture.js
  13063. /**
  13064. * @author mrdoob / http://mrdoob.com/
  13065. */
  13066. THREE.CubeTexture = function ( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  13067. images = images !== undefined ? images : [];
  13068. mapping = mapping !== undefined ? mapping : THREE.CubeReflectionMapping;
  13069. THREE.Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  13070. this.flipY = false;
  13071. };
  13072. THREE.CubeTexture.prototype = Object.create( THREE.Texture.prototype );
  13073. THREE.CubeTexture.prototype.constructor = THREE.CubeTexture;
  13074. Object.defineProperty( THREE.CubeTexture.prototype, 'images', {
  13075. get: function () {
  13076. return this.image;
  13077. },
  13078. set: function ( value ) {
  13079. this.image = value;
  13080. }
  13081. } );
  13082. // File:src/textures/CompressedTexture.js
  13083. /**
  13084. * @author alteredq / http://alteredqualia.com/
  13085. */
  13086. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  13087. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  13088. this.image = { width: width, height: height };
  13089. this.mipmaps = mipmaps;
  13090. // no flipping for cube textures
  13091. // (also flipping doesn't work for compressed textures )
  13092. this.flipY = false;
  13093. // can't generate mipmaps for compressed textures
  13094. // mips must be embedded in DDS files
  13095. this.generateMipmaps = false;
  13096. };
  13097. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  13098. THREE.CompressedTexture.prototype.constructor = THREE.CompressedTexture;
  13099. // File:src/textures/DataTexture.js
  13100. /**
  13101. * @author alteredq / http://alteredqualia.com/
  13102. */
  13103. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  13104. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  13105. this.image = { data: data, width: width, height: height };
  13106. this.magFilter = magFilter !== undefined ? magFilter : THREE.NearestFilter;
  13107. this.minFilter = minFilter !== undefined ? minFilter : THREE.NearestFilter;
  13108. this.flipY = false;
  13109. this.generateMipmaps = false;
  13110. };
  13111. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  13112. THREE.DataTexture.prototype.constructor = THREE.DataTexture;
  13113. // File:src/textures/VideoTexture.js
  13114. /**
  13115. * @author mrdoob / http://mrdoob.com/
  13116. */
  13117. THREE.VideoTexture = function ( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  13118. THREE.Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  13119. this.generateMipmaps = false;
  13120. var scope = this;
  13121. function update() {
  13122. requestAnimationFrame( update );
  13123. if ( video.readyState >= video.HAVE_CURRENT_DATA ) {
  13124. scope.needsUpdate = true;
  13125. }
  13126. }
  13127. update();
  13128. };
  13129. THREE.VideoTexture.prototype = Object.create( THREE.Texture.prototype );
  13130. THREE.VideoTexture.prototype.constructor = THREE.VideoTexture;
  13131. // File:src/objects/Group.js
  13132. /**
  13133. * @author mrdoob / http://mrdoob.com/
  13134. */
  13135. THREE.Group = function () {
  13136. THREE.Object3D.call( this );
  13137. this.type = 'Group';
  13138. };
  13139. THREE.Group.prototype = Object.create( THREE.Object3D.prototype );
  13140. THREE.Group.prototype.constructor = THREE.Group;
  13141. // File:src/objects/Points.js
  13142. /**
  13143. * @author alteredq / http://alteredqualia.com/
  13144. */
  13145. THREE.Points = function ( geometry, material ) {
  13146. THREE.Object3D.call( this );
  13147. this.type = 'Points';
  13148. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  13149. this.material = material !== undefined ? material : new THREE.PointsMaterial( { color: Math.random() * 0xffffff } );
  13150. };
  13151. THREE.Points.prototype = Object.create( THREE.Object3D.prototype );
  13152. THREE.Points.prototype.constructor = THREE.Points;
  13153. THREE.Points.prototype.raycast = ( function () {
  13154. var inverseMatrix = new THREE.Matrix4();
  13155. var ray = new THREE.Ray();
  13156. var sphere = new THREE.Sphere();
  13157. return function raycast( raycaster, intersects ) {
  13158. var object = this;
  13159. var geometry = this.geometry;
  13160. var matrixWorld = this.matrixWorld;
  13161. var threshold = raycaster.params.Points.threshold;
  13162. // Checking boundingSphere distance to ray
  13163. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  13164. sphere.copy( geometry.boundingSphere );
  13165. sphere.applyMatrix4( matrixWorld );
  13166. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  13167. //
  13168. inverseMatrix.getInverse( matrixWorld );
  13169. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  13170. var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  13171. var localThresholdSq = localThreshold * localThreshold;
  13172. var position = new THREE.Vector3();
  13173. function testPoint( point, index ) {
  13174. var rayPointDistanceSq = ray.distanceSqToPoint( point );
  13175. if ( rayPointDistanceSq < localThresholdSq ) {
  13176. var intersectPoint = ray.closestPointToPoint( point );
  13177. intersectPoint.applyMatrix4( matrixWorld );
  13178. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  13179. if ( distance < raycaster.near || distance > raycaster.far ) return;
  13180. intersects.push( {
  13181. distance: distance,
  13182. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  13183. point: intersectPoint.clone(),
  13184. index: index,
  13185. face: null,
  13186. object: object
  13187. } );
  13188. }
  13189. }
  13190. if ( geometry instanceof THREE.BufferGeometry ) {
  13191. var index = geometry.index;
  13192. var attributes = geometry.attributes;
  13193. var positions = attributes.position.array;
  13194. if ( index !== null ) {
  13195. var indices = index.array;
  13196. for ( var i = 0, il = indices.length; i < il; i ++ ) {
  13197. var a = indices[ i ];
  13198. position.fromArray( positions, a * 3 );
  13199. testPoint( position, a );
  13200. }
  13201. } else {
  13202. for ( var i = 0, l = positions.length / 3; i < l; i ++ ) {
  13203. position.fromArray( positions, i * 3 );
  13204. testPoint( position, i );
  13205. }
  13206. }
  13207. } else {
  13208. var vertices = geometry.vertices;
  13209. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  13210. testPoint( vertices[ i ], i );
  13211. }
  13212. }
  13213. };
  13214. }() );
  13215. THREE.Points.prototype.clone = function () {
  13216. return new this.constructor( this.geometry, this.material ).copy( this );
  13217. };
  13218. // File:src/objects/Line.js
  13219. /**
  13220. * @author mrdoob / http://mrdoob.com/
  13221. */
  13222. THREE.Line = function ( geometry, material, mode ) {
  13223. if ( mode === 1 ) {
  13224. console.warn( 'THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead.' );
  13225. return new THREE.LineSegments( geometry, material );
  13226. }
  13227. THREE.Object3D.call( this );
  13228. this.type = 'Line';
  13229. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  13230. this.material = material !== undefined ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  13231. };
  13232. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  13233. THREE.Line.prototype.constructor = THREE.Line;
  13234. THREE.Line.prototype.raycast = ( function () {
  13235. var inverseMatrix = new THREE.Matrix4();
  13236. var ray = new THREE.Ray();
  13237. var sphere = new THREE.Sphere();
  13238. return function raycast( raycaster, intersects ) {
  13239. var precision = raycaster.linePrecision;
  13240. var precisionSq = precision * precision;
  13241. var geometry = this.geometry;
  13242. var matrixWorld = this.matrixWorld;
  13243. // Checking boundingSphere distance to ray
  13244. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  13245. sphere.copy( geometry.boundingSphere );
  13246. sphere.applyMatrix4( matrixWorld );
  13247. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  13248. //
  13249. inverseMatrix.getInverse( matrixWorld );
  13250. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  13251. var vStart = new THREE.Vector3();
  13252. var vEnd = new THREE.Vector3();
  13253. var interSegment = new THREE.Vector3();
  13254. var interRay = new THREE.Vector3();
  13255. var step = this instanceof THREE.LineSegments ? 2 : 1;
  13256. if ( geometry instanceof THREE.BufferGeometry ) {
  13257. var index = geometry.index;
  13258. var attributes = geometry.attributes;
  13259. var positions = attributes.position.array;
  13260. if ( index !== null ) {
  13261. var indices = index.array;
  13262. for ( var i = 0, l = indices.length - 1; i < l; i += step ) {
  13263. var a = indices[ i ];
  13264. var b = indices[ i + 1 ];
  13265. vStart.fromArray( positions, a * 3 );
  13266. vEnd.fromArray( positions, b * 3 );
  13267. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  13268. if ( distSq > precisionSq ) continue;
  13269. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  13270. var distance = raycaster.ray.origin.distanceTo( interRay );
  13271. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  13272. intersects.push( {
  13273. distance: distance,
  13274. // What do we want? intersection point on the ray or on the segment??
  13275. // point: raycaster.ray.at( distance ),
  13276. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  13277. index: i,
  13278. face: null,
  13279. faceIndex: null,
  13280. object: this
  13281. } );
  13282. }
  13283. } else {
  13284. for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) {
  13285. vStart.fromArray( positions, 3 * i );
  13286. vEnd.fromArray( positions, 3 * i + 3 );
  13287. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  13288. if ( distSq > precisionSq ) continue;
  13289. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  13290. var distance = raycaster.ray.origin.distanceTo( interRay );
  13291. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  13292. intersects.push( {
  13293. distance: distance,
  13294. // What do we want? intersection point on the ray or on the segment??
  13295. // point: raycaster.ray.at( distance ),
  13296. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  13297. index: i,
  13298. face: null,
  13299. faceIndex: null,
  13300. object: this
  13301. } );
  13302. }
  13303. }
  13304. } else if ( geometry instanceof THREE.Geometry ) {
  13305. var vertices = geometry.vertices;
  13306. var nbVertices = vertices.length;
  13307. for ( var i = 0; i < nbVertices - 1; i += step ) {
  13308. var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  13309. if ( distSq > precisionSq ) continue;
  13310. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  13311. var distance = raycaster.ray.origin.distanceTo( interRay );
  13312. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  13313. intersects.push( {
  13314. distance: distance,
  13315. // What do we want? intersection point on the ray or on the segment??
  13316. // point: raycaster.ray.at( distance ),
  13317. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  13318. index: i,
  13319. face: null,
  13320. faceIndex: null,
  13321. object: this
  13322. } );
  13323. }
  13324. }
  13325. };
  13326. }() );
  13327. THREE.Line.prototype.clone = function () {
  13328. return new this.constructor( this.geometry, this.material ).copy( this );
  13329. };
  13330. // DEPRECATED
  13331. THREE.LineStrip = 0;
  13332. THREE.LinePieces = 1;
  13333. // File:src/objects/LineSegments.js
  13334. /**
  13335. * @author mrdoob / http://mrdoob.com/
  13336. */
  13337. THREE.LineSegments = function ( geometry, material ) {
  13338. THREE.Line.call( this, geometry, material );
  13339. this.type = 'LineSegments';
  13340. };
  13341. THREE.LineSegments.prototype = Object.create( THREE.Line.prototype );
  13342. THREE.LineSegments.prototype.constructor = THREE.LineSegments;
  13343. // File:src/objects/Mesh.js
  13344. /**
  13345. * @author mrdoob / http://mrdoob.com/
  13346. * @author alteredq / http://alteredqualia.com/
  13347. * @author mikael emtinger / http://gomo.se/
  13348. * @author jonobr1 / http://jonobr1.com/
  13349. */
  13350. THREE.Mesh = function ( geometry, material ) {
  13351. THREE.Object3D.call( this );
  13352. this.type = 'Mesh';
  13353. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  13354. this.material = material !== undefined ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  13355. this.drawMode = THREE.TrianglesDrawMode;
  13356. this.updateMorphTargets();
  13357. };
  13358. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  13359. THREE.Mesh.prototype.constructor = THREE.Mesh;
  13360. THREE.Mesh.prototype.setDrawMode = function ( value ) {
  13361. this.drawMode = value;
  13362. };
  13363. THREE.Mesh.prototype.updateMorphTargets = function () {
  13364. if ( this.geometry.morphTargets !== undefined && this.geometry.morphTargets.length > 0 ) {
  13365. this.morphTargetBase = - 1;
  13366. this.morphTargetInfluences = [];
  13367. this.morphTargetDictionary = {};
  13368. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  13369. this.morphTargetInfluences.push( 0 );
  13370. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  13371. }
  13372. }
  13373. };
  13374. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  13375. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  13376. return this.morphTargetDictionary[ name ];
  13377. }
  13378. console.warn( 'THREE.Mesh.getMorphTargetIndexByName: morph target ' + name + ' does not exist. Returning 0.' );
  13379. return 0;
  13380. };
  13381. THREE.Mesh.prototype.raycast = ( function () {
  13382. var inverseMatrix = new THREE.Matrix4();
  13383. var ray = new THREE.Ray();
  13384. var sphere = new THREE.Sphere();
  13385. var vA = new THREE.Vector3();
  13386. var vB = new THREE.Vector3();
  13387. var vC = new THREE.Vector3();
  13388. var tempA = new THREE.Vector3();
  13389. var tempB = new THREE.Vector3();
  13390. var tempC = new THREE.Vector3();
  13391. var uvA = new THREE.Vector2();
  13392. var uvB = new THREE.Vector2();
  13393. var uvC = new THREE.Vector2();
  13394. var barycoord = new THREE.Vector3();
  13395. var intersectionPoint = new THREE.Vector3();
  13396. var intersectionPointWorld = new THREE.Vector3();
  13397. function uvIntersection( point, p1, p2, p3, uv1, uv2, uv3 ) {
  13398. THREE.Triangle.barycoordFromPoint( point, p1, p2, p3, barycoord );
  13399. uv1.multiplyScalar( barycoord.x );
  13400. uv2.multiplyScalar( barycoord.y );
  13401. uv3.multiplyScalar( barycoord.z );
  13402. uv1.add( uv2 ).add( uv3 );
  13403. return uv1.clone();
  13404. }
  13405. function checkIntersection( object, raycaster, ray, pA, pB, pC, point ) {
  13406. var intersect;
  13407. var material = object.material;
  13408. if ( material.side === THREE.BackSide ) {
  13409. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  13410. } else {
  13411. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== THREE.DoubleSide, point );
  13412. }
  13413. if ( intersect === null ) return null;
  13414. intersectionPointWorld.copy( point );
  13415. intersectionPointWorld.applyMatrix4( object.matrixWorld );
  13416. var distance = raycaster.ray.origin.distanceTo( intersectionPointWorld );
  13417. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  13418. return {
  13419. distance: distance,
  13420. point: intersectionPointWorld.clone(),
  13421. object: object
  13422. };
  13423. }
  13424. function checkBufferGeometryIntersection( object, raycaster, ray, positions, uvs, a, b, c ) {
  13425. vA.fromArray( positions, a * 3 );
  13426. vB.fromArray( positions, b * 3 );
  13427. vC.fromArray( positions, c * 3 );
  13428. var intersection = checkIntersection( object, raycaster, ray, vA, vB, vC, intersectionPoint );
  13429. if ( intersection ) {
  13430. if ( uvs ) {
  13431. uvA.fromArray( uvs, a * 2 );
  13432. uvB.fromArray( uvs, b * 2 );
  13433. uvC.fromArray( uvs, c * 2 );
  13434. intersection.uv = uvIntersection( intersectionPoint, vA, vB, vC, uvA, uvB, uvC );
  13435. }
  13436. intersection.face = new THREE.Face3( a, b, c, THREE.Triangle.normal( vA, vB, vC ) );
  13437. intersection.faceIndex = a;
  13438. }
  13439. return intersection;
  13440. }
  13441. return function raycast( raycaster, intersects ) {
  13442. var geometry = this.geometry;
  13443. var material = this.material;
  13444. var matrixWorld = this.matrixWorld;
  13445. if ( material === undefined ) return;
  13446. // Checking boundingSphere distance to ray
  13447. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  13448. sphere.copy( geometry.boundingSphere );
  13449. sphere.applyMatrix4( matrixWorld );
  13450. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  13451. //
  13452. inverseMatrix.getInverse( matrixWorld );
  13453. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  13454. // Check boundingBox before continuing
  13455. if ( geometry.boundingBox !== null ) {
  13456. if ( ray.intersectsBox( geometry.boundingBox ) === false ) return;
  13457. }
  13458. var uvs, intersection;
  13459. if ( geometry instanceof THREE.BufferGeometry ) {
  13460. var a, b, c;
  13461. var index = geometry.index;
  13462. var attributes = geometry.attributes;
  13463. var positions = attributes.position.array;
  13464. if ( attributes.uv !== undefined ) {
  13465. uvs = attributes.uv.array;
  13466. }
  13467. if ( index !== null ) {
  13468. var indices = index.array;
  13469. for ( var i = 0, l = indices.length; i < l; i += 3 ) {
  13470. a = indices[ i ];
  13471. b = indices[ i + 1 ];
  13472. c = indices[ i + 2 ];
  13473. intersection = checkBufferGeometryIntersection( this, raycaster, ray, positions, uvs, a, b, c );
  13474. if ( intersection ) {
  13475. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indices buffer semantics
  13476. intersects.push( intersection );
  13477. }
  13478. }
  13479. } else {
  13480. for ( var i = 0, l = positions.length; i < l; i += 9 ) {
  13481. a = i / 3;
  13482. b = a + 1;
  13483. c = a + 2;
  13484. intersection = checkBufferGeometryIntersection( this, raycaster, ray, positions, uvs, a, b, c );
  13485. if ( intersection ) {
  13486. intersection.index = a; // triangle number in positions buffer semantics
  13487. intersects.push( intersection );
  13488. }
  13489. }
  13490. }
  13491. } else if ( geometry instanceof THREE.Geometry ) {
  13492. var fvA, fvB, fvC;
  13493. var isFaceMaterial = material instanceof THREE.MultiMaterial;
  13494. var materials = isFaceMaterial === true ? material.materials : null;
  13495. var vertices = geometry.vertices;
  13496. var faces = geometry.faces;
  13497. var faceVertexUvs = geometry.faceVertexUvs[ 0 ];
  13498. if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs;
  13499. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  13500. var face = faces[ f ];
  13501. var faceMaterial = isFaceMaterial === true ? materials[ face.materialIndex ] : material;
  13502. if ( faceMaterial === undefined ) continue;
  13503. fvA = vertices[ face.a ];
  13504. fvB = vertices[ face.b ];
  13505. fvC = vertices[ face.c ];
  13506. if ( faceMaterial.morphTargets === true ) {
  13507. var morphTargets = geometry.morphTargets;
  13508. var morphInfluences = this.morphTargetInfluences;
  13509. vA.set( 0, 0, 0 );
  13510. vB.set( 0, 0, 0 );
  13511. vC.set( 0, 0, 0 );
  13512. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  13513. var influence = morphInfluences[ t ];
  13514. if ( influence === 0 ) continue;
  13515. var targets = morphTargets[ t ].vertices;
  13516. vA.addScaledVector( tempA.subVectors( targets[ face.a ], fvA ), influence );
  13517. vB.addScaledVector( tempB.subVectors( targets[ face.b ], fvB ), influence );
  13518. vC.addScaledVector( tempC.subVectors( targets[ face.c ], fvC ), influence );
  13519. }
  13520. vA.add( fvA );
  13521. vB.add( fvB );
  13522. vC.add( fvC );
  13523. fvA = vA;
  13524. fvB = vB;
  13525. fvC = vC;
  13526. }
  13527. intersection = checkIntersection( this, raycaster, ray, fvA, fvB, fvC, intersectionPoint );
  13528. if ( intersection ) {
  13529. if ( uvs ) {
  13530. var uvs_f = uvs[ f ];
  13531. uvA.copy( uvs_f[ 0 ] );
  13532. uvB.copy( uvs_f[ 1 ] );
  13533. uvC.copy( uvs_f[ 2 ] );
  13534. intersection.uv = uvIntersection( intersectionPoint, fvA, fvB, fvC, uvA, uvB, uvC );
  13535. }
  13536. intersection.face = face;
  13537. intersection.faceIndex = f;
  13538. intersects.push( intersection );
  13539. }
  13540. }
  13541. }
  13542. };
  13543. }() );
  13544. THREE.Mesh.prototype.clone = function () {
  13545. return new this.constructor( this.geometry, this.material ).copy( this );
  13546. };
  13547. // File:src/objects/Bone.js
  13548. /**
  13549. * @author mikael emtinger / http://gomo.se/
  13550. * @author alteredq / http://alteredqualia.com/
  13551. * @author ikerr / http://verold.com
  13552. */
  13553. THREE.Bone = function ( skin ) {
  13554. THREE.Object3D.call( this );
  13555. this.type = 'Bone';
  13556. this.skin = skin;
  13557. };
  13558. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  13559. THREE.Bone.prototype.constructor = THREE.Bone;
  13560. THREE.Bone.prototype.copy = function ( source ) {
  13561. THREE.Object3D.prototype.copy.call( this, source );
  13562. this.skin = source.skin;
  13563. return this;
  13564. };
  13565. // File:src/objects/Skeleton.js
  13566. /**
  13567. * @author mikael emtinger / http://gomo.se/
  13568. * @author alteredq / http://alteredqualia.com/
  13569. * @author michael guerrero / http://realitymeltdown.com
  13570. * @author ikerr / http://verold.com
  13571. */
  13572. THREE.Skeleton = function ( bones, boneInverses, useVertexTexture ) {
  13573. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  13574. this.identityMatrix = new THREE.Matrix4();
  13575. // copy the bone array
  13576. bones = bones || [];
  13577. this.bones = bones.slice( 0 );
  13578. // create a bone texture or an array of floats
  13579. if ( this.useVertexTexture ) {
  13580. // layout (1 matrix = 4 pixels)
  13581. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  13582. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  13583. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  13584. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  13585. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  13586. var size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  13587. size = THREE.Math.nextPowerOfTwo( Math.ceil( size ) );
  13588. size = Math.max( size, 4 );
  13589. this.boneTextureWidth = size;
  13590. this.boneTextureHeight = size;
  13591. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  13592. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  13593. } else {
  13594. this.boneMatrices = new Float32Array( 16 * this.bones.length );
  13595. }
  13596. // use the supplied bone inverses or calculate the inverses
  13597. if ( boneInverses === undefined ) {
  13598. this.calculateInverses();
  13599. } else {
  13600. if ( this.bones.length === boneInverses.length ) {
  13601. this.boneInverses = boneInverses.slice( 0 );
  13602. } else {
  13603. console.warn( 'THREE.Skeleton bonInverses is the wrong length.' );
  13604. this.boneInverses = [];
  13605. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13606. this.boneInverses.push( new THREE.Matrix4() );
  13607. }
  13608. }
  13609. }
  13610. };
  13611. THREE.Skeleton.prototype.calculateInverses = function () {
  13612. this.boneInverses = [];
  13613. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13614. var inverse = new THREE.Matrix4();
  13615. if ( this.bones[ b ] ) {
  13616. inverse.getInverse( this.bones[ b ].matrixWorld );
  13617. }
  13618. this.boneInverses.push( inverse );
  13619. }
  13620. };
  13621. THREE.Skeleton.prototype.pose = function () {
  13622. var bone;
  13623. // recover the bind-time world matrices
  13624. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13625. bone = this.bones[ b ];
  13626. if ( bone ) {
  13627. bone.matrixWorld.getInverse( this.boneInverses[ b ] );
  13628. }
  13629. }
  13630. // compute the local matrices, positions, rotations and scales
  13631. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13632. bone = this.bones[ b ];
  13633. if ( bone ) {
  13634. if ( bone.parent ) {
  13635. bone.matrix.getInverse( bone.parent.matrixWorld );
  13636. bone.matrix.multiply( bone.matrixWorld );
  13637. } else {
  13638. bone.matrix.copy( bone.matrixWorld );
  13639. }
  13640. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  13641. }
  13642. }
  13643. };
  13644. THREE.Skeleton.prototype.update = ( function () {
  13645. var offsetMatrix = new THREE.Matrix4();
  13646. return function update() {
  13647. // flatten bone matrices to array
  13648. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13649. // compute the offset between the current and the original transform
  13650. var matrix = this.bones[ b ] ? this.bones[ b ].matrixWorld : this.identityMatrix;
  13651. offsetMatrix.multiplyMatrices( matrix, this.boneInverses[ b ] );
  13652. offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  13653. }
  13654. if ( this.useVertexTexture ) {
  13655. this.boneTexture.needsUpdate = true;
  13656. }
  13657. };
  13658. } )();
  13659. THREE.Skeleton.prototype.clone = function () {
  13660. return new THREE.Skeleton( this.bones, this.boneInverses, this.useVertexTexture );
  13661. };
  13662. // File:src/objects/SkinnedMesh.js
  13663. /**
  13664. * @author mikael emtinger / http://gomo.se/
  13665. * @author alteredq / http://alteredqualia.com/
  13666. * @author ikerr / http://verold.com
  13667. */
  13668. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  13669. THREE.Mesh.call( this, geometry, material );
  13670. this.type = 'SkinnedMesh';
  13671. this.bindMode = "attached";
  13672. this.bindMatrix = new THREE.Matrix4();
  13673. this.bindMatrixInverse = new THREE.Matrix4();
  13674. // init bones
  13675. // TODO: remove bone creation as there is no reason (other than
  13676. // convenience) for THREE.SkinnedMesh to do this.
  13677. var bones = [];
  13678. if ( this.geometry && this.geometry.bones !== undefined ) {
  13679. var bone, gbone;
  13680. for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {
  13681. gbone = this.geometry.bones[ b ];
  13682. bone = new THREE.Bone( this );
  13683. bones.push( bone );
  13684. bone.name = gbone.name;
  13685. bone.position.fromArray( gbone.pos );
  13686. bone.quaternion.fromArray( gbone.rotq );
  13687. if ( gbone.scl !== undefined ) bone.scale.fromArray( gbone.scl );
  13688. }
  13689. for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {
  13690. gbone = this.geometry.bones[ b ];
  13691. if ( gbone.parent !== - 1 && gbone.parent !== null ) {
  13692. bones[ gbone.parent ].add( bones[ b ] );
  13693. } else {
  13694. this.add( bones[ b ] );
  13695. }
  13696. }
  13697. }
  13698. this.normalizeSkinWeights();
  13699. this.updateMatrixWorld( true );
  13700. this.bind( new THREE.Skeleton( bones, undefined, useVertexTexture ), this.matrixWorld );
  13701. };
  13702. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  13703. THREE.SkinnedMesh.prototype.constructor = THREE.SkinnedMesh;
  13704. THREE.SkinnedMesh.prototype.bind = function( skeleton, bindMatrix ) {
  13705. this.skeleton = skeleton;
  13706. if ( bindMatrix === undefined ) {
  13707. this.updateMatrixWorld( true );
  13708. this.skeleton.calculateInverses();
  13709. bindMatrix = this.matrixWorld;
  13710. }
  13711. this.bindMatrix.copy( bindMatrix );
  13712. this.bindMatrixInverse.getInverse( bindMatrix );
  13713. };
  13714. THREE.SkinnedMesh.prototype.pose = function () {
  13715. this.skeleton.pose();
  13716. };
  13717. THREE.SkinnedMesh.prototype.normalizeSkinWeights = function () {
  13718. if ( this.geometry instanceof THREE.Geometry ) {
  13719. for ( var i = 0; i < this.geometry.skinWeights.length; i ++ ) {
  13720. var sw = this.geometry.skinWeights[ i ];
  13721. var scale = 1.0 / sw.lengthManhattan();
  13722. if ( scale !== Infinity ) {
  13723. sw.multiplyScalar( scale );
  13724. } else {
  13725. sw.set( 1, 0, 0, 0 ); // do something reasonable
  13726. }
  13727. }
  13728. } else if ( this.geometry instanceof THREE.BufferGeometry ) {
  13729. var vec = new THREE.Vector4();
  13730. var skinWeight = this.geometry.attributes.skinWeight;
  13731. for ( var i = 0; i < skinWeight.count; i ++ ) {
  13732. vec.x = skinWeight.getX( i );
  13733. vec.y = skinWeight.getY( i );
  13734. vec.z = skinWeight.getZ( i );
  13735. vec.w = skinWeight.getW( i );
  13736. var scale = 1.0 / vec.lengthManhattan();
  13737. if ( scale !== Infinity ) {
  13738. vec.multiplyScalar( scale );
  13739. } else {
  13740. vec.set( 1, 0, 0, 0 ); // do something reasonable
  13741. }
  13742. skinWeight.setXYZW( i, vec.x, vec.y, vec.z, vec.w );
  13743. }
  13744. }
  13745. };
  13746. THREE.SkinnedMesh.prototype.updateMatrixWorld = function( force ) {
  13747. THREE.Mesh.prototype.updateMatrixWorld.call( this, true );
  13748. if ( this.bindMode === "attached" ) {
  13749. this.bindMatrixInverse.getInverse( this.matrixWorld );
  13750. } else if ( this.bindMode === "detached" ) {
  13751. this.bindMatrixInverse.getInverse( this.bindMatrix );
  13752. } else {
  13753. console.warn( 'THREE.SkinnedMesh unrecognized bindMode: ' + this.bindMode );
  13754. }
  13755. };
  13756. THREE.SkinnedMesh.prototype.clone = function() {
  13757. return new this.constructor( this.geometry, this.material, this.useVertexTexture ).copy( this );
  13758. };
  13759. // File:src/objects/LOD.js
  13760. /**
  13761. * @author mikael emtinger / http://gomo.se/
  13762. * @author alteredq / http://alteredqualia.com/
  13763. * @author mrdoob / http://mrdoob.com/
  13764. */
  13765. THREE.LOD = function () {
  13766. THREE.Object3D.call( this );
  13767. this.type = 'LOD';
  13768. Object.defineProperties( this, {
  13769. levels: {
  13770. enumerable: true,
  13771. value: []
  13772. },
  13773. objects: {
  13774. get: function () {
  13775. console.warn( 'THREE.LOD: .objects has been renamed to .levels.' );
  13776. return this.levels;
  13777. }
  13778. }
  13779. } );
  13780. };
  13781. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  13782. THREE.LOD.prototype.constructor = THREE.LOD;
  13783. THREE.LOD.prototype.addLevel = function ( object, distance ) {
  13784. if ( distance === undefined ) distance = 0;
  13785. distance = Math.abs( distance );
  13786. var levels = this.levels;
  13787. for ( var l = 0; l < levels.length; l ++ ) {
  13788. if ( distance < levels[ l ].distance ) {
  13789. break;
  13790. }
  13791. }
  13792. levels.splice( l, 0, { distance: distance, object: object } );
  13793. this.add( object );
  13794. };
  13795. THREE.LOD.prototype.getObjectForDistance = function ( distance ) {
  13796. var levels = this.levels;
  13797. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  13798. if ( distance < levels[ i ].distance ) {
  13799. break;
  13800. }
  13801. }
  13802. return levels[ i - 1 ].object;
  13803. };
  13804. THREE.LOD.prototype.raycast = ( function () {
  13805. var matrixPosition = new THREE.Vector3();
  13806. return function raycast( raycaster, intersects ) {
  13807. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  13808. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  13809. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  13810. };
  13811. }() );
  13812. THREE.LOD.prototype.update = function () {
  13813. var v1 = new THREE.Vector3();
  13814. var v2 = new THREE.Vector3();
  13815. return function update( camera ) {
  13816. var levels = this.levels;
  13817. if ( levels.length > 1 ) {
  13818. v1.setFromMatrixPosition( camera.matrixWorld );
  13819. v2.setFromMatrixPosition( this.matrixWorld );
  13820. var distance = v1.distanceTo( v2 );
  13821. levels[ 0 ].object.visible = true;
  13822. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  13823. if ( distance >= levels[ i ].distance ) {
  13824. levels[ i - 1 ].object.visible = false;
  13825. levels[ i ].object.visible = true;
  13826. } else {
  13827. break;
  13828. }
  13829. }
  13830. for ( ; i < l; i ++ ) {
  13831. levels[ i ].object.visible = false;
  13832. }
  13833. }
  13834. };
  13835. }();
  13836. THREE.LOD.prototype.copy = function ( source ) {
  13837. THREE.Object3D.prototype.copy.call( this, source, false );
  13838. var levels = source.levels;
  13839. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  13840. var level = levels[ i ];
  13841. this.addLevel( level.object.clone(), level.distance );
  13842. }
  13843. return this;
  13844. };
  13845. THREE.LOD.prototype.toJSON = function ( meta ) {
  13846. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  13847. data.object.levels = [];
  13848. var levels = this.levels;
  13849. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  13850. var level = levels[ i ];
  13851. data.object.levels.push( {
  13852. object: level.object.uuid,
  13853. distance: level.distance
  13854. } );
  13855. }
  13856. return data;
  13857. };
  13858. // File:src/objects/Sprite.js
  13859. /**
  13860. * @author mikael emtinger / http://gomo.se/
  13861. * @author alteredq / http://alteredqualia.com/
  13862. */
  13863. THREE.Sprite = ( function () {
  13864. var indices = new Uint16Array( [ 0, 1, 2, 0, 2, 3 ] );
  13865. var vertices = new Float32Array( [ - 0.5, - 0.5, 0, 0.5, - 0.5, 0, 0.5, 0.5, 0, - 0.5, 0.5, 0 ] );
  13866. var uvs = new Float32Array( [ 0, 0, 1, 0, 1, 1, 0, 1 ] );
  13867. var geometry = new THREE.BufferGeometry();
  13868. geometry.setIndex( new THREE.BufferAttribute( indices, 1 ) );
  13869. geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  13870. geometry.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) );
  13871. return function Sprite( material ) {
  13872. THREE.Object3D.call( this );
  13873. this.type = 'Sprite';
  13874. this.geometry = geometry;
  13875. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  13876. };
  13877. } )();
  13878. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  13879. THREE.Sprite.prototype.constructor = THREE.Sprite;
  13880. THREE.Sprite.prototype.raycast = ( function () {
  13881. var matrixPosition = new THREE.Vector3();
  13882. return function raycast( raycaster, intersects ) {
  13883. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  13884. var distanceSq = raycaster.ray.distanceSqToPoint( matrixPosition );
  13885. var guessSizeSq = this.scale.x * this.scale.y / 4;
  13886. if ( distanceSq > guessSizeSq ) {
  13887. return;
  13888. }
  13889. intersects.push( {
  13890. distance: Math.sqrt( distanceSq ),
  13891. point: this.position,
  13892. face: null,
  13893. object: this
  13894. } );
  13895. };
  13896. }() );
  13897. THREE.Sprite.prototype.clone = function () {
  13898. return new this.constructor( this.material ).copy( this );
  13899. };
  13900. // Backwards compatibility
  13901. THREE.Particle = THREE.Sprite;
  13902. // File:src/objects/LensFlare.js
  13903. /**
  13904. * @author mikael emtinger / http://gomo.se/
  13905. * @author alteredq / http://alteredqualia.com/
  13906. */
  13907. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  13908. THREE.Object3D.call( this );
  13909. this.lensFlares = [];
  13910. this.positionScreen = new THREE.Vector3();
  13911. this.customUpdateCallback = undefined;
  13912. if ( texture !== undefined ) {
  13913. this.add( texture, size, distance, blending, color );
  13914. }
  13915. };
  13916. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  13917. THREE.LensFlare.prototype.constructor = THREE.LensFlare;
  13918. /*
  13919. * Add: adds another flare
  13920. */
  13921. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  13922. if ( size === undefined ) size = - 1;
  13923. if ( distance === undefined ) distance = 0;
  13924. if ( opacity === undefined ) opacity = 1;
  13925. if ( color === undefined ) color = new THREE.Color( 0xffffff );
  13926. if ( blending === undefined ) blending = THREE.NormalBlending;
  13927. distance = Math.min( distance, Math.max( 0, distance ) );
  13928. this.lensFlares.push( {
  13929. texture: texture, // THREE.Texture
  13930. size: size, // size in pixels (-1 = use texture.width)
  13931. distance: distance, // distance (0-1) from light source (0=at light source)
  13932. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is in front z = 1 is back
  13933. scale: 1, // scale
  13934. rotation: 0, // rotation
  13935. opacity: opacity, // opacity
  13936. color: color, // color
  13937. blending: blending // blending
  13938. } );
  13939. };
  13940. /*
  13941. * Update lens flares update positions on all flares based on the screen position
  13942. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  13943. */
  13944. THREE.LensFlare.prototype.updateLensFlares = function () {
  13945. var f, fl = this.lensFlares.length;
  13946. var flare;
  13947. var vecX = - this.positionScreen.x * 2;
  13948. var vecY = - this.positionScreen.y * 2;
  13949. for ( f = 0; f < fl; f ++ ) {
  13950. flare = this.lensFlares[ f ];
  13951. flare.x = this.positionScreen.x + vecX * flare.distance;
  13952. flare.y = this.positionScreen.y + vecY * flare.distance;
  13953. flare.wantedRotation = flare.x * Math.PI * 0.25;
  13954. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  13955. }
  13956. };
  13957. THREE.LensFlare.prototype.copy = function ( source ) {
  13958. THREE.Object3D.prototype.copy.call( this, source );
  13959. this.positionScreen.copy( source.positionScreen );
  13960. this.customUpdateCallback = source.customUpdateCallback;
  13961. for ( var i = 0, l = source.lensFlares.length; i < l; i ++ ) {
  13962. this.lensFlares.push( source.lensFlares[ i ] );
  13963. }
  13964. return this;
  13965. };
  13966. // File:src/scenes/Scene.js
  13967. /**
  13968. * @author mrdoob / http://mrdoob.com/
  13969. */
  13970. THREE.Scene = function () {
  13971. THREE.Object3D.call( this );
  13972. this.type = 'Scene';
  13973. this.fog = null;
  13974. this.overrideMaterial = null;
  13975. this.autoUpdate = true; // checked by the renderer
  13976. };
  13977. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  13978. THREE.Scene.prototype.constructor = THREE.Scene;
  13979. THREE.Scene.prototype.copy = function ( source, recursive ) {
  13980. THREE.Object3D.prototype.copy.call( this, source, recursive );
  13981. if ( source.fog !== null ) this.fog = source.fog.clone();
  13982. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  13983. this.autoUpdate = source.autoUpdate;
  13984. this.matrixAutoUpdate = source.matrixAutoUpdate;
  13985. return this;
  13986. };
  13987. // File:src/scenes/Fog.js
  13988. /**
  13989. * @author mrdoob / http://mrdoob.com/
  13990. * @author alteredq / http://alteredqualia.com/
  13991. */
  13992. THREE.Fog = function ( color, near, far ) {
  13993. this.name = '';
  13994. this.color = new THREE.Color( color );
  13995. this.near = ( near !== undefined ) ? near : 1;
  13996. this.far = ( far !== undefined ) ? far : 1000;
  13997. };
  13998. THREE.Fog.prototype.clone = function () {
  13999. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  14000. };
  14001. // File:src/scenes/FogExp2.js
  14002. /**
  14003. * @author mrdoob / http://mrdoob.com/
  14004. * @author alteredq / http://alteredqualia.com/
  14005. */
  14006. THREE.FogExp2 = function ( color, density ) {
  14007. this.name = '';
  14008. this.color = new THREE.Color( color );
  14009. this.density = ( density !== undefined ) ? density : 0.00025;
  14010. };
  14011. THREE.FogExp2.prototype.clone = function () {
  14012. return new THREE.FogExp2( this.color.getHex(), this.density );
  14013. };
  14014. // File:src/renderers/shaders/ShaderChunk.js
  14015. THREE.ShaderChunk = {};
  14016. // File:src/renderers/shaders/ShaderChunk/alphamap_fragment.glsl
  14017. THREE.ShaderChunk[ 'alphamap_fragment' ] = "#ifdef USE_ALPHAMAP\n diffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif\n";
  14018. // File:src/renderers/shaders/ShaderChunk/alphamap_pars_fragment.glsl
  14019. THREE.ShaderChunk[ 'alphamap_pars_fragment' ] = "#ifdef USE_ALPHAMAP\n uniform sampler2D alphaMap;\n#endif\n";
  14020. // File:src/renderers/shaders/ShaderChunk/alphatest_fragment.glsl
  14021. THREE.ShaderChunk[ 'alphatest_fragment' ] = "#ifdef ALPHATEST\n if ( diffuseColor.a < ALPHATEST ) discard;\n#endif\n";
  14022. // File:src/renderers/shaders/ShaderChunk/aomap_fragment.glsl
  14023. 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( STANDARD )\n float dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n #endif\n#endif\n";
  14024. // File:src/renderers/shaders/ShaderChunk/aomap_pars_fragment.glsl
  14025. THREE.ShaderChunk[ 'aomap_pars_fragment' ] = "#ifdef USE_AOMAP\n uniform sampler2D aoMap;\n uniform float aoMapIntensity;\n#endif";
  14026. // File:src/renderers/shaders/ShaderChunk/begin_vertex.glsl
  14027. THREE.ShaderChunk[ 'begin_vertex' ] = "\nvec3 transformed = vec3( position );\n";
  14028. // File:src/renderers/shaders/ShaderChunk/beginnormal_vertex.glsl
  14029. THREE.ShaderChunk[ 'beginnormal_vertex' ] = "\nvec3 objectNormal = vec3( normal );\n";
  14030. // File:src/renderers/shaders/ShaderChunk/bsdfs.glsl
  14031. 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";
  14032. // File:src/renderers/shaders/ShaderChunk/bumpmap_pars_fragment.glsl
  14033. 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";
  14034. // File:src/renderers/shaders/ShaderChunk/color_fragment.glsl
  14035. THREE.ShaderChunk[ 'color_fragment' ] = "#ifdef USE_COLOR\n diffuseColor.rgb *= vColor;\n#endif";
  14036. // File:src/renderers/shaders/ShaderChunk/color_pars_fragment.glsl
  14037. THREE.ShaderChunk[ 'color_pars_fragment' ] = "#ifdef USE_COLOR\n varying vec3 vColor;\n#endif\n";
  14038. // File:src/renderers/shaders/ShaderChunk/color_pars_vertex.glsl
  14039. THREE.ShaderChunk[ 'color_pars_vertex' ] = "#ifdef USE_COLOR\n varying vec3 vColor;\n#endif";
  14040. // File:src/renderers/shaders/ShaderChunk/color_vertex.glsl
  14041. THREE.ShaderChunk[ 'color_vertex' ] = "#ifdef USE_COLOR\n vColor.xyz = color.xyz;\n#endif";
  14042. // File:src/renderers/shaders/ShaderChunk/common.glsl
  14043. THREE.ShaderChunk[ 'common' ] = "#define PI 3.14159\n#define PI2 6.28318\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 ) ); }\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";
  14044. // File:src/renderers/shaders/ShaderChunk/cube_uv_reflection_fragment.glsl
  14045. 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";
  14046. // File:src/renderers/shaders/ShaderChunk/defaultnormal_vertex.glsl
  14047. THREE.ShaderChunk[ 'defaultnormal_vertex' ] = "#ifdef FLIP_SIDED\n objectNormal = -objectNormal;\n#endif\nvec3 transformedNormal = normalMatrix * objectNormal;\n";
  14048. // File:src/renderers/shaders/ShaderChunk/displacementmap_vertex.glsl
  14049. THREE.ShaderChunk[ 'displacementmap_vertex' ] = "#ifdef USE_DISPLACEMENTMAP\n transformed += normal * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n#endif\n";
  14050. // File:src/renderers/shaders/ShaderChunk/displacementmap_pars_vertex.glsl
  14051. THREE.ShaderChunk[ 'displacementmap_pars_vertex' ] = "#ifdef USE_DISPLACEMENTMAP\n uniform sampler2D displacementMap;\n uniform float displacementScale;\n uniform float displacementBias;\n#endif\n";
  14052. // File:src/renderers/shaders/ShaderChunk/emissivemap_fragment.glsl
  14053. 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";
  14054. // File:src/renderers/shaders/ShaderChunk/emissivemap_pars_fragment.glsl
  14055. THREE.ShaderChunk[ 'emissivemap_pars_fragment' ] = "#ifdef USE_EMISSIVEMAP\n uniform sampler2D emissiveMap;\n#endif\n";
  14056. // File:src/renderers/shaders/ShaderChunk/encodings_pars_fragment.glsl
  14057. 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";
  14058. // File:src/renderers/shaders/ShaderChunk/encodings_fragment.glsl
  14059. THREE.ShaderChunk[ 'encodings_fragment' ] = " gl_FragColor = linearToOutputTexel( gl_FragColor );\n";
  14060. // File:src/renderers/shaders/ShaderChunk/envmap_fragment.glsl
  14061. 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";
  14062. // File:src/renderers/shaders/ShaderChunk/envmap_pars_fragment.glsl
  14063. THREE.ShaderChunk[ 'envmap_pars_fragment' ] = "#if defined( USE_ENVMAP ) || defined( STANDARD )\n uniform float reflectivity;\n uniform float envMapIntenstiy;\n#endif\n#ifdef USE_ENVMAP\n #if ! defined( STANDARD ) && ( 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( STANDARD )\n uniform float refractionRatio;\n #else\n varying vec3 vReflect;\n #endif\n#endif\n";
  14064. // File:src/renderers/shaders/ShaderChunk/envmap_pars_vertex.glsl
  14065. 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";
  14066. // File:src/renderers/shaders/ShaderChunk/envmap_vertex.glsl
  14067. 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";
  14068. // File:src/renderers/shaders/ShaderChunk/fog_fragment.glsl
  14069. 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";
  14070. // File:src/renderers/shaders/ShaderChunk/fog_pars_fragment.glsl
  14071. 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";
  14072. // File:src/renderers/shaders/ShaderChunk/lightmap_fragment.glsl
  14073. THREE.ShaderChunk[ 'lightmap_fragment' ] = "#ifdef USE_LIGHTMAP\n reflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif\n";
  14074. // File:src/renderers/shaders/ShaderChunk/lightmap_pars_fragment.glsl
  14075. THREE.ShaderChunk[ 'lightmap_pars_fragment' ] = "#ifdef USE_LIGHTMAP\n uniform sampler2D lightMap;\n uniform float lightMapIntensity;\n#endif";
  14076. // File:src/renderers/shaders/ShaderChunk/lights_lambert_vertex.glsl
  14077. 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 directLight = getPointDirectLightIrradiance( pointLights[ i ], geometry );\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 directLight = getSpotDirectLightIrradiance( spotLights[ i ], geometry );\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 directLight = getDirectionalDirectLightIrradiance( directionalLights[ i ], geometry );\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";
  14078. // File:src/renderers/shaders/ShaderChunk/lights_pars.glsl
  14079. 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 IncidentLight getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry ) {\n IncidentLight directLight;\n directLight.color = directionalLight.color;\n directLight.direction = directionalLight.direction;\n directLight.visible = true;\n return directLight;\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 IncidentLight getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry ) {\n 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 return directLight;\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 IncidentLight getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry ) {\n 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 return directLight;\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( STANDARD )\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";
  14080. // File:src/renderers/shaders/ShaderChunk/lights_phong_fragment.glsl
  14081. THREE.ShaderChunk[ 'lights_phong_fragment' ] = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n";
  14082. // File:src/renderers/shaders/ShaderChunk/lights_phong_pars_fragment.glsl
  14083. 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";
  14084. // File:src/renderers/shaders/ShaderChunk/lights_standard_fragment.glsl
  14085. THREE.ShaderChunk[ 'lights_standard_fragment' ] = "StandardMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.specularRoughness = clamp( roughnessFactor, 0.04, 1.0 );\nmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n";
  14086. // File:src/renderers/shaders/ShaderChunk/lights_standard_pars_fragment.glsl
  14087. THREE.ShaderChunk[ 'lights_standard_pars_fragment' ] = "struct StandardMaterial {\n vec3 diffuseColor;\n float specularRoughness;\n vec3 specularColor;\n};\nvoid RE_Direct_Standard( const in IncidentLight directLight, const in GeometricContext geometry, const in StandardMaterial 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_Standard( const in vec3 irradiance, const in GeometricContext geometry, const in StandardMaterial material, inout ReflectedLight reflectedLight ) {\n reflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Standard( const in vec3 radiance, const in GeometricContext geometry, const in StandardMaterial material, inout ReflectedLight reflectedLight ) {\n reflectedLight.indirectSpecular += radiance * BRDF_Specular_GGX_Environment( geometry, material.specularColor, material.specularRoughness );\n}\n#define RE_Direct RE_Direct_Standard\n#define RE_IndirectDiffuse RE_IndirectDiffuse_Standard\n#define RE_IndirectSpecular RE_IndirectSpecular_Standard\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";
  14088. // File:src/renderers/shaders/ShaderChunk/lights_template.glsl
  14089. 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 directLight = getPointDirectLightIrradiance( pointLight, geometry );\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 directLight = getSpotDirectLightIrradiance( spotLight, geometry );\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 directLight = getDirectionalDirectLightIrradiance( directionalLight, geometry );\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( STANDARD ) && 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";
  14090. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_fragment.glsl
  14091. THREE.ShaderChunk[ 'logdepthbuf_fragment' ] = "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n gl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n#endif";
  14092. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_pars_fragment.glsl
  14093. 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";
  14094. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_pars_vertex.glsl
  14095. 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";
  14096. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_vertex.glsl
  14097. 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";
  14098. // File:src/renderers/shaders/ShaderChunk/map_fragment.glsl
  14099. THREE.ShaderChunk[ 'map_fragment' ] = "#ifdef USE_MAP\n vec4 texelColor = texture2D( map, vUv );\n texelColor = mapTexelToLinear( texelColor );\n diffuseColor *= texelColor;\n#endif\n";
  14100. // File:src/renderers/shaders/ShaderChunk/map_pars_fragment.glsl
  14101. THREE.ShaderChunk[ 'map_pars_fragment' ] = "#ifdef USE_MAP\n uniform sampler2D map;\n#endif\n";
  14102. // File:src/renderers/shaders/ShaderChunk/map_particle_fragment.glsl
  14103. 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";
  14104. // File:src/renderers/shaders/ShaderChunk/map_particle_pars_fragment.glsl
  14105. THREE.ShaderChunk[ 'map_particle_pars_fragment' ] = "#ifdef USE_MAP\n uniform vec4 offsetRepeat;\n uniform sampler2D map;\n#endif\n";
  14106. // File:src/renderers/shaders/ShaderChunk/metalnessmap_fragment.glsl
  14107. THREE.ShaderChunk[ 'metalnessmap_fragment' ] = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n vec4 texelMetalness = texture2D( metalnessMap, vUv );\n metalnessFactor *= texelMetalness.r;\n#endif\n";
  14108. // File:src/renderers/shaders/ShaderChunk/metalnessmap_pars_fragment.glsl
  14109. THREE.ShaderChunk[ 'metalnessmap_pars_fragment' ] = "#ifdef USE_METALNESSMAP\n uniform sampler2D metalnessMap;\n#endif";
  14110. // File:src/renderers/shaders/ShaderChunk/morphnormal_vertex.glsl
  14111. 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";
  14112. // File:src/renderers/shaders/ShaderChunk/morphtarget_pars_vertex.glsl
  14113. 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";
  14114. // File:src/renderers/shaders/ShaderChunk/morphtarget_vertex.glsl
  14115. 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";
  14116. // File:src/renderers/shaders/ShaderChunk/normal_fragment.glsl
  14117. 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";
  14118. // File:src/renderers/shaders/ShaderChunk/normalmap_pars_fragment.glsl
  14119. 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";
  14120. // File:src/renderers/shaders/ShaderChunk/premultiplied_alpha_fragment.glsl
  14121. THREE.ShaderChunk[ 'premultiplied_alpha_fragment' ] = "#ifdef PREMULTIPLIED_ALPHA\n gl_FragColor.rgb *= gl_FragColor.a;\n#endif\n";
  14122. // File:src/renderers/shaders/ShaderChunk/project_vertex.glsl
  14123. 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";
  14124. // File:src/renderers/shaders/ShaderChunk/roughnessmap_fragment.glsl
  14125. THREE.ShaderChunk[ 'roughnessmap_fragment' ] = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n vec4 texelRoughness = texture2D( roughnessMap, vUv );\n roughnessFactor *= texelRoughness.r;\n#endif\n";
  14126. // File:src/renderers/shaders/ShaderChunk/roughnessmap_pars_fragment.glsl
  14127. THREE.ShaderChunk[ 'roughnessmap_pars_fragment' ] = "#ifdef USE_ROUGHNESSMAP\n uniform sampler2D roughnessMap;\n#endif";
  14128. // File:src/renderers/shaders/ShaderChunk/shadowmap_pars_fragment.glsl
  14129. 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 unpackDepth( const in vec4 rgba_depth ) {\n const vec4 bit_shift = vec4( 1.0 / ( 256.0 * 256.0 * 256.0 ), 1.0 / ( 256.0 * 256.0 ), 1.0 / 256.0, 1.0 );\n return dot( rgba_depth, bit_shift );\n }\n float texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n return step( compare, unpackDepth( 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";
  14130. // File:src/renderers/shaders/ShaderChunk/shadowmap_pars_vertex.glsl
  14131. 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";
  14132. // File:src/renderers/shaders/ShaderChunk/shadowmap_vertex.glsl
  14133. 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";
  14134. // File:src/renderers/shaders/ShaderChunk/shadowmask_pars_fragment.glsl
  14135. 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";
  14136. // File:src/renderers/shaders/ShaderChunk/skinbase_vertex.glsl
  14137. 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";
  14138. // File:src/renderers/shaders/ShaderChunk/skinning_pars_vertex.glsl
  14139. 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 boneGlobalMatrices[ MAX_BONES ];\n mat4 getBoneMatrix( const in float i ) {\n mat4 bone = boneGlobalMatrices[ int(i) ];\n return bone;\n }\n #endif\n#endif\n";
  14140. // File:src/renderers/shaders/ShaderChunk/skinning_vertex.glsl
  14141. 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";
  14142. // File:src/renderers/shaders/ShaderChunk/skinnormal_vertex.glsl
  14143. 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";
  14144. // File:src/renderers/shaders/ShaderChunk/specularmap_fragment.glsl
  14145. 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";
  14146. // File:src/renderers/shaders/ShaderChunk/specularmap_pars_fragment.glsl
  14147. THREE.ShaderChunk[ 'specularmap_pars_fragment' ] = "#ifdef USE_SPECULARMAP\n uniform sampler2D specularMap;\n#endif";
  14148. // File:src/renderers/shaders/ShaderChunk/tonemapping_fragment.glsl
  14149. THREE.ShaderChunk[ 'tonemapping_fragment' ] = "#if defined( TONE_MAPPING )\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif\n";
  14150. // File:src/renderers/shaders/ShaderChunk/tonemapping_pars_fragment.glsl
  14151. 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";
  14152. // File:src/renderers/shaders/ShaderChunk/uv2_pars_fragment.glsl
  14153. THREE.ShaderChunk[ 'uv2_pars_fragment' ] = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n varying vec2 vUv2;\n#endif";
  14154. // File:src/renderers/shaders/ShaderChunk/uv2_pars_vertex.glsl
  14155. THREE.ShaderChunk[ 'uv2_pars_vertex' ] = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n attribute vec2 uv2;\n varying vec2 vUv2;\n#endif";
  14156. // File:src/renderers/shaders/ShaderChunk/uv2_vertex.glsl
  14157. THREE.ShaderChunk[ 'uv2_vertex' ] = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n vUv2 = uv2;\n#endif";
  14158. // File:src/renderers/shaders/ShaderChunk/uv_pars_fragment.glsl
  14159. 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";
  14160. // File:src/renderers/shaders/ShaderChunk/uv_pars_vertex.glsl
  14161. 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";
  14162. // File:src/renderers/shaders/ShaderChunk/uv_vertex.glsl
  14163. 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";
  14164. // File:src/renderers/shaders/ShaderChunk/worldpos_vertex.glsl
  14165. THREE.ShaderChunk[ 'worldpos_vertex' ] = "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( STANDARD ) || 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";
  14166. // File:src/renderers/shaders/UniformsUtils.js
  14167. /**
  14168. * Uniform Utilities
  14169. */
  14170. THREE.UniformsUtils = {
  14171. merge: function ( uniforms ) {
  14172. var merged = {};
  14173. for ( var u = 0; u < uniforms.length; u ++ ) {
  14174. var tmp = this.clone( uniforms[ u ] );
  14175. for ( var p in tmp ) {
  14176. merged[ p ] = tmp[ p ];
  14177. }
  14178. }
  14179. return merged;
  14180. },
  14181. clone: function ( uniforms_src ) {
  14182. var uniforms_dst = {};
  14183. for ( var u in uniforms_src ) {
  14184. uniforms_dst[ u ] = {};
  14185. for ( var p in uniforms_src[ u ] ) {
  14186. var parameter_src = uniforms_src[ u ][ p ];
  14187. if ( parameter_src instanceof THREE.Color ||
  14188. parameter_src instanceof THREE.Vector2 ||
  14189. parameter_src instanceof THREE.Vector3 ||
  14190. parameter_src instanceof THREE.Vector4 ||
  14191. parameter_src instanceof THREE.Matrix3 ||
  14192. parameter_src instanceof THREE.Matrix4 ||
  14193. parameter_src instanceof THREE.Texture ) {
  14194. uniforms_dst[ u ][ p ] = parameter_src.clone();
  14195. } else if ( Array.isArray( parameter_src ) ) {
  14196. uniforms_dst[ u ][ p ] = parameter_src.slice();
  14197. } else {
  14198. uniforms_dst[ u ][ p ] = parameter_src;
  14199. }
  14200. }
  14201. }
  14202. return uniforms_dst;
  14203. }
  14204. };
  14205. // File:src/renderers/shaders/UniformsLib.js
  14206. /**
  14207. * Uniforms library for shared webgl shaders
  14208. */
  14209. THREE.UniformsLib = {
  14210. common: {
  14211. "diffuse": { type: "c", value: new THREE.Color( 0xeeeeee ) },
  14212. "opacity": { type: "1f", value: 1.0 },
  14213. "map": { type: "t", value: null },
  14214. "offsetRepeat": { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  14215. "specularMap": { type: "t", value: null },
  14216. "alphaMap": { type: "t", value: null },
  14217. "envMap": { type: "t", value: null },
  14218. "flipEnvMap": { type: "1f", value: - 1 },
  14219. "reflectivity": { type: "1f", value: 1.0 },
  14220. "refractionRatio": { type: "1f", value: 0.98 }
  14221. },
  14222. aomap: {
  14223. "aoMap": { type: "t", value: null },
  14224. "aoMapIntensity": { type: "1f", value: 1 }
  14225. },
  14226. lightmap: {
  14227. "lightMap": { type: "t", value: null },
  14228. "lightMapIntensity": { type: "1f", value: 1 }
  14229. },
  14230. emissivemap: {
  14231. "emissiveMap": { type: "t", value: null }
  14232. },
  14233. bumpmap: {
  14234. "bumpMap": { type: "t", value: null },
  14235. "bumpScale": { type: "1f", value: 1 }
  14236. },
  14237. normalmap: {
  14238. "normalMap": { type: "t", value: null },
  14239. "normalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  14240. },
  14241. displacementmap: {
  14242. "displacementMap": { type: "t", value: null },
  14243. "displacementScale": { type: "1f", value: 1 },
  14244. "displacementBias": { type: "1f", value: 0 }
  14245. },
  14246. roughnessmap: {
  14247. "roughnessMap": { type: "t", value: null }
  14248. },
  14249. metalnessmap: {
  14250. "metalnessMap": { type: "t", value: null }
  14251. },
  14252. fog: {
  14253. "fogDensity": { type: "1f", value: 0.00025 },
  14254. "fogNear": { type: "1f", value: 1 },
  14255. "fogFar": { type: "1f", value: 2000 },
  14256. "fogColor": { type: "c", value: new THREE.Color( 0xffffff ) }
  14257. },
  14258. lights: {
  14259. "ambientLightColor": { type: "3fv", value: [] },
  14260. "directionalLights": { type: "sa", value: [], properties: {
  14261. "direction": { type: "v3" },
  14262. "color": { type: "c" },
  14263. "shadow": { type: "1i" },
  14264. "shadowBias": { type: "1f" },
  14265. "shadowRadius": { type: "1f" },
  14266. "shadowMapSize": { type: "v2" }
  14267. } },
  14268. "directionalShadowMap": { type: "tv", value: [] },
  14269. "directionalShadowMatrix": { type: "m4v", value: [] },
  14270. "spotLights": { type: "sa", value: [], properties: {
  14271. "color": { type: "c" },
  14272. "position": { type: "v3" },
  14273. "direction": { type: "v3" },
  14274. "distance": { type: "1f" },
  14275. "coneCos": { type: "1f" },
  14276. "penumbraCos": { type: "1f" },
  14277. "decay": { type: "1f" },
  14278. "shadow": { type: "1i" },
  14279. "shadowBias": { type: "1f" },
  14280. "shadowRadius": { type: "1f" },
  14281. "shadowMapSize": { type: "v2" }
  14282. } },
  14283. "spotShadowMap": { type: "tv", value: [] },
  14284. "spotShadowMatrix": { type: "m4v", value: [] },
  14285. "pointLights": { type: "sa", value: [], properties: {
  14286. "color": { type: "c" },
  14287. "position": { type: "v3" },
  14288. "decay": { type: "1f" },
  14289. "distance": { type: "1f" },
  14290. "shadow": { type: "1i" },
  14291. "shadowBias": { type: "1f" },
  14292. "shadowRadius": { type: "1f" },
  14293. "shadowMapSize": { type: "v2" }
  14294. } },
  14295. "pointShadowMap": { type: "tv", value: [] },
  14296. "pointShadowMatrix": { type: "m4v", value: [] },
  14297. "hemisphereLights": { type: "sa", value: [], properties: {
  14298. "direction": { type: "v3" },
  14299. "skyColor": { type: "c" },
  14300. "groundColor": { type: "c" }
  14301. } }
  14302. },
  14303. points: {
  14304. "diffuse": { type: "c", value: new THREE.Color( 0xeeeeee ) },
  14305. "opacity": { type: "1f", value: 1.0 },
  14306. "size": { type: "1f", value: 1.0 },
  14307. "scale": { type: "1f", value: 1.0 },
  14308. "map": { type: "t", value: null },
  14309. "offsetRepeat": { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) }
  14310. }
  14311. };
  14312. // File:src/renderers/shaders/ShaderLib/cube_frag.glsl
  14313. THREE.ShaderChunk[ 'cube_frag' ] = "uniform samplerCube tCube;\nuniform float tFlip;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <logdepthbuf_pars_fragment>\nvoid main() {\n gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );\n #include <logdepthbuf_fragment>\n}\n";
  14314. // File:src/renderers/shaders/ShaderLib/cube_vert.glsl
  14315. THREE.ShaderChunk[ 'cube_vert' ] = "varying vec3 vWorldPosition;\n#include <common>\n#include <logdepthbuf_pars_vertex>\nvoid main() {\n vWorldPosition = transformDirection( position, modelMatrix );\n gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n #include <logdepthbuf_vertex>\n}\n";
  14316. // File:src/renderers/shaders/ShaderLib/depth_frag.glsl
  14317. THREE.ShaderChunk[ 'depth_frag' ] = "uniform float mNear;\nuniform float mFar;\nuniform float opacity;\n#include <common>\n#include <logdepthbuf_pars_fragment>\nvoid main() {\n #include <logdepthbuf_fragment>\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 float color = 1.0 - smoothstep( mNear, mFar, depth );\n gl_FragColor = vec4( vec3( color ), opacity );\n}\n";
  14318. // File:src/renderers/shaders/ShaderLib/depth_vert.glsl
  14319. THREE.ShaderChunk[ 'depth_vert' ] = "#include <common>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\nvoid main() {\n #include <begin_vertex>\n #include <morphtarget_vertex>\n #include <project_vertex>\n #include <logdepthbuf_vertex>\n}\n";
  14320. // File:src/renderers/shaders/ShaderLib/depthRGBA_frag.glsl
  14321. THREE.ShaderChunk[ 'depthRGBA_frag' ] = "#include <common>\n#include <logdepthbuf_pars_fragment>\nvec4 pack_depth( const in float depth ) {\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( depth * bit_shift * vec4( 255 ), vec4( 256 ) ) / vec4( 255 );\n res -= res.xxyz * bit_mask;\n return res;\n}\nvoid main() {\n #include <logdepthbuf_fragment>\n #ifdef USE_LOGDEPTHBUF_EXT\n gl_FragData[ 0 ] = pack_depth( gl_FragDepthEXT );\n #else\n gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );\n #endif\n}\n";
  14322. // File:src/renderers/shaders/ShaderLib/depthRGBA_vert.glsl
  14323. THREE.ShaderChunk[ 'depthRGBA_vert' ] = "#include <common>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_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 <logdepthbuf_vertex>\n}\n";
  14324. // File:src/renderers/shaders/ShaderLib/distanceRGBA_frag.glsl
  14325. THREE.ShaderChunk[ 'distanceRGBA_frag' ] = "uniform vec3 lightPos;\nvarying vec4 vWorldPosition;\n#include <common>\nvec4 pack1K ( float depth ) {\n depth /= 1000.0;\n const vec4 bitSh = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );\n const vec4 bitMsk = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );\n vec4 res = mod( depth * bitSh * vec4( 255 ), vec4( 256 ) ) / vec4( 255 );\n res -= res.xxyz * bitMsk;\n return res;\n}\nfloat unpack1K ( vec4 color ) {\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( color, bitSh ) * 1000.0;\n}\nvoid main () {\n gl_FragColor = pack1K( length( vWorldPosition.xyz - lightPos.xyz ) );\n}\n";
  14326. // File:src/renderers/shaders/ShaderLib/distanceRGBA_vert.glsl
  14327. THREE.ShaderChunk[ 'distanceRGBA_vert' ] = "varying vec4 vWorldPosition;\n#include <common>\n#include <morphtarget_pars_vertex>\n#include <skinning_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 vWorldPosition = worldPosition;\n}\n";
  14328. // File:src/renderers/shaders/ShaderLib/equirect_frag.glsl
  14329. THREE.ShaderChunk[ 'equirect_frag' ] = "uniform sampler2D tEquirect;\nuniform float tFlip;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <logdepthbuf_pars_fragment>\nvoid main() {\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";
  14330. // File:src/renderers/shaders/ShaderLib/equirect_vert.glsl
  14331. THREE.ShaderChunk[ 'equirect_vert' ] = "varying vec3 vWorldPosition;\n#include <common>\n#include <logdepthbuf_pars_vertex>\nvoid main() {\n vWorldPosition = transformDirection( position, modelMatrix );\n gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n #include <logdepthbuf_vertex>\n}\n";
  14332. // File:src/renderers/shaders/ShaderLib/linedashed_frag.glsl
  14333. 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>\nvoid main() {\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";
  14334. // File:src/renderers/shaders/ShaderLib/linedashed_vert.glsl
  14335. 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>\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}\n";
  14336. // File:src/renderers/shaders/ShaderLib/meshbasic_frag.glsl
  14337. 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>\nvoid main() {\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";
  14338. // File:src/renderers/shaders/ShaderLib/meshbasic_vert.glsl
  14339. 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>\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 <envmap_vertex>\n}\n";
  14340. // File:src/renderers/shaders/ShaderLib/meshlambert_frag.glsl
  14341. 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 <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>\nvoid main() {\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";
  14342. // File:src/renderers/shaders/ShaderLib/meshlambert_vert.glsl
  14343. 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>\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 <worldpos_vertex>\n #include <envmap_vertex>\n #include <lights_lambert_vertex>\n #include <shadowmap_vertex>\n}\n";
  14344. // File:src/renderers/shaders/ShaderLib/meshphong_frag.glsl
  14345. 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 <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>\nvoid main() {\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";
  14346. // File:src/renderers/shaders/ShaderLib/meshphong_vert.glsl
  14347. 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>\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 vViewPosition = - mvPosition.xyz;\n #include <worldpos_vertex>\n #include <envmap_vertex>\n #include <shadowmap_vertex>\n}\n";
  14348. // File:src/renderers/shaders/ShaderLib/meshstandard_frag.glsl
  14349. THREE.ShaderChunk[ 'meshstandard_frag' ] = "#define STANDARD\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 <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_standard_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>\nvoid main() {\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_standard_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";
  14350. // File:src/renderers/shaders/ShaderLib/meshstandard_vert.glsl
  14351. THREE.ShaderChunk[ 'meshstandard_vert' ] = "#define STANDARD\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>\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 vViewPosition = - mvPosition.xyz;\n #include <worldpos_vertex>\n #include <shadowmap_vertex>\n}\n";
  14352. // File:src/renderers/shaders/ShaderLib/normal_frag.glsl
  14353. THREE.ShaderChunk[ 'normal_frag' ] = "uniform float opacity;\nvarying vec3 vNormal;\n#include <common>\n#include <logdepthbuf_pars_fragment>\nvoid main() {\n gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );\n #include <logdepthbuf_fragment>\n}\n";
  14354. // File:src/renderers/shaders/ShaderLib/normal_vert.glsl
  14355. THREE.ShaderChunk[ 'normal_vert' ] = "varying vec3 vNormal;\n#include <common>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_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}\n";
  14356. // File:src/renderers/shaders/ShaderLib/points_frag.glsl
  14357. 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>\nvoid main() {\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";
  14358. // File:src/renderers/shaders/ShaderLib/points_vert.glsl
  14359. 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>\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 <worldpos_vertex>\n #include <shadowmap_vertex>\n}\n";
  14360. // File:src/renderers/shaders/ShaderLib.js
  14361. /**
  14362. * Webgl Shader Library for three.js
  14363. *
  14364. * @author alteredq / http://alteredqualia.com/
  14365. * @author mrdoob / http://mrdoob.com/
  14366. * @author mikael emtinger / http://gomo.se/
  14367. */
  14368. THREE.ShaderLib = {
  14369. 'basic': {
  14370. uniforms: THREE.UniformsUtils.merge( [
  14371. THREE.UniformsLib[ 'common' ],
  14372. THREE.UniformsLib[ 'aomap' ],
  14373. THREE.UniformsLib[ 'fog' ]
  14374. ] ),
  14375. vertexShader: THREE.ShaderChunk[ 'meshbasic_vert' ],
  14376. fragmentShader: THREE.ShaderChunk[ 'meshbasic_frag' ]
  14377. },
  14378. 'lambert': {
  14379. uniforms: THREE.UniformsUtils.merge( [
  14380. THREE.UniformsLib[ 'common' ],
  14381. THREE.UniformsLib[ 'aomap' ],
  14382. THREE.UniformsLib[ 'lightmap' ],
  14383. THREE.UniformsLib[ 'emissivemap' ],
  14384. THREE.UniformsLib[ 'fog' ],
  14385. THREE.UniformsLib[ 'lights' ],
  14386. {
  14387. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) }
  14388. }
  14389. ] ),
  14390. vertexShader: THREE.ShaderChunk[ 'meshlambert_vert' ],
  14391. fragmentShader: THREE.ShaderChunk[ 'meshlambert_frag' ]
  14392. },
  14393. 'phong': {
  14394. uniforms: THREE.UniformsUtils.merge( [
  14395. THREE.UniformsLib[ 'common' ],
  14396. THREE.UniformsLib[ 'aomap' ],
  14397. THREE.UniformsLib[ 'lightmap' ],
  14398. THREE.UniformsLib[ 'emissivemap' ],
  14399. THREE.UniformsLib[ 'bumpmap' ],
  14400. THREE.UniformsLib[ 'normalmap' ],
  14401. THREE.UniformsLib[ 'displacementmap' ],
  14402. THREE.UniformsLib[ 'fog' ],
  14403. THREE.UniformsLib[ 'lights' ],
  14404. {
  14405. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  14406. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  14407. "shininess": { type: "1f", value: 30 }
  14408. }
  14409. ] ),
  14410. vertexShader: THREE.ShaderChunk[ 'meshphong_vert' ],
  14411. fragmentShader: THREE.ShaderChunk[ 'meshphong_frag' ]
  14412. },
  14413. 'standard': {
  14414. uniforms: THREE.UniformsUtils.merge( [
  14415. THREE.UniformsLib[ 'common' ],
  14416. THREE.UniformsLib[ 'aomap' ],
  14417. THREE.UniformsLib[ 'lightmap' ],
  14418. THREE.UniformsLib[ 'emissivemap' ],
  14419. THREE.UniformsLib[ 'bumpmap' ],
  14420. THREE.UniformsLib[ 'normalmap' ],
  14421. THREE.UniformsLib[ 'displacementmap' ],
  14422. THREE.UniformsLib[ 'roughnessmap' ],
  14423. THREE.UniformsLib[ 'metalnessmap' ],
  14424. THREE.UniformsLib[ 'fog' ],
  14425. THREE.UniformsLib[ 'lights' ],
  14426. {
  14427. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  14428. "roughness": { type: "1f", value: 0.5 },
  14429. "metalness": { type: "1f", value: 0 },
  14430. "envMapIntensity" : { type: "1f", value: 1 } // temporary
  14431. }
  14432. ] ),
  14433. vertexShader: THREE.ShaderChunk[ 'meshstandard_vert' ],
  14434. fragmentShader: THREE.ShaderChunk[ 'meshstandard_frag' ]
  14435. },
  14436. 'points': {
  14437. uniforms: THREE.UniformsUtils.merge( [
  14438. THREE.UniformsLib[ 'points' ],
  14439. THREE.UniformsLib[ 'fog' ]
  14440. ] ),
  14441. vertexShader: THREE.ShaderChunk[ 'points_vert' ],
  14442. fragmentShader: THREE.ShaderChunk[ 'points_frag' ]
  14443. },
  14444. 'dashed': {
  14445. uniforms: THREE.UniformsUtils.merge( [
  14446. THREE.UniformsLib[ 'common' ],
  14447. THREE.UniformsLib[ 'fog' ],
  14448. {
  14449. "scale" : { type: "1f", value: 1 },
  14450. "dashSize" : { type: "1f", value: 1 },
  14451. "totalSize": { type: "1f", value: 2 }
  14452. }
  14453. ] ),
  14454. vertexShader: THREE.ShaderChunk[ 'linedashed_vert' ],
  14455. fragmentShader: THREE.ShaderChunk[ 'linedashed_frag' ]
  14456. },
  14457. 'depth': {
  14458. uniforms: {
  14459. "mNear": { type: "1f", value: 1.0 },
  14460. "mFar" : { type: "1f", value: 2000.0 },
  14461. "opacity" : { type: "1f", value: 1.0 }
  14462. },
  14463. vertexShader: THREE.ShaderChunk[ 'depth_vert' ],
  14464. fragmentShader: THREE.ShaderChunk[ 'depth_frag' ]
  14465. },
  14466. 'normal': {
  14467. uniforms: {
  14468. "opacity" : { type: "1f", value: 1.0 }
  14469. },
  14470. vertexShader: THREE.ShaderChunk[ 'normal_vert' ],
  14471. fragmentShader: THREE.ShaderChunk[ 'normal_frag' ]
  14472. },
  14473. /* -------------------------------------------------------------------------
  14474. // Cube map shader
  14475. ------------------------------------------------------------------------- */
  14476. 'cube': {
  14477. uniforms: {
  14478. "tCube": { type: "t", value: null },
  14479. "tFlip": { type: "1f", value: - 1 }
  14480. },
  14481. vertexShader: THREE.ShaderChunk[ 'cube_vert' ],
  14482. fragmentShader: THREE.ShaderChunk[ 'cube_frag' ]
  14483. },
  14484. /* -------------------------------------------------------------------------
  14485. // Cube map shader
  14486. ------------------------------------------------------------------------- */
  14487. 'equirect': {
  14488. uniforms: {
  14489. "tEquirect": { type: "t", value: null },
  14490. "tFlip": { type: "1f", value: - 1 }
  14491. },
  14492. vertexShader: THREE.ShaderChunk[ 'equirect_vert' ],
  14493. fragmentShader: THREE.ShaderChunk[ 'equirect_frag' ]
  14494. },
  14495. /* Depth encoding into RGBA texture
  14496. *
  14497. * based on SpiderGL shadow map example
  14498. * http://spidergl.org/example.php?id=6
  14499. *
  14500. * originally from
  14501. * http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  14502. *
  14503. * see also
  14504. * http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  14505. */
  14506. 'depthRGBA': {
  14507. uniforms: {},
  14508. vertexShader: THREE.ShaderChunk[ 'depthRGBA_vert' ],
  14509. fragmentShader: THREE.ShaderChunk[ 'depthRGBA_frag' ]
  14510. },
  14511. 'distanceRGBA': {
  14512. uniforms: {
  14513. "lightPos": { type: "v3", value: new THREE.Vector3() }
  14514. },
  14515. vertexShader: THREE.ShaderChunk[ 'distanceRGBA_vert' ],
  14516. fragmentShader: THREE.ShaderChunk[ 'distanceRGBA_frag' ]
  14517. }
  14518. };
  14519. // File:src/renderers/WebGLRenderer.js
  14520. /**
  14521. * @author supereggbert / http://www.paulbrunt.co.uk/
  14522. * @author mrdoob / http://mrdoob.com/
  14523. * @author alteredq / http://alteredqualia.com/
  14524. * @author szimek / https://github.com/szimek/
  14525. */
  14526. THREE.WebGLRenderer = function ( parameters ) {
  14527. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  14528. parameters = parameters || {};
  14529. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  14530. _context = parameters.context !== undefined ? parameters.context : null,
  14531. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  14532. _depth = parameters.depth !== undefined ? parameters.depth : true,
  14533. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  14534. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  14535. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  14536. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false;
  14537. var lights = [];
  14538. var opaqueObjects = [];
  14539. var opaqueObjectsLastIndex = - 1;
  14540. var transparentObjects = [];
  14541. var transparentObjectsLastIndex = - 1;
  14542. var morphInfluences = new Float32Array( 8 );
  14543. var sprites = [];
  14544. var lensFlares = [];
  14545. // public properties
  14546. this.domElement = _canvas;
  14547. this.context = null;
  14548. // clearing
  14549. this.autoClear = true;
  14550. this.autoClearColor = true;
  14551. this.autoClearDepth = true;
  14552. this.autoClearStencil = true;
  14553. // scene graph
  14554. this.sortObjects = true;
  14555. // physically based shading
  14556. this.gammaFactor = 2.0; // for backwards compatibility
  14557. this.gammaInput = false;
  14558. this.gammaOutput = false;
  14559. // physical lights
  14560. this.physicallyCorrectLights = false;
  14561. // tone mapping
  14562. this.toneMapping = THREE.LinearToneMapping;
  14563. this.toneMappingExposure = 1.0;
  14564. this.toneMappingWhitePoint = 1.0;
  14565. // morphs
  14566. this.maxMorphTargets = 8;
  14567. this.maxMorphNormals = 4;
  14568. // flags
  14569. this.autoScaleCubemaps = true;
  14570. // internal properties
  14571. var _this = this,
  14572. // internal state cache
  14573. _currentProgram = null,
  14574. _currentRenderTarget = null,
  14575. _currentFramebuffer = null,
  14576. _currentMaterialId = - 1,
  14577. _currentGeometryProgram = '',
  14578. _currentCamera = null,
  14579. _currentScissor = new THREE.Vector4(),
  14580. _currentScissorTest = null,
  14581. _currentViewport = new THREE.Vector4(),
  14582. //
  14583. _usedTextureUnits = 0,
  14584. //
  14585. _clearColor = new THREE.Color( 0x000000 ),
  14586. _clearAlpha = 0,
  14587. _width = _canvas.width,
  14588. _height = _canvas.height,
  14589. _pixelRatio = 1,
  14590. _scissor = new THREE.Vector4( 0, 0, _width, _height ),
  14591. _scissorTest = false,
  14592. _viewport = new THREE.Vector4( 0, 0, _width, _height ),
  14593. // frustum
  14594. _frustum = new THREE.Frustum(),
  14595. // camera matrices cache
  14596. _projScreenMatrix = new THREE.Matrix4(),
  14597. _vector3 = new THREE.Vector3(),
  14598. // light arrays cache
  14599. _lights = {
  14600. hash: '',
  14601. ambient: [ 0, 0, 0 ],
  14602. directional: [],
  14603. directionalShadowMap: [],
  14604. directionalShadowMatrix: [],
  14605. spot: [],
  14606. spotShadowMap: [],
  14607. spotShadowMatrix: [],
  14608. point: [],
  14609. pointShadowMap: [],
  14610. pointShadowMatrix: [],
  14611. hemi: [],
  14612. shadows: []
  14613. },
  14614. // info
  14615. _infoMemory = {
  14616. geometries: 0,
  14617. textures: 0
  14618. },
  14619. _infoRender = {
  14620. calls: 0,
  14621. vertices: 0,
  14622. faces: 0,
  14623. points: 0
  14624. };
  14625. this.info = {
  14626. render: _infoRender,
  14627. memory: _infoMemory,
  14628. programs: null
  14629. };
  14630. // initialize
  14631. var _gl;
  14632. try {
  14633. var attributes = {
  14634. alpha: _alpha,
  14635. depth: _depth,
  14636. stencil: _stencil,
  14637. antialias: _antialias,
  14638. premultipliedAlpha: _premultipliedAlpha,
  14639. preserveDrawingBuffer: _preserveDrawingBuffer
  14640. };
  14641. _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  14642. if ( _gl === null ) {
  14643. if ( _canvas.getContext( 'webgl' ) !== null ) {
  14644. throw 'Error creating WebGL context with your selected attributes.';
  14645. } else {
  14646. throw 'Error creating WebGL context.';
  14647. }
  14648. }
  14649. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  14650. if ( _gl.getShaderPrecisionFormat === undefined ) {
  14651. _gl.getShaderPrecisionFormat = function () {
  14652. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  14653. };
  14654. }
  14655. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  14656. } catch ( error ) {
  14657. console.error( 'THREE.WebGLRenderer: ' + error );
  14658. }
  14659. var extensions = new THREE.WebGLExtensions( _gl );
  14660. extensions.get( 'OES_texture_float' );
  14661. extensions.get( 'OES_texture_float_linear' );
  14662. extensions.get( 'OES_texture_half_float' );
  14663. extensions.get( 'OES_texture_half_float_linear' );
  14664. extensions.get( 'OES_standard_derivatives' );
  14665. extensions.get( 'ANGLE_instanced_arrays' );
  14666. if ( extensions.get( 'OES_element_index_uint' ) ) {
  14667. THREE.BufferGeometry.MaxIndex = 4294967296;
  14668. }
  14669. var capabilities = new THREE.WebGLCapabilities( _gl, extensions, parameters );
  14670. var state = new THREE.WebGLState( _gl, extensions, paramThreeToGL );
  14671. var properties = new THREE.WebGLProperties();
  14672. var objects = new THREE.WebGLObjects( _gl, properties, this.info );
  14673. var programCache = new THREE.WebGLPrograms( this, capabilities );
  14674. var lightCache = new THREE.WebGLLights();
  14675. this.info.programs = programCache.programs;
  14676. var bufferRenderer = new THREE.WebGLBufferRenderer( _gl, extensions, _infoRender );
  14677. var indexedBufferRenderer = new THREE.WebGLIndexedBufferRenderer( _gl, extensions, _infoRender );
  14678. //
  14679. function getTargetPixelRatio() {
  14680. return _currentRenderTarget === null ? _pixelRatio : 1;
  14681. }
  14682. function glClearColor( r, g, b, a ) {
  14683. if ( _premultipliedAlpha === true ) {
  14684. r *= a; g *= a; b *= a;
  14685. }
  14686. state.clearColor( r, g, b, a );
  14687. }
  14688. function setDefaultGLState() {
  14689. state.init();
  14690. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
  14691. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
  14692. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  14693. }
  14694. function resetGLState() {
  14695. _currentProgram = null;
  14696. _currentCamera = null;
  14697. _currentGeometryProgram = '';
  14698. _currentMaterialId = - 1;
  14699. state.reset();
  14700. }
  14701. setDefaultGLState();
  14702. this.context = _gl;
  14703. this.capabilities = capabilities;
  14704. this.extensions = extensions;
  14705. this.properties = properties;
  14706. this.state = state;
  14707. // shadow map
  14708. var shadowMap = new THREE.WebGLShadowMap( this, _lights, objects );
  14709. this.shadowMap = shadowMap;
  14710. // Plugins
  14711. var spritePlugin = new THREE.SpritePlugin( this, sprites );
  14712. var lensFlarePlugin = new THREE.LensFlarePlugin( this, lensFlares );
  14713. // API
  14714. this.getContext = function () {
  14715. return _gl;
  14716. };
  14717. this.getContextAttributes = function () {
  14718. return _gl.getContextAttributes();
  14719. };
  14720. this.forceContextLoss = function () {
  14721. extensions.get( 'WEBGL_lose_context' ).loseContext();
  14722. };
  14723. this.getMaxAnisotropy = ( function () {
  14724. var value;
  14725. return function getMaxAnisotropy() {
  14726. if ( value !== undefined ) return value;
  14727. var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  14728. if ( extension !== null ) {
  14729. value = _gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  14730. } else {
  14731. value = 0;
  14732. }
  14733. return value;
  14734. };
  14735. } )();
  14736. this.getPrecision = function () {
  14737. return capabilities.precision;
  14738. };
  14739. this.getPixelRatio = function () {
  14740. return _pixelRatio;
  14741. };
  14742. this.setPixelRatio = function ( value ) {
  14743. if ( value === undefined ) return;
  14744. _pixelRatio = value;
  14745. this.setSize( _viewport.z, _viewport.w, false );
  14746. };
  14747. this.getSize = function () {
  14748. return {
  14749. width: _width,
  14750. height: _height
  14751. };
  14752. };
  14753. this.setSize = function ( width, height, updateStyle ) {
  14754. _width = width;
  14755. _height = height;
  14756. _canvas.width = width * _pixelRatio;
  14757. _canvas.height = height * _pixelRatio;
  14758. if ( updateStyle !== false ) {
  14759. _canvas.style.width = width + 'px';
  14760. _canvas.style.height = height + 'px';
  14761. }
  14762. this.setViewport( 0, 0, width, height );
  14763. };
  14764. this.setViewport = function ( x, y, width, height ) {
  14765. state.viewport( _viewport.set( x, y, width, height ) );
  14766. };
  14767. this.setScissor = function ( x, y, width, height ) {
  14768. state.scissor( _scissor.set( x, y, width, height ) );
  14769. };
  14770. this.setScissorTest = function ( boolean ) {
  14771. state.setScissorTest( _scissorTest = boolean );
  14772. };
  14773. // Clearing
  14774. this.getClearColor = function () {
  14775. return _clearColor;
  14776. };
  14777. this.setClearColor = function ( color, alpha ) {
  14778. _clearColor.set( color );
  14779. _clearAlpha = alpha !== undefined ? alpha : 1;
  14780. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  14781. };
  14782. this.getClearAlpha = function () {
  14783. return _clearAlpha;
  14784. };
  14785. this.setClearAlpha = function ( alpha ) {
  14786. _clearAlpha = alpha;
  14787. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  14788. };
  14789. this.clear = function ( color, depth, stencil ) {
  14790. var bits = 0;
  14791. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  14792. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  14793. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  14794. _gl.clear( bits );
  14795. };
  14796. this.clearColor = function () {
  14797. this.clear( true, false, false );
  14798. };
  14799. this.clearDepth = function () {
  14800. this.clear( false, true, false );
  14801. };
  14802. this.clearStencil = function () {
  14803. this.clear( false, false, true );
  14804. };
  14805. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  14806. this.setRenderTarget( renderTarget );
  14807. this.clear( color, depth, stencil );
  14808. };
  14809. // Reset
  14810. this.resetGLState = resetGLState;
  14811. this.dispose = function() {
  14812. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  14813. };
  14814. // Events
  14815. function onContextLost( event ) {
  14816. event.preventDefault();
  14817. resetGLState();
  14818. setDefaultGLState();
  14819. properties.clear();
  14820. }
  14821. function onTextureDispose( event ) {
  14822. var texture = event.target;
  14823. texture.removeEventListener( 'dispose', onTextureDispose );
  14824. deallocateTexture( texture );
  14825. _infoMemory.textures --;
  14826. }
  14827. function onRenderTargetDispose( event ) {
  14828. var renderTarget = event.target;
  14829. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  14830. deallocateRenderTarget( renderTarget );
  14831. _infoMemory.textures --;
  14832. }
  14833. function onMaterialDispose( event ) {
  14834. var material = event.target;
  14835. material.removeEventListener( 'dispose', onMaterialDispose );
  14836. deallocateMaterial( material );
  14837. }
  14838. // Buffer deallocation
  14839. function deallocateTexture( texture ) {
  14840. var textureProperties = properties.get( texture );
  14841. if ( texture.image && textureProperties.__image__webglTextureCube ) {
  14842. // cube texture
  14843. _gl.deleteTexture( textureProperties.__image__webglTextureCube );
  14844. } else {
  14845. // 2D texture
  14846. if ( textureProperties.__webglInit === undefined ) return;
  14847. _gl.deleteTexture( textureProperties.__webglTexture );
  14848. }
  14849. // remove all webgl properties
  14850. properties.delete( texture );
  14851. }
  14852. function deallocateRenderTarget( renderTarget ) {
  14853. var renderTargetProperties = properties.get( renderTarget );
  14854. var textureProperties = properties.get( renderTarget.texture );
  14855. if ( ! renderTarget || textureProperties.__webglTexture === undefined ) return;
  14856. _gl.deleteTexture( textureProperties.__webglTexture );
  14857. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  14858. for ( var i = 0; i < 6; i ++ ) {
  14859. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  14860. _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  14861. }
  14862. } else {
  14863. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  14864. _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  14865. }
  14866. properties.delete( renderTarget.texture );
  14867. properties.delete( renderTarget );
  14868. }
  14869. function deallocateMaterial( material ) {
  14870. releaseMaterialProgramReference( material );
  14871. properties.delete( material );
  14872. }
  14873. function releaseMaterialProgramReference( material ) {
  14874. var programInfo = properties.get( material ).program;
  14875. material.program = undefined;
  14876. if ( programInfo !== undefined ) {
  14877. programCache.releaseProgram( programInfo );
  14878. }
  14879. }
  14880. // Buffer rendering
  14881. this.renderBufferImmediate = function ( object, program, material ) {
  14882. state.initAttributes();
  14883. var buffers = properties.get( object );
  14884. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  14885. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  14886. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  14887. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  14888. var attributes = program.getAttributes();
  14889. if ( object.hasPositions ) {
  14890. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position );
  14891. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  14892. state.enableAttribute( attributes.position );
  14893. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  14894. }
  14895. if ( object.hasNormals ) {
  14896. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal );
  14897. if ( material.type !== 'MeshPhongMaterial' && material.type !== 'MeshStandardMaterial' && material.shading === THREE.FlatShading ) {
  14898. for ( var i = 0, l = object.count * 3; i < l; i += 9 ) {
  14899. var array = object.normalArray;
  14900. var nx = ( array[ i + 0 ] + array[ i + 3 ] + array[ i + 6 ] ) / 3;
  14901. var ny = ( array[ i + 1 ] + array[ i + 4 ] + array[ i + 7 ] ) / 3;
  14902. var nz = ( array[ i + 2 ] + array[ i + 5 ] + array[ i + 8 ] ) / 3;
  14903. array[ i + 0 ] = nx;
  14904. array[ i + 1 ] = ny;
  14905. array[ i + 2 ] = nz;
  14906. array[ i + 3 ] = nx;
  14907. array[ i + 4 ] = ny;
  14908. array[ i + 5 ] = nz;
  14909. array[ i + 6 ] = nx;
  14910. array[ i + 7 ] = ny;
  14911. array[ i + 8 ] = nz;
  14912. }
  14913. }
  14914. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  14915. state.enableAttribute( attributes.normal );
  14916. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  14917. }
  14918. if ( object.hasUvs && material.map ) {
  14919. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv );
  14920. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  14921. state.enableAttribute( attributes.uv );
  14922. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  14923. }
  14924. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  14925. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color );
  14926. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  14927. state.enableAttribute( attributes.color );
  14928. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  14929. }
  14930. state.disableUnusedAttributes();
  14931. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  14932. object.count = 0;
  14933. };
  14934. this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) {
  14935. setMaterial( material );
  14936. var program = setProgram( camera, fog, material, object );
  14937. var updateBuffers = false;
  14938. var geometryProgram = geometry.id + '_' + program.id + '_' + material.wireframe;
  14939. if ( geometryProgram !== _currentGeometryProgram ) {
  14940. _currentGeometryProgram = geometryProgram;
  14941. updateBuffers = true;
  14942. }
  14943. // morph targets
  14944. var morphTargetInfluences = object.morphTargetInfluences;
  14945. if ( morphTargetInfluences !== undefined ) {
  14946. var activeInfluences = [];
  14947. for ( var i = 0, l = morphTargetInfluences.length; i < l; i ++ ) {
  14948. var influence = morphTargetInfluences[ i ];
  14949. activeInfluences.push( [ influence, i ] );
  14950. }
  14951. activeInfluences.sort( absNumericalSort );
  14952. if ( activeInfluences.length > 8 ) {
  14953. activeInfluences.length = 8;
  14954. }
  14955. var morphAttributes = geometry.morphAttributes;
  14956. for ( var i = 0, l = activeInfluences.length; i < l; i ++ ) {
  14957. var influence = activeInfluences[ i ];
  14958. morphInfluences[ i ] = influence[ 0 ];
  14959. if ( influence[ 0 ] !== 0 ) {
  14960. var index = influence[ 1 ];
  14961. if ( material.morphTargets === true && morphAttributes.position ) geometry.addAttribute( 'morphTarget' + i, morphAttributes.position[ index ] );
  14962. if ( material.morphNormals === true && morphAttributes.normal ) geometry.addAttribute( 'morphNormal' + i, morphAttributes.normal[ index ] );
  14963. } else {
  14964. if ( material.morphTargets === true ) geometry.removeAttribute( 'morphTarget' + i );
  14965. if ( material.morphNormals === true ) geometry.removeAttribute( 'morphNormal' + i );
  14966. }
  14967. }
  14968. var uniforms = program.getUniforms();
  14969. if ( uniforms.morphTargetInfluences !== null ) {
  14970. _gl.uniform1fv( uniforms.morphTargetInfluences, morphInfluences );
  14971. }
  14972. updateBuffers = true;
  14973. }
  14974. //
  14975. var index = geometry.index;
  14976. var position = geometry.attributes.position;
  14977. if ( material.wireframe === true ) {
  14978. index = objects.getWireframeAttribute( geometry );
  14979. }
  14980. var renderer;
  14981. if ( index !== null ) {
  14982. renderer = indexedBufferRenderer;
  14983. renderer.setIndex( index );
  14984. } else {
  14985. renderer = bufferRenderer;
  14986. }
  14987. if ( updateBuffers ) {
  14988. setupVertexAttributes( material, program, geometry );
  14989. if ( index !== null ) {
  14990. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, objects.getAttributeBuffer( index ) );
  14991. }
  14992. }
  14993. //
  14994. var dataStart = 0;
  14995. var dataCount = Infinity;
  14996. if ( index !== null ) {
  14997. dataCount = index.count;
  14998. } else if ( position !== undefined ) {
  14999. dataCount = position.count;
  15000. }
  15001. var rangeStart = geometry.drawRange.start;
  15002. var rangeCount = geometry.drawRange.count;
  15003. var groupStart = group !== null ? group.start : 0;
  15004. var groupCount = group !== null ? group.count : Infinity;
  15005. var drawStart = Math.max( dataStart, rangeStart, groupStart );
  15006. var drawEnd = Math.min( dataStart + dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  15007. var drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  15008. //
  15009. if ( object instanceof THREE.Mesh ) {
  15010. if ( material.wireframe === true ) {
  15011. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  15012. renderer.setMode( _gl.LINES );
  15013. } else {
  15014. switch ( object.drawMode ) {
  15015. case THREE.TrianglesDrawMode:
  15016. renderer.setMode( _gl.TRIANGLES );
  15017. break;
  15018. case THREE.TriangleStripDrawMode:
  15019. renderer.setMode( _gl.TRIANGLE_STRIP );
  15020. break;
  15021. case THREE.TriangleFanDrawMode:
  15022. renderer.setMode( _gl.TRIANGLE_FAN );
  15023. break;
  15024. }
  15025. }
  15026. } else if ( object instanceof THREE.Line ) {
  15027. var lineWidth = material.linewidth;
  15028. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  15029. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  15030. if ( object instanceof THREE.LineSegments ) {
  15031. renderer.setMode( _gl.LINES );
  15032. } else {
  15033. renderer.setMode( _gl.LINE_STRIP );
  15034. }
  15035. } else if ( object instanceof THREE.Points ) {
  15036. renderer.setMode( _gl.POINTS );
  15037. }
  15038. if ( geometry instanceof THREE.InstancedBufferGeometry ) {
  15039. if ( geometry.maxInstancedCount > 0 ) {
  15040. renderer.renderInstances( geometry, drawStart, drawCount );
  15041. }
  15042. } else {
  15043. renderer.render( drawStart, drawCount );
  15044. }
  15045. };
  15046. function setupVertexAttributes( material, program, geometry, startIndex ) {
  15047. var extension;
  15048. if ( geometry instanceof THREE.InstancedBufferGeometry ) {
  15049. extension = extensions.get( 'ANGLE_instanced_arrays' );
  15050. if ( extension === null ) {
  15051. console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  15052. return;
  15053. }
  15054. }
  15055. if ( startIndex === undefined ) startIndex = 0;
  15056. state.initAttributes();
  15057. var geometryAttributes = geometry.attributes;
  15058. var programAttributes = program.getAttributes();
  15059. var materialDefaultAttributeValues = material.defaultAttributeValues;
  15060. for ( var name in programAttributes ) {
  15061. var programAttribute = programAttributes[ name ];
  15062. if ( programAttribute >= 0 ) {
  15063. var geometryAttribute = geometryAttributes[ name ];
  15064. if ( geometryAttribute !== undefined ) {
  15065. var size = geometryAttribute.itemSize;
  15066. var buffer = objects.getAttributeBuffer( geometryAttribute );
  15067. if ( geometryAttribute instanceof THREE.InterleavedBufferAttribute ) {
  15068. var data = geometryAttribute.data;
  15069. var stride = data.stride;
  15070. var offset = geometryAttribute.offset;
  15071. if ( data instanceof THREE.InstancedInterleavedBuffer ) {
  15072. state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute, extension );
  15073. if ( geometry.maxInstancedCount === undefined ) {
  15074. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  15075. }
  15076. } else {
  15077. state.enableAttribute( programAttribute );
  15078. }
  15079. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  15080. _gl.vertexAttribPointer( programAttribute, size, _gl.FLOAT, false, stride * data.array.BYTES_PER_ELEMENT, ( startIndex * stride + offset ) * data.array.BYTES_PER_ELEMENT );
  15081. } else {
  15082. if ( geometryAttribute instanceof THREE.InstancedBufferAttribute ) {
  15083. state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute, extension );
  15084. if ( geometry.maxInstancedCount === undefined ) {
  15085. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  15086. }
  15087. } else {
  15088. state.enableAttribute( programAttribute );
  15089. }
  15090. var type = _gl.FLOAT;
  15091. var normalized = false;
  15092. var array = geometryAttribute.array;
  15093. if ( array instanceof Uint8Array ) {
  15094. type = _gl.UNSIGNED_BYTE;
  15095. normalized = true;
  15096. }
  15097. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  15098. _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, startIndex * size * array.BYTES_PER_ELEMENT );
  15099. }
  15100. } else if ( materialDefaultAttributeValues !== undefined ) {
  15101. var value = materialDefaultAttributeValues[ name ];
  15102. if ( value !== undefined ) {
  15103. switch ( value.length ) {
  15104. case 2:
  15105. _gl.vertexAttrib2fv( programAttribute, value );
  15106. break;
  15107. case 3:
  15108. _gl.vertexAttrib3fv( programAttribute, value );
  15109. break;
  15110. case 4:
  15111. _gl.vertexAttrib4fv( programAttribute, value );
  15112. break;
  15113. default:
  15114. _gl.vertexAttrib1fv( programAttribute, value );
  15115. }
  15116. }
  15117. }
  15118. }
  15119. }
  15120. state.disableUnusedAttributes();
  15121. }
  15122. // Sorting
  15123. function absNumericalSort( a, b ) {
  15124. return Math.abs( b[ 0 ] ) - Math.abs( a[ 0 ] );
  15125. }
  15126. function painterSortStable ( a, b ) {
  15127. if ( a.object.renderOrder !== b.object.renderOrder ) {
  15128. return a.object.renderOrder - b.object.renderOrder;
  15129. } else if ( a.material.id !== b.material.id ) {
  15130. return a.material.id - b.material.id;
  15131. } else if ( a.z !== b.z ) {
  15132. return a.z - b.z;
  15133. } else {
  15134. return a.id - b.id;
  15135. }
  15136. }
  15137. function reversePainterSortStable ( a, b ) {
  15138. if ( a.object.renderOrder !== b.object.renderOrder ) {
  15139. return a.object.renderOrder - b.object.renderOrder;
  15140. } if ( a.z !== b.z ) {
  15141. return b.z - a.z;
  15142. } else {
  15143. return a.id - b.id;
  15144. }
  15145. }
  15146. // Rendering
  15147. this.render = function ( scene, camera, renderTarget, forceClear ) {
  15148. if ( camera instanceof THREE.Camera === false ) {
  15149. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  15150. return;
  15151. }
  15152. var fog = scene.fog;
  15153. // reset caching for this frame
  15154. _currentGeometryProgram = '';
  15155. _currentMaterialId = - 1;
  15156. _currentCamera = null;
  15157. // update scene graph
  15158. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  15159. // update camera matrices and frustum
  15160. if ( camera.parent === null ) camera.updateMatrixWorld();
  15161. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  15162. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  15163. _frustum.setFromMatrix( _projScreenMatrix );
  15164. lights.length = 0;
  15165. opaqueObjectsLastIndex = - 1;
  15166. transparentObjectsLastIndex = - 1;
  15167. sprites.length = 0;
  15168. lensFlares.length = 0;
  15169. projectObject( scene, camera );
  15170. opaqueObjects.length = opaqueObjectsLastIndex + 1;
  15171. transparentObjects.length = transparentObjectsLastIndex + 1;
  15172. if ( _this.sortObjects === true ) {
  15173. opaqueObjects.sort( painterSortStable );
  15174. transparentObjects.sort( reversePainterSortStable );
  15175. }
  15176. //
  15177. setupShadows( lights );
  15178. shadowMap.render( scene, camera );
  15179. setupLights( lights, camera );
  15180. //
  15181. _infoRender.calls = 0;
  15182. _infoRender.vertices = 0;
  15183. _infoRender.faces = 0;
  15184. _infoRender.points = 0;
  15185. if ( renderTarget === undefined ) {
  15186. renderTarget = null;
  15187. }
  15188. this.setRenderTarget( renderTarget );
  15189. if ( this.autoClear || forceClear ) {
  15190. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  15191. }
  15192. //
  15193. if ( scene.overrideMaterial ) {
  15194. var overrideMaterial = scene.overrideMaterial;
  15195. renderObjects( opaqueObjects, camera, fog, overrideMaterial );
  15196. renderObjects( transparentObjects, camera, fog, overrideMaterial );
  15197. } else {
  15198. // opaque pass (front-to-back order)
  15199. state.setBlending( THREE.NoBlending );
  15200. renderObjects( opaqueObjects, camera, fog );
  15201. // transparent pass (back-to-front order)
  15202. renderObjects( transparentObjects, camera, fog );
  15203. }
  15204. // custom render plugins (post pass)
  15205. spritePlugin.render( scene, camera );
  15206. lensFlarePlugin.render( scene, camera, _currentViewport );
  15207. // Generate mipmap if we're using any kind of mipmap filtering
  15208. if ( renderTarget ) {
  15209. var texture = renderTarget.texture;
  15210. if ( texture.generateMipmaps && isPowerOfTwo( renderTarget ) &&
  15211. texture.minFilter !== THREE.NearestFilter &&
  15212. texture.minFilter !== THREE.LinearFilter ) {
  15213. updateRenderTargetMipmap( renderTarget );
  15214. }
  15215. }
  15216. // Ensure depth buffer writing is enabled so it can be cleared on next render
  15217. state.setDepthTest( true );
  15218. state.setDepthWrite( true );
  15219. state.setColorWrite( true );
  15220. // _gl.finish();
  15221. };
  15222. function pushRenderItem( object, geometry, material, z, group ) {
  15223. var array, index;
  15224. // allocate the next position in the appropriate array
  15225. if ( material.transparent ) {
  15226. array = transparentObjects;
  15227. index = ++ transparentObjectsLastIndex;
  15228. } else {
  15229. array = opaqueObjects;
  15230. index = ++ opaqueObjectsLastIndex;
  15231. }
  15232. // recycle existing render item or grow the array
  15233. var renderItem = array[ index ];
  15234. if ( renderItem !== undefined ) {
  15235. renderItem.id = object.id;
  15236. renderItem.object = object;
  15237. renderItem.geometry = geometry;
  15238. renderItem.material = material;
  15239. renderItem.z = _vector3.z;
  15240. renderItem.group = group;
  15241. } else {
  15242. renderItem = {
  15243. id: object.id,
  15244. object: object,
  15245. geometry: geometry,
  15246. material: material,
  15247. z: _vector3.z,
  15248. group: group
  15249. };
  15250. // assert( index === array.length );
  15251. array.push( renderItem );
  15252. }
  15253. }
  15254. function projectObject( object, camera ) {
  15255. if ( object.visible === false ) return;
  15256. if ( object.layers.test( camera.layers ) ) {
  15257. if ( object instanceof THREE.Light ) {
  15258. lights.push( object );
  15259. } else if ( object instanceof THREE.Sprite ) {
  15260. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  15261. sprites.push( object );
  15262. }
  15263. } else if ( object instanceof THREE.LensFlare ) {
  15264. lensFlares.push( object );
  15265. } else if ( object instanceof THREE.ImmediateRenderObject ) {
  15266. if ( _this.sortObjects === true ) {
  15267. _vector3.setFromMatrixPosition( object.matrixWorld );
  15268. _vector3.applyProjection( _projScreenMatrix );
  15269. }
  15270. pushRenderItem( object, null, object.material, _vector3.z, null );
  15271. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.Points ) {
  15272. if ( object instanceof THREE.SkinnedMesh ) {
  15273. object.skeleton.update();
  15274. }
  15275. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  15276. var material = object.material;
  15277. if ( material.visible === true ) {
  15278. if ( _this.sortObjects === true ) {
  15279. _vector3.setFromMatrixPosition( object.matrixWorld );
  15280. _vector3.applyProjection( _projScreenMatrix );
  15281. }
  15282. var geometry = objects.update( object );
  15283. if ( material instanceof THREE.MultiMaterial ) {
  15284. var groups = geometry.groups;
  15285. var materials = material.materials;
  15286. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  15287. var group = groups[ i ];
  15288. var groupMaterial = materials[ group.materialIndex ];
  15289. if ( groupMaterial.visible === true ) {
  15290. pushRenderItem( object, geometry, groupMaterial, _vector3.z, group );
  15291. }
  15292. }
  15293. } else {
  15294. pushRenderItem( object, geometry, material, _vector3.z, null );
  15295. }
  15296. }
  15297. }
  15298. }
  15299. }
  15300. var children = object.children;
  15301. for ( var i = 0, l = children.length; i < l; i ++ ) {
  15302. projectObject( children[ i ], camera );
  15303. }
  15304. }
  15305. function renderObjects( renderList, camera, fog, overrideMaterial ) {
  15306. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  15307. var renderItem = renderList[ i ];
  15308. var object = renderItem.object;
  15309. var geometry = renderItem.geometry;
  15310. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  15311. var group = renderItem.group;
  15312. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  15313. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  15314. if ( object instanceof THREE.ImmediateRenderObject ) {
  15315. setMaterial( material );
  15316. var program = setProgram( camera, fog, material, object );
  15317. _currentGeometryProgram = '';
  15318. object.render( function ( object ) {
  15319. _this.renderBufferImmediate( object, program, material );
  15320. } );
  15321. } else {
  15322. _this.renderBufferDirect( camera, fog, geometry, material, object, group );
  15323. }
  15324. }
  15325. }
  15326. function initMaterial( material, fog, object ) {
  15327. var materialProperties = properties.get( material );
  15328. var parameters = programCache.getParameters( material, _lights, fog, object );
  15329. var code = programCache.getProgramCode( material, parameters );
  15330. var program = materialProperties.program;
  15331. var programChange = true;
  15332. if ( program === undefined ) {
  15333. // new material
  15334. material.addEventListener( 'dispose', onMaterialDispose );
  15335. } else if ( program.code !== code ) {
  15336. // changed glsl or parameters
  15337. releaseMaterialProgramReference( material );
  15338. } else if ( parameters.shaderID !== undefined ) {
  15339. // same glsl and uniform list
  15340. return;
  15341. } else {
  15342. // only rebuild uniform list
  15343. programChange = false;
  15344. }
  15345. if ( programChange ) {
  15346. if ( parameters.shaderID ) {
  15347. var shader = THREE.ShaderLib[ parameters.shaderID ];
  15348. materialProperties.__webglShader = {
  15349. name: material.type,
  15350. uniforms: THREE.UniformsUtils.clone( shader.uniforms ),
  15351. vertexShader: shader.vertexShader,
  15352. fragmentShader: shader.fragmentShader
  15353. };
  15354. } else {
  15355. materialProperties.__webglShader = {
  15356. name: material.type,
  15357. uniforms: material.uniforms,
  15358. vertexShader: material.vertexShader,
  15359. fragmentShader: material.fragmentShader
  15360. };
  15361. }
  15362. material.__webglShader = materialProperties.__webglShader;
  15363. program = programCache.acquireProgram( material, parameters, code );
  15364. materialProperties.program = program;
  15365. material.program = program;
  15366. }
  15367. var attributes = program.getAttributes();
  15368. if ( material.morphTargets ) {
  15369. material.numSupportedMorphTargets = 0;
  15370. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  15371. if ( attributes[ 'morphTarget' + i ] >= 0 ) {
  15372. material.numSupportedMorphTargets ++;
  15373. }
  15374. }
  15375. }
  15376. if ( material.morphNormals ) {
  15377. material.numSupportedMorphNormals = 0;
  15378. for ( var i = 0; i < _this.maxMorphNormals; i ++ ) {
  15379. if ( attributes[ 'morphNormal' + i ] >= 0 ) {
  15380. material.numSupportedMorphNormals ++;
  15381. }
  15382. }
  15383. }
  15384. materialProperties.uniformsList = [];
  15385. var uniforms = materialProperties.__webglShader.uniforms,
  15386. uniformLocations = materialProperties.program.getUniforms();
  15387. for ( var u in uniforms ) {
  15388. var location = uniformLocations[ u ];
  15389. if ( location ) {
  15390. materialProperties.uniformsList.push( [ materialProperties.__webglShader.uniforms[ u ], location ] );
  15391. }
  15392. }
  15393. if ( material instanceof THREE.MeshPhongMaterial ||
  15394. material instanceof THREE.MeshLambertMaterial ||
  15395. material instanceof THREE.MeshStandardMaterial ||
  15396. material.lights ) {
  15397. // store the light setup it was created for
  15398. materialProperties.lightsHash = _lights.hash;
  15399. // wire up the material to this renderer's lighting state
  15400. uniforms.ambientLightColor.value = _lights.ambient;
  15401. uniforms.directionalLights.value = _lights.directional;
  15402. uniforms.spotLights.value = _lights.spot;
  15403. uniforms.pointLights.value = _lights.point;
  15404. uniforms.hemisphereLights.value = _lights.hemi;
  15405. uniforms.directionalShadowMap.value = _lights.directionalShadowMap;
  15406. uniforms.directionalShadowMatrix.value = _lights.directionalShadowMatrix;
  15407. uniforms.spotShadowMap.value = _lights.spotShadowMap;
  15408. uniforms.spotShadowMatrix.value = _lights.spotShadowMatrix;
  15409. uniforms.pointShadowMap.value = _lights.pointShadowMap;
  15410. uniforms.pointShadowMatrix.value = _lights.pointShadowMatrix;
  15411. }
  15412. // detect dynamic uniforms
  15413. materialProperties.hasDynamicUniforms = false;
  15414. for ( var j = 0, jl = materialProperties.uniformsList.length; j < jl; j ++ ) {
  15415. var uniform = materialProperties.uniformsList[ j ][ 0 ];
  15416. if ( uniform.dynamic === true ) {
  15417. materialProperties.hasDynamicUniforms = true;
  15418. break;
  15419. }
  15420. }
  15421. }
  15422. function setMaterial( material ) {
  15423. setMaterialFaces( material );
  15424. if ( material.transparent === true ) {
  15425. state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  15426. } else {
  15427. state.setBlending( THREE.NoBlending );
  15428. }
  15429. state.setDepthFunc( material.depthFunc );
  15430. state.setDepthTest( material.depthTest );
  15431. state.setDepthWrite( material.depthWrite );
  15432. state.setColorWrite( material.colorWrite );
  15433. state.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  15434. }
  15435. function setMaterialFaces( material ) {
  15436. material.side !== THREE.DoubleSide ? state.enable( _gl.CULL_FACE ) : state.disable( _gl.CULL_FACE );
  15437. state.setFlipSided( material.side === THREE.BackSide );
  15438. }
  15439. function setProgram( camera, fog, material, object ) {
  15440. _usedTextureUnits = 0;
  15441. var materialProperties = properties.get( material );
  15442. if ( materialProperties.program === undefined ) {
  15443. material.needsUpdate = true;
  15444. }
  15445. if ( materialProperties.lightsHash !== undefined &&
  15446. materialProperties.lightsHash !== _lights.hash ) {
  15447. material.needsUpdate = true;
  15448. }
  15449. if ( material.needsUpdate ) {
  15450. initMaterial( material, fog, object );
  15451. material.needsUpdate = false;
  15452. }
  15453. var refreshProgram = false;
  15454. var refreshMaterial = false;
  15455. var refreshLights = false;
  15456. var program = materialProperties.program,
  15457. p_uniforms = program.getUniforms(),
  15458. m_uniforms = materialProperties.__webglShader.uniforms;
  15459. if ( program.id !== _currentProgram ) {
  15460. _gl.useProgram( program.program );
  15461. _currentProgram = program.id;
  15462. refreshProgram = true;
  15463. refreshMaterial = true;
  15464. refreshLights = true;
  15465. }
  15466. if ( material.id !== _currentMaterialId ) {
  15467. _currentMaterialId = material.id;
  15468. refreshMaterial = true;
  15469. }
  15470. if ( refreshProgram || camera !== _currentCamera ) {
  15471. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  15472. if ( capabilities.logarithmicDepthBuffer ) {
  15473. _gl.uniform1f( p_uniforms.logDepthBufFC, 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  15474. }
  15475. if ( camera !== _currentCamera ) {
  15476. _currentCamera = camera;
  15477. // lighting uniforms depend on the camera so enforce an update
  15478. // now, in case this material supports lights - or later, when
  15479. // the next material that does gets activated:
  15480. refreshMaterial = true; // set to true on material change
  15481. refreshLights = true; // remains set until update done
  15482. }
  15483. // load material specific uniforms
  15484. // (shader material also gets them for the sake of genericity)
  15485. if ( material instanceof THREE.ShaderMaterial ||
  15486. material instanceof THREE.MeshPhongMaterial ||
  15487. material instanceof THREE.MeshStandardMaterial ||
  15488. material.envMap ) {
  15489. if ( p_uniforms.cameraPosition !== undefined ) {
  15490. _vector3.setFromMatrixPosition( camera.matrixWorld );
  15491. _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  15492. }
  15493. }
  15494. if ( material instanceof THREE.MeshPhongMaterial ||
  15495. material instanceof THREE.MeshLambertMaterial ||
  15496. material instanceof THREE.MeshBasicMaterial ||
  15497. material instanceof THREE.MeshStandardMaterial ||
  15498. material instanceof THREE.ShaderMaterial ||
  15499. material.skinning ) {
  15500. if ( p_uniforms.viewMatrix !== undefined ) {
  15501. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  15502. }
  15503. }
  15504. if ( p_uniforms.toneMappingExposure !== undefined ) {
  15505. _gl.uniform1f( p_uniforms.toneMappingExposure, _this.toneMappingExposure );
  15506. }
  15507. if ( p_uniforms.toneMappingWhitePoint !== undefined ) {
  15508. _gl.uniform1f( p_uniforms.toneMappingWhitePoint, _this.toneMappingWhitePoint );
  15509. }
  15510. }
  15511. // skinning uniforms must be set even if material didn't change
  15512. // auto-setting of texture unit for bone texture must go before other textures
  15513. // not sure why, but otherwise weird things happen
  15514. if ( material.skinning ) {
  15515. if ( object.bindMatrix && p_uniforms.bindMatrix !== undefined ) {
  15516. _gl.uniformMatrix4fv( p_uniforms.bindMatrix, false, object.bindMatrix.elements );
  15517. }
  15518. if ( object.bindMatrixInverse && p_uniforms.bindMatrixInverse !== undefined ) {
  15519. _gl.uniformMatrix4fv( p_uniforms.bindMatrixInverse, false, object.bindMatrixInverse.elements );
  15520. }
  15521. if ( capabilities.floatVertexTextures && object.skeleton && object.skeleton.useVertexTexture ) {
  15522. if ( p_uniforms.boneTexture !== undefined ) {
  15523. var textureUnit = getTextureUnit();
  15524. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  15525. _this.setTexture( object.skeleton.boneTexture, textureUnit );
  15526. }
  15527. if ( p_uniforms.boneTextureWidth !== undefined ) {
  15528. _gl.uniform1i( p_uniforms.boneTextureWidth, object.skeleton.boneTextureWidth );
  15529. }
  15530. if ( p_uniforms.boneTextureHeight !== undefined ) {
  15531. _gl.uniform1i( p_uniforms.boneTextureHeight, object.skeleton.boneTextureHeight );
  15532. }
  15533. } else if ( object.skeleton && object.skeleton.boneMatrices ) {
  15534. if ( p_uniforms.boneGlobalMatrices !== undefined ) {
  15535. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.skeleton.boneMatrices );
  15536. }
  15537. }
  15538. }
  15539. if ( refreshMaterial ) {
  15540. if ( material instanceof THREE.MeshPhongMaterial ||
  15541. material instanceof THREE.MeshLambertMaterial ||
  15542. material instanceof THREE.MeshStandardMaterial ||
  15543. material.lights ) {
  15544. // the current material requires lighting info
  15545. // note: all lighting uniforms are always set correctly
  15546. // they simply reference the renderer's state for their
  15547. // values
  15548. //
  15549. // use the current material's .needsUpdate flags to set
  15550. // the GL state when required
  15551. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  15552. }
  15553. // refresh uniforms common to several materials
  15554. if ( fog && material.fog ) {
  15555. refreshUniformsFog( m_uniforms, fog );
  15556. }
  15557. if ( material instanceof THREE.MeshBasicMaterial ||
  15558. material instanceof THREE.MeshLambertMaterial ||
  15559. material instanceof THREE.MeshPhongMaterial ||
  15560. material instanceof THREE.MeshStandardMaterial ) {
  15561. refreshUniformsCommon( m_uniforms, material );
  15562. }
  15563. // refresh single material specific uniforms
  15564. if ( material instanceof THREE.LineBasicMaterial ) {
  15565. refreshUniformsLine( m_uniforms, material );
  15566. } else if ( material instanceof THREE.LineDashedMaterial ) {
  15567. refreshUniformsLine( m_uniforms, material );
  15568. refreshUniformsDash( m_uniforms, material );
  15569. } else if ( material instanceof THREE.PointsMaterial ) {
  15570. refreshUniformsPoints( m_uniforms, material );
  15571. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  15572. refreshUniformsLambert( m_uniforms, material );
  15573. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  15574. refreshUniformsPhong( m_uniforms, material );
  15575. } else if ( material instanceof THREE.MeshStandardMaterial ) {
  15576. refreshUniformsStandard( m_uniforms, material );
  15577. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  15578. m_uniforms.mNear.value = camera.near;
  15579. m_uniforms.mFar.value = camera.far;
  15580. m_uniforms.opacity.value = material.opacity;
  15581. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  15582. m_uniforms.opacity.value = material.opacity;
  15583. }
  15584. // load common uniforms
  15585. loadUniformsGeneric( materialProperties.uniformsList );
  15586. }
  15587. loadUniformsMatrices( p_uniforms, object );
  15588. if ( p_uniforms.modelMatrix !== undefined ) {
  15589. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  15590. }
  15591. if ( materialProperties.hasDynamicUniforms === true ) {
  15592. updateDynamicUniforms( materialProperties.uniformsList, object, camera );
  15593. }
  15594. return program;
  15595. }
  15596. function updateDynamicUniforms ( uniforms, object, camera ) {
  15597. var dynamicUniforms = [];
  15598. for ( var j = 0, jl = uniforms.length; j < jl; j ++ ) {
  15599. var uniform = uniforms[ j ][ 0 ];
  15600. var onUpdateCallback = uniform.onUpdateCallback;
  15601. if ( onUpdateCallback !== undefined ) {
  15602. onUpdateCallback.bind( uniform )( object, camera );
  15603. dynamicUniforms.push( uniforms[ j ] );
  15604. }
  15605. }
  15606. loadUniformsGeneric( dynamicUniforms );
  15607. }
  15608. // Uniforms (refresh uniforms objects)
  15609. function refreshUniformsCommon ( uniforms, material ) {
  15610. uniforms.opacity.value = material.opacity;
  15611. uniforms.diffuse.value = material.color;
  15612. if ( material.emissive ) {
  15613. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  15614. }
  15615. uniforms.map.value = material.map;
  15616. uniforms.specularMap.value = material.specularMap;
  15617. uniforms.alphaMap.value = material.alphaMap;
  15618. if ( material.aoMap ) {
  15619. uniforms.aoMap.value = material.aoMap;
  15620. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  15621. }
  15622. // uv repeat and offset setting priorities
  15623. // 1. color map
  15624. // 2. specular map
  15625. // 3. normal map
  15626. // 4. bump map
  15627. // 5. alpha map
  15628. // 6. emissive map
  15629. var uvScaleMap;
  15630. if ( material.map ) {
  15631. uvScaleMap = material.map;
  15632. } else if ( material.specularMap ) {
  15633. uvScaleMap = material.specularMap;
  15634. } else if ( material.displacementMap ) {
  15635. uvScaleMap = material.displacementMap;
  15636. } else if ( material.normalMap ) {
  15637. uvScaleMap = material.normalMap;
  15638. } else if ( material.bumpMap ) {
  15639. uvScaleMap = material.bumpMap;
  15640. } else if ( material.roughnessMap ) {
  15641. uvScaleMap = material.roughnessMap;
  15642. } else if ( material.metalnessMap ) {
  15643. uvScaleMap = material.metalnessMap;
  15644. } else if ( material.alphaMap ) {
  15645. uvScaleMap = material.alphaMap;
  15646. } else if ( material.emissiveMap ) {
  15647. uvScaleMap = material.emissiveMap;
  15648. }
  15649. if ( uvScaleMap !== undefined ) {
  15650. if ( uvScaleMap instanceof THREE.WebGLRenderTarget ) {
  15651. uvScaleMap = uvScaleMap.texture;
  15652. }
  15653. var offset = uvScaleMap.offset;
  15654. var repeat = uvScaleMap.repeat;
  15655. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  15656. }
  15657. uniforms.envMap.value = material.envMap;
  15658. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : - 1;
  15659. uniforms.reflectivity.value = material.reflectivity;
  15660. uniforms.refractionRatio.value = material.refractionRatio;
  15661. }
  15662. function refreshUniformsLine ( uniforms, material ) {
  15663. uniforms.diffuse.value = material.color;
  15664. uniforms.opacity.value = material.opacity;
  15665. }
  15666. function refreshUniformsDash ( uniforms, material ) {
  15667. uniforms.dashSize.value = material.dashSize;
  15668. uniforms.totalSize.value = material.dashSize + material.gapSize;
  15669. uniforms.scale.value = material.scale;
  15670. }
  15671. function refreshUniformsPoints ( uniforms, material ) {
  15672. uniforms.diffuse.value = material.color;
  15673. uniforms.opacity.value = material.opacity;
  15674. uniforms.size.value = material.size * _pixelRatio;
  15675. uniforms.scale.value = _canvas.clientHeight / 2.0; // TODO: Cache this.
  15676. uniforms.map.value = material.map;
  15677. if ( material.map !== null ) {
  15678. var offset = material.map.offset;
  15679. var repeat = material.map.repeat;
  15680. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  15681. }
  15682. }
  15683. function refreshUniformsFog ( uniforms, fog ) {
  15684. uniforms.fogColor.value = fog.color;
  15685. if ( fog instanceof THREE.Fog ) {
  15686. uniforms.fogNear.value = fog.near;
  15687. uniforms.fogFar.value = fog.far;
  15688. } else if ( fog instanceof THREE.FogExp2 ) {
  15689. uniforms.fogDensity.value = fog.density;
  15690. }
  15691. }
  15692. function refreshUniformsLambert ( uniforms, material ) {
  15693. if ( material.lightMap ) {
  15694. uniforms.lightMap.value = material.lightMap;
  15695. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  15696. }
  15697. if ( material.emissiveMap ) {
  15698. uniforms.emissiveMap.value = material.emissiveMap;
  15699. }
  15700. }
  15701. function refreshUniformsPhong ( uniforms, material ) {
  15702. uniforms.specular.value = material.specular;
  15703. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  15704. if ( material.lightMap ) {
  15705. uniforms.lightMap.value = material.lightMap;
  15706. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  15707. }
  15708. if ( material.emissiveMap ) {
  15709. uniforms.emissiveMap.value = material.emissiveMap;
  15710. }
  15711. if ( material.bumpMap ) {
  15712. uniforms.bumpMap.value = material.bumpMap;
  15713. uniforms.bumpScale.value = material.bumpScale;
  15714. }
  15715. if ( material.normalMap ) {
  15716. uniforms.normalMap.value = material.normalMap;
  15717. uniforms.normalScale.value.copy( material.normalScale );
  15718. }
  15719. if ( material.displacementMap ) {
  15720. uniforms.displacementMap.value = material.displacementMap;
  15721. uniforms.displacementScale.value = material.displacementScale;
  15722. uniforms.displacementBias.value = material.displacementBias;
  15723. }
  15724. }
  15725. function refreshUniformsStandard ( uniforms, material ) {
  15726. uniforms.roughness.value = material.roughness;
  15727. uniforms.metalness.value = material.metalness;
  15728. if ( material.roughnessMap ) {
  15729. uniforms.roughnessMap.value = material.roughnessMap;
  15730. }
  15731. if ( material.metalnessMap ) {
  15732. uniforms.metalnessMap.value = material.metalnessMap;
  15733. }
  15734. if ( material.lightMap ) {
  15735. uniforms.lightMap.value = material.lightMap;
  15736. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  15737. }
  15738. if ( material.emissiveMap ) {
  15739. uniforms.emissiveMap.value = material.emissiveMap;
  15740. }
  15741. if ( material.bumpMap ) {
  15742. uniforms.bumpMap.value = material.bumpMap;
  15743. uniforms.bumpScale.value = material.bumpScale;
  15744. }
  15745. if ( material.normalMap ) {
  15746. uniforms.normalMap.value = material.normalMap;
  15747. uniforms.normalScale.value.copy( material.normalScale );
  15748. }
  15749. if ( material.displacementMap ) {
  15750. uniforms.displacementMap.value = material.displacementMap;
  15751. uniforms.displacementScale.value = material.displacementScale;
  15752. uniforms.displacementBias.value = material.displacementBias;
  15753. }
  15754. if ( material.envMap ) {
  15755. //uniforms.envMap.value = material.envMap; // part of uniforms common
  15756. uniforms.envMapIntensity.value = material.envMapIntensity;
  15757. }
  15758. }
  15759. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  15760. function markUniformsLightsNeedsUpdate ( uniforms, value ) {
  15761. uniforms.ambientLightColor.needsUpdate = value;
  15762. uniforms.directionalLights.needsUpdate = value;
  15763. uniforms.pointLights.needsUpdate = value;
  15764. uniforms.spotLights.needsUpdate = value;
  15765. uniforms.hemisphereLights.needsUpdate = value;
  15766. }
  15767. // Uniforms (load to GPU)
  15768. function loadUniformsMatrices ( uniforms, object ) {
  15769. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object.modelViewMatrix.elements );
  15770. if ( uniforms.normalMatrix ) {
  15771. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object.normalMatrix.elements );
  15772. }
  15773. }
  15774. function getTextureUnit() {
  15775. var textureUnit = _usedTextureUnits;
  15776. if ( textureUnit >= capabilities.maxTextures ) {
  15777. console.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  15778. }
  15779. _usedTextureUnits += 1;
  15780. return textureUnit;
  15781. }
  15782. function loadUniform( uniform, type, location, value ) {
  15783. var texture, textureUnit;
  15784. if ( type === '1i' ) {
  15785. _gl.uniform1i( location, value );
  15786. } else if ( type === '1f' ) {
  15787. _gl.uniform1f( location, value );
  15788. } else if ( type === '2f' ) {
  15789. _gl.uniform2f( location, value[ 0 ], value[ 1 ] );
  15790. } else if ( type === '3f' ) {
  15791. _gl.uniform3f( location, value[ 0 ], value[ 1 ], value[ 2 ] );
  15792. } else if ( type === '4f' ) {
  15793. _gl.uniform4f( location, value[ 0 ], value[ 1 ], value[ 2 ], value[ 3 ] );
  15794. } else if ( type === '1iv' ) {
  15795. _gl.uniform1iv( location, value );
  15796. } else if ( type === '3iv' ) {
  15797. _gl.uniform3iv( location, value );
  15798. } else if ( type === '1fv' ) {
  15799. _gl.uniform1fv( location, value );
  15800. } else if ( type === '2fv' ) {
  15801. _gl.uniform2fv( location, value );
  15802. } else if ( type === '3fv' ) {
  15803. _gl.uniform3fv( location, value );
  15804. } else if ( type === '4fv' ) {
  15805. _gl.uniform4fv( location, value );
  15806. } else if ( type === 'Matrix2fv' ) {
  15807. _gl.uniformMatrix2fv( location, false, value );
  15808. } else if ( type === 'Matrix3fv' ) {
  15809. _gl.uniformMatrix3fv( location, false, value );
  15810. } else if ( type === 'Matrix4fv' ) {
  15811. _gl.uniformMatrix4fv( location, false, value );
  15812. //
  15813. } else if ( type === 'i' ) {
  15814. // console.warn( 'THREE.WebGLRenderer: Uniform "i" is now "1i".' );
  15815. _gl.uniform1i( location, value );
  15816. } else if ( type === 'f' ) {
  15817. // console.warn( 'THREE.WebGLRenderer: Uniform "f" is now "1f".' );
  15818. _gl.uniform1f( location, value );
  15819. } else if ( type === 'iv1' ) {
  15820. // console.warn( 'THREE.WebGLRenderer: Uniform "iv1" is now "1iv".' );
  15821. _gl.uniform1iv( location, value );
  15822. } else if ( type === 'iv' ) {
  15823. // console.warn( 'THREE.WebGLRenderer: Uniform "iv" is now "3iv".' );
  15824. _gl.uniform3iv( location, value );
  15825. } else if ( type === 'fv1' ) {
  15826. // console.warn( 'THREE.WebGLRenderer: Uniform "fv1" is now "1fv".' );
  15827. _gl.uniform1fv( location, value );
  15828. } else if ( type === 'fv' ) {
  15829. // console.warn( 'THREE.WebGLRenderer: Uniform "fv" is now "3fv".' );
  15830. _gl.uniform3fv( location, value );
  15831. } else if ( type === 'v2' ) {
  15832. // single THREE.Vector2
  15833. _gl.uniform2f( location, value.x, value.y );
  15834. } else if ( type === 'v3' ) {
  15835. // single THREE.Vector3
  15836. _gl.uniform3f( location, value.x, value.y, value.z );
  15837. } else if ( type === 'v4' ) {
  15838. // single THREE.Vector4
  15839. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  15840. } else if ( type === 'c' ) {
  15841. // single THREE.Color
  15842. _gl.uniform3f( location, value.r, value.g, value.b );
  15843. } else if ( type === 's' ) {
  15844. // TODO: Optimize this
  15845. var properties = uniform.properties;
  15846. for ( var name in properties ) {
  15847. var property = properties[ name ];
  15848. var locationProperty = location[ name ];
  15849. var valueProperty = value[ name ];
  15850. loadUniform( property, property.type, locationProperty, valueProperty );
  15851. }
  15852. } else if ( type === 'sa' ) {
  15853. // TODO: Optimize this
  15854. var properties = uniform.properties;
  15855. for ( var i = 0, l = value.length; i < l; i ++ ) {
  15856. for ( var name in properties ) {
  15857. var property = properties[ name ];
  15858. var locationProperty = location[ i ][ name ];
  15859. var valueProperty = value[ i ][ name ];
  15860. loadUniform( property, property.type, locationProperty, valueProperty );
  15861. }
  15862. }
  15863. } else if ( type === 'v2v' ) {
  15864. // array of THREE.Vector2
  15865. if ( uniform._array === undefined ) {
  15866. uniform._array = new Float32Array( 2 * value.length );
  15867. }
  15868. for ( var i = 0, i2 = 0, il = value.length; i < il; i ++, i2 += 2 ) {
  15869. uniform._array[ i2 + 0 ] = value[ i ].x;
  15870. uniform._array[ i2 + 1 ] = value[ i ].y;
  15871. }
  15872. _gl.uniform2fv( location, uniform._array );
  15873. } else if ( type === 'v3v' ) {
  15874. // array of THREE.Vector3
  15875. if ( uniform._array === undefined ) {
  15876. uniform._array = new Float32Array( 3 * value.length );
  15877. }
  15878. for ( var i = 0, i3 = 0, il = value.length; i < il; i ++, i3 += 3 ) {
  15879. uniform._array[ i3 + 0 ] = value[ i ].x;
  15880. uniform._array[ i3 + 1 ] = value[ i ].y;
  15881. uniform._array[ i3 + 2 ] = value[ i ].z;
  15882. }
  15883. _gl.uniform3fv( location, uniform._array );
  15884. } else if ( type === 'v4v' ) {
  15885. // array of THREE.Vector4
  15886. if ( uniform._array === undefined ) {
  15887. uniform._array = new Float32Array( 4 * value.length );
  15888. }
  15889. for ( var i = 0, i4 = 0, il = value.length; i < il; i ++, i4 += 4 ) {
  15890. uniform._array[ i4 + 0 ] = value[ i ].x;
  15891. uniform._array[ i4 + 1 ] = value[ i ].y;
  15892. uniform._array[ i4 + 2 ] = value[ i ].z;
  15893. uniform._array[ i4 + 3 ] = value[ i ].w;
  15894. }
  15895. _gl.uniform4fv( location, uniform._array );
  15896. } else if ( type === 'm2' ) {
  15897. // single THREE.Matrix2
  15898. _gl.uniformMatrix2fv( location, false, value.elements );
  15899. } else if ( type === 'm3' ) {
  15900. // single THREE.Matrix3
  15901. _gl.uniformMatrix3fv( location, false, value.elements );
  15902. } else if ( type === 'm3v' ) {
  15903. // array of THREE.Matrix3
  15904. if ( uniform._array === undefined ) {
  15905. uniform._array = new Float32Array( 9 * value.length );
  15906. }
  15907. for ( var i = 0, il = value.length; i < il; i ++ ) {
  15908. value[ i ].flattenToArrayOffset( uniform._array, i * 9 );
  15909. }
  15910. _gl.uniformMatrix3fv( location, false, uniform._array );
  15911. } else if ( type === 'm4' ) {
  15912. // single THREE.Matrix4
  15913. _gl.uniformMatrix4fv( location, false, value.elements );
  15914. } else if ( type === 'm4v' ) {
  15915. // array of THREE.Matrix4
  15916. if ( uniform._array === undefined ) {
  15917. uniform._array = new Float32Array( 16 * value.length );
  15918. }
  15919. for ( var i = 0, il = value.length; i < il; i ++ ) {
  15920. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  15921. }
  15922. _gl.uniformMatrix4fv( location, false, uniform._array );
  15923. } else if ( type === 't' ) {
  15924. // single THREE.Texture (2d or cube)
  15925. texture = value;
  15926. textureUnit = getTextureUnit();
  15927. _gl.uniform1i( location, textureUnit );
  15928. if ( ! texture ) return;
  15929. if ( texture instanceof THREE.CubeTexture ||
  15930. ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {
  15931. // CompressedTexture can have Array in image :/
  15932. setCubeTexture( texture, textureUnit );
  15933. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  15934. setCubeTextureDynamic( texture.texture, textureUnit );
  15935. } else if ( texture instanceof THREE.WebGLRenderTarget ) {
  15936. _this.setTexture( texture.texture, textureUnit );
  15937. } else {
  15938. _this.setTexture( texture, textureUnit );
  15939. }
  15940. } else if ( type === 'tv' ) {
  15941. // array of THREE.Texture (2d or cube)
  15942. if ( uniform._array === undefined ) {
  15943. uniform._array = [];
  15944. }
  15945. for ( var i = 0, il = uniform.value.length; i < il; i ++ ) {
  15946. uniform._array[ i ] = getTextureUnit();
  15947. }
  15948. _gl.uniform1iv( location, uniform._array );
  15949. for ( var i = 0, il = uniform.value.length; i < il; i ++ ) {
  15950. texture = uniform.value[ i ];
  15951. textureUnit = uniform._array[ i ];
  15952. if ( ! texture ) continue;
  15953. if ( texture instanceof THREE.CubeTexture ||
  15954. ( texture.image instanceof Array && texture.image.length === 6 ) ) {
  15955. // CompressedTexture can have Array in image :/
  15956. setCubeTexture( texture, textureUnit );
  15957. } else if ( texture instanceof THREE.WebGLRenderTarget ) {
  15958. _this.setTexture( texture.texture, textureUnit );
  15959. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  15960. setCubeTextureDynamic( texture.texture, textureUnit );
  15961. } else {
  15962. _this.setTexture( texture, textureUnit );
  15963. }
  15964. }
  15965. } else {
  15966. console.warn( 'THREE.WebGLRenderer: Unknown uniform type: ' + type );
  15967. }
  15968. }
  15969. function loadUniformsGeneric( uniforms ) {
  15970. for ( var i = 0, l = uniforms.length; i < l; i ++ ) {
  15971. var uniform = uniforms[ i ][ 0 ];
  15972. // needsUpdate property is not added to all uniforms.
  15973. if ( uniform.needsUpdate === false ) continue;
  15974. var type = uniform.type;
  15975. var location = uniforms[ i ][ 1 ];
  15976. var value = uniform.value;
  15977. loadUniform( uniform, type, location, value );
  15978. }
  15979. }
  15980. function setupShadows ( lights ) {
  15981. var lightShadowsLength = 0;
  15982. for ( var i = 0, l = lights.length; i < l; i ++ ) {
  15983. var light = lights[ i ];
  15984. if ( light.castShadow ) {
  15985. _lights.shadows[ lightShadowsLength ++ ] = light;
  15986. }
  15987. }
  15988. _lights.shadows.length = lightShadowsLength;
  15989. }
  15990. function setupLights ( lights, camera ) {
  15991. var l, ll, light,
  15992. r = 0, g = 0, b = 0,
  15993. color,
  15994. intensity,
  15995. distance,
  15996. viewMatrix = camera.matrixWorldInverse,
  15997. directionalLength = 0,
  15998. pointLength = 0,
  15999. spotLength = 0,
  16000. hemiLength = 0;
  16001. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  16002. light = lights[ l ];
  16003. color = light.color;
  16004. intensity = light.intensity;
  16005. distance = light.distance;
  16006. if ( light instanceof THREE.AmbientLight ) {
  16007. r += color.r * intensity;
  16008. g += color.g * intensity;
  16009. b += color.b * intensity;
  16010. } else if ( light instanceof THREE.DirectionalLight ) {
  16011. var uniforms = lightCache.get( light );
  16012. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  16013. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  16014. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  16015. uniforms.direction.sub( _vector3 );
  16016. uniforms.direction.transformDirection( viewMatrix );
  16017. uniforms.shadow = light.castShadow;
  16018. if ( light.castShadow ) {
  16019. uniforms.shadowBias = light.shadow.bias;
  16020. uniforms.shadowRadius = light.shadow.radius;
  16021. uniforms.shadowMapSize = light.shadow.mapSize;
  16022. }
  16023. _lights.directionalShadowMap[ directionalLength ] = light.shadow.map;
  16024. _lights.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  16025. _lights.directional[ directionalLength ++ ] = uniforms;
  16026. } else if ( light instanceof THREE.SpotLight ) {
  16027. var uniforms = lightCache.get( light );
  16028. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  16029. uniforms.position.applyMatrix4( viewMatrix );
  16030. uniforms.color.copy( color ).multiplyScalar( intensity );
  16031. uniforms.distance = distance;
  16032. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  16033. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  16034. uniforms.direction.sub( _vector3 );
  16035. uniforms.direction.transformDirection( viewMatrix );
  16036. uniforms.coneCos = Math.cos( light.angle );
  16037. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  16038. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  16039. uniforms.shadow = light.castShadow;
  16040. if ( light.castShadow ) {
  16041. uniforms.shadowBias = light.shadow.bias;
  16042. uniforms.shadowRadius = light.shadow.radius;
  16043. uniforms.shadowMapSize = light.shadow.mapSize;
  16044. }
  16045. _lights.spotShadowMap[ spotLength ] = light.shadow.map;
  16046. _lights.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  16047. _lights.spot[ spotLength ++ ] = uniforms;
  16048. } else if ( light instanceof THREE.PointLight ) {
  16049. var uniforms = lightCache.get( light );
  16050. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  16051. uniforms.position.applyMatrix4( viewMatrix );
  16052. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  16053. uniforms.distance = light.distance;
  16054. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  16055. uniforms.shadow = light.castShadow;
  16056. if ( light.castShadow ) {
  16057. uniforms.shadowBias = light.shadow.bias;
  16058. uniforms.shadowRadius = light.shadow.radius;
  16059. uniforms.shadowMapSize = light.shadow.mapSize;
  16060. }
  16061. _lights.pointShadowMap[ pointLength ] = light.shadow.map;
  16062. if ( _lights.pointShadowMatrix[ pointLength ] === undefined ) {
  16063. _lights.pointShadowMatrix[ pointLength ] = new THREE.Matrix4();
  16064. }
  16065. // for point lights we set the shadow matrix to be a translation-only matrix
  16066. // equal to inverse of the light's position
  16067. _vector3.setFromMatrixPosition( light.matrixWorld ).negate();
  16068. _lights.pointShadowMatrix[ pointLength ].identity().setPosition( _vector3 );
  16069. _lights.point[ pointLength ++ ] = uniforms;
  16070. } else if ( light instanceof THREE.HemisphereLight ) {
  16071. var uniforms = lightCache.get( light );
  16072. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  16073. uniforms.direction.transformDirection( viewMatrix );
  16074. uniforms.direction.normalize();
  16075. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  16076. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  16077. _lights.hemi[ hemiLength ++ ] = uniforms;
  16078. }
  16079. }
  16080. _lights.ambient[ 0 ] = r;
  16081. _lights.ambient[ 1 ] = g;
  16082. _lights.ambient[ 2 ] = b;
  16083. _lights.directional.length = directionalLength;
  16084. _lights.spot.length = spotLength;
  16085. _lights.point.length = pointLength;
  16086. _lights.hemi.length = hemiLength;
  16087. _lights.hash = directionalLength + ',' + pointLength + ',' + spotLength + ',' + hemiLength + ',' + _lights.shadows.length;
  16088. }
  16089. // GL state setting
  16090. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  16091. if ( cullFace === THREE.CullFaceNone ) {
  16092. state.disable( _gl.CULL_FACE );
  16093. } else {
  16094. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  16095. _gl.frontFace( _gl.CW );
  16096. } else {
  16097. _gl.frontFace( _gl.CCW );
  16098. }
  16099. if ( cullFace === THREE.CullFaceBack ) {
  16100. _gl.cullFace( _gl.BACK );
  16101. } else if ( cullFace === THREE.CullFaceFront ) {
  16102. _gl.cullFace( _gl.FRONT );
  16103. } else {
  16104. _gl.cullFace( _gl.FRONT_AND_BACK );
  16105. }
  16106. state.enable( _gl.CULL_FACE );
  16107. }
  16108. };
  16109. // Textures
  16110. function setTextureParameters ( textureType, texture, isPowerOfTwoImage ) {
  16111. var extension;
  16112. if ( isPowerOfTwoImage ) {
  16113. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  16114. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  16115. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  16116. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  16117. } else {
  16118. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  16119. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  16120. if ( texture.wrapS !== THREE.ClampToEdgeWrapping || texture.wrapT !== THREE.ClampToEdgeWrapping ) {
  16121. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.', texture );
  16122. }
  16123. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  16124. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  16125. if ( texture.minFilter !== THREE.NearestFilter && texture.minFilter !== THREE.LinearFilter ) {
  16126. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.', texture );
  16127. }
  16128. }
  16129. extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  16130. if ( extension ) {
  16131. if ( texture.type === THREE.FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return;
  16132. if ( texture.type === THREE.HalfFloatType && extensions.get( 'OES_texture_half_float_linear' ) === null ) return;
  16133. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  16134. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _this.getMaxAnisotropy() ) );
  16135. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  16136. }
  16137. }
  16138. }
  16139. function uploadTexture( textureProperties, texture, slot ) {
  16140. if ( textureProperties.__webglInit === undefined ) {
  16141. textureProperties.__webglInit = true;
  16142. texture.addEventListener( 'dispose', onTextureDispose );
  16143. textureProperties.__webglTexture = _gl.createTexture();
  16144. _infoMemory.textures ++;
  16145. }
  16146. state.activeTexture( _gl.TEXTURE0 + slot );
  16147. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  16148. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  16149. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  16150. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  16151. var image = clampToMaxSize( texture.image, capabilities.maxTextureSize );
  16152. if ( textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( image ) === false ) {
  16153. image = makePowerOfTwo( image );
  16154. }
  16155. var isPowerOfTwoImage = isPowerOfTwo( image ),
  16156. glFormat = paramThreeToGL( texture.format ),
  16157. glType = paramThreeToGL( texture.type );
  16158. setTextureParameters( _gl.TEXTURE_2D, texture, isPowerOfTwoImage );
  16159. var mipmap, mipmaps = texture.mipmaps;
  16160. if ( texture instanceof THREE.DataTexture ) {
  16161. // use manually created mipmaps if available
  16162. // if there are no manual mipmaps
  16163. // set 0 level mipmap and then use GL to generate other mipmap levels
  16164. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  16165. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  16166. mipmap = mipmaps[ i ];
  16167. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  16168. }
  16169. texture.generateMipmaps = false;
  16170. } else {
  16171. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  16172. }
  16173. } else if ( texture instanceof THREE.CompressedTexture ) {
  16174. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  16175. mipmap = mipmaps[ i ];
  16176. if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) {
  16177. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  16178. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  16179. } else {
  16180. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()" );
  16181. }
  16182. } else {
  16183. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  16184. }
  16185. }
  16186. } else {
  16187. // regular Texture (image, video, canvas)
  16188. // use manually created mipmaps if available
  16189. // if there are no manual mipmaps
  16190. // set 0 level mipmap and then use GL to generate other mipmap levels
  16191. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  16192. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  16193. mipmap = mipmaps[ i ];
  16194. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  16195. }
  16196. texture.generateMipmaps = false;
  16197. } else {
  16198. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, image );
  16199. }
  16200. }
  16201. if ( texture.generateMipmaps && isPowerOfTwoImage ) _gl.generateMipmap( _gl.TEXTURE_2D );
  16202. textureProperties.__version = texture.version;
  16203. if ( texture.onUpdate ) texture.onUpdate( texture );
  16204. }
  16205. this.setTexture = function ( texture, slot ) {
  16206. var textureProperties = properties.get( texture );
  16207. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  16208. var image = texture.image;
  16209. if ( image === undefined ) {
  16210. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined', texture );
  16211. return;
  16212. }
  16213. if ( image.complete === false ) {
  16214. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture );
  16215. return;
  16216. }
  16217. uploadTexture( textureProperties, texture, slot );
  16218. return;
  16219. }
  16220. state.activeTexture( _gl.TEXTURE0 + slot );
  16221. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  16222. };
  16223. function clampToMaxSize ( image, maxSize ) {
  16224. if ( image.width > maxSize || image.height > maxSize ) {
  16225. // Warning: Scaling through the canvas will only work with images that use
  16226. // premultiplied alpha.
  16227. var scale = maxSize / Math.max( image.width, image.height );
  16228. var canvas = document.createElement( 'canvas' );
  16229. canvas.width = Math.floor( image.width * scale );
  16230. canvas.height = Math.floor( image.height * scale );
  16231. var context = canvas.getContext( '2d' );
  16232. context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
  16233. console.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  16234. return canvas;
  16235. }
  16236. return image;
  16237. }
  16238. function isPowerOfTwo( image ) {
  16239. return THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height );
  16240. }
  16241. function textureNeedsPowerOfTwo( texture ) {
  16242. if ( texture.wrapS !== THREE.ClampToEdgeWrapping || texture.wrapT !== THREE.ClampToEdgeWrapping ) return true;
  16243. if ( texture.minFilter !== THREE.NearestFilter && texture.minFilter !== THREE.LinearFilter ) return true;
  16244. return false;
  16245. }
  16246. function makePowerOfTwo( image ) {
  16247. if ( image instanceof HTMLImageElement || image instanceof HTMLCanvasElement ) {
  16248. var canvas = document.createElement( 'canvas' );
  16249. canvas.width = THREE.Math.nearestPowerOfTwo( image.width );
  16250. canvas.height = THREE.Math.nearestPowerOfTwo( image.height );
  16251. var context = canvas.getContext( '2d' );
  16252. context.drawImage( image, 0, 0, canvas.width, canvas.height );
  16253. console.warn( 'THREE.WebGLRenderer: image is not power of two (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  16254. return canvas;
  16255. }
  16256. return image;
  16257. }
  16258. function setCubeTexture ( texture, slot ) {
  16259. var textureProperties = properties.get( texture );
  16260. if ( texture.image.length === 6 ) {
  16261. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  16262. if ( ! textureProperties.__image__webglTextureCube ) {
  16263. texture.addEventListener( 'dispose', onTextureDispose );
  16264. textureProperties.__image__webglTextureCube = _gl.createTexture();
  16265. _infoMemory.textures ++;
  16266. }
  16267. state.activeTexture( _gl.TEXTURE0 + slot );
  16268. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  16269. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  16270. var isCompressed = texture instanceof THREE.CompressedTexture;
  16271. var isDataTexture = texture.image[ 0 ] instanceof THREE.DataTexture;
  16272. var cubeImage = [];
  16273. for ( var i = 0; i < 6; i ++ ) {
  16274. if ( _this.autoScaleCubemaps && ! isCompressed && ! isDataTexture ) {
  16275. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], capabilities.maxCubemapSize );
  16276. } else {
  16277. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  16278. }
  16279. }
  16280. var image = cubeImage[ 0 ],
  16281. isPowerOfTwoImage = isPowerOfTwo( image ),
  16282. glFormat = paramThreeToGL( texture.format ),
  16283. glType = paramThreeToGL( texture.type );
  16284. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isPowerOfTwoImage );
  16285. for ( var i = 0; i < 6; i ++ ) {
  16286. if ( ! isCompressed ) {
  16287. if ( isDataTexture ) {
  16288. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  16289. } else {
  16290. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  16291. }
  16292. } else {
  16293. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  16294. for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  16295. mipmap = mipmaps[ j ];
  16296. if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) {
  16297. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  16298. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  16299. } else {
  16300. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setCubeTexture()" );
  16301. }
  16302. } else {
  16303. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  16304. }
  16305. }
  16306. }
  16307. }
  16308. if ( texture.generateMipmaps && isPowerOfTwoImage ) {
  16309. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  16310. }
  16311. textureProperties.__version = texture.version;
  16312. if ( texture.onUpdate ) texture.onUpdate( texture );
  16313. } else {
  16314. state.activeTexture( _gl.TEXTURE0 + slot );
  16315. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  16316. }
  16317. }
  16318. }
  16319. function setCubeTextureDynamic ( texture, slot ) {
  16320. state.activeTexture( _gl.TEXTURE0 + slot );
  16321. state.bindTexture( _gl.TEXTURE_CUBE_MAP, properties.get( texture ).__webglTexture );
  16322. }
  16323. // Render targets
  16324. // Setup storage for target texture and bind it to correct framebuffer
  16325. function setupFrameBufferTexture ( framebuffer, renderTarget, attachment, textureTarget ) {
  16326. var glFormat = paramThreeToGL( renderTarget.texture.format );
  16327. var glType = paramThreeToGL( renderTarget.texture.type );
  16328. state.texImage2D( textureTarget, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  16329. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  16330. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
  16331. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  16332. }
  16333. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  16334. function setupRenderBufferStorage ( renderbuffer, renderTarget ) {
  16335. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  16336. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  16337. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  16338. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  16339. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  16340. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  16341. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  16342. } else {
  16343. // FIXME: We don't support !depth !stencil
  16344. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  16345. }
  16346. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  16347. }
  16348. // Setup GL resources for a non-texture depth buffer
  16349. function setupDepthRenderbuffer( renderTarget ) {
  16350. var renderTargetProperties = properties.get( renderTarget );
  16351. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  16352. if ( isCube ) {
  16353. renderTargetProperties.__webglDepthbuffer = [];
  16354. for ( var i = 0; i < 6; i ++ ) {
  16355. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  16356. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  16357. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget );
  16358. }
  16359. } else {
  16360. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  16361. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  16362. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget );
  16363. }
  16364. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  16365. }
  16366. // Set up GL resources for the render target
  16367. function setupRenderTarget( renderTarget ) {
  16368. var renderTargetProperties = properties.get( renderTarget );
  16369. var textureProperties = properties.get( renderTarget.texture );
  16370. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  16371. textureProperties.__webglTexture = _gl.createTexture();
  16372. _infoMemory.textures ++;
  16373. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  16374. var isTargetPowerOfTwo = THREE.Math.isPowerOfTwo( renderTarget.width ) && THREE.Math.isPowerOfTwo( renderTarget.height );
  16375. // Setup framebuffer
  16376. if ( isCube ) {
  16377. renderTargetProperties.__webglFramebuffer = [];
  16378. for ( var i = 0; i < 6; i ++ ) {
  16379. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  16380. }
  16381. } else {
  16382. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  16383. }
  16384. // Setup color buffer
  16385. if ( isCube ) {
  16386. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  16387. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, isTargetPowerOfTwo );
  16388. for ( var i = 0; i < 6; i ++ ) {
  16389. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  16390. }
  16391. if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  16392. state.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  16393. } else {
  16394. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  16395. setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, isTargetPowerOfTwo );
  16396. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D );
  16397. if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  16398. state.bindTexture( _gl.TEXTURE_2D, null );
  16399. }
  16400. // Setup depth and stencil buffers
  16401. if ( renderTarget.depthBuffer ) {
  16402. setupDepthRenderbuffer( renderTarget );
  16403. }
  16404. }
  16405. this.getCurrentRenderTarget = function() {
  16406. return _currentRenderTarget;
  16407. }
  16408. this.setRenderTarget = function ( renderTarget ) {
  16409. _currentRenderTarget = renderTarget;
  16410. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  16411. setupRenderTarget( renderTarget );
  16412. }
  16413. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  16414. var framebuffer;
  16415. if ( renderTarget ) {
  16416. var renderTargetProperties = properties.get( renderTarget );
  16417. if ( isCube ) {
  16418. framebuffer = renderTargetProperties.__webglFramebuffer[ renderTarget.activeCubeFace ];
  16419. } else {
  16420. framebuffer = renderTargetProperties.__webglFramebuffer;
  16421. }
  16422. _currentScissor.copy( renderTarget.scissor );
  16423. _currentScissorTest = renderTarget.scissorTest;
  16424. _currentViewport.copy( renderTarget.viewport );
  16425. } else {
  16426. framebuffer = null;
  16427. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio );
  16428. _currentScissorTest = _scissorTest;
  16429. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio );
  16430. }
  16431. if ( _currentFramebuffer !== framebuffer ) {
  16432. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  16433. _currentFramebuffer = framebuffer;
  16434. }
  16435. state.scissor( _currentScissor );
  16436. state.setScissorTest( _currentScissorTest );
  16437. state.viewport( _currentViewport );
  16438. if ( isCube ) {
  16439. var textureProperties = properties.get( renderTarget.texture );
  16440. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, renderTarget.activeMipMapLevel );
  16441. }
  16442. };
  16443. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) {
  16444. if ( renderTarget instanceof THREE.WebGLRenderTarget === false ) {
  16445. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  16446. return;
  16447. }
  16448. var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  16449. if ( framebuffer ) {
  16450. var restore = false;
  16451. if ( framebuffer !== _currentFramebuffer ) {
  16452. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  16453. restore = true;
  16454. }
  16455. try {
  16456. var texture = renderTarget.texture;
  16457. if ( texture.format !== THREE.RGBAFormat
  16458. && paramThreeToGL( texture.format ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  16459. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  16460. return;
  16461. }
  16462. if ( texture.type !== THREE.UnsignedByteType
  16463. && paramThreeToGL( texture.type ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE )
  16464. && ! ( texture.type === THREE.FloatType && extensions.get( 'WEBGL_color_buffer_float' ) )
  16465. && ! ( texture.type === THREE.HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) {
  16466. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  16467. return;
  16468. }
  16469. if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
  16470. _gl.readPixels( x, y, width, height, paramThreeToGL( texture.format ), paramThreeToGL( texture.type ), buffer );
  16471. } else {
  16472. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  16473. }
  16474. } finally {
  16475. if ( restore ) {
  16476. _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
  16477. }
  16478. }
  16479. }
  16480. };
  16481. function updateRenderTargetMipmap( renderTarget ) {
  16482. var target = renderTarget instanceof THREE.WebGLRenderTargetCube ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  16483. var texture = properties.get( renderTarget.texture ).__webglTexture;
  16484. state.bindTexture( target, texture );
  16485. _gl.generateMipmap( target );
  16486. state.bindTexture( target, null );
  16487. }
  16488. // Fallback filters for non-power-of-2 textures
  16489. function filterFallback ( f ) {
  16490. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  16491. return _gl.NEAREST;
  16492. }
  16493. return _gl.LINEAR;
  16494. }
  16495. // Map three.js constants to WebGL constants
  16496. function paramThreeToGL ( p ) {
  16497. var extension;
  16498. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  16499. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  16500. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  16501. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  16502. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  16503. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  16504. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  16505. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  16506. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  16507. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  16508. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  16509. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  16510. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  16511. if ( p === THREE.ByteType ) return _gl.BYTE;
  16512. if ( p === THREE.ShortType ) return _gl.SHORT;
  16513. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  16514. if ( p === THREE.IntType ) return _gl.INT;
  16515. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  16516. if ( p === THREE.FloatType ) return _gl.FLOAT;
  16517. extension = extensions.get( 'OES_texture_half_float' );
  16518. if ( extension !== null ) {
  16519. if ( p === THREE.HalfFloatType ) return extension.HALF_FLOAT_OES;
  16520. }
  16521. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  16522. if ( p === THREE.RGBFormat ) return _gl.RGB;
  16523. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  16524. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  16525. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  16526. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  16527. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  16528. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  16529. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  16530. if ( p === THREE.OneFactor ) return _gl.ONE;
  16531. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  16532. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  16533. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  16534. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  16535. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  16536. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  16537. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  16538. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  16539. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  16540. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  16541. if ( extension !== null ) {
  16542. if ( p === THREE.RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  16543. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  16544. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  16545. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  16546. }
  16547. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  16548. if ( extension !== null ) {
  16549. if ( p === THREE.RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  16550. if ( p === THREE.RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  16551. if ( p === THREE.RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  16552. if ( p === THREE.RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  16553. }
  16554. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  16555. if ( extension !== null ) {
  16556. if ( p === THREE.RGB_ETC1_Format ) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  16557. }
  16558. extension = extensions.get( 'EXT_blend_minmax' );
  16559. if ( extension !== null ) {
  16560. if ( p === THREE.MinEquation ) return extension.MIN_EXT;
  16561. if ( p === THREE.MaxEquation ) return extension.MAX_EXT;
  16562. }
  16563. return 0;
  16564. }
  16565. };
  16566. // File:src/renderers/WebGLRenderTarget.js
  16567. /**
  16568. * @author szimek / https://github.com/szimek/
  16569. * @author alteredq / http://alteredqualia.com/
  16570. * @author Marius Kintel / https://github.com/kintel
  16571. */
  16572. /*
  16573. In options, we can specify:
  16574. * Texture parameters for an auto-generated target texture
  16575. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  16576. */
  16577. THREE.WebGLRenderTarget = function ( width, height, options ) {
  16578. this.uuid = THREE.Math.generateUUID();
  16579. this.width = width;
  16580. this.height = height;
  16581. this.scissor = new THREE.Vector4( 0, 0, width, height );
  16582. this.scissorTest = false;
  16583. this.viewport = new THREE.Vector4( 0, 0, width, height );
  16584. options = options || {};
  16585. if ( options.minFilter === undefined ) options.minFilter = THREE.LinearFilter;
  16586. this.texture = new THREE.Texture( undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  16587. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  16588. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  16589. };
  16590. THREE.WebGLRenderTarget.prototype = {
  16591. constructor: THREE.WebGLRenderTarget,
  16592. setSize: function ( width, height ) {
  16593. if ( this.width !== width || this.height !== height ) {
  16594. this.width = width;
  16595. this.height = height;
  16596. this.dispose();
  16597. }
  16598. this.viewport.set( 0, 0, width, height );
  16599. this.scissor.set( 0, 0, width, height );
  16600. },
  16601. clone: function () {
  16602. return new this.constructor().copy( this );
  16603. },
  16604. copy: function ( source ) {
  16605. this.width = source.width;
  16606. this.height = source.height;
  16607. this.viewport.copy( source.viewport );
  16608. this.texture = source.texture.clone();
  16609. this.depthBuffer = source.depthBuffer;
  16610. this.stencilBuffer = source.stencilBuffer;
  16611. return this;
  16612. },
  16613. dispose: function () {
  16614. this.dispatchEvent( { type: 'dispose' } );
  16615. }
  16616. };
  16617. THREE.EventDispatcher.prototype.apply( THREE.WebGLRenderTarget.prototype );
  16618. // File:src/renderers/WebGLRenderTargetCube.js
  16619. /**
  16620. * @author alteredq / http://alteredqualia.com
  16621. */
  16622. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  16623. THREE.WebGLRenderTarget.call( this, width, height, options );
  16624. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  16625. this.activeMipMapLevel = 0;
  16626. };
  16627. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  16628. THREE.WebGLRenderTargetCube.prototype.constructor = THREE.WebGLRenderTargetCube;
  16629. // File:src/renderers/webgl/WebGLBufferRenderer.js
  16630. /**
  16631. * @author mrdoob / http://mrdoob.com/
  16632. */
  16633. THREE.WebGLBufferRenderer = function ( _gl, extensions, _infoRender ) {
  16634. var mode;
  16635. function setMode( value ) {
  16636. mode = value;
  16637. }
  16638. function render( start, count ) {
  16639. _gl.drawArrays( mode, start, count );
  16640. _infoRender.calls ++;
  16641. _infoRender.vertices += count;
  16642. if ( mode === _gl.TRIANGLES ) _infoRender.faces += count / 3;
  16643. }
  16644. function renderInstances( geometry ) {
  16645. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  16646. if ( extension === null ) {
  16647. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  16648. return;
  16649. }
  16650. var position = geometry.attributes.position;
  16651. var count = 0;
  16652. if ( position instanceof THREE.InterleavedBufferAttribute ) {
  16653. count = position.data.count;
  16654. extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount );
  16655. } else {
  16656. count = position.count;
  16657. extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount );
  16658. }
  16659. _infoRender.calls ++;
  16660. _infoRender.vertices += count * geometry.maxInstancedCount;
  16661. if ( mode === _gl.TRIANGLES ) _infoRender.faces += geometry.maxInstancedCount * count / 3;
  16662. }
  16663. this.setMode = setMode;
  16664. this.render = render;
  16665. this.renderInstances = renderInstances;
  16666. };
  16667. // File:src/renderers/webgl/WebGLIndexedBufferRenderer.js
  16668. /**
  16669. * @author mrdoob / http://mrdoob.com/
  16670. */
  16671. THREE.WebGLIndexedBufferRenderer = function ( _gl, extensions, _infoRender ) {
  16672. var mode;
  16673. function setMode( value ) {
  16674. mode = value;
  16675. }
  16676. var type, size;
  16677. function setIndex( index ) {
  16678. if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) {
  16679. type = _gl.UNSIGNED_INT;
  16680. size = 4;
  16681. } else {
  16682. type = _gl.UNSIGNED_SHORT;
  16683. size = 2;
  16684. }
  16685. }
  16686. function render( start, count ) {
  16687. _gl.drawElements( mode, count, type, start * size );
  16688. _infoRender.calls ++;
  16689. _infoRender.vertices += count;
  16690. if ( mode === _gl.TRIANGLES ) _infoRender.faces += count / 3;
  16691. }
  16692. function renderInstances( geometry, start, count ) {
  16693. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  16694. if ( extension === null ) {
  16695. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  16696. return;
  16697. }
  16698. extension.drawElementsInstancedANGLE( mode, count, type, start * size, geometry.maxInstancedCount );
  16699. _infoRender.calls ++;
  16700. _infoRender.vertices += count * geometry.maxInstancedCount;
  16701. if ( mode === _gl.TRIANGLES ) _infoRender.faces += geometry.maxInstancedCount * count / 3;
  16702. }
  16703. this.setMode = setMode;
  16704. this.setIndex = setIndex;
  16705. this.render = render;
  16706. this.renderInstances = renderInstances;
  16707. };
  16708. // File:src/renderers/webgl/WebGLExtensions.js
  16709. /**
  16710. * @author mrdoob / http://mrdoob.com/
  16711. */
  16712. THREE.WebGLExtensions = function ( gl ) {
  16713. var extensions = {};
  16714. this.get = function ( name ) {
  16715. if ( extensions[ name ] !== undefined ) {
  16716. return extensions[ name ];
  16717. }
  16718. var extension;
  16719. switch ( name ) {
  16720. case 'EXT_texture_filter_anisotropic':
  16721. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  16722. break;
  16723. case 'WEBGL_compressed_texture_s3tc':
  16724. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  16725. break;
  16726. case 'WEBGL_compressed_texture_pvrtc':
  16727. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  16728. break;
  16729. case 'WEBGL_compressed_texture_etc1':
  16730. extension = gl.getExtension( 'WEBGL_compressed_texture_etc1' );
  16731. break;
  16732. default:
  16733. extension = gl.getExtension( name );
  16734. }
  16735. if ( extension === null ) {
  16736. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  16737. }
  16738. extensions[ name ] = extension;
  16739. return extension;
  16740. };
  16741. };
  16742. // File:src/renderers/webgl/WebGLCapabilities.js
  16743. THREE.WebGLCapabilities = function ( gl, extensions, parameters ) {
  16744. function getMaxPrecision( precision ) {
  16745. if ( precision === 'highp' ) {
  16746. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  16747. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  16748. return 'highp';
  16749. }
  16750. precision = 'mediump';
  16751. }
  16752. if ( precision === 'mediump' ) {
  16753. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  16754. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  16755. return 'mediump';
  16756. }
  16757. }
  16758. return 'lowp';
  16759. }
  16760. this.getMaxPrecision = getMaxPrecision;
  16761. this.precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  16762. this.logarithmicDepthBuffer = parameters.logarithmicDepthBuffer !== undefined ? parameters.logarithmicDepthBuffer : false;
  16763. this.maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  16764. this.maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  16765. this.maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  16766. this.maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  16767. this.maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  16768. this.maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  16769. this.maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  16770. this.maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  16771. this.vertexTextures = this.maxVertexTextures > 0;
  16772. this.floatFragmentTextures = !! extensions.get( 'OES_texture_float' );
  16773. this.floatVertexTextures = this.vertexTextures && this.floatFragmentTextures;
  16774. var _maxPrecision = getMaxPrecision( this.precision );
  16775. if ( _maxPrecision !== this.precision ) {
  16776. console.warn( 'THREE.WebGLRenderer:', this.precision, 'not supported, using', _maxPrecision, 'instead.' );
  16777. this.precision = _maxPrecision;
  16778. }
  16779. if ( this.logarithmicDepthBuffer ) {
  16780. this.logarithmicDepthBuffer = !! extensions.get( 'EXT_frag_depth' );
  16781. }
  16782. };
  16783. // File:src/renderers/webgl/WebGLGeometries.js
  16784. /**
  16785. * @author mrdoob / http://mrdoob.com/
  16786. */
  16787. THREE.WebGLGeometries = function ( gl, properties, info ) {
  16788. var geometries = {};
  16789. function get( object ) {
  16790. var geometry = object.geometry;
  16791. if ( geometries[ geometry.id ] !== undefined ) {
  16792. return geometries[ geometry.id ];
  16793. }
  16794. geometry.addEventListener( 'dispose', onGeometryDispose );
  16795. var buffergeometry;
  16796. if ( geometry instanceof THREE.BufferGeometry ) {
  16797. buffergeometry = geometry;
  16798. } else if ( geometry instanceof THREE.Geometry ) {
  16799. if ( geometry._bufferGeometry === undefined ) {
  16800. geometry._bufferGeometry = new THREE.BufferGeometry().setFromObject( object );
  16801. }
  16802. buffergeometry = geometry._bufferGeometry;
  16803. }
  16804. geometries[ geometry.id ] = buffergeometry;
  16805. info.memory.geometries ++;
  16806. return buffergeometry;
  16807. }
  16808. function onGeometryDispose( event ) {
  16809. var geometry = event.target;
  16810. var buffergeometry = geometries[ geometry.id ];
  16811. if ( buffergeometry.index !== null ) {
  16812. deleteAttribute( buffergeometry.index );
  16813. }
  16814. deleteAttributes( buffergeometry.attributes );
  16815. geometry.removeEventListener( 'dispose', onGeometryDispose );
  16816. delete geometries[ geometry.id ];
  16817. // TODO
  16818. var property = properties.get( geometry );
  16819. if ( property.wireframe ) {
  16820. deleteAttribute( property.wireframe );
  16821. }
  16822. properties.delete( geometry );
  16823. var bufferproperty = properties.get( buffergeometry );
  16824. if ( bufferproperty.wireframe ) {
  16825. deleteAttribute( bufferproperty.wireframe );
  16826. }
  16827. properties.delete( buffergeometry );
  16828. //
  16829. info.memory.geometries --;
  16830. }
  16831. function getAttributeBuffer( attribute ) {
  16832. if ( attribute instanceof THREE.InterleavedBufferAttribute ) {
  16833. return properties.get( attribute.data ).__webglBuffer;
  16834. }
  16835. return properties.get( attribute ).__webglBuffer;
  16836. }
  16837. function deleteAttribute( attribute ) {
  16838. var buffer = getAttributeBuffer( attribute );
  16839. if ( buffer !== undefined ) {
  16840. gl.deleteBuffer( buffer );
  16841. removeAttributeBuffer( attribute );
  16842. }
  16843. }
  16844. function deleteAttributes( attributes ) {
  16845. for ( var name in attributes ) {
  16846. deleteAttribute( attributes[ name ] );
  16847. }
  16848. }
  16849. function removeAttributeBuffer( attribute ) {
  16850. if ( attribute instanceof THREE.InterleavedBufferAttribute ) {
  16851. properties.delete( attribute.data );
  16852. } else {
  16853. properties.delete( attribute );
  16854. }
  16855. }
  16856. this.get = get;
  16857. };
  16858. // File:src/renderers/webgl/WebGLLights.js
  16859. /**
  16860. * @author mrdoob / http://mrdoob.com/
  16861. */
  16862. THREE.WebGLLights = function () {
  16863. var lights = {};
  16864. this.get = function ( light ) {
  16865. if ( lights[ light.id ] !== undefined ) {
  16866. return lights[ light.id ];
  16867. }
  16868. var uniforms;
  16869. switch ( light.type ) {
  16870. case 'DirectionalLight':
  16871. uniforms = {
  16872. direction: new THREE.Vector3(),
  16873. color: new THREE.Color(),
  16874. shadow: false,
  16875. shadowBias: 0,
  16876. shadowRadius: 1,
  16877. shadowMapSize: new THREE.Vector2()
  16878. };
  16879. break;
  16880. case 'SpotLight':
  16881. uniforms = {
  16882. position: new THREE.Vector3(),
  16883. direction: new THREE.Vector3(),
  16884. color: new THREE.Color(),
  16885. distance: 0,
  16886. coneCos: 0,
  16887. penumbraCos: 0,
  16888. decay: 0,
  16889. shadow: false,
  16890. shadowBias: 0,
  16891. shadowRadius: 1,
  16892. shadowMapSize: new THREE.Vector2()
  16893. };
  16894. break;
  16895. case 'PointLight':
  16896. uniforms = {
  16897. position: new THREE.Vector3(),
  16898. color: new THREE.Color(),
  16899. distance: 0,
  16900. decay: 0,
  16901. shadow: false,
  16902. shadowBias: 0,
  16903. shadowRadius: 1,
  16904. shadowMapSize: new THREE.Vector2()
  16905. };
  16906. break;
  16907. case 'HemisphereLight':
  16908. uniforms = {
  16909. direction: new THREE.Vector3(),
  16910. skyColor: new THREE.Color(),
  16911. groundColor: new THREE.Color()
  16912. };
  16913. break;
  16914. }
  16915. lights[ light.id ] = uniforms;
  16916. return uniforms;
  16917. };
  16918. };
  16919. // File:src/renderers/webgl/WebGLObjects.js
  16920. /**
  16921. * @author mrdoob / http://mrdoob.com/
  16922. */
  16923. THREE.WebGLObjects = function ( gl, properties, info ) {
  16924. var geometries = new THREE.WebGLGeometries( gl, properties, info );
  16925. //
  16926. function update( object ) {
  16927. // TODO: Avoid updating twice (when using shadowMap). Maybe add frame counter.
  16928. var geometry = geometries.get( object );
  16929. if ( object.geometry instanceof THREE.Geometry ) {
  16930. geometry.updateFromObject( object );
  16931. }
  16932. var index = geometry.index;
  16933. var attributes = geometry.attributes;
  16934. if ( index !== null ) {
  16935. updateAttribute( index, gl.ELEMENT_ARRAY_BUFFER );
  16936. }
  16937. for ( var name in attributes ) {
  16938. updateAttribute( attributes[ name ], gl.ARRAY_BUFFER );
  16939. }
  16940. // morph targets
  16941. var morphAttributes = geometry.morphAttributes;
  16942. for ( var name in morphAttributes ) {
  16943. var array = morphAttributes[ name ];
  16944. for ( var i = 0, l = array.length; i < l; i ++ ) {
  16945. updateAttribute( array[ i ], gl.ARRAY_BUFFER );
  16946. }
  16947. }
  16948. return geometry;
  16949. }
  16950. function updateAttribute( attribute, bufferType ) {
  16951. var data = ( attribute instanceof THREE.InterleavedBufferAttribute ) ? attribute.data : attribute;
  16952. var attributeProperties = properties.get( data );
  16953. if ( attributeProperties.__webglBuffer === undefined ) {
  16954. createBuffer( attributeProperties, data, bufferType );
  16955. } else if ( attributeProperties.version !== data.version ) {
  16956. updateBuffer( attributeProperties, data, bufferType );
  16957. }
  16958. }
  16959. function createBuffer( attributeProperties, data, bufferType ) {
  16960. attributeProperties.__webglBuffer = gl.createBuffer();
  16961. gl.bindBuffer( bufferType, attributeProperties.__webglBuffer );
  16962. var usage = data.dynamic ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW;
  16963. gl.bufferData( bufferType, data.array, usage );
  16964. attributeProperties.version = data.version;
  16965. }
  16966. function updateBuffer( attributeProperties, data, bufferType ) {
  16967. gl.bindBuffer( bufferType, attributeProperties.__webglBuffer );
  16968. if ( data.dynamic === false || data.updateRange.count === - 1 ) {
  16969. // Not using update ranges
  16970. gl.bufferSubData( bufferType, 0, data.array );
  16971. } else if ( data.updateRange.count === 0 ) {
  16972. 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.' );
  16973. } else {
  16974. gl.bufferSubData( bufferType, data.updateRange.offset * data.array.BYTES_PER_ELEMENT,
  16975. data.array.subarray( data.updateRange.offset, data.updateRange.offset + data.updateRange.count ) );
  16976. data.updateRange.count = 0; // reset range
  16977. }
  16978. attributeProperties.version = data.version;
  16979. }
  16980. function getAttributeBuffer( attribute ) {
  16981. if ( attribute instanceof THREE.InterleavedBufferAttribute ) {
  16982. return properties.get( attribute.data ).__webglBuffer;
  16983. }
  16984. return properties.get( attribute ).__webglBuffer;
  16985. }
  16986. function getWireframeAttribute( geometry ) {
  16987. var property = properties.get( geometry );
  16988. if ( property.wireframe !== undefined ) {
  16989. return property.wireframe;
  16990. }
  16991. var indices = [];
  16992. var index = geometry.index;
  16993. var attributes = geometry.attributes;
  16994. var position = attributes.position;
  16995. // console.time( 'wireframe' );
  16996. if ( index !== null ) {
  16997. var edges = {};
  16998. var array = index.array;
  16999. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  17000. var a = array[ i + 0 ];
  17001. var b = array[ i + 1 ];
  17002. var c = array[ i + 2 ];
  17003. if ( checkEdge( edges, a, b ) ) indices.push( a, b );
  17004. if ( checkEdge( edges, b, c ) ) indices.push( b, c );
  17005. if ( checkEdge( edges, c, a ) ) indices.push( c, a );
  17006. }
  17007. } else {
  17008. var array = attributes.position.array;
  17009. for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  17010. var a = i + 0;
  17011. var b = i + 1;
  17012. var c = i + 2;
  17013. indices.push( a, b, b, c, c, a );
  17014. }
  17015. }
  17016. // console.timeEnd( 'wireframe' );
  17017. var TypeArray = position.count > 65535 ? Uint32Array : Uint16Array;
  17018. var attribute = new THREE.BufferAttribute( new TypeArray( indices ), 1 );
  17019. updateAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  17020. property.wireframe = attribute;
  17021. return attribute;
  17022. }
  17023. function checkEdge( edges, a, b ) {
  17024. if ( a > b ) {
  17025. var tmp = a;
  17026. a = b;
  17027. b = tmp;
  17028. }
  17029. var list = edges[ a ];
  17030. if ( list === undefined ) {
  17031. edges[ a ] = [ b ];
  17032. return true;
  17033. } else if ( list.indexOf( b ) === -1 ) {
  17034. list.push( b );
  17035. return true;
  17036. }
  17037. return false;
  17038. }
  17039. this.getAttributeBuffer = getAttributeBuffer;
  17040. this.getWireframeAttribute = getWireframeAttribute;
  17041. this.update = update;
  17042. };
  17043. // File:src/renderers/webgl/WebGLProgram.js
  17044. THREE.WebGLProgram = ( function () {
  17045. var programIdCount = 0;
  17046. // TODO: Combine the regex
  17047. var structRe = /^([\w\d_]+)\.([\w\d_]+)$/;
  17048. var arrayStructRe = /^([\w\d_]+)\[(\d+)\]\.([\w\d_]+)$/;
  17049. var arrayRe = /^([\w\d_]+)\[0\]$/;
  17050. function getEncodingComponents( encoding ) {
  17051. switch ( encoding ) {
  17052. case THREE.LinearEncoding:
  17053. return [ 'Linear','( value )' ];
  17054. case THREE.sRGBEncoding:
  17055. return [ 'sRGB','( value )' ];
  17056. case THREE.RGBEEncoding:
  17057. return [ 'RGBE','( value )' ];
  17058. case THREE.RGBM7Encoding:
  17059. return [ 'RGBM','( value, 7.0 )' ];
  17060. case THREE.RGBM16Encoding:
  17061. return [ 'RGBM','( value, 16.0 )' ];
  17062. case THREE.RGBDEncoding:
  17063. return [ 'RGBD','( value, 256.0 )' ];
  17064. case THREE.GammaEncoding:
  17065. return [ 'Gamma','( value, float( GAMMA_FACTOR ) )' ];
  17066. default:
  17067. throw new Error( 'unsupported encoding: ' + encoding );
  17068. }
  17069. }
  17070. function getTexelDecodingFunction( functionName, encoding ) {
  17071. var components = getEncodingComponents( encoding );
  17072. return "vec4 " + functionName + "( vec4 value ) { return " + components[ 0 ] + "ToLinear" + components[ 1 ] + "; }";
  17073. }
  17074. function getTexelEncodingFunction( functionName, encoding ) {
  17075. var components = getEncodingComponents( encoding );
  17076. return "vec4 " + functionName + "( vec4 value ) { return LinearTo" + components[ 0 ] + components[ 1 ] + "; }";
  17077. }
  17078. function getToneMappingFunction( functionName, toneMapping ) {
  17079. var toneMappingName;
  17080. switch ( toneMapping ) {
  17081. case THREE.LinearToneMapping:
  17082. toneMappingName = "Linear";
  17083. break;
  17084. case THREE.ReinhardToneMapping:
  17085. toneMappingName = "Reinhard";
  17086. break;
  17087. case THREE.Uncharted2ToneMapping:
  17088. toneMappingName = "Uncharted2";
  17089. break;
  17090. case THREE.CineonToneMapping:
  17091. toneMappingName = "OptimizedCineon";
  17092. break;
  17093. default:
  17094. throw new Error( 'unsupported toneMapping: ' + toneMapping );
  17095. }
  17096. return "vec3 " + functionName + "( vec3 color ) { return " + toneMappingName + "ToneMapping( color ); }";
  17097. }
  17098. function generateExtensions( extensions, parameters, rendererExtensions ) {
  17099. extensions = extensions || {};
  17100. var chunks = [
  17101. ( extensions.derivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.normalMap || parameters.flatShading ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  17102. ( extensions.fragDepth || parameters.logarithmicDepthBuffer ) && rendererExtensions.get( 'EXT_frag_depth' ) ? '#extension GL_EXT_frag_depth : enable' : '',
  17103. ( extensions.drawBuffers ) && rendererExtensions.get( 'WEBGL_draw_buffers' ) ? '#extension GL_EXT_draw_buffers : require' : '',
  17104. ( extensions.shaderTextureLOD || parameters.envMap ) && rendererExtensions.get( 'EXT_shader_texture_lod' ) ? '#extension GL_EXT_shader_texture_lod : enable' : '',
  17105. ];
  17106. return chunks.filter( filterEmptyLine ).join( '\n' );
  17107. }
  17108. function generateDefines( defines ) {
  17109. var chunks = [];
  17110. for ( var name in defines ) {
  17111. var value = defines[ name ];
  17112. if ( value === false ) continue;
  17113. chunks.push( '#define ' + name + ' ' + value );
  17114. }
  17115. return chunks.join( '\n' );
  17116. }
  17117. function fetchUniformLocations( gl, program, identifiers ) {
  17118. var uniforms = {};
  17119. var n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  17120. for ( var i = 0; i < n; i ++ ) {
  17121. var info = gl.getActiveUniform( program, i );
  17122. var name = info.name;
  17123. var location = gl.getUniformLocation( program, name );
  17124. //console.log("THREE.WebGLProgram: ACTIVE UNIFORM:", name);
  17125. var matches = structRe.exec( name );
  17126. if ( matches ) {
  17127. var structName = matches[ 1 ];
  17128. var structProperty = matches[ 2 ];
  17129. var uniformsStruct = uniforms[ structName ];
  17130. if ( ! uniformsStruct ) {
  17131. uniformsStruct = uniforms[ structName ] = {};
  17132. }
  17133. uniformsStruct[ structProperty ] = location;
  17134. continue;
  17135. }
  17136. matches = arrayStructRe.exec( name );
  17137. if ( matches ) {
  17138. var arrayName = matches[ 1 ];
  17139. var arrayIndex = matches[ 2 ];
  17140. var arrayProperty = matches[ 3 ];
  17141. var uniformsArray = uniforms[ arrayName ];
  17142. if ( ! uniformsArray ) {
  17143. uniformsArray = uniforms[ arrayName ] = [];
  17144. }
  17145. var uniformsArrayIndex = uniformsArray[ arrayIndex ];
  17146. if ( ! uniformsArrayIndex ) {
  17147. uniformsArrayIndex = uniformsArray[ arrayIndex ] = {};
  17148. }
  17149. uniformsArrayIndex[ arrayProperty ] = location;
  17150. continue;
  17151. }
  17152. matches = arrayRe.exec( name );
  17153. if ( matches ) {
  17154. var arrayName = matches[ 1 ];
  17155. uniforms[ arrayName ] = location;
  17156. continue;
  17157. }
  17158. uniforms[ name ] = location;
  17159. }
  17160. return uniforms;
  17161. }
  17162. function fetchAttributeLocations( gl, program, identifiers ) {
  17163. var attributes = {};
  17164. var n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  17165. for ( var i = 0; i < n; i ++ ) {
  17166. var info = gl.getActiveAttrib( program, i );
  17167. var name = info.name;
  17168. // console.log("THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:", name, i );
  17169. attributes[ name ] = gl.getAttribLocation( program, name );
  17170. }
  17171. return attributes;
  17172. }
  17173. function filterEmptyLine( string ) {
  17174. return string !== '';
  17175. }
  17176. function replaceLightNums( string, parameters ) {
  17177. return string
  17178. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  17179. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  17180. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  17181. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights );
  17182. }
  17183. function parseIncludes( string ) {
  17184. var pattern = /#include +<([\w\d.]+)>/g;
  17185. function replace( match, include ) {
  17186. var replace = THREE.ShaderChunk[ include ];
  17187. if ( replace === undefined ) {
  17188. throw new Error( 'Can not resolve #include <' + include + '>' );
  17189. }
  17190. return parseIncludes( replace );
  17191. }
  17192. return string.replace( pattern, replace );
  17193. }
  17194. function unrollLoops( string ) {
  17195. var pattern = /for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  17196. function replace( match, start, end, snippet ) {
  17197. var unroll = '';
  17198. for ( var i = parseInt( start ); i < parseInt( end ); i ++ ) {
  17199. unroll += snippet.replace( /\[ i \]/g, '[ ' + i + ' ]' );
  17200. }
  17201. return unroll;
  17202. }
  17203. return string.replace( pattern, replace );
  17204. }
  17205. return function WebGLProgram( renderer, code, material, parameters ) {
  17206. var gl = renderer.context;
  17207. var extensions = material.extensions;
  17208. var defines = material.defines;
  17209. var vertexShader = material.__webglShader.vertexShader;
  17210. var fragmentShader = material.__webglShader.fragmentShader;
  17211. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  17212. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  17213. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  17214. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  17215. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  17216. }
  17217. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  17218. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  17219. var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  17220. if ( parameters.envMap ) {
  17221. switch ( material.envMap.mapping ) {
  17222. case THREE.CubeReflectionMapping:
  17223. case THREE.CubeRefractionMapping:
  17224. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  17225. break;
  17226. case THREE.CubeUVReflectionMapping:
  17227. case THREE.CubeUVRefractionMapping:
  17228. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  17229. break;
  17230. case THREE.EquirectangularReflectionMapping:
  17231. case THREE.EquirectangularRefractionMapping:
  17232. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  17233. break;
  17234. case THREE.SphericalReflectionMapping:
  17235. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  17236. break;
  17237. }
  17238. switch ( material.envMap.mapping ) {
  17239. case THREE.CubeRefractionMapping:
  17240. case THREE.EquirectangularRefractionMapping:
  17241. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  17242. break;
  17243. }
  17244. switch ( material.combine ) {
  17245. case THREE.MultiplyOperation:
  17246. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  17247. break;
  17248. case THREE.MixOperation:
  17249. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  17250. break;
  17251. case THREE.AddOperation:
  17252. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  17253. break;
  17254. }
  17255. }
  17256. var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  17257. // console.log( 'building new program ' );
  17258. //
  17259. var customExtensions = generateExtensions( extensions, parameters, renderer.extensions );
  17260. var customDefines = generateDefines( defines );
  17261. //
  17262. var program = gl.createProgram();
  17263. var prefixVertex, prefixFragment;
  17264. if ( material instanceof THREE.RawShaderMaterial ) {
  17265. prefixVertex = '';
  17266. prefixFragment = '';
  17267. } else {
  17268. prefixVertex = [
  17269. 'precision ' + parameters.precision + ' float;',
  17270. 'precision ' + parameters.precision + ' int;',
  17271. '#define SHADER_NAME ' + material.__webglShader.name,
  17272. customDefines,
  17273. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  17274. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  17275. '#define MAX_BONES ' + parameters.maxBones,
  17276. parameters.map ? '#define USE_MAP' : '',
  17277. parameters.envMap ? '#define USE_ENVMAP' : '',
  17278. parameters.envMap ? '#define ' + envMapModeDefine : '',
  17279. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  17280. parameters.aoMap ? '#define USE_AOMAP' : '',
  17281. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  17282. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  17283. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  17284. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  17285. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  17286. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  17287. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  17288. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  17289. parameters.vertexColors ? '#define USE_COLOR' : '',
  17290. parameters.flatShading ? '#define FLAT_SHADED' : '',
  17291. parameters.skinning ? '#define USE_SKINNING' : '',
  17292. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  17293. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  17294. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  17295. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  17296. parameters.flipSided ? '#define FLIP_SIDED' : '',
  17297. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  17298. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  17299. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  17300. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  17301. parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  17302. 'uniform mat4 modelMatrix;',
  17303. 'uniform mat4 modelViewMatrix;',
  17304. 'uniform mat4 projectionMatrix;',
  17305. 'uniform mat4 viewMatrix;',
  17306. 'uniform mat3 normalMatrix;',
  17307. 'uniform vec3 cameraPosition;',
  17308. 'attribute vec3 position;',
  17309. 'attribute vec3 normal;',
  17310. 'attribute vec2 uv;',
  17311. '#ifdef USE_COLOR',
  17312. ' attribute vec3 color;',
  17313. '#endif',
  17314. '#ifdef USE_MORPHTARGETS',
  17315. ' attribute vec3 morphTarget0;',
  17316. ' attribute vec3 morphTarget1;',
  17317. ' attribute vec3 morphTarget2;',
  17318. ' attribute vec3 morphTarget3;',
  17319. ' #ifdef USE_MORPHNORMALS',
  17320. ' attribute vec3 morphNormal0;',
  17321. ' attribute vec3 morphNormal1;',
  17322. ' attribute vec3 morphNormal2;',
  17323. ' attribute vec3 morphNormal3;',
  17324. ' #else',
  17325. ' attribute vec3 morphTarget4;',
  17326. ' attribute vec3 morphTarget5;',
  17327. ' attribute vec3 morphTarget6;',
  17328. ' attribute vec3 morphTarget7;',
  17329. ' #endif',
  17330. '#endif',
  17331. '#ifdef USE_SKINNING',
  17332. ' attribute vec4 skinIndex;',
  17333. ' attribute vec4 skinWeight;',
  17334. '#endif',
  17335. '\n'
  17336. ].filter( filterEmptyLine ).join( '\n' );
  17337. prefixFragment = [
  17338. customExtensions,
  17339. 'precision ' + parameters.precision + ' float;',
  17340. 'precision ' + parameters.precision + ' int;',
  17341. '#define SHADER_NAME ' + material.__webglShader.name,
  17342. customDefines,
  17343. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest : '',
  17344. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  17345. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  17346. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  17347. parameters.map ? '#define USE_MAP' : '',
  17348. parameters.envMap ? '#define USE_ENVMAP' : '',
  17349. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  17350. parameters.envMap ? '#define ' + envMapModeDefine : '',
  17351. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  17352. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  17353. parameters.aoMap ? '#define USE_AOMAP' : '',
  17354. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  17355. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  17356. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  17357. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  17358. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  17359. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  17360. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  17361. parameters.vertexColors ? '#define USE_COLOR' : '',
  17362. parameters.flatShading ? '#define FLAT_SHADED' : '',
  17363. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  17364. parameters.flipSided ? '#define FLIP_SIDED' : '',
  17365. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  17366. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  17367. parameters.premultipliedAlpha ? "#define PREMULTIPLIED_ALPHA" : '',
  17368. parameters.physicallyCorrectLights ? "#define PHYSICALLY_CORRECT_LIGHTS" : '',
  17369. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  17370. parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  17371. parameters.envMap && renderer.extensions.get( 'EXT_shader_texture_lod' ) ? '#define TEXTURE_LOD_EXT' : '',
  17372. 'uniform mat4 viewMatrix;',
  17373. 'uniform vec3 cameraPosition;',
  17374. ( parameters.toneMapping !== THREE.NoToneMapping ) ? "#define TONE_MAPPING" : '',
  17375. ( parameters.toneMapping !== THREE.NoToneMapping ) ? THREE.ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  17376. ( parameters.toneMapping !== THREE.NoToneMapping ) ? getToneMappingFunction( "toneMapping", parameters.toneMapping ) : '',
  17377. ( 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
  17378. parameters.mapEncoding ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '',
  17379. parameters.envMapEncoding ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '',
  17380. parameters.emissiveMapEncoding ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '',
  17381. parameters.outputEncoding ? getTexelEncodingFunction( "linearToOutputTexel", parameters.outputEncoding ) : '',
  17382. '\n'
  17383. ].filter( filterEmptyLine ).join( '\n' );
  17384. }
  17385. vertexShader = parseIncludes( vertexShader, parameters );
  17386. vertexShader = replaceLightNums( vertexShader, parameters );
  17387. fragmentShader = parseIncludes( fragmentShader, parameters );
  17388. fragmentShader = replaceLightNums( fragmentShader, parameters );
  17389. if ( material instanceof THREE.ShaderMaterial === false ) {
  17390. vertexShader = unrollLoops( vertexShader );
  17391. fragmentShader = unrollLoops( fragmentShader );
  17392. }
  17393. var vertexGlsl = prefixVertex + vertexShader;
  17394. var fragmentGlsl = prefixFragment + fragmentShader;
  17395. // console.log( '*VERTEX*', vertexGlsl );
  17396. // console.log( '*FRAGMENT*', fragmentGlsl );
  17397. var glVertexShader = THREE.WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  17398. var glFragmentShader = THREE.WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  17399. gl.attachShader( program, glVertexShader );
  17400. gl.attachShader( program, glFragmentShader );
  17401. // Force a particular attribute to index 0.
  17402. if ( material.index0AttributeName !== undefined ) {
  17403. gl.bindAttribLocation( program, 0, material.index0AttributeName );
  17404. } else if ( parameters.morphTargets === true ) {
  17405. // programs with morphTargets displace position out of attribute 0
  17406. gl.bindAttribLocation( program, 0, 'position' );
  17407. }
  17408. gl.linkProgram( program );
  17409. var programLog = gl.getProgramInfoLog( program );
  17410. var vertexLog = gl.getShaderInfoLog( glVertexShader );
  17411. var fragmentLog = gl.getShaderInfoLog( glFragmentShader );
  17412. var runnable = true;
  17413. var haveDiagnostics = true;
  17414. // console.log( '**VERTEX**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glVertexShader ) );
  17415. // console.log( '**FRAGMENT**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glFragmentShader ) );
  17416. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  17417. runnable = false;
  17418. console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), 'gl.VALIDATE_STATUS', gl.getProgramParameter( program, gl.VALIDATE_STATUS ), 'gl.getProgramInfoLog', programLog, vertexLog, fragmentLog );
  17419. } else if ( programLog !== '' ) {
  17420. console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog );
  17421. } else if ( vertexLog === '' || fragmentLog === '' ) {
  17422. haveDiagnostics = false;
  17423. }
  17424. if ( haveDiagnostics ) {
  17425. this.diagnostics = {
  17426. runnable: runnable,
  17427. material: material,
  17428. programLog: programLog,
  17429. vertexShader: {
  17430. log: vertexLog,
  17431. prefix: prefixVertex
  17432. },
  17433. fragmentShader: {
  17434. log: fragmentLog,
  17435. prefix: prefixFragment
  17436. }
  17437. };
  17438. }
  17439. // clean up
  17440. gl.deleteShader( glVertexShader );
  17441. gl.deleteShader( glFragmentShader );
  17442. // set up caching for uniform locations
  17443. var cachedUniforms;
  17444. this.getUniforms = function() {
  17445. if ( cachedUniforms === undefined ) {
  17446. cachedUniforms = fetchUniformLocations( gl, program );
  17447. }
  17448. return cachedUniforms;
  17449. };
  17450. // set up caching for attribute locations
  17451. var cachedAttributes;
  17452. this.getAttributes = function() {
  17453. if ( cachedAttributes === undefined ) {
  17454. cachedAttributes = fetchAttributeLocations( gl, program );
  17455. }
  17456. return cachedAttributes;
  17457. };
  17458. // free resource
  17459. this.destroy = function() {
  17460. gl.deleteProgram( program );
  17461. this.program = undefined;
  17462. };
  17463. // DEPRECATED
  17464. Object.defineProperties( this, {
  17465. uniforms: {
  17466. get: function() {
  17467. console.warn( 'THREE.WebGLProgram: .uniforms is now .getUniforms().' );
  17468. return this.getUniforms();
  17469. }
  17470. },
  17471. attributes: {
  17472. get: function() {
  17473. console.warn( 'THREE.WebGLProgram: .attributes is now .getAttributes().' );
  17474. return this.getAttributes();
  17475. }
  17476. }
  17477. } );
  17478. //
  17479. this.id = programIdCount ++;
  17480. this.code = code;
  17481. this.usedTimes = 1;
  17482. this.program = program;
  17483. this.vertexShader = glVertexShader;
  17484. this.fragmentShader = glFragmentShader;
  17485. return this;
  17486. };
  17487. } )();
  17488. // File:src/renderers/webgl/WebGLPrograms.js
  17489. THREE.WebGLPrograms = function ( renderer, capabilities ) {
  17490. var programs = [];
  17491. var shaderIDs = {
  17492. MeshDepthMaterial: 'depth',
  17493. MeshNormalMaterial: 'normal',
  17494. MeshBasicMaterial: 'basic',
  17495. MeshLambertMaterial: 'lambert',
  17496. MeshPhongMaterial: 'phong',
  17497. MeshStandardMaterial: 'standard',
  17498. LineBasicMaterial: 'basic',
  17499. LineDashedMaterial: 'dashed',
  17500. PointsMaterial: 'points'
  17501. };
  17502. var parameterNames = [
  17503. "precision", "supportsVertexTextures", "map", "mapEncoding", "envMap", "envMapMode", "envMapEncoding",
  17504. "lightMap", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "displacementMap", "specularMap",
  17505. "roughnessMap", "metalnessMap",
  17506. "alphaMap", "combine", "vertexColors", "fog", "useFog", "fogExp",
  17507. "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning",
  17508. "maxBones", "useVertexTexture", "morphTargets", "morphNormals",
  17509. "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha",
  17510. "numDirLights", "numPointLights", "numSpotLights", "numHemiLights",
  17511. "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights',
  17512. "alphaTest", "doubleSided", "flipSided"
  17513. ];
  17514. function allocateBones ( object ) {
  17515. if ( capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture ) {
  17516. return 1024;
  17517. } else {
  17518. // default for when object is not specified
  17519. // ( for example when prebuilding shader to be used with multiple objects )
  17520. //
  17521. // - leave some extra space for other uniforms
  17522. // - limit here is ANGLE's 254 max uniform vectors
  17523. // (up to 54 should be safe)
  17524. var nVertexUniforms = capabilities.maxVertexUniforms;
  17525. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  17526. var maxBones = nVertexMatrices;
  17527. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  17528. maxBones = Math.min( object.skeleton.bones.length, maxBones );
  17529. if ( maxBones < object.skeleton.bones.length ) {
  17530. console.warn( 'WebGLRenderer: too many bones - ' + object.skeleton.bones.length + ', this GPU supports just ' + maxBones + ' (try OpenGL instead of ANGLE)' );
  17531. }
  17532. }
  17533. return maxBones;
  17534. }
  17535. }
  17536. function getTextureEncodingFromMap( map, gammaOverrideLinear ) {
  17537. var encoding;
  17538. if ( ! map ) {
  17539. encoding = THREE.LinearEncoding;
  17540. } else if ( map instanceof THREE.Texture ) {
  17541. encoding = map.encoding;
  17542. } else if ( map instanceof THREE.WebGLRenderTarget ) {
  17543. encoding = map.texture.encoding;
  17544. }
  17545. // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point.
  17546. if ( encoding === THREE.LinearEncoding && gammaOverrideLinear ) {
  17547. encoding = THREE.GammaEncoding;
  17548. }
  17549. return encoding;
  17550. }
  17551. this.getParameters = function ( material, lights, fog, object ) {
  17552. var shaderID = shaderIDs[ material.type ];
  17553. // heuristics to create shader parameters according to lights in the scene
  17554. // (not to blow over maxLights budget)
  17555. var maxBones = allocateBones( object );
  17556. var precision = renderer.getPrecision();
  17557. if ( material.precision !== null ) {
  17558. precision = capabilities.getMaxPrecision( material.precision );
  17559. if ( precision !== material.precision ) {
  17560. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  17561. }
  17562. }
  17563. var parameters = {
  17564. shaderID: shaderID,
  17565. precision: precision,
  17566. supportsVertexTextures: capabilities.vertexTextures,
  17567. outputEncoding: getTextureEncodingFromMap( renderer.getCurrentRenderTarget(), renderer.gammaOutput ),
  17568. map: !! material.map,
  17569. mapEncoding: getTextureEncodingFromMap( material.map, renderer.gammaInput ),
  17570. envMap: !! material.envMap,
  17571. envMapMode: material.envMap && material.envMap.mapping,
  17572. envMapEncoding: getTextureEncodingFromMap( material.envMap, renderer.gammaInput ),
  17573. envMapCubeUV: ( !! material.envMap ) && ( ( material.envMap.mapping === THREE.CubeUVReflectionMapping ) || ( material.envMap.mapping === THREE.CubeUVRefractionMapping ) ),
  17574. lightMap: !! material.lightMap,
  17575. aoMap: !! material.aoMap,
  17576. emissiveMap: !! material.emissiveMap,
  17577. emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap, renderer.gammaInput ),
  17578. bumpMap: !! material.bumpMap,
  17579. normalMap: !! material.normalMap,
  17580. displacementMap: !! material.displacementMap,
  17581. roughnessMap: !! material.roughnessMap,
  17582. metalnessMap: !! material.metalnessMap,
  17583. specularMap: !! material.specularMap,
  17584. alphaMap: !! material.alphaMap,
  17585. combine: material.combine,
  17586. vertexColors: material.vertexColors,
  17587. fog: fog,
  17588. useFog: material.fog,
  17589. fogExp: fog instanceof THREE.FogExp2,
  17590. flatShading: material.shading === THREE.FlatShading,
  17591. sizeAttenuation: material.sizeAttenuation,
  17592. logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer,
  17593. skinning: material.skinning,
  17594. maxBones: maxBones,
  17595. useVertexTexture: capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture,
  17596. morphTargets: material.morphTargets,
  17597. morphNormals: material.morphNormals,
  17598. maxMorphTargets: renderer.maxMorphTargets,
  17599. maxMorphNormals: renderer.maxMorphNormals,
  17600. numDirLights: lights.directional.length,
  17601. numPointLights: lights.point.length,
  17602. numSpotLights: lights.spot.length,
  17603. numHemiLights: lights.hemi.length,
  17604. shadowMapEnabled: renderer.shadowMap.enabled && object.receiveShadow && lights.shadows.length > 0,
  17605. shadowMapType: renderer.shadowMap.type,
  17606. toneMapping: renderer.toneMapping,
  17607. physicallyCorrectLights: renderer.physicallyCorrectLights,
  17608. premultipliedAlpha: material.premultipliedAlpha,
  17609. alphaTest: material.alphaTest,
  17610. doubleSided: material.side === THREE.DoubleSide,
  17611. flipSided: material.side === THREE.BackSide
  17612. };
  17613. return parameters;
  17614. };
  17615. this.getProgramCode = function ( material, parameters ) {
  17616. var array = [];
  17617. if ( parameters.shaderID ) {
  17618. array.push( parameters.shaderID );
  17619. } else {
  17620. array.push( material.fragmentShader );
  17621. array.push( material.vertexShader );
  17622. }
  17623. if ( material.defines !== undefined ) {
  17624. for ( var name in material.defines ) {
  17625. array.push( name );
  17626. array.push( material.defines[ name ] );
  17627. }
  17628. }
  17629. for ( var i = 0; i < parameterNames.length; i ++ ) {
  17630. array.push( parameters[ parameterNames[ i ] ] );
  17631. }
  17632. return array.join();
  17633. };
  17634. this.acquireProgram = function ( material, parameters, code ) {
  17635. var program;
  17636. // Check if code has been already compiled
  17637. for ( var p = 0, pl = programs.length; p < pl; p ++ ) {
  17638. var programInfo = programs[ p ];
  17639. if ( programInfo.code === code ) {
  17640. program = programInfo;
  17641. ++ program.usedTimes;
  17642. break;
  17643. }
  17644. }
  17645. if ( program === undefined ) {
  17646. program = new THREE.WebGLProgram( renderer, code, material, parameters );
  17647. programs.push( program );
  17648. }
  17649. return program;
  17650. };
  17651. this.releaseProgram = function( program ) {
  17652. if ( -- program.usedTimes === 0 ) {
  17653. // Remove from unordered set
  17654. var i = programs.indexOf( program );
  17655. programs[ i ] = programs[ programs.length - 1 ];
  17656. programs.pop();
  17657. // Free WebGL resources
  17658. program.destroy();
  17659. }
  17660. };
  17661. // Exposed for resource monitoring & error feedback via renderer.info:
  17662. this.programs = programs;
  17663. };
  17664. // File:src/renderers/webgl/WebGLProperties.js
  17665. /**
  17666. * @author fordacious / fordacious.github.io
  17667. */
  17668. THREE.WebGLProperties = function () {
  17669. var properties = {};
  17670. this.get = function ( object ) {
  17671. var uuid = object.uuid;
  17672. var map = properties[ uuid ];
  17673. if ( map === undefined ) {
  17674. map = {};
  17675. properties[ uuid ] = map;
  17676. }
  17677. return map;
  17678. };
  17679. this.delete = function ( object ) {
  17680. delete properties[ object.uuid ];
  17681. };
  17682. this.clear = function () {
  17683. properties = {};
  17684. };
  17685. };
  17686. // File:src/renderers/webgl/WebGLShader.js
  17687. THREE.WebGLShader = ( function () {
  17688. function addLineNumbers( string ) {
  17689. var lines = string.split( '\n' );
  17690. for ( var i = 0; i < lines.length; i ++ ) {
  17691. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  17692. }
  17693. return lines.join( '\n' );
  17694. }
  17695. return function WebGLShader( gl, type, string ) {
  17696. var shader = gl.createShader( type );
  17697. gl.shaderSource( shader, string );
  17698. gl.compileShader( shader );
  17699. if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) {
  17700. console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' );
  17701. }
  17702. if ( gl.getShaderInfoLog( shader ) !== '' ) {
  17703. console.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', type === gl.VERTEX_SHADER ? 'vertex' : 'fragment', gl.getShaderInfoLog( shader ), addLineNumbers( string ) );
  17704. }
  17705. // --enable-privileged-webgl-extension
  17706. // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  17707. return shader;
  17708. };
  17709. } )();
  17710. // File:src/renderers/webgl/WebGLShadowMap.js
  17711. /**
  17712. * @author alteredq / http://alteredqualia.com/
  17713. * @author mrdoob / http://mrdoob.com/
  17714. */
  17715. THREE.WebGLShadowMap = function ( _renderer, _lights, _objects ) {
  17716. var _gl = _renderer.context,
  17717. _state = _renderer.state,
  17718. _frustum = new THREE.Frustum(),
  17719. _projScreenMatrix = new THREE.Matrix4(),
  17720. _lightShadows = _lights.shadows,
  17721. _shadowMapSize = new THREE.Vector2(),
  17722. _lookTarget = new THREE.Vector3(),
  17723. _lightPositionWorld = new THREE.Vector3(),
  17724. _renderList = [],
  17725. _MorphingFlag = 1,
  17726. _SkinningFlag = 2,
  17727. _NumberOfMaterialVariants = ( _MorphingFlag | _SkinningFlag ) + 1,
  17728. _depthMaterials = new Array( _NumberOfMaterialVariants ),
  17729. _distanceMaterials = new Array( _NumberOfMaterialVariants );
  17730. var cubeDirections = [
  17731. new THREE.Vector3( 1, 0, 0 ), new THREE.Vector3( - 1, 0, 0 ), new THREE.Vector3( 0, 0, 1 ),
  17732. new THREE.Vector3( 0, 0, - 1 ), new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, - 1, 0 )
  17733. ];
  17734. var cubeUps = [
  17735. new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 1, 0 ),
  17736. new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 0, 1 ), new THREE.Vector3( 0, 0, - 1 )
  17737. ];
  17738. var cube2DViewPorts = [
  17739. new THREE.Vector4(), new THREE.Vector4(), new THREE.Vector4(),
  17740. new THREE.Vector4(), new THREE.Vector4(), new THREE.Vector4()
  17741. ];
  17742. // init
  17743. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  17744. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  17745. var distanceShader = THREE.ShaderLib[ "distanceRGBA" ];
  17746. var distanceUniforms = THREE.UniformsUtils.clone( distanceShader.uniforms );
  17747. for ( var i = 0; i !== _NumberOfMaterialVariants; ++ i ) {
  17748. var useMorphing = ( i & _MorphingFlag ) !== 0;
  17749. var useSkinning = ( i & _SkinningFlag ) !== 0;
  17750. var depthMaterial = new THREE.ShaderMaterial( {
  17751. uniforms: depthUniforms,
  17752. vertexShader: depthShader.vertexShader,
  17753. fragmentShader: depthShader.fragmentShader,
  17754. morphTargets: useMorphing,
  17755. skinning: useSkinning
  17756. } );
  17757. _depthMaterials[ i ] = depthMaterial;
  17758. var distanceMaterial = new THREE.ShaderMaterial( {
  17759. defines: {
  17760. 'USE_SHADOWMAP': ''
  17761. },
  17762. uniforms: distanceUniforms,
  17763. vertexShader: distanceShader.vertexShader,
  17764. fragmentShader: distanceShader.fragmentShader,
  17765. morphTargets: useMorphing,
  17766. skinning: useSkinning
  17767. } );
  17768. _distanceMaterials[ i ] = distanceMaterial;
  17769. }
  17770. //
  17771. var scope = this;
  17772. this.enabled = false;
  17773. this.autoUpdate = true;
  17774. this.needsUpdate = false;
  17775. this.type = THREE.PCFShadowMap;
  17776. this.cullFace = THREE.CullFaceFront;
  17777. this.render = function ( scene, camera ) {
  17778. if ( scope.enabled === false ) return;
  17779. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  17780. if ( _lightShadows.length === 0 ) return;
  17781. // Set GL state for depth map.
  17782. _state.clearColor( 1, 1, 1, 1 );
  17783. _state.disable( _gl.BLEND );
  17784. _state.enable( _gl.CULL_FACE );
  17785. _gl.frontFace( _gl.CCW );
  17786. _gl.cullFace( scope.cullFace === THREE.CullFaceFront ? _gl.FRONT : _gl.BACK );
  17787. _state.setDepthTest( true );
  17788. _state.setScissorTest( false );
  17789. // render depth map
  17790. var faceCount, isPointLight;
  17791. for ( var i = 0, il = _lightShadows.length; i < il; i ++ ) {
  17792. var light = _lightShadows[ i ];
  17793. var shadow = light.shadow;
  17794. var shadowCamera = shadow.camera;
  17795. _shadowMapSize.copy( shadow.mapSize );
  17796. if ( light instanceof THREE.PointLight ) {
  17797. faceCount = 6;
  17798. isPointLight = true;
  17799. var vpWidth = _shadowMapSize.x;
  17800. var vpHeight = _shadowMapSize.y;
  17801. // These viewports map a cube-map onto a 2D texture with the
  17802. // following orientation:
  17803. //
  17804. // xzXZ
  17805. // y Y
  17806. //
  17807. // X - Positive x direction
  17808. // x - Negative x direction
  17809. // Y - Positive y direction
  17810. // y - Negative y direction
  17811. // Z - Positive z direction
  17812. // z - Negative z direction
  17813. // positive X
  17814. cube2DViewPorts[ 0 ].set( vpWidth * 2, vpHeight, vpWidth, vpHeight );
  17815. // negative X
  17816. cube2DViewPorts[ 1 ].set( 0, vpHeight, vpWidth, vpHeight );
  17817. // positive Z
  17818. cube2DViewPorts[ 2 ].set( vpWidth * 3, vpHeight, vpWidth, vpHeight );
  17819. // negative Z
  17820. cube2DViewPorts[ 3 ].set( vpWidth, vpHeight, vpWidth, vpHeight );
  17821. // positive Y
  17822. cube2DViewPorts[ 4 ].set( vpWidth * 3, 0, vpWidth, vpHeight );
  17823. // negative Y
  17824. cube2DViewPorts[ 5 ].set( vpWidth, 0, vpWidth, vpHeight );
  17825. _shadowMapSize.x *= 4.0;
  17826. _shadowMapSize.y *= 2.0;
  17827. } else {
  17828. faceCount = 1;
  17829. isPointLight = false;
  17830. }
  17831. if ( shadow.map === null ) {
  17832. var pars = { minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter, format: THREE.RGBAFormat };
  17833. shadow.map = new THREE.WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  17834. shadowCamera.updateProjectionMatrix();
  17835. }
  17836. if ( shadow instanceof THREE.SpotLightShadow ) {
  17837. shadow.update( light );
  17838. }
  17839. var shadowMap = shadow.map;
  17840. var shadowMatrix = shadow.matrix;
  17841. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  17842. shadowCamera.position.copy( _lightPositionWorld );
  17843. _renderer.setRenderTarget( shadowMap );
  17844. _renderer.clear();
  17845. // render shadow map for each cube face (if omni-directional) or
  17846. // run a single pass if not
  17847. for ( var face = 0; face < faceCount; face ++ ) {
  17848. if ( isPointLight ) {
  17849. _lookTarget.copy( shadowCamera.position );
  17850. _lookTarget.add( cubeDirections[ face ] );
  17851. shadowCamera.up.copy( cubeUps[ face ] );
  17852. shadowCamera.lookAt( _lookTarget );
  17853. var vpDimensions = cube2DViewPorts[ face ];
  17854. _state.viewport( vpDimensions );
  17855. } else {
  17856. _lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  17857. shadowCamera.lookAt( _lookTarget );
  17858. }
  17859. shadowCamera.updateMatrixWorld();
  17860. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  17861. // compute shadow matrix
  17862. shadowMatrix.set(
  17863. 0.5, 0.0, 0.0, 0.5,
  17864. 0.0, 0.5, 0.0, 0.5,
  17865. 0.0, 0.0, 0.5, 0.5,
  17866. 0.0, 0.0, 0.0, 1.0
  17867. );
  17868. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  17869. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  17870. // update camera matrices and frustum
  17871. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  17872. _frustum.setFromMatrix( _projScreenMatrix );
  17873. // set object matrices & frustum culling
  17874. _renderList.length = 0;
  17875. projectObject( scene, camera, shadowCamera );
  17876. // render shadow map
  17877. // render regular objects
  17878. for ( var j = 0, jl = _renderList.length; j < jl; j ++ ) {
  17879. var object = _renderList[ j ];
  17880. var geometry = _objects.update( object );
  17881. var material = object.material;
  17882. if ( material instanceof THREE.MultiMaterial ) {
  17883. var groups = geometry.groups;
  17884. var materials = material.materials;
  17885. for ( var k = 0, kl = groups.length; k < kl; k ++ ) {
  17886. var group = groups[ k ];
  17887. var groupMaterial = materials[ group.materialIndex ];
  17888. if ( groupMaterial.visible === true ) {
  17889. var depthMaterial = getDepthMaterial( object, groupMaterial, isPointLight, _lightPositionWorld );
  17890. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  17891. }
  17892. }
  17893. } else {
  17894. var depthMaterial = getDepthMaterial( object, material, isPointLight, _lightPositionWorld );
  17895. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  17896. }
  17897. }
  17898. }
  17899. }
  17900. // Restore GL state.
  17901. var clearColor = _renderer.getClearColor(),
  17902. clearAlpha = _renderer.getClearAlpha();
  17903. _renderer.setClearColor( clearColor, clearAlpha );
  17904. _state.enable( _gl.BLEND );
  17905. if ( scope.cullFace === THREE.CullFaceFront ) {
  17906. _gl.cullFace( _gl.BACK );
  17907. }
  17908. scope.needsUpdate = false;
  17909. };
  17910. function getDepthMaterial( object, material, isPointLight, lightPositionWorld ) {
  17911. var geometry = object.geometry;
  17912. var newMaterial = null;
  17913. var materialVariants = _depthMaterials;
  17914. var customMaterial = object.customDepthMaterial;
  17915. if ( isPointLight ) {
  17916. materialVariants = _distanceMaterials;
  17917. customMaterial = object.customDistanceMaterial;
  17918. }
  17919. if ( ! customMaterial ) {
  17920. var useMorphing = geometry.morphTargets !== undefined &&
  17921. geometry.morphTargets.length > 0 && material.morphTargets;
  17922. var useSkinning = object instanceof THREE.SkinnedMesh && material.skinning;
  17923. var variantIndex = 0;
  17924. if ( useMorphing ) variantIndex |= _MorphingFlag;
  17925. if ( useSkinning ) variantIndex |= _SkinningFlag;
  17926. newMaterial = materialVariants[ variantIndex ];
  17927. } else {
  17928. newMaterial = customMaterial;
  17929. }
  17930. newMaterial.visible = material.visible;
  17931. newMaterial.wireframe = material.wireframe;
  17932. newMaterial.wireframeLinewidth = material.wireframeLinewidth;
  17933. if ( isPointLight && newMaterial.uniforms.lightPos !== undefined ) {
  17934. newMaterial.uniforms.lightPos.value.copy( lightPositionWorld );
  17935. }
  17936. return newMaterial;
  17937. }
  17938. function projectObject( object, camera, shadowCamera ) {
  17939. if ( object.visible === false ) return;
  17940. if ( object.layers.test( camera.layers ) && ( object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.Points ) ) {
  17941. if ( object.castShadow && ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) ) {
  17942. var material = object.material;
  17943. if ( material.visible === true ) {
  17944. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  17945. _renderList.push( object );
  17946. }
  17947. }
  17948. }
  17949. var children = object.children;
  17950. for ( var i = 0, l = children.length; i < l; i ++ ) {
  17951. projectObject( children[ i ], camera, shadowCamera );
  17952. }
  17953. }
  17954. };
  17955. // File:src/renderers/webgl/WebGLState.js
  17956. /**
  17957. * @author mrdoob / http://mrdoob.com/
  17958. */
  17959. THREE.WebGLState = function ( gl, extensions, paramThreeToGL ) {
  17960. var _this = this;
  17961. var color = new THREE.Vector4();
  17962. var maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  17963. var newAttributes = new Uint8Array( maxVertexAttributes );
  17964. var enabledAttributes = new Uint8Array( maxVertexAttributes );
  17965. var attributeDivisors = new Uint8Array( maxVertexAttributes );
  17966. var capabilities = {};
  17967. var compressedTextureFormats = null;
  17968. var currentBlending = null;
  17969. var currentBlendEquation = null;
  17970. var currentBlendSrc = null;
  17971. var currentBlendDst = null;
  17972. var currentBlendEquationAlpha = null;
  17973. var currentBlendSrcAlpha = null;
  17974. var currentBlendDstAlpha = null;
  17975. var currentPremultipledAlpha = false;
  17976. var currentDepthFunc = null;
  17977. var currentDepthWrite = null;
  17978. var currentColorWrite = null;
  17979. var currentStencilWrite = null;
  17980. var currentStencilFunc = null;
  17981. var currentStencilRef = null;
  17982. var currentStencilMask = null;
  17983. var currentStencilFail = null;
  17984. var currentStencilZFail = null;
  17985. var currentStencilZPass = null;
  17986. var currentFlipSided = null;
  17987. var currentLineWidth = null;
  17988. var currentPolygonOffsetFactor = null;
  17989. var currentPolygonOffsetUnits = null;
  17990. var currentScissorTest = null;
  17991. var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  17992. var currentTextureSlot = undefined;
  17993. var currentBoundTextures = {};
  17994. var currentClearColor = new THREE.Vector4();
  17995. var currentClearDepth = null;
  17996. var currentClearStencil = null;
  17997. var currentScissor = new THREE.Vector4();
  17998. var currentViewport = new THREE.Vector4();
  17999. var emptyTexture = gl.createTexture();
  18000. gl.bindTexture( gl.TEXTURE_2D, emptyTexture );
  18001. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR );
  18002. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB, 1, 1, 0, gl.RGB, gl.UNSIGNED_BYTE, new Uint8Array( 3 ) );
  18003. this.init = function () {
  18004. this.clearColor( 0, 0, 0, 1 );
  18005. this.clearDepth( 1 );
  18006. this.clearStencil( 0 );
  18007. this.enable( gl.DEPTH_TEST );
  18008. gl.depthFunc( gl.LEQUAL );
  18009. gl.frontFace( gl.CCW );
  18010. gl.cullFace( gl.BACK );
  18011. this.enable( gl.CULL_FACE );
  18012. this.enable( gl.BLEND );
  18013. gl.blendEquation( gl.FUNC_ADD );
  18014. gl.blendFunc( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA );
  18015. };
  18016. this.initAttributes = function () {
  18017. for ( var i = 0, l = newAttributes.length; i < l; i ++ ) {
  18018. newAttributes[ i ] = 0;
  18019. }
  18020. };
  18021. this.enableAttribute = function ( attribute ) {
  18022. newAttributes[ attribute ] = 1;
  18023. if ( enabledAttributes[ attribute ] === 0 ) {
  18024. gl.enableVertexAttribArray( attribute );
  18025. enabledAttributes[ attribute ] = 1;
  18026. }
  18027. if ( attributeDivisors[ attribute ] !== 0 ) {
  18028. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  18029. extension.vertexAttribDivisorANGLE( attribute, 0 );
  18030. attributeDivisors[ attribute ] = 0;
  18031. }
  18032. };
  18033. this.enableAttributeAndDivisor = function ( attribute, meshPerAttribute, extension ) {
  18034. newAttributes[ attribute ] = 1;
  18035. if ( enabledAttributes[ attribute ] === 0 ) {
  18036. gl.enableVertexAttribArray( attribute );
  18037. enabledAttributes[ attribute ] = 1;
  18038. }
  18039. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  18040. extension.vertexAttribDivisorANGLE( attribute, meshPerAttribute );
  18041. attributeDivisors[ attribute ] = meshPerAttribute;
  18042. }
  18043. };
  18044. this.disableUnusedAttributes = function () {
  18045. for ( var i = 0, l = enabledAttributes.length; i < l; i ++ ) {
  18046. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  18047. gl.disableVertexAttribArray( i );
  18048. enabledAttributes[ i ] = 0;
  18049. }
  18050. }
  18051. };
  18052. this.enable = function ( id ) {
  18053. if ( capabilities[ id ] !== true ) {
  18054. gl.enable( id );
  18055. capabilities[ id ] = true;
  18056. }
  18057. };
  18058. this.disable = function ( id ) {
  18059. if ( capabilities[ id ] !== false ) {
  18060. gl.disable( id );
  18061. capabilities[ id ] = false;
  18062. }
  18063. };
  18064. this.getCompressedTextureFormats = function () {
  18065. if ( compressedTextureFormats === null ) {
  18066. compressedTextureFormats = [];
  18067. if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) ||
  18068. extensions.get( 'WEBGL_compressed_texture_s3tc' ) ||
  18069. extensions.get( 'WEBGL_compressed_texture_etc1' ) ) {
  18070. var formats = gl.getParameter( gl.COMPRESSED_TEXTURE_FORMATS );
  18071. for ( var i = 0; i < formats.length; i ++ ) {
  18072. compressedTextureFormats.push( formats[ i ] );
  18073. }
  18074. }
  18075. }
  18076. return compressedTextureFormats;
  18077. };
  18078. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  18079. if ( blending === THREE.NoBlending ) {
  18080. this.disable( gl.BLEND );
  18081. } else {
  18082. this.enable( gl.BLEND );
  18083. }
  18084. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  18085. if ( blending === THREE.AdditiveBlending ) {
  18086. if ( premultipliedAlpha ) {
  18087. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  18088. gl.blendFuncSeparate( gl.ONE, gl.ONE, gl.ONE, gl.ONE );
  18089. } else {
  18090. gl.blendEquation( gl.FUNC_ADD );
  18091. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  18092. }
  18093. } else if ( blending === THREE.SubtractiveBlending ) {
  18094. if ( premultipliedAlpha ) {
  18095. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  18096. gl.blendFuncSeparate( gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA );
  18097. } else {
  18098. gl.blendEquation( gl.FUNC_ADD );
  18099. gl.blendFunc( gl.ZERO, gl.ONE_MINUS_SRC_COLOR );
  18100. }
  18101. } else if ( blending === THREE.MultiplyBlending ) {
  18102. if ( premultipliedAlpha ) {
  18103. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  18104. gl.blendFuncSeparate( gl.ZERO, gl.ZERO, gl.SRC_COLOR, gl.SRC_ALPHA );
  18105. } else {
  18106. gl.blendEquation( gl.FUNC_ADD );
  18107. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  18108. }
  18109. } else {
  18110. if ( premultipliedAlpha ) {
  18111. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  18112. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  18113. } else {
  18114. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  18115. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  18116. }
  18117. }
  18118. currentBlending = blending;
  18119. currentPremultipledAlpha = premultipliedAlpha;
  18120. }
  18121. if ( blending === THREE.CustomBlending ) {
  18122. blendEquationAlpha = blendEquationAlpha || blendEquation;
  18123. blendSrcAlpha = blendSrcAlpha || blendSrc;
  18124. blendDstAlpha = blendDstAlpha || blendDst;
  18125. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  18126. gl.blendEquationSeparate( paramThreeToGL( blendEquation ), paramThreeToGL( blendEquationAlpha ) );
  18127. currentBlendEquation = blendEquation;
  18128. currentBlendEquationAlpha = blendEquationAlpha;
  18129. }
  18130. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  18131. gl.blendFuncSeparate( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ), paramThreeToGL( blendSrcAlpha ), paramThreeToGL( blendDstAlpha ) );
  18132. currentBlendSrc = blendSrc;
  18133. currentBlendDst = blendDst;
  18134. currentBlendSrcAlpha = blendSrcAlpha;
  18135. currentBlendDstAlpha = blendDstAlpha;
  18136. }
  18137. } else {
  18138. currentBlendEquation = null;
  18139. currentBlendSrc = null;
  18140. currentBlendDst = null;
  18141. currentBlendEquationAlpha = null;
  18142. currentBlendSrcAlpha = null;
  18143. currentBlendDstAlpha = null;
  18144. }
  18145. };
  18146. this.setDepthFunc = function ( depthFunc ) {
  18147. if ( currentDepthFunc !== depthFunc ) {
  18148. if ( depthFunc ) {
  18149. switch ( depthFunc ) {
  18150. case THREE.NeverDepth:
  18151. gl.depthFunc( gl.NEVER );
  18152. break;
  18153. case THREE.AlwaysDepth:
  18154. gl.depthFunc( gl.ALWAYS );
  18155. break;
  18156. case THREE.LessDepth:
  18157. gl.depthFunc( gl.LESS );
  18158. break;
  18159. case THREE.LessEqualDepth:
  18160. gl.depthFunc( gl.LEQUAL );
  18161. break;
  18162. case THREE.EqualDepth:
  18163. gl.depthFunc( gl.EQUAL );
  18164. break;
  18165. case THREE.GreaterEqualDepth:
  18166. gl.depthFunc( gl.GEQUAL );
  18167. break;
  18168. case THREE.GreaterDepth:
  18169. gl.depthFunc( gl.GREATER );
  18170. break;
  18171. case THREE.NotEqualDepth:
  18172. gl.depthFunc( gl.NOTEQUAL );
  18173. break;
  18174. default:
  18175. gl.depthFunc( gl.LEQUAL );
  18176. }
  18177. } else {
  18178. gl.depthFunc( gl.LEQUAL );
  18179. }
  18180. currentDepthFunc = depthFunc;
  18181. }
  18182. };
  18183. this.setDepthTest = function ( depthTest ) {
  18184. if ( depthTest ) {
  18185. this.enable( gl.DEPTH_TEST );
  18186. } else {
  18187. this.disable( gl.DEPTH_TEST );
  18188. }
  18189. };
  18190. this.setDepthWrite = function ( depthWrite ) {
  18191. // TODO: Rename to setDepthMask
  18192. if ( currentDepthWrite !== depthWrite ) {
  18193. gl.depthMask( depthWrite );
  18194. currentDepthWrite = depthWrite;
  18195. }
  18196. };
  18197. this.setColorWrite = function ( colorWrite ) {
  18198. // TODO: Rename to setColorMask
  18199. if ( currentColorWrite !== colorWrite ) {
  18200. gl.colorMask( colorWrite, colorWrite, colorWrite, colorWrite );
  18201. currentColorWrite = colorWrite;
  18202. }
  18203. };
  18204. this.setStencilFunc = function ( stencilFunc, stencilRef, stencilMask ) {
  18205. if ( currentStencilFunc !== stencilFunc ||
  18206. currentStencilRef !== stencilRef ||
  18207. currentStencilMask !== stencilMask ) {
  18208. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  18209. currentStencilFunc = stencilFunc;
  18210. currentStencilRef = stencilRef;
  18211. currentStencilMask = stencilMask;
  18212. }
  18213. };
  18214. this.setStencilOp = function ( stencilFail, stencilZFail, stencilZPass ) {
  18215. if ( currentStencilFail !== stencilFail ||
  18216. currentStencilZFail !== stencilZFail ||
  18217. currentStencilZPass !== stencilZPass ) {
  18218. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  18219. currentStencilFail = stencilFail;
  18220. currentStencilZFail = stencilZFail;
  18221. currentStencilZPass = stencilZPass;
  18222. }
  18223. };
  18224. this.setStencilTest = function ( stencilTest ) {
  18225. if ( stencilTest ) {
  18226. this.enable( gl.STENCIL_TEST );
  18227. } else {
  18228. this.disable( gl.STENCIL_TEST );
  18229. }
  18230. };
  18231. this.setStencilWrite = function ( stencilWrite ) {
  18232. // TODO: Rename to setStencilMask
  18233. if ( currentStencilWrite !== stencilWrite ) {
  18234. gl.stencilMask( stencilWrite );
  18235. currentStencilWrite = stencilWrite;
  18236. }
  18237. };
  18238. this.setFlipSided = function ( flipSided ) {
  18239. if ( currentFlipSided !== flipSided ) {
  18240. if ( flipSided ) {
  18241. gl.frontFace( gl.CW );
  18242. } else {
  18243. gl.frontFace( gl.CCW );
  18244. }
  18245. currentFlipSided = flipSided;
  18246. }
  18247. };
  18248. this.setLineWidth = function ( width ) {
  18249. if ( width !== currentLineWidth ) {
  18250. gl.lineWidth( width );
  18251. currentLineWidth = width;
  18252. }
  18253. };
  18254. this.setPolygonOffset = function ( polygonOffset, factor, units ) {
  18255. if ( polygonOffset ) {
  18256. this.enable( gl.POLYGON_OFFSET_FILL );
  18257. } else {
  18258. this.disable( gl.POLYGON_OFFSET_FILL );
  18259. }
  18260. if ( polygonOffset && ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) ) {
  18261. gl.polygonOffset( factor, units );
  18262. currentPolygonOffsetFactor = factor;
  18263. currentPolygonOffsetUnits = units;
  18264. }
  18265. };
  18266. this.getScissorTest = function () {
  18267. return currentScissorTest;
  18268. };
  18269. this.setScissorTest = function ( scissorTest ) {
  18270. currentScissorTest = scissorTest;
  18271. if ( scissorTest ) {
  18272. this.enable( gl.SCISSOR_TEST );
  18273. } else {
  18274. this.disable( gl.SCISSOR_TEST );
  18275. }
  18276. };
  18277. // texture
  18278. this.activeTexture = function ( webglSlot ) {
  18279. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  18280. if ( currentTextureSlot !== webglSlot ) {
  18281. gl.activeTexture( webglSlot );
  18282. currentTextureSlot = webglSlot;
  18283. }
  18284. };
  18285. this.bindTexture = function ( webglType, webglTexture ) {
  18286. if ( currentTextureSlot === undefined ) {
  18287. _this.activeTexture();
  18288. }
  18289. var boundTexture = currentBoundTextures[ currentTextureSlot ];
  18290. if ( boundTexture === undefined ) {
  18291. boundTexture = { type: undefined, texture: undefined };
  18292. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  18293. }
  18294. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  18295. gl.bindTexture( webglType, webglTexture || emptyTexture );
  18296. boundTexture.type = webglType;
  18297. boundTexture.texture = webglTexture;
  18298. }
  18299. };
  18300. this.compressedTexImage2D = function () {
  18301. try {
  18302. gl.compressedTexImage2D.apply( gl, arguments );
  18303. } catch ( error ) {
  18304. console.error( error );
  18305. }
  18306. };
  18307. this.texImage2D = function () {
  18308. try {
  18309. gl.texImage2D.apply( gl, arguments );
  18310. } catch ( error ) {
  18311. console.error( error );
  18312. }
  18313. };
  18314. // clear values
  18315. this.clearColor = function ( r, g, b, a ) {
  18316. color.set( r, g, b, a );
  18317. if ( currentClearColor.equals( color ) === false ) {
  18318. gl.clearColor( r, g, b, a );
  18319. currentClearColor.copy( color );
  18320. }
  18321. };
  18322. this.clearDepth = function ( depth ) {
  18323. if ( currentClearDepth !== depth ) {
  18324. gl.clearDepth( depth );
  18325. currentClearDepth = depth;
  18326. }
  18327. };
  18328. this.clearStencil = function ( stencil ) {
  18329. if ( currentClearStencil !== stencil ) {
  18330. gl.clearStencil( stencil );
  18331. currentClearStencil = stencil;
  18332. }
  18333. };
  18334. //
  18335. this.scissor = function ( scissor ) {
  18336. if ( currentScissor.equals( scissor ) === false ) {
  18337. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  18338. currentScissor.copy( scissor );
  18339. }
  18340. };
  18341. this.viewport = function ( viewport ) {
  18342. if ( currentViewport.equals( viewport ) === false ) {
  18343. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  18344. currentViewport.copy( viewport );
  18345. }
  18346. };
  18347. //
  18348. this.reset = function () {
  18349. for ( var i = 0; i < enabledAttributes.length; i ++ ) {
  18350. if ( enabledAttributes[ i ] === 1 ) {
  18351. gl.disableVertexAttribArray( i );
  18352. enabledAttributes[ i ] = 0;
  18353. }
  18354. }
  18355. capabilities = {};
  18356. compressedTextureFormats = null;
  18357. currentTextureSlot = undefined;
  18358. currentBoundTextures = {};
  18359. currentBlending = null;
  18360. currentColorWrite = null;
  18361. currentDepthWrite = null;
  18362. currentStencilWrite = null;
  18363. currentFlipSided = null;
  18364. };
  18365. };
  18366. // File:src/renderers/webgl/plugins/LensFlarePlugin.js
  18367. /**
  18368. * @author mikael emtinger / http://gomo.se/
  18369. * @author alteredq / http://alteredqualia.com/
  18370. */
  18371. THREE.LensFlarePlugin = function ( renderer, flares ) {
  18372. var gl = renderer.context;
  18373. var state = renderer.state;
  18374. var vertexBuffer, elementBuffer;
  18375. var shader, program, attributes, uniforms;
  18376. var tempTexture, occlusionTexture;
  18377. function init() {
  18378. var vertices = new Float32Array( [
  18379. - 1, - 1, 0, 0,
  18380. 1, - 1, 1, 0,
  18381. 1, 1, 1, 1,
  18382. - 1, 1, 0, 1
  18383. ] );
  18384. var faces = new Uint16Array( [
  18385. 0, 1, 2,
  18386. 0, 2, 3
  18387. ] );
  18388. // buffers
  18389. vertexBuffer = gl.createBuffer();
  18390. elementBuffer = gl.createBuffer();
  18391. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  18392. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  18393. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  18394. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  18395. // textures
  18396. tempTexture = gl.createTexture();
  18397. occlusionTexture = gl.createTexture();
  18398. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  18399. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB, 16, 16, 0, gl.RGB, gl.UNSIGNED_BYTE, null );
  18400. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  18401. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  18402. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  18403. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  18404. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  18405. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, 16, 16, 0, gl.RGBA, gl.UNSIGNED_BYTE, null );
  18406. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  18407. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  18408. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  18409. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  18410. shader = {
  18411. vertexShader: [
  18412. "uniform lowp int renderType;",
  18413. "uniform vec3 screenPosition;",
  18414. "uniform vec2 scale;",
  18415. "uniform float rotation;",
  18416. "uniform sampler2D occlusionMap;",
  18417. "attribute vec2 position;",
  18418. "attribute vec2 uv;",
  18419. "varying vec2 vUV;",
  18420. "varying float vVisibility;",
  18421. "void main() {",
  18422. "vUV = uv;",
  18423. "vec2 pos = position;",
  18424. "if ( renderType == 2 ) {",
  18425. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  18426. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  18427. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  18428. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  18429. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  18430. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  18431. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  18432. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  18433. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  18434. "vVisibility = visibility.r / 9.0;",
  18435. "vVisibility *= 1.0 - visibility.g / 9.0;",
  18436. "vVisibility *= visibility.b / 9.0;",
  18437. "vVisibility *= 1.0 - visibility.a / 9.0;",
  18438. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  18439. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  18440. "}",
  18441. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  18442. "}"
  18443. ].join( "\n" ),
  18444. fragmentShader: [
  18445. "uniform lowp int renderType;",
  18446. "uniform sampler2D map;",
  18447. "uniform float opacity;",
  18448. "uniform vec3 color;",
  18449. "varying vec2 vUV;",
  18450. "varying float vVisibility;",
  18451. "void main() {",
  18452. // pink square
  18453. "if ( renderType == 0 ) {",
  18454. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  18455. // restore
  18456. "} else if ( renderType == 1 ) {",
  18457. "gl_FragColor = texture2D( map, vUV );",
  18458. // flare
  18459. "} else {",
  18460. "vec4 texture = texture2D( map, vUV );",
  18461. "texture.a *= opacity * vVisibility;",
  18462. "gl_FragColor = texture;",
  18463. "gl_FragColor.rgb *= color;",
  18464. "}",
  18465. "}"
  18466. ].join( "\n" )
  18467. };
  18468. program = createProgram( shader );
  18469. attributes = {
  18470. vertex: gl.getAttribLocation ( program, "position" ),
  18471. uv: gl.getAttribLocation ( program, "uv" )
  18472. };
  18473. uniforms = {
  18474. renderType: gl.getUniformLocation( program, "renderType" ),
  18475. map: gl.getUniformLocation( program, "map" ),
  18476. occlusionMap: gl.getUniformLocation( program, "occlusionMap" ),
  18477. opacity: gl.getUniformLocation( program, "opacity" ),
  18478. color: gl.getUniformLocation( program, "color" ),
  18479. scale: gl.getUniformLocation( program, "scale" ),
  18480. rotation: gl.getUniformLocation( program, "rotation" ),
  18481. screenPosition: gl.getUniformLocation( program, "screenPosition" )
  18482. };
  18483. }
  18484. /*
  18485. * Render lens flares
  18486. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  18487. * reads these back and calculates occlusion.
  18488. */
  18489. this.render = function ( scene, camera, viewport ) {
  18490. if ( flares.length === 0 ) return;
  18491. var tempPosition = new THREE.Vector3();
  18492. var invAspect = viewport.w / viewport.z,
  18493. halfViewportWidth = viewport.z * 0.5,
  18494. halfViewportHeight = viewport.w * 0.5;
  18495. var size = 16 / viewport.w,
  18496. scale = new THREE.Vector2( size * invAspect, size );
  18497. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  18498. screenPositionPixels = new THREE.Vector2( 1, 1 );
  18499. var validArea = new THREE.Box2();
  18500. validArea.min.set( 0, 0 );
  18501. validArea.max.set( viewport.z - 16, viewport.w - 16 );
  18502. if ( program === undefined ) {
  18503. init();
  18504. }
  18505. gl.useProgram( program );
  18506. state.initAttributes();
  18507. state.enableAttribute( attributes.vertex );
  18508. state.enableAttribute( attributes.uv );
  18509. state.disableUnusedAttributes();
  18510. // loop through all lens flares to update their occlusion and positions
  18511. // setup gl and common used attribs/uniforms
  18512. gl.uniform1i( uniforms.occlusionMap, 0 );
  18513. gl.uniform1i( uniforms.map, 1 );
  18514. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  18515. gl.vertexAttribPointer( attributes.vertex, 2, gl.FLOAT, false, 2 * 8, 0 );
  18516. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  18517. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  18518. state.disable( gl.CULL_FACE );
  18519. state.setDepthWrite( false );
  18520. for ( var i = 0, l = flares.length; i < l; i ++ ) {
  18521. size = 16 / viewport.w;
  18522. scale.set( size * invAspect, size );
  18523. // calc object screen position
  18524. var flare = flares[ i ];
  18525. tempPosition.set( flare.matrixWorld.elements[ 12 ], flare.matrixWorld.elements[ 13 ], flare.matrixWorld.elements[ 14 ] );
  18526. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  18527. tempPosition.applyProjection( camera.projectionMatrix );
  18528. // setup arrays for gl programs
  18529. screenPosition.copy( tempPosition );
  18530. // horizontal and vertical coordinate of the lower left corner of the pixels to copy
  18531. screenPositionPixels.x = viewport.x + ( screenPosition.x * halfViewportWidth ) + halfViewportWidth - 8;
  18532. screenPositionPixels.y = viewport.y + ( screenPosition.y * halfViewportHeight ) + halfViewportHeight - 8;
  18533. // screen cull
  18534. if ( validArea.containsPoint( screenPositionPixels ) === true ) {
  18535. // save current RGB to temp texture
  18536. state.activeTexture( gl.TEXTURE0 );
  18537. state.bindTexture( gl.TEXTURE_2D, null );
  18538. state.activeTexture( gl.TEXTURE1 );
  18539. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  18540. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGB, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 );
  18541. // render pink quad
  18542. gl.uniform1i( uniforms.renderType, 0 );
  18543. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  18544. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  18545. state.disable( gl.BLEND );
  18546. state.enable( gl.DEPTH_TEST );
  18547. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  18548. // copy result to occlusionMap
  18549. state.activeTexture( gl.TEXTURE0 );
  18550. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  18551. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGBA, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 );
  18552. // restore graphics
  18553. gl.uniform1i( uniforms.renderType, 1 );
  18554. state.disable( gl.DEPTH_TEST );
  18555. state.activeTexture( gl.TEXTURE1 );
  18556. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  18557. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  18558. // update object positions
  18559. flare.positionScreen.copy( screenPosition );
  18560. if ( flare.customUpdateCallback ) {
  18561. flare.customUpdateCallback( flare );
  18562. } else {
  18563. flare.updateLensFlares();
  18564. }
  18565. // render flares
  18566. gl.uniform1i( uniforms.renderType, 2 );
  18567. state.enable( gl.BLEND );
  18568. for ( var j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  18569. var sprite = flare.lensFlares[ j ];
  18570. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  18571. screenPosition.x = sprite.x;
  18572. screenPosition.y = sprite.y;
  18573. screenPosition.z = sprite.z;
  18574. size = sprite.size * sprite.scale / viewport.w;
  18575. scale.x = size * invAspect;
  18576. scale.y = size;
  18577. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  18578. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  18579. gl.uniform1f( uniforms.rotation, sprite.rotation );
  18580. gl.uniform1f( uniforms.opacity, sprite.opacity );
  18581. gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  18582. state.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  18583. renderer.setTexture( sprite.texture, 1 );
  18584. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  18585. }
  18586. }
  18587. }
  18588. }
  18589. // restore gl
  18590. state.enable( gl.CULL_FACE );
  18591. state.enable( gl.DEPTH_TEST );
  18592. state.setDepthWrite( true );
  18593. renderer.resetGLState();
  18594. };
  18595. function createProgram ( shader ) {
  18596. var program = gl.createProgram();
  18597. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  18598. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  18599. var prefix = "precision " + renderer.getPrecision() + " float;\n";
  18600. gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  18601. gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  18602. gl.compileShader( fragmentShader );
  18603. gl.compileShader( vertexShader );
  18604. gl.attachShader( program, fragmentShader );
  18605. gl.attachShader( program, vertexShader );
  18606. gl.linkProgram( program );
  18607. return program;
  18608. }
  18609. };
  18610. // File:src/renderers/webgl/plugins/SpritePlugin.js
  18611. /**
  18612. * @author mikael emtinger / http://gomo.se/
  18613. * @author alteredq / http://alteredqualia.com/
  18614. */
  18615. THREE.SpritePlugin = function ( renderer, sprites ) {
  18616. var gl = renderer.context;
  18617. var state = renderer.state;
  18618. var vertexBuffer, elementBuffer;
  18619. var program, attributes, uniforms;
  18620. var texture;
  18621. // decompose matrixWorld
  18622. var spritePosition = new THREE.Vector3();
  18623. var spriteRotation = new THREE.Quaternion();
  18624. var spriteScale = new THREE.Vector3();
  18625. function init() {
  18626. var vertices = new Float32Array( [
  18627. - 0.5, - 0.5, 0, 0,
  18628. 0.5, - 0.5, 1, 0,
  18629. 0.5, 0.5, 1, 1,
  18630. - 0.5, 0.5, 0, 1
  18631. ] );
  18632. var faces = new Uint16Array( [
  18633. 0, 1, 2,
  18634. 0, 2, 3
  18635. ] );
  18636. vertexBuffer = gl.createBuffer();
  18637. elementBuffer = gl.createBuffer();
  18638. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  18639. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  18640. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  18641. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  18642. program = createProgram();
  18643. attributes = {
  18644. position: gl.getAttribLocation ( program, 'position' ),
  18645. uv: gl.getAttribLocation ( program, 'uv' )
  18646. };
  18647. uniforms = {
  18648. uvOffset: gl.getUniformLocation( program, 'uvOffset' ),
  18649. uvScale: gl.getUniformLocation( program, 'uvScale' ),
  18650. rotation: gl.getUniformLocation( program, 'rotation' ),
  18651. scale: gl.getUniformLocation( program, 'scale' ),
  18652. color: gl.getUniformLocation( program, 'color' ),
  18653. map: gl.getUniformLocation( program, 'map' ),
  18654. opacity: gl.getUniformLocation( program, 'opacity' ),
  18655. modelViewMatrix: gl.getUniformLocation( program, 'modelViewMatrix' ),
  18656. projectionMatrix: gl.getUniformLocation( program, 'projectionMatrix' ),
  18657. fogType: gl.getUniformLocation( program, 'fogType' ),
  18658. fogDensity: gl.getUniformLocation( program, 'fogDensity' ),
  18659. fogNear: gl.getUniformLocation( program, 'fogNear' ),
  18660. fogFar: gl.getUniformLocation( program, 'fogFar' ),
  18661. fogColor: gl.getUniformLocation( program, 'fogColor' ),
  18662. alphaTest: gl.getUniformLocation( program, 'alphaTest' )
  18663. };
  18664. var canvas = document.createElement( 'canvas' );
  18665. canvas.width = 8;
  18666. canvas.height = 8;
  18667. var context = canvas.getContext( '2d' );
  18668. context.fillStyle = 'white';
  18669. context.fillRect( 0, 0, 8, 8 );
  18670. texture = new THREE.Texture( canvas );
  18671. texture.needsUpdate = true;
  18672. }
  18673. this.render = function ( scene, camera ) {
  18674. if ( sprites.length === 0 ) return;
  18675. // setup gl
  18676. if ( program === undefined ) {
  18677. init();
  18678. }
  18679. gl.useProgram( program );
  18680. state.initAttributes();
  18681. state.enableAttribute( attributes.position );
  18682. state.enableAttribute( attributes.uv );
  18683. state.disableUnusedAttributes();
  18684. state.disable( gl.CULL_FACE );
  18685. state.enable( gl.BLEND );
  18686. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  18687. gl.vertexAttribPointer( attributes.position, 2, gl.FLOAT, false, 2 * 8, 0 );
  18688. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  18689. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  18690. gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  18691. state.activeTexture( gl.TEXTURE0 );
  18692. gl.uniform1i( uniforms.map, 0 );
  18693. var oldFogType = 0;
  18694. var sceneFogType = 0;
  18695. var fog = scene.fog;
  18696. if ( fog ) {
  18697. gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  18698. if ( fog instanceof THREE.Fog ) {
  18699. gl.uniform1f( uniforms.fogNear, fog.near );
  18700. gl.uniform1f( uniforms.fogFar, fog.far );
  18701. gl.uniform1i( uniforms.fogType, 1 );
  18702. oldFogType = 1;
  18703. sceneFogType = 1;
  18704. } else if ( fog instanceof THREE.FogExp2 ) {
  18705. gl.uniform1f( uniforms.fogDensity, fog.density );
  18706. gl.uniform1i( uniforms.fogType, 2 );
  18707. oldFogType = 2;
  18708. sceneFogType = 2;
  18709. }
  18710. } else {
  18711. gl.uniform1i( uniforms.fogType, 0 );
  18712. oldFogType = 0;
  18713. sceneFogType = 0;
  18714. }
  18715. // update positions and sort
  18716. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  18717. var sprite = sprites[ i ];
  18718. sprite.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  18719. sprite.z = - sprite.modelViewMatrix.elements[ 14 ];
  18720. }
  18721. sprites.sort( painterSortStable );
  18722. // render all sprites
  18723. var scale = [];
  18724. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  18725. var sprite = sprites[ i ];
  18726. var material = sprite.material;
  18727. gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  18728. gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite.modelViewMatrix.elements );
  18729. sprite.matrixWorld.decompose( spritePosition, spriteRotation, spriteScale );
  18730. scale[ 0 ] = spriteScale.x;
  18731. scale[ 1 ] = spriteScale.y;
  18732. var fogType = 0;
  18733. if ( scene.fog && material.fog ) {
  18734. fogType = sceneFogType;
  18735. }
  18736. if ( oldFogType !== fogType ) {
  18737. gl.uniform1i( uniforms.fogType, fogType );
  18738. oldFogType = fogType;
  18739. }
  18740. if ( material.map !== null ) {
  18741. gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y );
  18742. gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y );
  18743. } else {
  18744. gl.uniform2f( uniforms.uvOffset, 0, 0 );
  18745. gl.uniform2f( uniforms.uvScale, 1, 1 );
  18746. }
  18747. gl.uniform1f( uniforms.opacity, material.opacity );
  18748. gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  18749. gl.uniform1f( uniforms.rotation, material.rotation );
  18750. gl.uniform2fv( uniforms.scale, scale );
  18751. state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  18752. state.setDepthTest( material.depthTest );
  18753. state.setDepthWrite( material.depthWrite );
  18754. if ( material.map && material.map.image && material.map.image.width ) {
  18755. renderer.setTexture( material.map, 0 );
  18756. } else {
  18757. renderer.setTexture( texture, 0 );
  18758. }
  18759. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  18760. }
  18761. // restore gl
  18762. state.enable( gl.CULL_FACE );
  18763. renderer.resetGLState();
  18764. };
  18765. function createProgram () {
  18766. var program = gl.createProgram();
  18767. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  18768. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  18769. gl.shaderSource( vertexShader, [
  18770. 'precision ' + renderer.getPrecision() + ' float;',
  18771. 'uniform mat4 modelViewMatrix;',
  18772. 'uniform mat4 projectionMatrix;',
  18773. 'uniform float rotation;',
  18774. 'uniform vec2 scale;',
  18775. 'uniform vec2 uvOffset;',
  18776. 'uniform vec2 uvScale;',
  18777. 'attribute vec2 position;',
  18778. 'attribute vec2 uv;',
  18779. 'varying vec2 vUV;',
  18780. 'void main() {',
  18781. 'vUV = uvOffset + uv * uvScale;',
  18782. 'vec2 alignedPosition = position * scale;',
  18783. 'vec2 rotatedPosition;',
  18784. 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  18785. 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  18786. 'vec4 finalPosition;',
  18787. 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  18788. 'finalPosition.xy += rotatedPosition;',
  18789. 'finalPosition = projectionMatrix * finalPosition;',
  18790. 'gl_Position = finalPosition;',
  18791. '}'
  18792. ].join( '\n' ) );
  18793. gl.shaderSource( fragmentShader, [
  18794. 'precision ' + renderer.getPrecision() + ' float;',
  18795. 'uniform vec3 color;',
  18796. 'uniform sampler2D map;',
  18797. 'uniform float opacity;',
  18798. 'uniform int fogType;',
  18799. 'uniform vec3 fogColor;',
  18800. 'uniform float fogDensity;',
  18801. 'uniform float fogNear;',
  18802. 'uniform float fogFar;',
  18803. 'uniform float alphaTest;',
  18804. 'varying vec2 vUV;',
  18805. 'void main() {',
  18806. 'vec4 texture = texture2D( map, vUV );',
  18807. 'if ( texture.a < alphaTest ) discard;',
  18808. 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  18809. 'if ( fogType > 0 ) {',
  18810. 'float depth = gl_FragCoord.z / gl_FragCoord.w;',
  18811. 'float fogFactor = 0.0;',
  18812. 'if ( fogType == 1 ) {',
  18813. 'fogFactor = smoothstep( fogNear, fogFar, depth );',
  18814. '} else {',
  18815. 'const float LOG2 = 1.442695;',
  18816. 'fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );',
  18817. 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  18818. '}',
  18819. 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );',
  18820. '}',
  18821. '}'
  18822. ].join( '\n' ) );
  18823. gl.compileShader( vertexShader );
  18824. gl.compileShader( fragmentShader );
  18825. gl.attachShader( program, vertexShader );
  18826. gl.attachShader( program, fragmentShader );
  18827. gl.linkProgram( program );
  18828. return program;
  18829. }
  18830. function painterSortStable ( a, b ) {
  18831. if ( a.renderOrder !== b.renderOrder ) {
  18832. return a.renderOrder - b.renderOrder;
  18833. } else if ( a.z !== b.z ) {
  18834. return b.z - a.z;
  18835. } else {
  18836. return b.id - a.id;
  18837. }
  18838. }
  18839. };
  18840. // File:src/Three.Legacy.js
  18841. /**
  18842. * @author mrdoob / http://mrdoob.com/
  18843. */
  18844. Object.defineProperties( THREE.Box2.prototype, {
  18845. empty: {
  18846. value: function () {
  18847. console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' );
  18848. return this.isEmpty();
  18849. }
  18850. },
  18851. isIntersectionBox: {
  18852. value: function ( box ) {
  18853. console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
  18854. return this.intersectsBox( box );
  18855. }
  18856. }
  18857. } );
  18858. Object.defineProperties( THREE.Box3.prototype, {
  18859. empty: {
  18860. value: function () {
  18861. console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' );
  18862. return this.isEmpty();
  18863. }
  18864. },
  18865. isIntersectionBox: {
  18866. value: function ( box ) {
  18867. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  18868. return this.intersectsBox( box );
  18869. }
  18870. },
  18871. isIntersectionSphere: {
  18872. value: function ( sphere ) {
  18873. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  18874. return this.intersectsSphere( sphere );
  18875. }
  18876. }
  18877. } );
  18878. Object.defineProperties( THREE.Matrix3.prototype, {
  18879. multiplyVector3: {
  18880. value: function ( vector ) {
  18881. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  18882. return vector.applyMatrix3( this );
  18883. }
  18884. },
  18885. multiplyVector3Array: {
  18886. value: function ( a ) {
  18887. console.warn( 'THREE.Matrix3: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  18888. return this.applyToVector3Array( a );
  18889. }
  18890. }
  18891. } );
  18892. Object.defineProperties( THREE.Matrix4.prototype, {
  18893. extractPosition: {
  18894. value: function ( m ) {
  18895. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  18896. return this.copyPosition( m );
  18897. }
  18898. },
  18899. setRotationFromQuaternion: {
  18900. value: function ( q ) {
  18901. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  18902. return this.makeRotationFromQuaternion( q );
  18903. }
  18904. },
  18905. multiplyVector3: {
  18906. value: function ( vector ) {
  18907. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  18908. return vector.applyProjection( this );
  18909. }
  18910. },
  18911. multiplyVector4: {
  18912. value: function ( vector ) {
  18913. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  18914. return vector.applyMatrix4( this );
  18915. }
  18916. },
  18917. multiplyVector3Array: {
  18918. value: function ( a ) {
  18919. console.warn( 'THREE.Matrix4: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  18920. return this.applyToVector3Array( a );
  18921. }
  18922. },
  18923. rotateAxis: {
  18924. value: function ( v ) {
  18925. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  18926. v.transformDirection( this );
  18927. }
  18928. },
  18929. crossVector: {
  18930. value: function ( vector ) {
  18931. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  18932. return vector.applyMatrix4( this );
  18933. }
  18934. },
  18935. translate: {
  18936. value: function ( v ) {
  18937. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  18938. }
  18939. },
  18940. rotateX: {
  18941. value: function ( angle ) {
  18942. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  18943. }
  18944. },
  18945. rotateY: {
  18946. value: function ( angle ) {
  18947. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  18948. }
  18949. },
  18950. rotateZ: {
  18951. value: function ( angle ) {
  18952. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  18953. }
  18954. },
  18955. rotateByAxis: {
  18956. value: function ( axis, angle ) {
  18957. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  18958. }
  18959. }
  18960. } );
  18961. Object.defineProperties( THREE.Plane.prototype, {
  18962. isIntersectionLine: {
  18963. value: function ( line ) {
  18964. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  18965. return this.intersectsLine( line );
  18966. }
  18967. }
  18968. } );
  18969. Object.defineProperties( THREE.Quaternion.prototype, {
  18970. multiplyVector3: {
  18971. value: function ( vector ) {
  18972. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  18973. return vector.applyQuaternion( this );
  18974. }
  18975. }
  18976. } );
  18977. Object.defineProperties( THREE.Ray.prototype, {
  18978. isIntersectionBox: {
  18979. value: function ( box ) {
  18980. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  18981. return this.intersectsBox( box );
  18982. }
  18983. },
  18984. isIntersectionPlane: {
  18985. value: function ( plane ) {
  18986. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  18987. return this.intersectsPlane( plane );
  18988. }
  18989. },
  18990. isIntersectionSphere: {
  18991. value: function ( sphere ) {
  18992. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  18993. return this.intersectsSphere( sphere );
  18994. }
  18995. }
  18996. } );
  18997. Object.defineProperties( THREE.Vector3.prototype, {
  18998. setEulerFromRotationMatrix: {
  18999. value: function () {
  19000. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  19001. }
  19002. },
  19003. setEulerFromQuaternion: {
  19004. value: function () {
  19005. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  19006. }
  19007. },
  19008. getPositionFromMatrix: {
  19009. value: function ( m ) {
  19010. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  19011. return this.setFromMatrixPosition( m );
  19012. }
  19013. },
  19014. getScaleFromMatrix: {
  19015. value: function ( m ) {
  19016. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  19017. return this.setFromMatrixScale( m );
  19018. }
  19019. },
  19020. getColumnFromMatrix: {
  19021. value: function ( index, matrix ) {
  19022. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  19023. return this.setFromMatrixColumn( index, matrix );
  19024. }
  19025. }
  19026. } );
  19027. //
  19028. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  19029. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' );
  19030. return new THREE.Face3( a, b, c, normal, color, materialIndex );
  19031. };
  19032. THREE.Vertex = function ( x, y, z ) {
  19033. console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' );
  19034. return new THREE.Vector3( x, y, z );
  19035. };
  19036. //
  19037. Object.defineProperties( THREE.Object3D.prototype, {
  19038. eulerOrder: {
  19039. get: function () {
  19040. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  19041. return this.rotation.order;
  19042. },
  19043. set: function ( value ) {
  19044. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  19045. this.rotation.order = value;
  19046. }
  19047. },
  19048. getChildByName: {
  19049. value: function ( name ) {
  19050. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  19051. return this.getObjectByName( name );
  19052. }
  19053. },
  19054. renderDepth: {
  19055. set: function ( value ) {
  19056. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  19057. }
  19058. },
  19059. translate: {
  19060. value: function ( distance, axis ) {
  19061. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  19062. return this.translateOnAxis( axis, distance );
  19063. }
  19064. },
  19065. useQuaternion: {
  19066. get: function () {
  19067. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  19068. },
  19069. set: function ( value ) {
  19070. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  19071. }
  19072. }
  19073. } );
  19074. //
  19075. Object.defineProperties( THREE, {
  19076. PointCloud: {
  19077. value: function ( geometry, material ) {
  19078. console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
  19079. return new THREE.Points( geometry, material );
  19080. }
  19081. },
  19082. ParticleSystem: {
  19083. value: function ( geometry, material ) {
  19084. console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
  19085. return new THREE.Points( geometry, material );
  19086. }
  19087. }
  19088. } );
  19089. //
  19090. Object.defineProperties( THREE.Light.prototype, {
  19091. onlyShadow: {
  19092. set: function ( value ) {
  19093. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  19094. }
  19095. },
  19096. shadowCameraFov: {
  19097. set: function ( value ) {
  19098. console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' );
  19099. this.shadow.camera.fov = value;
  19100. }
  19101. },
  19102. shadowCameraLeft: {
  19103. set: function ( value ) {
  19104. console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' );
  19105. this.shadow.camera.left = value;
  19106. }
  19107. },
  19108. shadowCameraRight: {
  19109. set: function ( value ) {
  19110. console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' );
  19111. this.shadow.camera.right = value;
  19112. }
  19113. },
  19114. shadowCameraTop: {
  19115. set: function ( value ) {
  19116. console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' );
  19117. this.shadow.camera.top = value;
  19118. }
  19119. },
  19120. shadowCameraBottom: {
  19121. set: function ( value ) {
  19122. console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' );
  19123. this.shadow.camera.bottom = value;
  19124. }
  19125. },
  19126. shadowCameraNear: {
  19127. set: function ( value ) {
  19128. console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' );
  19129. this.shadow.camera.near = value;
  19130. }
  19131. },
  19132. shadowCameraFar: {
  19133. set: function ( value ) {
  19134. console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' );
  19135. this.shadow.camera.far = value;
  19136. }
  19137. },
  19138. shadowCameraVisible: {
  19139. set: function ( value ) {
  19140. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );
  19141. }
  19142. },
  19143. shadowBias: {
  19144. set: function ( value ) {
  19145. console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' );
  19146. this.shadow.bias = value;
  19147. }
  19148. },
  19149. shadowDarkness: {
  19150. set: function ( value ) {
  19151. console.warn( 'THREE.Light: .shadowDarkness has been removed.' );
  19152. }
  19153. },
  19154. shadowMapWidth: {
  19155. set: function ( value ) {
  19156. console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' );
  19157. this.shadow.mapSize.width = value;
  19158. }
  19159. },
  19160. shadowMapHeight: {
  19161. set: function ( value ) {
  19162. console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' );
  19163. this.shadow.mapSize.height = value;
  19164. }
  19165. }
  19166. } );
  19167. //
  19168. Object.defineProperties( THREE.BufferAttribute.prototype, {
  19169. length: {
  19170. get: function () {
  19171. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Please use .count.' );
  19172. return this.array.length;
  19173. }
  19174. }
  19175. } );
  19176. Object.defineProperties( THREE.BufferGeometry.prototype, {
  19177. drawcalls: {
  19178. get: function () {
  19179. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  19180. return this.groups;
  19181. }
  19182. },
  19183. offsets: {
  19184. get: function () {
  19185. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  19186. return this.groups;
  19187. }
  19188. },
  19189. addIndex: {
  19190. value: function ( index ) {
  19191. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  19192. this.setIndex( index );
  19193. }
  19194. },
  19195. addDrawCall: {
  19196. value: function ( start, count, indexOffset ) {
  19197. if ( indexOffset !== undefined ) {
  19198. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  19199. }
  19200. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  19201. this.addGroup( start, count );
  19202. }
  19203. },
  19204. clearDrawCalls: {
  19205. value: function () {
  19206. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  19207. this.clearGroups();
  19208. }
  19209. },
  19210. computeTangents: {
  19211. value: function () {
  19212. console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' );
  19213. }
  19214. },
  19215. computeOffsets: {
  19216. value: function () {
  19217. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );
  19218. }
  19219. }
  19220. } );
  19221. //
  19222. Object.defineProperties( THREE.Material.prototype, {
  19223. wrapAround: {
  19224. get: function () {
  19225. console.warn( 'THREE.' + this.type + ': .wrapAround has been removed.' );
  19226. },
  19227. set: function ( value ) {
  19228. console.warn( 'THREE.' + this.type + ': .wrapAround has been removed.' );
  19229. }
  19230. },
  19231. wrapRGB: {
  19232. get: function () {
  19233. console.warn( 'THREE.' + this.type + ': .wrapRGB has been removed.' );
  19234. return new THREE.Color();
  19235. }
  19236. }
  19237. } );
  19238. Object.defineProperties( THREE, {
  19239. PointCloudMaterial: {
  19240. value: function ( parameters ) {
  19241. console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
  19242. return new THREE.PointsMaterial( parameters );
  19243. }
  19244. },
  19245. ParticleBasicMaterial: {
  19246. value: function ( parameters ) {
  19247. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
  19248. return new THREE.PointsMaterial( parameters );
  19249. }
  19250. },
  19251. ParticleSystemMaterial:{
  19252. value: function ( parameters ) {
  19253. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
  19254. return new THREE.PointsMaterial( parameters );
  19255. }
  19256. }
  19257. } );
  19258. Object.defineProperties( THREE.MeshPhongMaterial.prototype, {
  19259. metal: {
  19260. get: function () {
  19261. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' );
  19262. return false;
  19263. },
  19264. set: function ( value ) {
  19265. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' );
  19266. }
  19267. }
  19268. } );
  19269. Object.defineProperties( THREE.ShaderMaterial.prototype, {
  19270. derivatives: {
  19271. get: function () {
  19272. console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  19273. return this.extensions.derivatives;
  19274. },
  19275. set: function ( value ) {
  19276. console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  19277. this.extensions.derivatives = value;
  19278. }
  19279. }
  19280. } );
  19281. //
  19282. Object.defineProperties( THREE.WebGLRenderer.prototype, {
  19283. supportsFloatTextures: {
  19284. value: function () {
  19285. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  19286. return this.extensions.get( 'OES_texture_float' );
  19287. }
  19288. },
  19289. supportsHalfFloatTextures: {
  19290. value: function () {
  19291. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  19292. return this.extensions.get( 'OES_texture_half_float' );
  19293. }
  19294. },
  19295. supportsStandardDerivatives: {
  19296. value: function () {
  19297. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  19298. return this.extensions.get( 'OES_standard_derivatives' );
  19299. }
  19300. },
  19301. supportsCompressedTextureS3TC: {
  19302. value: function () {
  19303. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  19304. return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  19305. }
  19306. },
  19307. supportsCompressedTexturePVRTC: {
  19308. value: function () {
  19309. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  19310. return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  19311. }
  19312. },
  19313. supportsBlendMinMax: {
  19314. value: function () {
  19315. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  19316. return this.extensions.get( 'EXT_blend_minmax' );
  19317. }
  19318. },
  19319. supportsVertexTextures: {
  19320. value: function () {
  19321. return this.capabilities.vertexTextures;
  19322. }
  19323. },
  19324. supportsInstancedArrays: {
  19325. value: function () {
  19326. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  19327. return this.extensions.get( 'ANGLE_instanced_arrays' );
  19328. }
  19329. },
  19330. enableScissorTest: {
  19331. value: function ( boolean ) {
  19332. console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' );
  19333. this.setScissorTest( boolean );
  19334. }
  19335. },
  19336. initMaterial: {
  19337. value: function () {
  19338. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  19339. }
  19340. },
  19341. addPrePlugin: {
  19342. value: function () {
  19343. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  19344. }
  19345. },
  19346. addPostPlugin: {
  19347. value: function () {
  19348. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  19349. }
  19350. },
  19351. updateShadowMap: {
  19352. value: function () {
  19353. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  19354. }
  19355. },
  19356. shadowMapEnabled: {
  19357. get: function () {
  19358. return this.shadowMap.enabled;
  19359. },
  19360. set: function ( value ) {
  19361. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  19362. this.shadowMap.enabled = value;
  19363. }
  19364. },
  19365. shadowMapType: {
  19366. get: function () {
  19367. return this.shadowMap.type;
  19368. },
  19369. set: function ( value ) {
  19370. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  19371. this.shadowMap.type = value;
  19372. }
  19373. },
  19374. shadowMapCullFace: {
  19375. get: function () {
  19376. return this.shadowMap.cullFace;
  19377. },
  19378. set: function ( value ) {
  19379. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace is now .shadowMap.cullFace.' );
  19380. this.shadowMap.cullFace = value;
  19381. }
  19382. }
  19383. } );
  19384. //
  19385. Object.defineProperties( THREE.WebGLRenderTarget.prototype, {
  19386. wrapS: {
  19387. get: function () {
  19388. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  19389. return this.texture.wrapS;
  19390. },
  19391. set: function ( value ) {
  19392. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  19393. this.texture.wrapS = value;
  19394. }
  19395. },
  19396. wrapT: {
  19397. get: function () {
  19398. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  19399. return this.texture.wrapT;
  19400. },
  19401. set: function ( value ) {
  19402. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  19403. this.texture.wrapT = value;
  19404. }
  19405. },
  19406. magFilter: {
  19407. get: function () {
  19408. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  19409. return this.texture.magFilter;
  19410. },
  19411. set: function ( value ) {
  19412. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  19413. this.texture.magFilter = value;
  19414. }
  19415. },
  19416. minFilter: {
  19417. get: function () {
  19418. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  19419. return this.texture.minFilter;
  19420. },
  19421. set: function ( value ) {
  19422. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  19423. this.texture.minFilter = value;
  19424. }
  19425. },
  19426. anisotropy: {
  19427. get: function () {
  19428. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  19429. return this.texture.anisotropy;
  19430. },
  19431. set: function ( value ) {
  19432. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  19433. this.texture.anisotropy = value;
  19434. }
  19435. },
  19436. offset: {
  19437. get: function () {
  19438. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  19439. return this.texture.offset;
  19440. },
  19441. set: function ( value ) {
  19442. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  19443. this.texture.offset = value;
  19444. }
  19445. },
  19446. repeat: {
  19447. get: function () {
  19448. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  19449. return this.texture.repeat;
  19450. },
  19451. set: function ( value ) {
  19452. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  19453. this.texture.repeat = value;
  19454. }
  19455. },
  19456. format: {
  19457. get: function () {
  19458. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  19459. return this.texture.format;
  19460. },
  19461. set: function ( value ) {
  19462. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  19463. this.texture.format = value;
  19464. }
  19465. },
  19466. type: {
  19467. get: function () {
  19468. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  19469. return this.texture.type;
  19470. },
  19471. set: function ( value ) {
  19472. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  19473. this.texture.type = value;
  19474. }
  19475. },
  19476. generateMipmaps: {
  19477. get: function () {
  19478. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  19479. return this.texture.generateMipmaps;
  19480. },
  19481. set: function ( value ) {
  19482. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  19483. this.texture.generateMipmaps = value;
  19484. }
  19485. }
  19486. } );
  19487. //
  19488. THREE.GeometryUtils = {
  19489. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  19490. console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  19491. var matrix;
  19492. if ( geometry2 instanceof THREE.Mesh ) {
  19493. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  19494. matrix = geometry2.matrix;
  19495. geometry2 = geometry2.geometry;
  19496. }
  19497. geometry1.merge( geometry2, matrix, materialIndexOffset );
  19498. },
  19499. center: function ( geometry ) {
  19500. console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
  19501. return geometry.center();
  19502. }
  19503. };
  19504. THREE.ImageUtils = {
  19505. crossOrigin: undefined,
  19506. loadTexture: function ( url, mapping, onLoad, onError ) {
  19507. console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
  19508. var loader = new THREE.TextureLoader();
  19509. loader.setCrossOrigin( this.crossOrigin );
  19510. var texture = loader.load( url, onLoad, undefined, onError );
  19511. if ( mapping ) texture.mapping = mapping;
  19512. return texture;
  19513. },
  19514. loadTextureCube: function ( urls, mapping, onLoad, onError ) {
  19515. console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
  19516. var loader = new THREE.CubeTextureLoader();
  19517. loader.setCrossOrigin( this.crossOrigin );
  19518. var texture = loader.load( urls, onLoad, undefined, onError );
  19519. if ( mapping ) texture.mapping = mapping;
  19520. return texture;
  19521. },
  19522. loadCompressedTexture: function () {
  19523. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' );
  19524. },
  19525. loadCompressedTextureCube: function () {
  19526. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' );
  19527. }
  19528. };
  19529. //
  19530. THREE.Projector = function () {
  19531. console.error( 'THREE.Projector has been moved to /examples/js/renderers/Projector.js.' );
  19532. this.projectVector = function ( vector, camera ) {
  19533. console.warn( 'THREE.Projector: .projectVector() is now vector.project().' );
  19534. vector.project( camera );
  19535. };
  19536. this.unprojectVector = function ( vector, camera ) {
  19537. console.warn( 'THREE.Projector: .unprojectVector() is now vector.unproject().' );
  19538. vector.unproject( camera );
  19539. };
  19540. this.pickingRay = function ( vector, camera ) {
  19541. console.error( 'THREE.Projector: .pickingRay() is now raycaster.setFromCamera().' );
  19542. };
  19543. };
  19544. //
  19545. THREE.CanvasRenderer = function () {
  19546. console.error( 'THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js' );
  19547. this.domElement = document.createElement( 'canvas' );
  19548. this.clear = function () {};
  19549. this.render = function () {};
  19550. this.setClearColor = function () {};
  19551. this.setSize = function () {};
  19552. };
  19553. //
  19554. THREE.MeshFaceMaterial = THREE.MultiMaterial;
  19555. // File:src/extras/CurveUtils.js
  19556. /**
  19557. * @author zz85 / http://www.lab4games.net/zz85/blog
  19558. */
  19559. THREE.CurveUtils = {
  19560. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  19561. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  19562. },
  19563. // Puay Bing, thanks for helping with this derivative!
  19564. tangentCubicBezier: function ( t, p0, p1, p2, p3 ) {
  19565. return - 3 * p0 * ( 1 - t ) * ( 1 - t ) +
  19566. 3 * p1 * ( 1 - t ) * ( 1 - t ) - 6 * t * p1 * ( 1 - t ) +
  19567. 6 * t * p2 * ( 1 - t ) - 3 * t * t * p2 +
  19568. 3 * t * t * p3;
  19569. },
  19570. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  19571. // To check if my formulas are correct
  19572. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  19573. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  19574. var h01 = - 6 * t * t + 6 * t; // − 2t3 + 3t2
  19575. var h11 = 3 * t * t - 2 * t; // t3 − t2
  19576. return h00 + h10 + h01 + h11;
  19577. },
  19578. // Catmull-Rom
  19579. interpolate: function( p0, p1, p2, p3, t ) {
  19580. var v0 = ( p2 - p0 ) * 0.5;
  19581. var v1 = ( p3 - p1 ) * 0.5;
  19582. var t2 = t * t;
  19583. var t3 = t * t2;
  19584. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  19585. }
  19586. };
  19587. // File:src/extras/SceneUtils.js
  19588. /**
  19589. * @author alteredq / http://alteredqualia.com/
  19590. */
  19591. THREE.SceneUtils = {
  19592. createMultiMaterialObject: function ( geometry, materials ) {
  19593. var group = new THREE.Group();
  19594. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  19595. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  19596. }
  19597. return group;
  19598. },
  19599. detach: function ( child, parent, scene ) {
  19600. child.applyMatrix( parent.matrixWorld );
  19601. parent.remove( child );
  19602. scene.add( child );
  19603. },
  19604. attach: function ( child, scene, parent ) {
  19605. var matrixWorldInverse = new THREE.Matrix4();
  19606. matrixWorldInverse.getInverse( parent.matrixWorld );
  19607. child.applyMatrix( matrixWorldInverse );
  19608. scene.remove( child );
  19609. parent.add( child );
  19610. }
  19611. };
  19612. // File:src/extras/ShapeUtils.js
  19613. /**
  19614. * @author zz85 / http://www.lab4games.net/zz85/blog
  19615. */
  19616. THREE.ShapeUtils = {
  19617. // calculate area of the contour polygon
  19618. area: function ( contour ) {
  19619. var n = contour.length;
  19620. var a = 0.0;
  19621. for ( var p = n - 1, q = 0; q < n; p = q ++ ) {
  19622. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  19623. }
  19624. return a * 0.5;
  19625. },
  19626. triangulate: ( function () {
  19627. /**
  19628. * This code is a quick port of code written in C++ which was submitted to
  19629. * flipcode.com by John W. Ratcliff // July 22, 2000
  19630. * See original code and more information here:
  19631. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  19632. *
  19633. * ported to actionscript by Zevan Rosser
  19634. * www.actionsnippet.com
  19635. *
  19636. * ported to javascript by Joshua Koo
  19637. * http://www.lab4games.net/zz85/blog
  19638. *
  19639. */
  19640. function snip( contour, u, v, w, n, verts ) {
  19641. var p;
  19642. var ax, ay, bx, by;
  19643. var cx, cy, px, py;
  19644. ax = contour[ verts[ u ] ].x;
  19645. ay = contour[ verts[ u ] ].y;
  19646. bx = contour[ verts[ v ] ].x;
  19647. by = contour[ verts[ v ] ].y;
  19648. cx = contour[ verts[ w ] ].x;
  19649. cy = contour[ verts[ w ] ].y;
  19650. if ( Number.EPSILON > ( ( ( bx - ax ) * ( cy - ay ) ) - ( ( by - ay ) * ( cx - ax ) ) ) ) return false;
  19651. var aX, aY, bX, bY, cX, cY;
  19652. var apx, apy, bpx, bpy, cpx, cpy;
  19653. var cCROSSap, bCROSScp, aCROSSbp;
  19654. aX = cx - bx; aY = cy - by;
  19655. bX = ax - cx; bY = ay - cy;
  19656. cX = bx - ax; cY = by - ay;
  19657. for ( p = 0; p < n; p ++ ) {
  19658. px = contour[ verts[ p ] ].x;
  19659. py = contour[ verts[ p ] ].y;
  19660. if ( ( ( px === ax ) && ( py === ay ) ) ||
  19661. ( ( px === bx ) && ( py === by ) ) ||
  19662. ( ( px === cx ) && ( py === cy ) ) ) continue;
  19663. apx = px - ax; apy = py - ay;
  19664. bpx = px - bx; bpy = py - by;
  19665. cpx = px - cx; cpy = py - cy;
  19666. // see if p is inside triangle abc
  19667. aCROSSbp = aX * bpy - aY * bpx;
  19668. cCROSSap = cX * apy - cY * apx;
  19669. bCROSScp = bX * cpy - bY * cpx;
  19670. if ( ( aCROSSbp >= - Number.EPSILON ) && ( bCROSScp >= - Number.EPSILON ) && ( cCROSSap >= - Number.EPSILON ) ) return false;
  19671. }
  19672. return true;
  19673. }
  19674. // takes in an contour array and returns
  19675. return function ( contour, indices ) {
  19676. var n = contour.length;
  19677. if ( n < 3 ) return null;
  19678. var result = [],
  19679. verts = [],
  19680. vertIndices = [];
  19681. /* we want a counter-clockwise polygon in verts */
  19682. var u, v, w;
  19683. if ( THREE.ShapeUtils.area( contour ) > 0.0 ) {
  19684. for ( v = 0; v < n; v ++ ) verts[ v ] = v;
  19685. } else {
  19686. for ( v = 0; v < n; v ++ ) verts[ v ] = ( n - 1 ) - v;
  19687. }
  19688. var nv = n;
  19689. /* remove nv - 2 vertices, creating 1 triangle every time */
  19690. var count = 2 * nv; /* error detection */
  19691. for ( v = nv - 1; nv > 2; ) {
  19692. /* if we loop, it is probably a non-simple polygon */
  19693. if ( ( count -- ) <= 0 ) {
  19694. //** Triangulate: ERROR - probable bad polygon!
  19695. //throw ( "Warning, unable to triangulate polygon!" );
  19696. //return null;
  19697. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  19698. console.warn( 'THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()' );
  19699. if ( indices ) return vertIndices;
  19700. return result;
  19701. }
  19702. /* three consecutive vertices in current polygon, <u,v,w> */
  19703. u = v; if ( nv <= u ) u = 0; /* previous */
  19704. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  19705. w = v + 1; if ( nv <= w ) w = 0; /* next */
  19706. if ( snip( contour, u, v, w, nv, verts ) ) {
  19707. var a, b, c, s, t;
  19708. /* true names of the vertices */
  19709. a = verts[ u ];
  19710. b = verts[ v ];
  19711. c = verts[ w ];
  19712. /* output Triangle */
  19713. result.push( [ contour[ a ],
  19714. contour[ b ],
  19715. contour[ c ] ] );
  19716. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  19717. /* remove v from the remaining polygon */
  19718. for ( s = v, t = v + 1; t < nv; s ++, t ++ ) {
  19719. verts[ s ] = verts[ t ];
  19720. }
  19721. nv --;
  19722. /* reset error detection counter */
  19723. count = 2 * nv;
  19724. }
  19725. }
  19726. if ( indices ) return vertIndices;
  19727. return result;
  19728. }
  19729. } )(),
  19730. triangulateShape: function ( contour, holes ) {
  19731. function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) {
  19732. // inOtherPt needs to be collinear to the inSegment
  19733. if ( inSegPt1.x !== inSegPt2.x ) {
  19734. if ( inSegPt1.x < inSegPt2.x ) {
  19735. return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) );
  19736. } else {
  19737. return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) );
  19738. }
  19739. } else {
  19740. if ( inSegPt1.y < inSegPt2.y ) {
  19741. return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) );
  19742. } else {
  19743. return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) );
  19744. }
  19745. }
  19746. }
  19747. function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) {
  19748. var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y;
  19749. var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y;
  19750. var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x;
  19751. var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y;
  19752. var limit = seg1dy * seg2dx - seg1dx * seg2dy;
  19753. var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy;
  19754. if ( Math.abs( limit ) > Number.EPSILON ) {
  19755. // not parallel
  19756. var perpSeg2;
  19757. if ( limit > 0 ) {
  19758. if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return [];
  19759. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  19760. if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return [];
  19761. } else {
  19762. if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return [];
  19763. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  19764. if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return [];
  19765. }
  19766. // i.e. to reduce rounding errors
  19767. // intersection at endpoint of segment#1?
  19768. if ( perpSeg2 === 0 ) {
  19769. if ( ( inExcludeAdjacentSegs ) &&
  19770. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  19771. return [ inSeg1Pt1 ];
  19772. }
  19773. if ( perpSeg2 === limit ) {
  19774. if ( ( inExcludeAdjacentSegs ) &&
  19775. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  19776. return [ inSeg1Pt2 ];
  19777. }
  19778. // intersection at endpoint of segment#2?
  19779. if ( perpSeg1 === 0 ) return [ inSeg2Pt1 ];
  19780. if ( perpSeg1 === limit ) return [ inSeg2Pt2 ];
  19781. // return real intersection point
  19782. var factorSeg1 = perpSeg2 / limit;
  19783. return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx,
  19784. y: inSeg1Pt1.y + factorSeg1 * seg1dy } ];
  19785. } else {
  19786. // parallel or collinear
  19787. if ( ( perpSeg1 !== 0 ) ||
  19788. ( seg2dy * seg1seg2dx !== seg2dx * seg1seg2dy ) ) return [];
  19789. // they are collinear or degenerate
  19790. var seg1Pt = ( ( seg1dx === 0 ) && ( seg1dy === 0 ) ); // segment1 is just a point?
  19791. var seg2Pt = ( ( seg2dx === 0 ) && ( seg2dy === 0 ) ); // segment2 is just a point?
  19792. // both segments are points
  19793. if ( seg1Pt && seg2Pt ) {
  19794. if ( ( inSeg1Pt1.x !== inSeg2Pt1.x ) ||
  19795. ( inSeg1Pt1.y !== inSeg2Pt1.y ) ) return []; // they are distinct points
  19796. return [ inSeg1Pt1 ]; // they are the same point
  19797. }
  19798. // segment#1 is a single point
  19799. if ( seg1Pt ) {
  19800. if ( ! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2
  19801. return [ inSeg1Pt1 ];
  19802. }
  19803. // segment#2 is a single point
  19804. if ( seg2Pt ) {
  19805. if ( ! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1
  19806. return [ inSeg2Pt1 ];
  19807. }
  19808. // they are collinear segments, which might overlap
  19809. var seg1min, seg1max, seg1minVal, seg1maxVal;
  19810. var seg2min, seg2max, seg2minVal, seg2maxVal;
  19811. if ( seg1dx !== 0 ) {
  19812. // the segments are NOT on a vertical line
  19813. if ( inSeg1Pt1.x < inSeg1Pt2.x ) {
  19814. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x;
  19815. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x;
  19816. } else {
  19817. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x;
  19818. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x;
  19819. }
  19820. if ( inSeg2Pt1.x < inSeg2Pt2.x ) {
  19821. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x;
  19822. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x;
  19823. } else {
  19824. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x;
  19825. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x;
  19826. }
  19827. } else {
  19828. // the segments are on a vertical line
  19829. if ( inSeg1Pt1.y < inSeg1Pt2.y ) {
  19830. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y;
  19831. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y;
  19832. } else {
  19833. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y;
  19834. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y;
  19835. }
  19836. if ( inSeg2Pt1.y < inSeg2Pt2.y ) {
  19837. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y;
  19838. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y;
  19839. } else {
  19840. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y;
  19841. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y;
  19842. }
  19843. }
  19844. if ( seg1minVal <= seg2minVal ) {
  19845. if ( seg1maxVal < seg2minVal ) return [];
  19846. if ( seg1maxVal === seg2minVal ) {
  19847. if ( inExcludeAdjacentSegs ) return [];
  19848. return [ seg2min ];
  19849. }
  19850. if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ];
  19851. return [ seg2min, seg2max ];
  19852. } else {
  19853. if ( seg1minVal > seg2maxVal ) return [];
  19854. if ( seg1minVal === seg2maxVal ) {
  19855. if ( inExcludeAdjacentSegs ) return [];
  19856. return [ seg1min ];
  19857. }
  19858. if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ];
  19859. return [ seg1min, seg2max ];
  19860. }
  19861. }
  19862. }
  19863. function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) {
  19864. // The order of legs is important
  19865. // translation of all points, so that Vertex is at (0,0)
  19866. var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y;
  19867. var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y;
  19868. var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y;
  19869. // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg.
  19870. var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX;
  19871. var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX;
  19872. if ( Math.abs( from2toAngle ) > Number.EPSILON ) {
  19873. // angle != 180 deg.
  19874. var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX;
  19875. // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle );
  19876. if ( from2toAngle > 0 ) {
  19877. // main angle < 180 deg.
  19878. return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) );
  19879. } else {
  19880. // main angle > 180 deg.
  19881. return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) );
  19882. }
  19883. } else {
  19884. // angle == 180 deg.
  19885. // console.log( "from2to: 180 deg., from2other: " + from2otherAngle );
  19886. return ( from2otherAngle > 0 );
  19887. }
  19888. }
  19889. function removeHoles( contour, holes ) {
  19890. var shape = contour.concat(); // work on this shape
  19891. var hole;
  19892. function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) {
  19893. // Check if hole point lies within angle around shape point
  19894. var lastShapeIdx = shape.length - 1;
  19895. var prevShapeIdx = inShapeIdx - 1;
  19896. if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx;
  19897. var nextShapeIdx = inShapeIdx + 1;
  19898. if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0;
  19899. var insideAngle = isPointInsideAngle( shape[ inShapeIdx ], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[ inHoleIdx ] );
  19900. if ( ! insideAngle ) {
  19901. // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y );
  19902. return false;
  19903. }
  19904. // Check if shape point lies within angle around hole point
  19905. var lastHoleIdx = hole.length - 1;
  19906. var prevHoleIdx = inHoleIdx - 1;
  19907. if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx;
  19908. var nextHoleIdx = inHoleIdx + 1;
  19909. if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0;
  19910. insideAngle = isPointInsideAngle( hole[ inHoleIdx ], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[ inShapeIdx ] );
  19911. if ( ! insideAngle ) {
  19912. // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y );
  19913. return false;
  19914. }
  19915. return true;
  19916. }
  19917. function intersectsShapeEdge( inShapePt, inHolePt ) {
  19918. // checks for intersections with shape edges
  19919. var sIdx, nextIdx, intersection;
  19920. for ( sIdx = 0; sIdx < shape.length; sIdx ++ ) {
  19921. nextIdx = sIdx + 1; nextIdx %= shape.length;
  19922. intersection = intersect_segments_2D( inShapePt, inHolePt, shape[ sIdx ], shape[ nextIdx ], true );
  19923. if ( intersection.length > 0 ) return true;
  19924. }
  19925. return false;
  19926. }
  19927. var indepHoles = [];
  19928. function intersectsHoleEdge( inShapePt, inHolePt ) {
  19929. // checks for intersections with hole edges
  19930. var ihIdx, chkHole,
  19931. hIdx, nextIdx, intersection;
  19932. for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx ++ ) {
  19933. chkHole = holes[ indepHoles[ ihIdx ]];
  19934. for ( hIdx = 0; hIdx < chkHole.length; hIdx ++ ) {
  19935. nextIdx = hIdx + 1; nextIdx %= chkHole.length;
  19936. intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[ hIdx ], chkHole[ nextIdx ], true );
  19937. if ( intersection.length > 0 ) return true;
  19938. }
  19939. }
  19940. return false;
  19941. }
  19942. var holeIndex, shapeIndex,
  19943. shapePt, holePt,
  19944. holeIdx, cutKey, failedCuts = [],
  19945. tmpShape1, tmpShape2,
  19946. tmpHole1, tmpHole2;
  19947. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  19948. indepHoles.push( h );
  19949. }
  19950. var minShapeIndex = 0;
  19951. var counter = indepHoles.length * 2;
  19952. while ( indepHoles.length > 0 ) {
  19953. counter --;
  19954. if ( counter < 0 ) {
  19955. console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" );
  19956. break;
  19957. }
  19958. // search for shape-vertex and hole-vertex,
  19959. // which can be connected without intersections
  19960. for ( shapeIndex = minShapeIndex; shapeIndex < shape.length; shapeIndex ++ ) {
  19961. shapePt = shape[ shapeIndex ];
  19962. holeIndex = - 1;
  19963. // search for hole which can be reached without intersections
  19964. for ( var h = 0; h < indepHoles.length; h ++ ) {
  19965. holeIdx = indepHoles[ h ];
  19966. // prevent multiple checks
  19967. cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx;
  19968. if ( failedCuts[ cutKey ] !== undefined ) continue;
  19969. hole = holes[ holeIdx ];
  19970. for ( var h2 = 0; h2 < hole.length; h2 ++ ) {
  19971. holePt = hole[ h2 ];
  19972. if ( ! isCutLineInsideAngles( shapeIndex, h2 ) ) continue;
  19973. if ( intersectsShapeEdge( shapePt, holePt ) ) continue;
  19974. if ( intersectsHoleEdge( shapePt, holePt ) ) continue;
  19975. holeIndex = h2;
  19976. indepHoles.splice( h, 1 );
  19977. tmpShape1 = shape.slice( 0, shapeIndex + 1 );
  19978. tmpShape2 = shape.slice( shapeIndex );
  19979. tmpHole1 = hole.slice( holeIndex );
  19980. tmpHole2 = hole.slice( 0, holeIndex + 1 );
  19981. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  19982. minShapeIndex = shapeIndex;
  19983. // Debug only, to show the selected cuts
  19984. // glob_CutLines.push( [ shapePt, holePt ] );
  19985. break;
  19986. }
  19987. if ( holeIndex >= 0 ) break; // hole-vertex found
  19988. failedCuts[ cutKey ] = true; // remember failure
  19989. }
  19990. if ( holeIndex >= 0 ) break; // hole-vertex found
  19991. }
  19992. }
  19993. return shape; /* shape with no holes */
  19994. }
  19995. var i, il, f, face,
  19996. key, index,
  19997. allPointsMap = {};
  19998. // 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.
  19999. var allpoints = contour.concat();
  20000. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  20001. Array.prototype.push.apply( allpoints, holes[ h ] );
  20002. }
  20003. //console.log( "allpoints",allpoints, allpoints.length );
  20004. // prepare all points map
  20005. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  20006. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  20007. if ( allPointsMap[ key ] !== undefined ) {
  20008. console.warn( "THREE.Shape: Duplicate point", key );
  20009. }
  20010. allPointsMap[ key ] = i;
  20011. }
  20012. // remove holes by cutting paths to holes and adding them to the shape
  20013. var shapeWithoutHoles = removeHoles( contour, holes );
  20014. var triangles = THREE.ShapeUtils.triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape
  20015. //console.log( "triangles",triangles, triangles.length );
  20016. // check all face vertices against all points map
  20017. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  20018. face = triangles[ i ];
  20019. for ( f = 0; f < 3; f ++ ) {
  20020. key = face[ f ].x + ":" + face[ f ].y;
  20021. index = allPointsMap[ key ];
  20022. if ( index !== undefined ) {
  20023. face[ f ] = index;
  20024. }
  20025. }
  20026. }
  20027. return triangles.concat();
  20028. },
  20029. isClockWise: function ( pts ) {
  20030. return THREE.ShapeUtils.area( pts ) < 0;
  20031. },
  20032. // Bezier Curves formulas obtained from
  20033. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  20034. // Quad Bezier Functions
  20035. b2: ( function () {
  20036. function b2p0( t, p ) {
  20037. var k = 1 - t;
  20038. return k * k * p;
  20039. }
  20040. function b2p1( t, p ) {
  20041. return 2 * ( 1 - t ) * t * p;
  20042. }
  20043. function b2p2( t, p ) {
  20044. return t * t * p;
  20045. }
  20046. return function ( t, p0, p1, p2 ) {
  20047. return b2p0( t, p0 ) + b2p1( t, p1 ) + b2p2( t, p2 );
  20048. };
  20049. } )(),
  20050. // Cubic Bezier Functions
  20051. b3: ( function () {
  20052. function b3p0( t, p ) {
  20053. var k = 1 - t;
  20054. return k * k * k * p;
  20055. }
  20056. function b3p1( t, p ) {
  20057. var k = 1 - t;
  20058. return 3 * k * k * t * p;
  20059. }
  20060. function b3p2( t, p ) {
  20061. var k = 1 - t;
  20062. return 3 * k * t * t * p;
  20063. }
  20064. function b3p3( t, p ) {
  20065. return t * t * t * p;
  20066. }
  20067. return function ( t, p0, p1, p2, p3 ) {
  20068. return b3p0( t, p0 ) + b3p1( t, p1 ) + b3p2( t, p2 ) + b3p3( t, p3 );
  20069. };
  20070. } )()
  20071. };
  20072. // File:src/extras/core/Curve.js
  20073. /**
  20074. * @author zz85 / http://www.lab4games.net/zz85/blog
  20075. * Extensible curve object
  20076. *
  20077. * Some common of Curve methods
  20078. * .getPoint(t), getTangent(t)
  20079. * .getPointAt(u), getTagentAt(u)
  20080. * .getPoints(), .getSpacedPoints()
  20081. * .getLength()
  20082. * .updateArcLengths()
  20083. *
  20084. * This following classes subclasses THREE.Curve:
  20085. *
  20086. * -- 2d classes --
  20087. * THREE.LineCurve
  20088. * THREE.QuadraticBezierCurve
  20089. * THREE.CubicBezierCurve
  20090. * THREE.SplineCurve
  20091. * THREE.ArcCurve
  20092. * THREE.EllipseCurve
  20093. *
  20094. * -- 3d classes --
  20095. * THREE.LineCurve3
  20096. * THREE.QuadraticBezierCurve3
  20097. * THREE.CubicBezierCurve3
  20098. * THREE.SplineCurve3
  20099. * THREE.ClosedSplineCurve3
  20100. *
  20101. * A series of curves can be represented as a THREE.CurvePath
  20102. *
  20103. **/
  20104. /**************************************************************
  20105. * Abstract Curve base class
  20106. **************************************************************/
  20107. THREE.Curve = function () {
  20108. };
  20109. THREE.Curve.prototype = {
  20110. constructor: THREE.Curve,
  20111. // Virtual base class method to overwrite and implement in subclasses
  20112. // - t [0 .. 1]
  20113. getPoint: function ( t ) {
  20114. console.warn( "THREE.Curve: Warning, getPoint() not implemented!" );
  20115. return null;
  20116. },
  20117. // Get point at relative position in curve according to arc length
  20118. // - u [0 .. 1]
  20119. getPointAt: function ( u ) {
  20120. var t = this.getUtoTmapping( u );
  20121. return this.getPoint( t );
  20122. },
  20123. // Get sequence of points using getPoint( t )
  20124. getPoints: function ( divisions ) {
  20125. if ( ! divisions ) divisions = 5;
  20126. var d, pts = [];
  20127. for ( d = 0; d <= divisions; d ++ ) {
  20128. pts.push( this.getPoint( d / divisions ) );
  20129. }
  20130. return pts;
  20131. },
  20132. // Get sequence of points using getPointAt( u )
  20133. getSpacedPoints: function ( divisions ) {
  20134. if ( ! divisions ) divisions = 5;
  20135. var d, pts = [];
  20136. for ( d = 0; d <= divisions; d ++ ) {
  20137. pts.push( this.getPointAt( d / divisions ) );
  20138. }
  20139. return pts;
  20140. },
  20141. // Get total curve arc length
  20142. getLength: function () {
  20143. var lengths = this.getLengths();
  20144. return lengths[ lengths.length - 1 ];
  20145. },
  20146. // Get list of cumulative segment lengths
  20147. getLengths: function ( divisions ) {
  20148. if ( ! divisions ) divisions = ( this.__arcLengthDivisions ) ? ( this.__arcLengthDivisions ) : 200;
  20149. if ( this.cacheArcLengths
  20150. && ( this.cacheArcLengths.length === divisions + 1 )
  20151. && ! this.needsUpdate ) {
  20152. //console.log( "cached", this.cacheArcLengths );
  20153. return this.cacheArcLengths;
  20154. }
  20155. this.needsUpdate = false;
  20156. var cache = [];
  20157. var current, last = this.getPoint( 0 );
  20158. var p, sum = 0;
  20159. cache.push( 0 );
  20160. for ( p = 1; p <= divisions; p ++ ) {
  20161. current = this.getPoint ( p / divisions );
  20162. sum += current.distanceTo( last );
  20163. cache.push( sum );
  20164. last = current;
  20165. }
  20166. this.cacheArcLengths = cache;
  20167. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  20168. },
  20169. updateArcLengths: function() {
  20170. this.needsUpdate = true;
  20171. this.getLengths();
  20172. },
  20173. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  20174. getUtoTmapping: function ( u, distance ) {
  20175. var arcLengths = this.getLengths();
  20176. var i = 0, il = arcLengths.length;
  20177. var targetArcLength; // The targeted u distance value to get
  20178. if ( distance ) {
  20179. targetArcLength = distance;
  20180. } else {
  20181. targetArcLength = u * arcLengths[ il - 1 ];
  20182. }
  20183. //var time = Date.now();
  20184. // binary search for the index with largest value smaller than target u distance
  20185. var low = 0, high = il - 1, comparison;
  20186. while ( low <= high ) {
  20187. 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
  20188. comparison = arcLengths[ i ] - targetArcLength;
  20189. if ( comparison < 0 ) {
  20190. low = i + 1;
  20191. } else if ( comparison > 0 ) {
  20192. high = i - 1;
  20193. } else {
  20194. high = i;
  20195. break;
  20196. // DONE
  20197. }
  20198. }
  20199. i = high;
  20200. //console.log('b' , i, low, high, Date.now()- time);
  20201. if ( arcLengths[ i ] === targetArcLength ) {
  20202. var t = i / ( il - 1 );
  20203. return t;
  20204. }
  20205. // we could get finer grain at lengths, or use simple interpolation between two points
  20206. var lengthBefore = arcLengths[ i ];
  20207. var lengthAfter = arcLengths[ i + 1 ];
  20208. var segmentLength = lengthAfter - lengthBefore;
  20209. // determine where we are between the 'before' and 'after' points
  20210. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  20211. // add that fractional amount to t
  20212. var t = ( i + segmentFraction ) / ( il - 1 );
  20213. return t;
  20214. },
  20215. // Returns a unit vector tangent at t
  20216. // In case any sub curve does not implement its tangent derivation,
  20217. // 2 points a small delta apart will be used to find its gradient
  20218. // which seems to give a reasonable approximation
  20219. getTangent: function( t ) {
  20220. var delta = 0.0001;
  20221. var t1 = t - delta;
  20222. var t2 = t + delta;
  20223. // Capping in case of danger
  20224. if ( t1 < 0 ) t1 = 0;
  20225. if ( t2 > 1 ) t2 = 1;
  20226. var pt1 = this.getPoint( t1 );
  20227. var pt2 = this.getPoint( t2 );
  20228. var vec = pt2.clone().sub( pt1 );
  20229. return vec.normalize();
  20230. },
  20231. getTangentAt: function ( u ) {
  20232. var t = this.getUtoTmapping( u );
  20233. return this.getTangent( t );
  20234. }
  20235. };
  20236. // TODO: Transformation for Curves?
  20237. /**************************************************************
  20238. * 3D Curves
  20239. **************************************************************/
  20240. // A Factory method for creating new curve subclasses
  20241. THREE.Curve.create = function ( constructor, getPointFunc ) {
  20242. constructor.prototype = Object.create( THREE.Curve.prototype );
  20243. constructor.prototype.constructor = constructor;
  20244. constructor.prototype.getPoint = getPointFunc;
  20245. return constructor;
  20246. };
  20247. // File:src/extras/core/CurvePath.js
  20248. /**
  20249. * @author zz85 / http://www.lab4games.net/zz85/blog
  20250. *
  20251. **/
  20252. /**************************************************************
  20253. * Curved Path - a curve path is simply a array of connected
  20254. * curves, but retains the api of a curve
  20255. **************************************************************/
  20256. THREE.CurvePath = function () {
  20257. this.curves = [];
  20258. this.autoClose = false; // Automatically closes the path
  20259. };
  20260. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  20261. THREE.CurvePath.prototype.constructor = THREE.CurvePath;
  20262. THREE.CurvePath.prototype.add = function ( curve ) {
  20263. this.curves.push( curve );
  20264. };
  20265. /*
  20266. THREE.CurvePath.prototype.checkConnection = function() {
  20267. // TODO
  20268. // If the ending of curve is not connected to the starting
  20269. // or the next curve, then, this is not a real path
  20270. };
  20271. */
  20272. THREE.CurvePath.prototype.closePath = function() {
  20273. // TODO Test
  20274. // and verify for vector3 (needs to implement equals)
  20275. // Add a line curve if start and end of lines are not connected
  20276. var startPoint = this.curves[ 0 ].getPoint( 0 );
  20277. var endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  20278. if ( ! startPoint.equals( endPoint ) ) {
  20279. this.curves.push( new THREE.LineCurve( endPoint, startPoint ) );
  20280. }
  20281. };
  20282. // To get accurate point with reference to
  20283. // entire path distance at time t,
  20284. // following has to be done:
  20285. // 1. Length of each sub path have to be known
  20286. // 2. Locate and identify type of curve
  20287. // 3. Get t for the curve
  20288. // 4. Return curve.getPointAt(t')
  20289. THREE.CurvePath.prototype.getPoint = function( t ) {
  20290. var d = t * this.getLength();
  20291. var curveLengths = this.getCurveLengths();
  20292. var i = 0;
  20293. // To think about boundaries points.
  20294. while ( i < curveLengths.length ) {
  20295. if ( curveLengths[ i ] >= d ) {
  20296. var diff = curveLengths[ i ] - d;
  20297. var curve = this.curves[ i ];
  20298. var u = 1 - diff / curve.getLength();
  20299. return curve.getPointAt( u );
  20300. }
  20301. i ++;
  20302. }
  20303. return null;
  20304. // loop where sum != 0, sum > d , sum+1 <d
  20305. };
  20306. /*
  20307. THREE.CurvePath.prototype.getTangent = function( t ) {
  20308. };
  20309. */
  20310. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  20311. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  20312. // getPoint() depends on getLength
  20313. THREE.CurvePath.prototype.getLength = function() {
  20314. var lens = this.getCurveLengths();
  20315. return lens[ lens.length - 1 ];
  20316. };
  20317. // Compute lengths and cache them
  20318. // We cannot overwrite getLengths() because UtoT mapping uses it.
  20319. THREE.CurvePath.prototype.getCurveLengths = function() {
  20320. // We use cache values if curves and cache array are same length
  20321. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  20322. return this.cacheLengths;
  20323. }
  20324. // Get length of sub-curve
  20325. // Push sums into cached array
  20326. var lengths = [], sums = 0;
  20327. for ( var i = 0, l = this.curves.length; i < l; i ++ ) {
  20328. sums += this.curves[ i ].getLength();
  20329. lengths.push( sums );
  20330. }
  20331. this.cacheLengths = lengths;
  20332. return lengths;
  20333. };
  20334. /**************************************************************
  20335. * Create Geometries Helpers
  20336. **************************************************************/
  20337. /// Generate geometry from path points (for Line or Points objects)
  20338. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  20339. var pts = this.getPoints( divisions );
  20340. return this.createGeometry( pts );
  20341. };
  20342. // Generate geometry from equidistant sampling along the path
  20343. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  20344. var pts = this.getSpacedPoints( divisions );
  20345. return this.createGeometry( pts );
  20346. };
  20347. THREE.CurvePath.prototype.createGeometry = function( points ) {
  20348. var geometry = new THREE.Geometry();
  20349. for ( var i = 0, l = points.length; i < l; i ++ ) {
  20350. var point = points[ i ];
  20351. geometry.vertices.push( new THREE.Vector3( point.x, point.y, point.z || 0 ) );
  20352. }
  20353. return geometry;
  20354. };
  20355. // File:src/extras/core/Font.js
  20356. /**
  20357. * @author zz85 / http://www.lab4games.net/zz85/blog
  20358. * @author mrdoob / http://mrdoob.com/
  20359. */
  20360. THREE.Font = function ( data ) {
  20361. this.data = data;
  20362. };
  20363. THREE.Font.prototype = {
  20364. constructor: THREE.Font,
  20365. generateShapes: function ( text, size, divisions ) {
  20366. function createPaths( text ) {
  20367. var chars = String( text ).split( '' );
  20368. var scale = size / data.resolution;
  20369. var offset = 0;
  20370. var paths = [];
  20371. for ( var i = 0; i < chars.length; i ++ ) {
  20372. var ret = createPath( chars[ i ], scale, offset );
  20373. offset += ret.offset;
  20374. paths.push( ret.path );
  20375. }
  20376. return paths;
  20377. }
  20378. function createPath( c, scale, offset ) {
  20379. var glyph = data.glyphs[ c ] || data.glyphs[ '?' ];
  20380. if ( ! glyph ) return;
  20381. var path = new THREE.Path();
  20382. var pts = [], b2 = THREE.ShapeUtils.b2, b3 = THREE.ShapeUtils.b3;
  20383. var x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2, laste;
  20384. if ( glyph.o ) {
  20385. var outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  20386. for ( var i = 0, l = outline.length; i < l; ) {
  20387. var action = outline[ i ++ ];
  20388. switch ( action ) {
  20389. case 'm': // moveTo
  20390. x = outline[ i ++ ] * scale + offset;
  20391. y = outline[ i ++ ] * scale;
  20392. path.moveTo( x, y );
  20393. break;
  20394. case 'l': // lineTo
  20395. x = outline[ i ++ ] * scale + offset;
  20396. y = outline[ i ++ ] * scale;
  20397. path.lineTo( x, y );
  20398. break;
  20399. case 'q': // quadraticCurveTo
  20400. cpx = outline[ i ++ ] * scale + offset;
  20401. cpy = outline[ i ++ ] * scale;
  20402. cpx1 = outline[ i ++ ] * scale + offset;
  20403. cpy1 = outline[ i ++ ] * scale;
  20404. path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
  20405. laste = pts[ pts.length - 1 ];
  20406. if ( laste ) {
  20407. cpx0 = laste.x;
  20408. cpy0 = laste.y;
  20409. for ( var i2 = 1; i2 <= divisions; i2 ++ ) {
  20410. var t = i2 / divisions;
  20411. b2( t, cpx0, cpx1, cpx );
  20412. b2( t, cpy0, cpy1, cpy );
  20413. }
  20414. }
  20415. break;
  20416. case 'b': // bezierCurveTo
  20417. cpx = outline[ i ++ ] * scale + offset;
  20418. cpy = outline[ i ++ ] * scale;
  20419. cpx1 = outline[ i ++ ] * scale + offset;
  20420. cpy1 = outline[ i ++ ] * scale;
  20421. cpx2 = outline[ i ++ ] * scale + offset;
  20422. cpy2 = outline[ i ++ ] * scale;
  20423. path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
  20424. laste = pts[ pts.length - 1 ];
  20425. if ( laste ) {
  20426. cpx0 = laste.x;
  20427. cpy0 = laste.y;
  20428. for ( var i2 = 1; i2 <= divisions; i2 ++ ) {
  20429. var t = i2 / divisions;
  20430. b3( t, cpx0, cpx1, cpx2, cpx );
  20431. b3( t, cpy0, cpy1, cpy2, cpy );
  20432. }
  20433. }
  20434. break;
  20435. }
  20436. }
  20437. }
  20438. return { offset: glyph.ha * scale, path: path };
  20439. }
  20440. //
  20441. if ( size === undefined ) size = 100;
  20442. if ( divisions === undefined ) divisions = 4;
  20443. var data = this.data;
  20444. var paths = createPaths( text );
  20445. var shapes = [];
  20446. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  20447. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  20448. }
  20449. return shapes;
  20450. }
  20451. };
  20452. // File:src/extras/core/Path.js
  20453. /**
  20454. * @author zz85 / http://www.lab4games.net/zz85/blog
  20455. * Creates free form 2d path using series of points, lines or curves.
  20456. *
  20457. **/
  20458. THREE.Path = function ( points ) {
  20459. THREE.CurvePath.call( this );
  20460. this.actions = [];
  20461. if ( points ) {
  20462. this.fromPoints( points );
  20463. }
  20464. };
  20465. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  20466. THREE.Path.prototype.constructor = THREE.Path;
  20467. // TODO Clean up PATH API
  20468. // Create path using straight lines to connect all points
  20469. // - vectors: array of Vector2
  20470. THREE.Path.prototype.fromPoints = function ( vectors ) {
  20471. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  20472. for ( var i = 1, l = vectors.length; i < l; i ++ ) {
  20473. this.lineTo( vectors[ i ].x, vectors[ i ].y );
  20474. }
  20475. };
  20476. // startPath() endPath()?
  20477. THREE.Path.prototype.moveTo = function ( x, y ) {
  20478. this.actions.push( { action: 'moveTo', args: [ x, y ] } );
  20479. };
  20480. THREE.Path.prototype.lineTo = function ( x, y ) {
  20481. var lastargs = this.actions[ this.actions.length - 1 ].args;
  20482. var x0 = lastargs[ lastargs.length - 2 ];
  20483. var y0 = lastargs[ lastargs.length - 1 ];
  20484. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  20485. this.curves.push( curve );
  20486. this.actions.push( { action: 'lineTo', args: [ x, y ] } );
  20487. };
  20488. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  20489. var lastargs = this.actions[ this.actions.length - 1 ].args;
  20490. var x0 = lastargs[ lastargs.length - 2 ];
  20491. var y0 = lastargs[ lastargs.length - 1 ];
  20492. var curve = new THREE.QuadraticBezierCurve(
  20493. new THREE.Vector2( x0, y0 ),
  20494. new THREE.Vector2( aCPx, aCPy ),
  20495. new THREE.Vector2( aX, aY )
  20496. );
  20497. this.curves.push( curve );
  20498. this.actions.push( { action: 'quadraticCurveTo', args: [ aCPx, aCPy, aX, aY ] } );
  20499. };
  20500. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  20501. var lastargs = this.actions[ this.actions.length - 1 ].args;
  20502. var x0 = lastargs[ lastargs.length - 2 ];
  20503. var y0 = lastargs[ lastargs.length - 1 ];
  20504. var curve = new THREE.CubicBezierCurve(
  20505. new THREE.Vector2( x0, y0 ),
  20506. new THREE.Vector2( aCP1x, aCP1y ),
  20507. new THREE.Vector2( aCP2x, aCP2y ),
  20508. new THREE.Vector2( aX, aY )
  20509. );
  20510. this.curves.push( curve );
  20511. this.actions.push( { action: 'bezierCurveTo', args: [ aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ] } );
  20512. };
  20513. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  20514. var args = Array.prototype.slice.call( arguments );
  20515. var lastargs = this.actions[ this.actions.length - 1 ].args;
  20516. var x0 = lastargs[ lastargs.length - 2 ];
  20517. var y0 = lastargs[ lastargs.length - 1 ];
  20518. var npts = [ new THREE.Vector2( x0, y0 ) ];
  20519. Array.prototype.push.apply( npts, pts );
  20520. var curve = new THREE.SplineCurve( npts );
  20521. this.curves.push( curve );
  20522. this.actions.push( { action: 'splineThru', args: args } );
  20523. };
  20524. // FUTURE: Change the API or follow canvas API?
  20525. THREE.Path.prototype.arc = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  20526. var lastargs = this.actions[ this.actions.length - 1 ].args;
  20527. var x0 = lastargs[ lastargs.length - 2 ];
  20528. var y0 = lastargs[ lastargs.length - 1 ];
  20529. this.absarc( aX + x0, aY + y0, aRadius,
  20530. aStartAngle, aEndAngle, aClockwise );
  20531. };
  20532. THREE.Path.prototype.absarc = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  20533. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  20534. };
  20535. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  20536. var lastargs = this.actions[ this.actions.length - 1 ].args;
  20537. var x0 = lastargs[ lastargs.length - 2 ];
  20538. var y0 = lastargs[ lastargs.length - 1 ];
  20539. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  20540. };
  20541. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  20542. var args = [
  20543. aX, aY,
  20544. xRadius, yRadius,
  20545. aStartAngle, aEndAngle,
  20546. aClockwise,
  20547. aRotation || 0 // aRotation is optional.
  20548. ];
  20549. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  20550. this.curves.push( curve );
  20551. var lastPoint = curve.getPoint( 1 );
  20552. args.push( lastPoint.x );
  20553. args.push( lastPoint.y );
  20554. this.actions.push( { action: 'ellipse', args: args } );
  20555. };
  20556. THREE.Path.prototype.getSpacedPoints = function ( divisions ) {
  20557. if ( ! divisions ) divisions = 40;
  20558. var points = [];
  20559. for ( var i = 0; i < divisions; i ++ ) {
  20560. points.push( this.getPoint( i / divisions ) );
  20561. //if ( !this.getPoint( i / divisions ) ) throw "DIE";
  20562. }
  20563. if ( this.autoClose ) {
  20564. points.push( points[ 0 ] );
  20565. }
  20566. return points;
  20567. };
  20568. /* Return an array of vectors based on contour of the path */
  20569. THREE.Path.prototype.getPoints = function( divisions ) {
  20570. divisions = divisions || 12;
  20571. var b2 = THREE.ShapeUtils.b2;
  20572. var b3 = THREE.ShapeUtils.b3;
  20573. var points = [];
  20574. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  20575. laste, tx, ty;
  20576. for ( var i = 0, l = this.actions.length; i < l; i ++ ) {
  20577. var item = this.actions[ i ];
  20578. var action = item.action;
  20579. var args = item.args;
  20580. switch ( action ) {
  20581. case 'moveTo':
  20582. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  20583. break;
  20584. case 'lineTo':
  20585. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  20586. break;
  20587. case 'quadraticCurveTo':
  20588. cpx = args[ 2 ];
  20589. cpy = args[ 3 ];
  20590. cpx1 = args[ 0 ];
  20591. cpy1 = args[ 1 ];
  20592. if ( points.length > 0 ) {
  20593. laste = points[ points.length - 1 ];
  20594. cpx0 = laste.x;
  20595. cpy0 = laste.y;
  20596. } else {
  20597. laste = this.actions[ i - 1 ].args;
  20598. cpx0 = laste[ laste.length - 2 ];
  20599. cpy0 = laste[ laste.length - 1 ];
  20600. }
  20601. for ( var j = 1; j <= divisions; j ++ ) {
  20602. var t = j / divisions;
  20603. tx = b2( t, cpx0, cpx1, cpx );
  20604. ty = b2( t, cpy0, cpy1, cpy );
  20605. points.push( new THREE.Vector2( tx, ty ) );
  20606. }
  20607. break;
  20608. case 'bezierCurveTo':
  20609. cpx = args[ 4 ];
  20610. cpy = args[ 5 ];
  20611. cpx1 = args[ 0 ];
  20612. cpy1 = args[ 1 ];
  20613. cpx2 = args[ 2 ];
  20614. cpy2 = args[ 3 ];
  20615. if ( points.length > 0 ) {
  20616. laste = points[ points.length - 1 ];
  20617. cpx0 = laste.x;
  20618. cpy0 = laste.y;
  20619. } else {
  20620. laste = this.actions[ i - 1 ].args;
  20621. cpx0 = laste[ laste.length - 2 ];
  20622. cpy0 = laste[ laste.length - 1 ];
  20623. }
  20624. for ( var j = 1; j <= divisions; j ++ ) {
  20625. var t = j / divisions;
  20626. tx = b3( t, cpx0, cpx1, cpx2, cpx );
  20627. ty = b3( t, cpy0, cpy1, cpy2, cpy );
  20628. points.push( new THREE.Vector2( tx, ty ) );
  20629. }
  20630. break;
  20631. case 'splineThru':
  20632. laste = this.actions[ i - 1 ].args;
  20633. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  20634. var spts = [ last ];
  20635. var n = divisions * args[ 0 ].length;
  20636. spts = spts.concat( args[ 0 ] );
  20637. var spline = new THREE.SplineCurve( spts );
  20638. for ( var j = 1; j <= n; j ++ ) {
  20639. points.push( spline.getPointAt( j / n ) );
  20640. }
  20641. break;
  20642. case 'arc':
  20643. var aX = args[ 0 ], aY = args[ 1 ],
  20644. aRadius = args[ 2 ],
  20645. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  20646. aClockwise = !! args[ 5 ];
  20647. var deltaAngle = aEndAngle - aStartAngle;
  20648. var angle;
  20649. var tdivisions = divisions * 2;
  20650. for ( var j = 1; j <= tdivisions; j ++ ) {
  20651. var t = j / tdivisions;
  20652. if ( ! aClockwise ) {
  20653. t = 1 - t;
  20654. }
  20655. angle = aStartAngle + t * deltaAngle;
  20656. tx = aX + aRadius * Math.cos( angle );
  20657. ty = aY + aRadius * Math.sin( angle );
  20658. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  20659. points.push( new THREE.Vector2( tx, ty ) );
  20660. }
  20661. //console.log(points);
  20662. break;
  20663. case 'ellipse':
  20664. var aX = args[ 0 ], aY = args[ 1 ],
  20665. xRadius = args[ 2 ],
  20666. yRadius = args[ 3 ],
  20667. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  20668. aClockwise = !! args[ 6 ],
  20669. aRotation = args[ 7 ];
  20670. var deltaAngle = aEndAngle - aStartAngle;
  20671. var angle;
  20672. var tdivisions = divisions * 2;
  20673. var cos, sin;
  20674. if ( aRotation !== 0 ) {
  20675. cos = Math.cos( aRotation );
  20676. sin = Math.sin( aRotation );
  20677. }
  20678. for ( var j = 1; j <= tdivisions; j ++ ) {
  20679. var t = j / tdivisions;
  20680. if ( ! aClockwise ) {
  20681. t = 1 - t;
  20682. }
  20683. angle = aStartAngle + t * deltaAngle;
  20684. tx = aX + xRadius * Math.cos( angle );
  20685. ty = aY + yRadius * Math.sin( angle );
  20686. if ( aRotation !== 0 ) {
  20687. var x = tx, y = ty;
  20688. // Rotate the point about the center of the ellipse.
  20689. tx = ( x - aX ) * cos - ( y - aY ) * sin + aX;
  20690. ty = ( x - aX ) * sin + ( y - aY ) * cos + aY;
  20691. }
  20692. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  20693. points.push( new THREE.Vector2( tx, ty ) );
  20694. }
  20695. //console.log(points);
  20696. break;
  20697. } // end switch
  20698. }
  20699. // Normalize to remove the closing point by default.
  20700. var lastPoint = points[ points.length - 1 ];
  20701. if ( Math.abs( lastPoint.x - points[ 0 ].x ) < Number.EPSILON &&
  20702. Math.abs( lastPoint.y - points[ 0 ].y ) < Number.EPSILON )
  20703. points.splice( points.length - 1, 1 );
  20704. if ( this.autoClose ) {
  20705. points.push( points[ 0 ] );
  20706. }
  20707. return points;
  20708. };
  20709. //
  20710. // Breaks path into shapes
  20711. //
  20712. // Assumptions (if parameter isCCW==true the opposite holds):
  20713. // - solid shapes are defined clockwise (CW)
  20714. // - holes are defined counterclockwise (CCW)
  20715. //
  20716. // If parameter noHoles==true:
  20717. // - all subPaths are regarded as solid shapes
  20718. // - definition order CW/CCW has no relevance
  20719. //
  20720. THREE.Path.prototype.toShapes = function( isCCW, noHoles ) {
  20721. function extractSubpaths( inActions ) {
  20722. var subPaths = [], lastPath = new THREE.Path();
  20723. for ( var i = 0, l = inActions.length; i < l; i ++ ) {
  20724. var item = inActions[ i ];
  20725. var args = item.args;
  20726. var action = item.action;
  20727. if ( action === 'moveTo' ) {
  20728. if ( lastPath.actions.length !== 0 ) {
  20729. subPaths.push( lastPath );
  20730. lastPath = new THREE.Path();
  20731. }
  20732. }
  20733. lastPath[ action ].apply( lastPath, args );
  20734. }
  20735. if ( lastPath.actions.length !== 0 ) {
  20736. subPaths.push( lastPath );
  20737. }
  20738. // console.log(subPaths);
  20739. return subPaths;
  20740. }
  20741. function toShapesNoHoles( inSubpaths ) {
  20742. var shapes = [];
  20743. for ( var i = 0, l = inSubpaths.length; i < l; i ++ ) {
  20744. var tmpPath = inSubpaths[ i ];
  20745. var tmpShape = new THREE.Shape();
  20746. tmpShape.actions = tmpPath.actions;
  20747. tmpShape.curves = tmpPath.curves;
  20748. shapes.push( tmpShape );
  20749. }
  20750. //console.log("shape", shapes);
  20751. return shapes;
  20752. }
  20753. function isPointInsidePolygon( inPt, inPolygon ) {
  20754. var polyLen = inPolygon.length;
  20755. // inPt on polygon contour => immediate success or
  20756. // toggling of inside/outside at every single! intersection point of an edge
  20757. // with the horizontal line through inPt, left of inPt
  20758. // not counting lowerY endpoints of edges and whole edges on that line
  20759. var inside = false;
  20760. for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  20761. var edgeLowPt = inPolygon[ p ];
  20762. var edgeHighPt = inPolygon[ q ];
  20763. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  20764. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  20765. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  20766. // not parallel
  20767. if ( edgeDy < 0 ) {
  20768. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  20769. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  20770. }
  20771. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  20772. if ( inPt.y === edgeLowPt.y ) {
  20773. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  20774. // continue; // no intersection or edgeLowPt => doesn't count !!!
  20775. } else {
  20776. var perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  20777. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  20778. if ( perpEdge < 0 ) continue;
  20779. inside = ! inside; // true intersection left of inPt
  20780. }
  20781. } else {
  20782. // parallel or collinear
  20783. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  20784. // edge lies on the same horizontal line as inPt
  20785. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  20786. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  20787. // continue;
  20788. }
  20789. }
  20790. return inside;
  20791. }
  20792. var isClockWise = THREE.ShapeUtils.isClockWise;
  20793. var subPaths = extractSubpaths( this.actions );
  20794. if ( subPaths.length === 0 ) return [];
  20795. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  20796. var solid, tmpPath, tmpShape, shapes = [];
  20797. if ( subPaths.length === 1 ) {
  20798. tmpPath = subPaths[ 0 ];
  20799. tmpShape = new THREE.Shape();
  20800. tmpShape.actions = tmpPath.actions;
  20801. tmpShape.curves = tmpPath.curves;
  20802. shapes.push( tmpShape );
  20803. return shapes;
  20804. }
  20805. var holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  20806. holesFirst = isCCW ? ! holesFirst : holesFirst;
  20807. // console.log("Holes first", holesFirst);
  20808. var betterShapeHoles = [];
  20809. var newShapes = [];
  20810. var newShapeHoles = [];
  20811. var mainIdx = 0;
  20812. var tmpPoints;
  20813. newShapes[ mainIdx ] = undefined;
  20814. newShapeHoles[ mainIdx ] = [];
  20815. for ( var i = 0, l = subPaths.length; i < l; i ++ ) {
  20816. tmpPath = subPaths[ i ];
  20817. tmpPoints = tmpPath.getPoints();
  20818. solid = isClockWise( tmpPoints );
  20819. solid = isCCW ? ! solid : solid;
  20820. if ( solid ) {
  20821. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  20822. newShapes[ mainIdx ] = { s: new THREE.Shape(), p: tmpPoints };
  20823. newShapes[ mainIdx ].s.actions = tmpPath.actions;
  20824. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  20825. if ( holesFirst ) mainIdx ++;
  20826. newShapeHoles[ mainIdx ] = [];
  20827. //console.log('cw', i);
  20828. } else {
  20829. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  20830. //console.log('ccw', i);
  20831. }
  20832. }
  20833. // only Holes? -> probably all Shapes with wrong orientation
  20834. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  20835. if ( newShapes.length > 1 ) {
  20836. var ambiguous = false;
  20837. var toChange = [];
  20838. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  20839. betterShapeHoles[ sIdx ] = [];
  20840. }
  20841. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  20842. var sho = newShapeHoles[ sIdx ];
  20843. for ( var hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  20844. var ho = sho[ hIdx ];
  20845. var hole_unassigned = true;
  20846. for ( var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  20847. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  20848. if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  20849. if ( hole_unassigned ) {
  20850. hole_unassigned = false;
  20851. betterShapeHoles[ s2Idx ].push( ho );
  20852. } else {
  20853. ambiguous = true;
  20854. }
  20855. }
  20856. }
  20857. if ( hole_unassigned ) {
  20858. betterShapeHoles[ sIdx ].push( ho );
  20859. }
  20860. }
  20861. }
  20862. // console.log("ambiguous: ", ambiguous);
  20863. if ( toChange.length > 0 ) {
  20864. // console.log("to change: ", toChange);
  20865. if ( ! ambiguous ) newShapeHoles = betterShapeHoles;
  20866. }
  20867. }
  20868. var tmpHoles;
  20869. for ( var i = 0, il = newShapes.length; i < il; i ++ ) {
  20870. tmpShape = newShapes[ i ].s;
  20871. shapes.push( tmpShape );
  20872. tmpHoles = newShapeHoles[ i ];
  20873. for ( var j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  20874. tmpShape.holes.push( tmpHoles[ j ].h );
  20875. }
  20876. }
  20877. //console.log("shape", shapes);
  20878. return shapes;
  20879. };
  20880. // File:src/extras/core/Shape.js
  20881. /**
  20882. * @author zz85 / http://www.lab4games.net/zz85/blog
  20883. * Defines a 2d shape plane using paths.
  20884. **/
  20885. // STEP 1 Create a path.
  20886. // STEP 2 Turn path into shape.
  20887. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  20888. // STEP 3a - Extract points from each shape, turn to vertices
  20889. // STEP 3b - Triangulate each shape, add faces.
  20890. THREE.Shape = function () {
  20891. THREE.Path.apply( this, arguments );
  20892. this.holes = [];
  20893. };
  20894. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  20895. THREE.Shape.prototype.constructor = THREE.Shape;
  20896. // Convenience method to return ExtrudeGeometry
  20897. THREE.Shape.prototype.extrude = function ( options ) {
  20898. return new THREE.ExtrudeGeometry( this, options );
  20899. };
  20900. // Convenience method to return ShapeGeometry
  20901. THREE.Shape.prototype.makeGeometry = function ( options ) {
  20902. return new THREE.ShapeGeometry( this, options );
  20903. };
  20904. // Get points of holes
  20905. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  20906. var holesPts = [];
  20907. for ( var i = 0, l = this.holes.length; i < l; i ++ ) {
  20908. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  20909. }
  20910. return holesPts;
  20911. };
  20912. // Get points of shape and holes (keypoints based on segments parameter)
  20913. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  20914. return {
  20915. shape: this.getPoints( divisions ),
  20916. holes: this.getPointsHoles( divisions )
  20917. };
  20918. };
  20919. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  20920. return this.extractAllPoints( divisions );
  20921. };
  20922. // File:src/extras/curves/LineCurve.js
  20923. /**************************************************************
  20924. * Line
  20925. **************************************************************/
  20926. THREE.LineCurve = function ( v1, v2 ) {
  20927. this.v1 = v1;
  20928. this.v2 = v2;
  20929. };
  20930. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  20931. THREE.LineCurve.prototype.constructor = THREE.LineCurve;
  20932. THREE.LineCurve.prototype.getPoint = function ( t ) {
  20933. var point = this.v2.clone().sub( this.v1 );
  20934. point.multiplyScalar( t ).add( this.v1 );
  20935. return point;
  20936. };
  20937. // Line curve is linear, so we can overwrite default getPointAt
  20938. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  20939. return this.getPoint( u );
  20940. };
  20941. THREE.LineCurve.prototype.getTangent = function( t ) {
  20942. var tangent = this.v2.clone().sub( this.v1 );
  20943. return tangent.normalize();
  20944. };
  20945. // File:src/extras/curves/QuadraticBezierCurve.js
  20946. /**************************************************************
  20947. * Quadratic Bezier curve
  20948. **************************************************************/
  20949. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  20950. this.v0 = v0;
  20951. this.v1 = v1;
  20952. this.v2 = v2;
  20953. };
  20954. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  20955. THREE.QuadraticBezierCurve.prototype.constructor = THREE.QuadraticBezierCurve;
  20956. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  20957. var b2 = THREE.ShapeUtils.b2;
  20958. return new THREE.Vector2(
  20959. b2( t, this.v0.x, this.v1.x, this.v2.x ),
  20960. b2( t, this.v0.y, this.v1.y, this.v2.y )
  20961. );
  20962. };
  20963. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  20964. var tangentQuadraticBezier = THREE.CurveUtils.tangentQuadraticBezier;
  20965. return new THREE.Vector2(
  20966. tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x ),
  20967. tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y )
  20968. ).normalize();
  20969. };
  20970. // File:src/extras/curves/CubicBezierCurve.js
  20971. /**************************************************************
  20972. * Cubic Bezier curve
  20973. **************************************************************/
  20974. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  20975. this.v0 = v0;
  20976. this.v1 = v1;
  20977. this.v2 = v2;
  20978. this.v3 = v3;
  20979. };
  20980. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  20981. THREE.CubicBezierCurve.prototype.constructor = THREE.CubicBezierCurve;
  20982. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  20983. var b3 = THREE.ShapeUtils.b3;
  20984. return new THREE.Vector2(
  20985. b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ),
  20986. b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y )
  20987. );
  20988. };
  20989. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  20990. var tangentCubicBezier = THREE.CurveUtils.tangentCubicBezier;
  20991. return new THREE.Vector2(
  20992. tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ),
  20993. tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y )
  20994. ).normalize();
  20995. };
  20996. // File:src/extras/curves/SplineCurve.js
  20997. /**************************************************************
  20998. * Spline curve
  20999. **************************************************************/
  21000. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  21001. this.points = ( points == undefined ) ? [] : points;
  21002. };
  21003. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  21004. THREE.SplineCurve.prototype.constructor = THREE.SplineCurve;
  21005. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  21006. var points = this.points;
  21007. var point = ( points.length - 1 ) * t;
  21008. var intPoint = Math.floor( point );
  21009. var weight = point - intPoint;
  21010. var point0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  21011. var point1 = points[ intPoint ];
  21012. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  21013. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  21014. var interpolate = THREE.CurveUtils.interpolate;
  21015. return new THREE.Vector2(
  21016. interpolate( point0.x, point1.x, point2.x, point3.x, weight ),
  21017. interpolate( point0.y, point1.y, point2.y, point3.y, weight )
  21018. );
  21019. };
  21020. // File:src/extras/curves/EllipseCurve.js
  21021. /**************************************************************
  21022. * Ellipse curve
  21023. **************************************************************/
  21024. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  21025. this.aX = aX;
  21026. this.aY = aY;
  21027. this.xRadius = xRadius;
  21028. this.yRadius = yRadius;
  21029. this.aStartAngle = aStartAngle;
  21030. this.aEndAngle = aEndAngle;
  21031. this.aClockwise = aClockwise;
  21032. this.aRotation = aRotation || 0;
  21033. };
  21034. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  21035. THREE.EllipseCurve.prototype.constructor = THREE.EllipseCurve;
  21036. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  21037. var deltaAngle = this.aEndAngle - this.aStartAngle;
  21038. if ( deltaAngle < 0 ) deltaAngle += Math.PI * 2;
  21039. if ( deltaAngle > Math.PI * 2 ) deltaAngle -= Math.PI * 2;
  21040. var angle;
  21041. if ( this.aClockwise === true ) {
  21042. angle = this.aEndAngle + ( 1 - t ) * ( Math.PI * 2 - deltaAngle );
  21043. } else {
  21044. angle = this.aStartAngle + t * deltaAngle;
  21045. }
  21046. var x = this.aX + this.xRadius * Math.cos( angle );
  21047. var y = this.aY + this.yRadius * Math.sin( angle );
  21048. if ( this.aRotation !== 0 ) {
  21049. var cos = Math.cos( this.aRotation );
  21050. var sin = Math.sin( this.aRotation );
  21051. var tx = x, ty = y;
  21052. // Rotate the point about the center of the ellipse.
  21053. x = ( tx - this.aX ) * cos - ( ty - this.aY ) * sin + this.aX;
  21054. y = ( tx - this.aX ) * sin + ( ty - this.aY ) * cos + this.aY;
  21055. }
  21056. return new THREE.Vector2( x, y );
  21057. };
  21058. // File:src/extras/curves/ArcCurve.js
  21059. /**************************************************************
  21060. * Arc curve
  21061. **************************************************************/
  21062. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  21063. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  21064. };
  21065. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  21066. THREE.ArcCurve.prototype.constructor = THREE.ArcCurve;
  21067. // File:src/extras/curves/LineCurve3.js
  21068. /**************************************************************
  21069. * Line3D
  21070. **************************************************************/
  21071. THREE.LineCurve3 = THREE.Curve.create(
  21072. function ( v1, v2 ) {
  21073. this.v1 = v1;
  21074. this.v2 = v2;
  21075. },
  21076. function ( t ) {
  21077. var vector = new THREE.Vector3();
  21078. vector.subVectors( this.v2, this.v1 ); // diff
  21079. vector.multiplyScalar( t );
  21080. vector.add( this.v1 );
  21081. return vector;
  21082. }
  21083. );
  21084. // File:src/extras/curves/QuadraticBezierCurve3.js
  21085. /**************************************************************
  21086. * Quadratic Bezier 3D curve
  21087. **************************************************************/
  21088. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  21089. function ( v0, v1, v2 ) {
  21090. this.v0 = v0;
  21091. this.v1 = v1;
  21092. this.v2 = v2;
  21093. },
  21094. function ( t ) {
  21095. var b2 = THREE.ShapeUtils.b2;
  21096. return new THREE.Vector3(
  21097. b2( t, this.v0.x, this.v1.x, this.v2.x ),
  21098. b2( t, this.v0.y, this.v1.y, this.v2.y ),
  21099. b2( t, this.v0.z, this.v1.z, this.v2.z )
  21100. );
  21101. }
  21102. );
  21103. // File:src/extras/curves/CubicBezierCurve3.js
  21104. /**************************************************************
  21105. * Cubic Bezier 3D curve
  21106. **************************************************************/
  21107. THREE.CubicBezierCurve3 = THREE.Curve.create(
  21108. function ( v0, v1, v2, v3 ) {
  21109. this.v0 = v0;
  21110. this.v1 = v1;
  21111. this.v2 = v2;
  21112. this.v3 = v3;
  21113. },
  21114. function ( t ) {
  21115. var b3 = THREE.ShapeUtils.b3;
  21116. return new THREE.Vector3(
  21117. b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ),
  21118. b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ),
  21119. b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z )
  21120. );
  21121. }
  21122. );
  21123. // File:src/extras/curves/SplineCurve3.js
  21124. /**************************************************************
  21125. * Spline 3D curve
  21126. **************************************************************/
  21127. THREE.SplineCurve3 = THREE.Curve.create(
  21128. function ( points /* array of Vector3 */ ) {
  21129. console.warn( 'THREE.SplineCurve3 will be deprecated. Please use THREE.CatmullRomCurve3' );
  21130. this.points = ( points == undefined ) ? [] : points;
  21131. },
  21132. function ( t ) {
  21133. var points = this.points;
  21134. var point = ( points.length - 1 ) * t;
  21135. var intPoint = Math.floor( point );
  21136. var weight = point - intPoint;
  21137. var point0 = points[ intPoint == 0 ? intPoint : intPoint - 1 ];
  21138. var point1 = points[ intPoint ];
  21139. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  21140. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  21141. var interpolate = THREE.CurveUtils.interpolate;
  21142. return new THREE.Vector3(
  21143. interpolate( point0.x, point1.x, point2.x, point3.x, weight ),
  21144. interpolate( point0.y, point1.y, point2.y, point3.y, weight ),
  21145. interpolate( point0.z, point1.z, point2.z, point3.z, weight )
  21146. );
  21147. }
  21148. );
  21149. // File:src/extras/curves/CatmullRomCurve3.js
  21150. /**
  21151. * @author zz85 https://github.com/zz85
  21152. *
  21153. * Centripetal CatmullRom Curve - which is useful for avoiding
  21154. * cusps and self-intersections in non-uniform catmull rom curves.
  21155. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  21156. *
  21157. * curve.type accepts centripetal(default), chordal and catmullrom
  21158. * curve.tension is used for catmullrom which defaults to 0.5
  21159. */
  21160. THREE.CatmullRomCurve3 = ( function() {
  21161. var
  21162. tmp = new THREE.Vector3(),
  21163. px = new CubicPoly(),
  21164. py = new CubicPoly(),
  21165. pz = new CubicPoly();
  21166. /*
  21167. Based on an optimized c++ solution in
  21168. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  21169. - http://ideone.com/NoEbVM
  21170. This CubicPoly class could be used for reusing some variables and calculations,
  21171. but for three.js curve use, it could be possible inlined and flatten into a single function call
  21172. which can be placed in CurveUtils.
  21173. */
  21174. function CubicPoly() {
  21175. }
  21176. /*
  21177. * Compute coefficients for a cubic polynomial
  21178. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  21179. * such that
  21180. * p(0) = x0, p(1) = x1
  21181. * and
  21182. * p'(0) = t0, p'(1) = t1.
  21183. */
  21184. CubicPoly.prototype.init = function( x0, x1, t0, t1 ) {
  21185. this.c0 = x0;
  21186. this.c1 = t0;
  21187. this.c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  21188. this.c3 = 2 * x0 - 2 * x1 + t0 + t1;
  21189. };
  21190. CubicPoly.prototype.initNonuniformCatmullRom = function( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  21191. // compute tangents when parameterized in [t1,t2]
  21192. var t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  21193. var t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  21194. // rescale tangents for parametrization in [0,1]
  21195. t1 *= dt1;
  21196. t2 *= dt1;
  21197. // initCubicPoly
  21198. this.init( x1, x2, t1, t2 );
  21199. };
  21200. // standard Catmull-Rom spline: interpolate between x1 and x2 with previous/following points x1/x4
  21201. CubicPoly.prototype.initCatmullRom = function( x0, x1, x2, x3, tension ) {
  21202. this.init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  21203. };
  21204. CubicPoly.prototype.calc = function( t ) {
  21205. var t2 = t * t;
  21206. var t3 = t2 * t;
  21207. return this.c0 + this.c1 * t + this.c2 * t2 + this.c3 * t3;
  21208. };
  21209. // Subclass Three.js curve
  21210. return THREE.Curve.create(
  21211. function ( p /* array of Vector3 */ ) {
  21212. this.points = p || [];
  21213. this.closed = false;
  21214. },
  21215. function ( t ) {
  21216. var points = this.points,
  21217. point, intPoint, weight, l;
  21218. l = points.length;
  21219. if ( l < 2 ) console.log( 'duh, you need at least 2 points' );
  21220. point = ( l - ( this.closed ? 0 : 1 ) ) * t;
  21221. intPoint = Math.floor( point );
  21222. weight = point - intPoint;
  21223. if ( this.closed ) {
  21224. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  21225. } else if ( weight === 0 && intPoint === l - 1 ) {
  21226. intPoint = l - 2;
  21227. weight = 1;
  21228. }
  21229. var p0, p1, p2, p3; // 4 points
  21230. if ( this.closed || intPoint > 0 ) {
  21231. p0 = points[ ( intPoint - 1 ) % l ];
  21232. } else {
  21233. // extrapolate first point
  21234. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  21235. p0 = tmp;
  21236. }
  21237. p1 = points[ intPoint % l ];
  21238. p2 = points[ ( intPoint + 1 ) % l ];
  21239. if ( this.closed || intPoint + 2 < l ) {
  21240. p3 = points[ ( intPoint + 2 ) % l ];
  21241. } else {
  21242. // extrapolate last point
  21243. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  21244. p3 = tmp;
  21245. }
  21246. if ( this.type === undefined || this.type === 'centripetal' || this.type === 'chordal' ) {
  21247. // init Centripetal / Chordal Catmull-Rom
  21248. var pow = this.type === 'chordal' ? 0.5 : 0.25;
  21249. var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  21250. var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  21251. var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  21252. // safety check for repeated points
  21253. if ( dt1 < 1e-4 ) dt1 = 1.0;
  21254. if ( dt0 < 1e-4 ) dt0 = dt1;
  21255. if ( dt2 < 1e-4 ) dt2 = dt1;
  21256. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  21257. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  21258. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  21259. } else if ( this.type === 'catmullrom' ) {
  21260. var tension = this.tension !== undefined ? this.tension : 0.5;
  21261. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, tension );
  21262. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, tension );
  21263. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, tension );
  21264. }
  21265. var v = new THREE.Vector3(
  21266. px.calc( weight ),
  21267. py.calc( weight ),
  21268. pz.calc( weight )
  21269. );
  21270. return v;
  21271. }
  21272. );
  21273. } )();
  21274. // File:src/extras/curves/ClosedSplineCurve3.js
  21275. /**************************************************************
  21276. * Closed Spline 3D curve
  21277. **************************************************************/
  21278. THREE.ClosedSplineCurve3 = function ( points ) {
  21279. console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Please use THREE.CatmullRomCurve3.' );
  21280. THREE.CatmullRomCurve3.call( this, points );
  21281. this.type = 'catmullrom';
  21282. this.closed = true;
  21283. };
  21284. THREE.ClosedSplineCurve3.prototype = Object.create( THREE.CatmullRomCurve3.prototype );
  21285. // File:src/extras/geometries/BoxGeometry.js
  21286. /**
  21287. * @author mrdoob / http://mrdoob.com/
  21288. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  21289. */
  21290. THREE.BoxGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  21291. THREE.Geometry.call( this );
  21292. this.type = 'BoxGeometry';
  21293. this.parameters = {
  21294. width: width,
  21295. height: height,
  21296. depth: depth,
  21297. widthSegments: widthSegments,
  21298. heightSegments: heightSegments,
  21299. depthSegments: depthSegments
  21300. };
  21301. this.fromBufferGeometry( new THREE.BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) );
  21302. this.mergeVertices();
  21303. };
  21304. THREE.BoxGeometry.prototype = Object.create( THREE.Geometry.prototype );
  21305. THREE.BoxGeometry.prototype.constructor = THREE.BoxGeometry;
  21306. THREE.CubeGeometry = THREE.BoxGeometry;
  21307. // File:src/extras/geometries/BoxBufferGeometry.js
  21308. /**
  21309. * @author Mugen87 / https://github.com/Mugen87
  21310. */
  21311. THREE.BoxBufferGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  21312. THREE.BufferGeometry.call( this );
  21313. this.type = 'BoxBufferGeometry';
  21314. this.parameters = {
  21315. width: width,
  21316. height: height,
  21317. depth: depth,
  21318. widthSegments: widthSegments,
  21319. heightSegments: heightSegments,
  21320. depthSegments: depthSegments
  21321. };
  21322. var scope = this;
  21323. // segments
  21324. widthSegments = Math.floor( widthSegments ) || 1;
  21325. heightSegments = Math.floor( heightSegments ) || 1;
  21326. depthSegments = Math.floor( depthSegments ) || 1;
  21327. // these are used to calculate buffer length
  21328. var vertexCount = calculateVertexCount( widthSegments, heightSegments, depthSegments );
  21329. var indexCount = ( vertexCount / 4 ) * 6;
  21330. // buffers
  21331. var indices = new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount );
  21332. var vertices = new Float32Array( vertexCount * 3 );
  21333. var normals = new Float32Array( vertexCount * 3 );
  21334. var uvs = new Float32Array( vertexCount * 2 );
  21335. // offset variables
  21336. var vertexBufferOffset = 0;
  21337. var uvBufferOffset = 0;
  21338. var indexBufferOffset = 0;
  21339. var numberOfVertices = 0;
  21340. // group variables
  21341. var groupStart = 0;
  21342. // build each side of the box geometry
  21343. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  21344. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  21345. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  21346. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  21347. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  21348. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  21349. // build geometry
  21350. this.setIndex( new THREE.BufferAttribute( indices, 1 ) );
  21351. this.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  21352. this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
  21353. this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) );
  21354. // helper functions
  21355. function calculateVertexCount ( w, h, d ) {
  21356. var segments = 0;
  21357. // calculate the amount of segments for each side
  21358. segments += w * h * 2; // xy
  21359. segments += w * d * 2; // xz
  21360. segments += d * h * 2; // zy
  21361. return segments * 4; // four vertices per segments
  21362. }
  21363. function buildPlane ( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  21364. var segmentWidth = width / gridX;
  21365. var segmentHeight = height / gridY;
  21366. var widthHalf = width / 2;
  21367. var heightHalf = height / 2;
  21368. var depthHalf = depth / 2;
  21369. var gridX1 = gridX + 1;
  21370. var gridY1 = gridY + 1;
  21371. var vertexCounter = 0;
  21372. var groupCount = 0;
  21373. var vector = new THREE.Vector3();
  21374. // generate vertices, normals and uvs
  21375. for ( var iy = 0; iy < gridY1; iy ++ ) {
  21376. var y = iy * segmentHeight - heightHalf;
  21377. for ( var ix = 0; ix < gridX1; ix ++ ) {
  21378. var x = ix * segmentWidth - widthHalf;
  21379. // set values to correct vector component
  21380. vector[ u ] = x * udir;
  21381. vector[ v ] = y * vdir;
  21382. vector[ w ] = depthHalf;
  21383. // now apply vector to vertex buffer
  21384. vertices[ vertexBufferOffset ] = vector.x;
  21385. vertices[ vertexBufferOffset + 1 ] = vector.y;
  21386. vertices[ vertexBufferOffset + 2 ] = vector.z;
  21387. // set values to correct vector component
  21388. vector[ u ] = 0;
  21389. vector[ v ] = 0;
  21390. vector[ w ] = depth > 0 ? 1 : - 1;
  21391. // now apply vector to normal buffer
  21392. normals[ vertexBufferOffset ] = vector.x;
  21393. normals[ vertexBufferOffset + 1 ] = vector.y;
  21394. normals[ vertexBufferOffset + 2 ] = vector.z;
  21395. // uvs
  21396. uvs[ uvBufferOffset ] = ix / gridX;
  21397. uvs[ uvBufferOffset + 1 ] = 1 - ( iy / gridY );
  21398. // update offsets and counters
  21399. vertexBufferOffset += 3;
  21400. uvBufferOffset += 2;
  21401. vertexCounter += 1;
  21402. }
  21403. }
  21404. // 1. you need three indices to draw a single face
  21405. // 2. a single segment consists of two faces
  21406. // 3. so we need to generate six (2*3) indices per segment
  21407. for ( iy = 0; iy < gridY; iy ++ ) {
  21408. for ( ix = 0; ix < gridX; ix ++ ) {
  21409. // indices
  21410. var a = numberOfVertices + ix + gridX1 * iy;
  21411. var b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  21412. var c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  21413. var d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  21414. // face one
  21415. indices[ indexBufferOffset ] = a;
  21416. indices[ indexBufferOffset + 1 ] = b;
  21417. indices[ indexBufferOffset + 2 ] = d;
  21418. // face two
  21419. indices[ indexBufferOffset + 3 ] = b;
  21420. indices[ indexBufferOffset + 4 ] = c;
  21421. indices[ indexBufferOffset + 5 ] = d;
  21422. // update offsets and counters
  21423. indexBufferOffset += 6;
  21424. groupCount += 6;
  21425. }
  21426. }
  21427. // add a group to the geometry. this will ensure multi material support
  21428. scope.addGroup( groupStart, groupCount, materialIndex );
  21429. // calculate new start value for groups
  21430. groupStart += groupCount;
  21431. // update total number of vertices
  21432. numberOfVertices += vertexCounter;
  21433. }
  21434. };
  21435. THREE.BoxBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  21436. THREE.BoxBufferGeometry.prototype.constructor = THREE.BoxBufferGeometry;
  21437. // File:src/extras/geometries/CircleGeometry.js
  21438. /**
  21439. * @author hughes
  21440. */
  21441. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  21442. THREE.Geometry.call( this );
  21443. this.type = 'CircleGeometry';
  21444. this.parameters = {
  21445. radius: radius,
  21446. segments: segments,
  21447. thetaStart: thetaStart,
  21448. thetaLength: thetaLength
  21449. };
  21450. this.fromBufferGeometry( new THREE.CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) );
  21451. };
  21452. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  21453. THREE.CircleGeometry.prototype.constructor = THREE.CircleGeometry;
  21454. // File:src/extras/geometries/CircleBufferGeometry.js
  21455. /**
  21456. * @author benaadams / https://twitter.com/ben_a_adams
  21457. */
  21458. THREE.CircleBufferGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  21459. THREE.BufferGeometry.call( this );
  21460. this.type = 'CircleBufferGeometry';
  21461. this.parameters = {
  21462. radius: radius,
  21463. segments: segments,
  21464. thetaStart: thetaStart,
  21465. thetaLength: thetaLength
  21466. };
  21467. radius = radius || 50;
  21468. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  21469. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  21470. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  21471. var vertices = segments + 2;
  21472. var positions = new Float32Array( vertices * 3 );
  21473. var normals = new Float32Array( vertices * 3 );
  21474. var uvs = new Float32Array( vertices * 2 );
  21475. // center data is already zero, but need to set a few extras
  21476. normals[ 2 ] = 1.0;
  21477. uvs[ 0 ] = 0.5;
  21478. uvs[ 1 ] = 0.5;
  21479. for ( var s = 0, i = 3, ii = 2 ; s <= segments; s ++, i += 3, ii += 2 ) {
  21480. var segment = thetaStart + s / segments * thetaLength;
  21481. positions[ i ] = radius * Math.cos( segment );
  21482. positions[ i + 1 ] = radius * Math.sin( segment );
  21483. normals[ i + 2 ] = 1; // normal z
  21484. uvs[ ii ] = ( positions[ i ] / radius + 1 ) / 2;
  21485. uvs[ ii + 1 ] = ( positions[ i + 1 ] / radius + 1 ) / 2;
  21486. }
  21487. var indices = [];
  21488. for ( var i = 1; i <= segments; i ++ ) {
  21489. indices.push( i, i + 1, 0 );
  21490. }
  21491. this.setIndex( new THREE.BufferAttribute( new Uint16Array( indices ), 1 ) );
  21492. this.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
  21493. this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
  21494. this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) );
  21495. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  21496. };
  21497. THREE.CircleBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  21498. THREE.CircleBufferGeometry.prototype.constructor = THREE.CircleBufferGeometry;
  21499. // File:src/extras/geometries/CylinderBufferGeometry.js
  21500. /**
  21501. * @author Mugen87 / https://github.com/Mugen87
  21502. */
  21503. THREE.CylinderBufferGeometry = function ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  21504. THREE.BufferGeometry.call( this );
  21505. this.type = 'CylinderBufferGeometry';
  21506. this.parameters = {
  21507. radiusTop: radiusTop,
  21508. radiusBottom: radiusBottom,
  21509. height: height,
  21510. radialSegments: radialSegments,
  21511. heightSegments: heightSegments,
  21512. openEnded: openEnded,
  21513. thetaStart: thetaStart,
  21514. thetaLength: thetaLength
  21515. };
  21516. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  21517. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  21518. height = height !== undefined ? height : 100;
  21519. radialSegments = Math.floor( radialSegments ) || 8;
  21520. heightSegments = Math.floor( heightSegments ) || 1;
  21521. openEnded = openEnded !== undefined ? openEnded : false;
  21522. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  21523. thetaLength = thetaLength !== undefined ? thetaLength : 2 * Math.PI;
  21524. // used to calculate buffer length
  21525. var vertexCount = calculateVertexCount();
  21526. var indexCount = calculateIndexCount();
  21527. // buffers
  21528. var indices = new THREE.BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 );
  21529. var vertices = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  21530. var normals = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  21531. var uvs = new THREE.BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  21532. // helper variables
  21533. var index = 0, indexOffset = 0, indexArray = [], halfHeight = height / 2;
  21534. // generate geometry
  21535. generateTorso();
  21536. if( openEnded === false ) {
  21537. if( radiusTop > 0 ) {
  21538. generateCap( true );
  21539. }
  21540. if( radiusBottom > 0 ) {
  21541. generateCap( false );
  21542. }
  21543. }
  21544. // build geometry
  21545. this.setIndex( indices );
  21546. this.addAttribute( 'position', vertices );
  21547. this.addAttribute( 'normal', normals );
  21548. this.addAttribute( 'uv', uvs );
  21549. // helper functions
  21550. function calculateVertexCount () {
  21551. var count = ( radialSegments + 1 ) * ( heightSegments + 1 );
  21552. if ( openEnded === false ) {
  21553. count += ( ( radialSegments + 1 ) * 2 ) + ( radialSegments * 2 );
  21554. }
  21555. return count;
  21556. }
  21557. function calculateIndexCount () {
  21558. var count = radialSegments * heightSegments * 2 * 3;
  21559. if ( openEnded === false ) {
  21560. count += radialSegments * 2 * 3;
  21561. }
  21562. return count;
  21563. }
  21564. function generateTorso () {
  21565. var x, y;
  21566. var normal = new THREE.Vector3();
  21567. var vertex = new THREE.Vector3();
  21568. // this will be used to calculate the normal
  21569. var tanTheta = ( radiusBottom - radiusTop ) / height;
  21570. // generate vertices, normals and uvs
  21571. for ( y = 0; y <= heightSegments; y ++ ) {
  21572. var indexRow = [];
  21573. var v = y / heightSegments;
  21574. // calculate the radius of the current row
  21575. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  21576. for ( x = 0; x <= radialSegments; x ++ ) {
  21577. var u = x / radialSegments;
  21578. // vertex
  21579. vertex.x = radius * Math.sin( u * thetaLength + thetaStart );
  21580. vertex.y = - v * height + halfHeight;
  21581. vertex.z = radius * Math.cos( u * thetaLength + thetaStart );
  21582. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  21583. // normal
  21584. normal.copy( vertex );
  21585. // handle special case if radiusTop/radiusBottom is zero
  21586. if( ( radiusTop === 0 && y === 0 ) || ( radiusBottom === 0 && y === heightSegments ) ) {
  21587. normal.x = Math.sin( u * thetaLength + thetaStart );
  21588. normal.z = Math.cos( u * thetaLength + thetaStart );
  21589. }
  21590. normal.setY( Math.sqrt( normal.x * normal.x + normal.z * normal.z ) * tanTheta ).normalize();
  21591. normals.setXYZ( index, normal.x, normal.y, normal.z );
  21592. // uv
  21593. uvs.setXY( index, u, 1 - v );
  21594. // save index of vertex in respective row
  21595. indexRow.push( index );
  21596. // increase index
  21597. index ++;
  21598. }
  21599. // now save vertices of the row in our index array
  21600. indexArray.push( indexRow );
  21601. }
  21602. // generate indices
  21603. for ( x = 0; x < radialSegments; x ++ ) {
  21604. for ( y = 0; y < heightSegments; y ++ ) {
  21605. // we use the index array to access the correct indices
  21606. var i1 = indexArray[ y ][ x ];
  21607. var i2 = indexArray[ y + 1 ][ x ];
  21608. var i3 = indexArray[ y + 1 ][ x + 1 ];
  21609. var i4 = indexArray[ y ][ x + 1 ];
  21610. // face one
  21611. indices.setX( indexOffset, i1 ); indexOffset++;
  21612. indices.setX( indexOffset, i2 ); indexOffset++;
  21613. indices.setX( indexOffset, i4 ); indexOffset++;
  21614. // face two
  21615. indices.setX( indexOffset, i2 ); indexOffset++;
  21616. indices.setX( indexOffset, i3 ); indexOffset++;
  21617. indices.setX( indexOffset, i4 ); indexOffset++;
  21618. }
  21619. }
  21620. }
  21621. function generateCap ( top ) {
  21622. var x, centerIndexStart, centerIndexEnd;
  21623. var uv = new THREE.Vector2();
  21624. var vertex = new THREE.Vector3();
  21625. var radius = ( top === true ) ? radiusTop : radiusBottom;
  21626. var sign = ( top === true ) ? 1 : - 1;
  21627. // save the index of the first center vertex
  21628. centerIndexStart = index;
  21629. // first we generate the center vertex data of the cap.
  21630. // because the geometry needs one set of uvs per face,
  21631. // we must generate a center vertex per face/segment
  21632. for ( x = 1; x <= radialSegments; x ++ ) {
  21633. // vertex
  21634. vertices.setXYZ( index, 0, halfHeight * sign, 0 );
  21635. // normal
  21636. normals.setXYZ( index, 0, sign, 0 );
  21637. // uv
  21638. if( top === true ) {
  21639. uv.x = x / radialSegments;
  21640. uv.y = 0;
  21641. } else {
  21642. uv.x = ( x - 1 ) / radialSegments;
  21643. uv.y = 1;
  21644. }
  21645. uvs.setXY( index, uv.x, uv.y );
  21646. // increase index
  21647. index++;
  21648. }
  21649. // save the index of the last center vertex
  21650. centerIndexEnd = index;
  21651. // now we generate the surrounding vertices, normals and uvs
  21652. for ( x = 0; x <= radialSegments; x ++ ) {
  21653. var u = x / radialSegments;
  21654. // vertex
  21655. vertex.x = radius * Math.sin( u * thetaLength + thetaStart );
  21656. vertex.y = halfHeight * sign;
  21657. vertex.z = radius * Math.cos( u * thetaLength + thetaStart );
  21658. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  21659. // normal
  21660. normals.setXYZ( index, 0, sign, 0 );
  21661. // uv
  21662. uvs.setXY( index, u, ( top === true ) ? 1 : 0 );
  21663. // increase index
  21664. index ++;
  21665. }
  21666. // generate indices
  21667. for ( x = 0; x < radialSegments; x ++ ) {
  21668. var c = centerIndexStart + x;
  21669. var i = centerIndexEnd + x;
  21670. if( top === true ) {
  21671. // face top
  21672. indices.setX( indexOffset, i ); indexOffset++;
  21673. indices.setX( indexOffset, i + 1 ); indexOffset++;
  21674. indices.setX( indexOffset, c ); indexOffset++;
  21675. } else {
  21676. // face bottom
  21677. indices.setX( indexOffset, i + 1); indexOffset++;
  21678. indices.setX( indexOffset, i ); indexOffset++;
  21679. indices.setX( indexOffset, c ); indexOffset++;
  21680. }
  21681. }
  21682. }
  21683. };
  21684. THREE.CylinderBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  21685. THREE.CylinderBufferGeometry.prototype.constructor = THREE.CylinderBufferGeometry;
  21686. // File:src/extras/geometries/CylinderGeometry.js
  21687. /**
  21688. * @author mrdoob / http://mrdoob.com/
  21689. */
  21690. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  21691. THREE.Geometry.call( this );
  21692. this.type = 'CylinderGeometry';
  21693. this.parameters = {
  21694. radiusTop: radiusTop,
  21695. radiusBottom: radiusBottom,
  21696. height: height,
  21697. radialSegments: radialSegments,
  21698. heightSegments: heightSegments,
  21699. openEnded: openEnded,
  21700. thetaStart: thetaStart,
  21701. thetaLength: thetaLength
  21702. };
  21703. this.fromBufferGeometry( new THREE.CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) );
  21704. this.mergeVertices();
  21705. };
  21706. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  21707. THREE.CylinderGeometry.prototype.constructor = THREE.CylinderGeometry;
  21708. // File:src/extras/geometries/EdgesGeometry.js
  21709. /**
  21710. * @author WestLangley / http://github.com/WestLangley
  21711. */
  21712. THREE.EdgesGeometry = function ( geometry, thresholdAngle ) {
  21713. THREE.BufferGeometry.call( this );
  21714. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  21715. var thresholdDot = Math.cos( THREE.Math.DEG2RAD * thresholdAngle );
  21716. var edge = [ 0, 0 ], hash = {};
  21717. function sortFunction( a, b ) {
  21718. return a - b;
  21719. }
  21720. var keys = [ 'a', 'b', 'c' ];
  21721. var geometry2;
  21722. if ( geometry instanceof THREE.BufferGeometry ) {
  21723. geometry2 = new THREE.Geometry();
  21724. geometry2.fromBufferGeometry( geometry );
  21725. } else {
  21726. geometry2 = geometry.clone();
  21727. }
  21728. geometry2.mergeVertices();
  21729. geometry2.computeFaceNormals();
  21730. var vertices = geometry2.vertices;
  21731. var faces = geometry2.faces;
  21732. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21733. var face = faces[ i ];
  21734. for ( var j = 0; j < 3; j ++ ) {
  21735. edge[ 0 ] = face[ keys[ j ] ];
  21736. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  21737. edge.sort( sortFunction );
  21738. var key = edge.toString();
  21739. if ( hash[ key ] === undefined ) {
  21740. hash[ key ] = { vert1: edge[ 0 ], vert2: edge[ 1 ], face1: i, face2: undefined };
  21741. } else {
  21742. hash[ key ].face2 = i;
  21743. }
  21744. }
  21745. }
  21746. var coords = [];
  21747. for ( var key in hash ) {
  21748. var h = hash[ key ];
  21749. if ( h.face2 === undefined || faces[ h.face1 ].normal.dot( faces[ h.face2 ].normal ) <= thresholdDot ) {
  21750. var vertex = vertices[ h.vert1 ];
  21751. coords.push( vertex.x );
  21752. coords.push( vertex.y );
  21753. coords.push( vertex.z );
  21754. vertex = vertices[ h.vert2 ];
  21755. coords.push( vertex.x );
  21756. coords.push( vertex.y );
  21757. coords.push( vertex.z );
  21758. }
  21759. }
  21760. this.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( coords ), 3 ) );
  21761. };
  21762. THREE.EdgesGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  21763. THREE.EdgesGeometry.prototype.constructor = THREE.EdgesGeometry;
  21764. // File:src/extras/geometries/ExtrudeGeometry.js
  21765. /**
  21766. * @author zz85 / http://www.lab4games.net/zz85/blog
  21767. *
  21768. * Creates extruded geometry from a path shape.
  21769. *
  21770. * parameters = {
  21771. *
  21772. * curveSegments: <int>, // number of points on the curves
  21773. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  21774. * amount: <int>, // Depth to extrude the shape
  21775. *
  21776. * bevelEnabled: <bool>, // turn on bevel
  21777. * bevelThickness: <float>, // how deep into the original shape bevel goes
  21778. * bevelSize: <float>, // how far from shape outline is bevel
  21779. * bevelSegments: <int>, // number of bevel layers
  21780. *
  21781. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  21782. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  21783. *
  21784. * uvGenerator: <Object> // object that provides UV generator functions
  21785. *
  21786. * }
  21787. **/
  21788. THREE.ExtrudeGeometry = function ( shapes, options ) {
  21789. if ( typeof( shapes ) === "undefined" ) {
  21790. shapes = [];
  21791. return;
  21792. }
  21793. THREE.Geometry.call( this );
  21794. this.type = 'ExtrudeGeometry';
  21795. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  21796. this.addShapeList( shapes, options );
  21797. this.computeFaceNormals();
  21798. // can't really use automatic vertex normals
  21799. // as then front and back sides get smoothed too
  21800. // should do separate smoothing just for sides
  21801. //this.computeVertexNormals();
  21802. //console.log( "took", ( Date.now() - startTime ) );
  21803. };
  21804. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  21805. THREE.ExtrudeGeometry.prototype.constructor = THREE.ExtrudeGeometry;
  21806. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  21807. var sl = shapes.length;
  21808. for ( var s = 0; s < sl; s ++ ) {
  21809. var shape = shapes[ s ];
  21810. this.addShape( shape, options );
  21811. }
  21812. };
  21813. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  21814. var amount = options.amount !== undefined ? options.amount : 100;
  21815. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  21816. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  21817. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  21818. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  21819. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  21820. var steps = options.steps !== undefined ? options.steps : 1;
  21821. var extrudePath = options.extrudePath;
  21822. var extrudePts, extrudeByPath = false;
  21823. // Use default WorldUVGenerator if no UV generators are specified.
  21824. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  21825. var splineTube, binormal, normal, position2;
  21826. if ( extrudePath ) {
  21827. extrudePts = extrudePath.getSpacedPoints( steps );
  21828. extrudeByPath = true;
  21829. bevelEnabled = false; // bevels not supported for path extrusion
  21830. // SETUP TNB variables
  21831. // Reuse TNB from TubeGeomtry for now.
  21832. // TODO1 - have a .isClosed in spline?
  21833. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames( extrudePath, steps, false );
  21834. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  21835. binormal = new THREE.Vector3();
  21836. normal = new THREE.Vector3();
  21837. position2 = new THREE.Vector3();
  21838. }
  21839. // Safeguards if bevels are not enabled
  21840. if ( ! bevelEnabled ) {
  21841. bevelSegments = 0;
  21842. bevelThickness = 0;
  21843. bevelSize = 0;
  21844. }
  21845. // Variables initialization
  21846. var ahole, h, hl; // looping of holes
  21847. var scope = this;
  21848. var shapesOffset = this.vertices.length;
  21849. var shapePoints = shape.extractPoints( curveSegments );
  21850. var vertices = shapePoints.shape;
  21851. var holes = shapePoints.holes;
  21852. var reverse = ! THREE.ShapeUtils.isClockWise( vertices );
  21853. if ( reverse ) {
  21854. vertices = vertices.reverse();
  21855. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  21856. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  21857. ahole = holes[ h ];
  21858. if ( THREE.ShapeUtils.isClockWise( ahole ) ) {
  21859. holes[ h ] = ahole.reverse();
  21860. }
  21861. }
  21862. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  21863. }
  21864. var faces = THREE.ShapeUtils.triangulateShape( vertices, holes );
  21865. /* Vertices */
  21866. var contour = vertices; // vertices has all points but contour has only points of circumference
  21867. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  21868. ahole = holes[ h ];
  21869. vertices = vertices.concat( ahole );
  21870. }
  21871. function scalePt2 ( pt, vec, size ) {
  21872. if ( ! vec ) console.error( "THREE.ExtrudeGeometry: vec does not exist" );
  21873. return vec.clone().multiplyScalar( size ).add( pt );
  21874. }
  21875. var b, bs, t, z,
  21876. vert, vlen = vertices.length,
  21877. face, flen = faces.length;
  21878. // Find directions for point movement
  21879. function getBevelVec( inPt, inPrev, inNext ) {
  21880. // computes for inPt the corresponding point inPt' on a new contour
  21881. // shifted by 1 unit (length of normalized vector) to the left
  21882. // if we walk along contour clockwise, this new contour is outside the old one
  21883. //
  21884. // inPt' is the intersection of the two lines parallel to the two
  21885. // adjacent edges of inPt at a distance of 1 unit on the left side.
  21886. var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt
  21887. // good reading for geometry algorithms (here: line-line intersection)
  21888. // http://geomalgorithms.com/a05-_intersect-1.html
  21889. var v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y;
  21890. var v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y;
  21891. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  21892. // check for collinear edges
  21893. var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  21894. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  21895. // not collinear
  21896. // length of vectors for normalizing
  21897. var v_prev_len = Math.sqrt( v_prev_lensq );
  21898. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  21899. // shift adjacent points by unit vectors to the left
  21900. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  21901. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  21902. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  21903. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  21904. // scaling factor for v_prev to intersection point
  21905. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  21906. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  21907. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  21908. // vector from inPt to intersection point
  21909. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  21910. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  21911. // Don't normalize!, otherwise sharp corners become ugly
  21912. // but prevent crazy spikes
  21913. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  21914. if ( v_trans_lensq <= 2 ) {
  21915. return new THREE.Vector2( v_trans_x, v_trans_y );
  21916. } else {
  21917. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  21918. }
  21919. } else {
  21920. // handle special case of collinear edges
  21921. var direction_eq = false; // assumes: opposite
  21922. if ( v_prev_x > Number.EPSILON ) {
  21923. if ( v_next_x > Number.EPSILON ) {
  21924. direction_eq = true;
  21925. }
  21926. } else {
  21927. if ( v_prev_x < - Number.EPSILON ) {
  21928. if ( v_next_x < - Number.EPSILON ) {
  21929. direction_eq = true;
  21930. }
  21931. } else {
  21932. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  21933. direction_eq = true;
  21934. }
  21935. }
  21936. }
  21937. if ( direction_eq ) {
  21938. // console.log("Warning: lines are a straight sequence");
  21939. v_trans_x = - v_prev_y;
  21940. v_trans_y = v_prev_x;
  21941. shrink_by = Math.sqrt( v_prev_lensq );
  21942. } else {
  21943. // console.log("Warning: lines are a straight spike");
  21944. v_trans_x = v_prev_x;
  21945. v_trans_y = v_prev_y;
  21946. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  21947. }
  21948. }
  21949. return new THREE.Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  21950. }
  21951. var contourMovements = [];
  21952. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  21953. if ( j === il ) j = 0;
  21954. if ( k === il ) k = 0;
  21955. // (j)---(i)---(k)
  21956. // console.log('i,j,k', i, j , k)
  21957. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  21958. }
  21959. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  21960. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  21961. ahole = holes[ h ];
  21962. oneHoleMovements = [];
  21963. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  21964. if ( j === il ) j = 0;
  21965. if ( k === il ) k = 0;
  21966. // (j)---(i)---(k)
  21967. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  21968. }
  21969. holesMovements.push( oneHoleMovements );
  21970. verticesMovements = verticesMovements.concat( oneHoleMovements );
  21971. }
  21972. // Loop bevelSegments, 1 for the front, 1 for the back
  21973. for ( b = 0; b < bevelSegments; b ++ ) {
  21974. //for ( b = bevelSegments; b > 0; b -- ) {
  21975. t = b / bevelSegments;
  21976. z = bevelThickness * ( 1 - t );
  21977. //z = bevelThickness * t;
  21978. bs = bevelSize * ( Math.sin ( t * Math.PI / 2 ) ); // curved
  21979. //bs = bevelSize * t; // linear
  21980. // contract shape
  21981. for ( i = 0, il = contour.length; i < il; i ++ ) {
  21982. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  21983. v( vert.x, vert.y, - z );
  21984. }
  21985. // expand holes
  21986. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  21987. ahole = holes[ h ];
  21988. oneHoleMovements = holesMovements[ h ];
  21989. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  21990. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  21991. v( vert.x, vert.y, - z );
  21992. }
  21993. }
  21994. }
  21995. bs = bevelSize;
  21996. // Back facing vertices
  21997. for ( i = 0; i < vlen; i ++ ) {
  21998. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  21999. if ( ! extrudeByPath ) {
  22000. v( vert.x, vert.y, 0 );
  22001. } else {
  22002. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  22003. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  22004. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  22005. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  22006. v( position2.x, position2.y, position2.z );
  22007. }
  22008. }
  22009. // Add stepped vertices...
  22010. // Including front facing vertices
  22011. var s;
  22012. for ( s = 1; s <= steps; s ++ ) {
  22013. for ( i = 0; i < vlen; i ++ ) {
  22014. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  22015. if ( ! extrudeByPath ) {
  22016. v( vert.x, vert.y, amount / steps * s );
  22017. } else {
  22018. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  22019. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  22020. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  22021. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  22022. v( position2.x, position2.y, position2.z );
  22023. }
  22024. }
  22025. }
  22026. // Add bevel segments planes
  22027. //for ( b = 1; b <= bevelSegments; b ++ ) {
  22028. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  22029. t = b / bevelSegments;
  22030. z = bevelThickness * ( 1 - t );
  22031. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  22032. bs = bevelSize * Math.sin ( t * Math.PI / 2 );
  22033. // contract shape
  22034. for ( i = 0, il = contour.length; i < il; i ++ ) {
  22035. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  22036. v( vert.x, vert.y, amount + z );
  22037. }
  22038. // expand holes
  22039. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  22040. ahole = holes[ h ];
  22041. oneHoleMovements = holesMovements[ h ];
  22042. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  22043. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  22044. if ( ! extrudeByPath ) {
  22045. v( vert.x, vert.y, amount + z );
  22046. } else {
  22047. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  22048. }
  22049. }
  22050. }
  22051. }
  22052. /* Faces */
  22053. // Top and bottom faces
  22054. buildLidFaces();
  22055. // Sides faces
  22056. buildSideFaces();
  22057. ///// Internal functions
  22058. function buildLidFaces() {
  22059. if ( bevelEnabled ) {
  22060. var layer = 0; // steps + 1
  22061. var offset = vlen * layer;
  22062. // Bottom faces
  22063. for ( i = 0; i < flen; i ++ ) {
  22064. face = faces[ i ];
  22065. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  22066. }
  22067. layer = steps + bevelSegments * 2;
  22068. offset = vlen * layer;
  22069. // Top faces
  22070. for ( i = 0; i < flen; i ++ ) {
  22071. face = faces[ i ];
  22072. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  22073. }
  22074. } else {
  22075. // Bottom faces
  22076. for ( i = 0; i < flen; i ++ ) {
  22077. face = faces[ i ];
  22078. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  22079. }
  22080. // Top faces
  22081. for ( i = 0; i < flen; i ++ ) {
  22082. face = faces[ i ];
  22083. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  22084. }
  22085. }
  22086. }
  22087. // Create faces for the z-sides of the shape
  22088. function buildSideFaces() {
  22089. var layeroffset = 0;
  22090. sidewalls( contour, layeroffset );
  22091. layeroffset += contour.length;
  22092. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  22093. ahole = holes[ h ];
  22094. sidewalls( ahole, layeroffset );
  22095. //, true
  22096. layeroffset += ahole.length;
  22097. }
  22098. }
  22099. function sidewalls( contour, layeroffset ) {
  22100. var j, k;
  22101. i = contour.length;
  22102. while ( -- i >= 0 ) {
  22103. j = i;
  22104. k = i - 1;
  22105. if ( k < 0 ) k = contour.length - 1;
  22106. //console.log('b', i,j, i-1, k,vertices.length);
  22107. var s = 0, sl = steps + bevelSegments * 2;
  22108. for ( s = 0; s < sl; s ++ ) {
  22109. var slen1 = vlen * s;
  22110. var slen2 = vlen * ( s + 1 );
  22111. var a = layeroffset + j + slen1,
  22112. b = layeroffset + k + slen1,
  22113. c = layeroffset + k + slen2,
  22114. d = layeroffset + j + slen2;
  22115. f4( a, b, c, d, contour, s, sl, j, k );
  22116. }
  22117. }
  22118. }
  22119. function v( x, y, z ) {
  22120. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  22121. }
  22122. function f3( a, b, c ) {
  22123. a += shapesOffset;
  22124. b += shapesOffset;
  22125. c += shapesOffset;
  22126. scope.faces.push( new THREE.Face3( a, b, c, null, null, 0 ) );
  22127. var uvs = uvgen.generateTopUV( scope, a, b, c );
  22128. scope.faceVertexUvs[ 0 ].push( uvs );
  22129. }
  22130. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  22131. a += shapesOffset;
  22132. b += shapesOffset;
  22133. c += shapesOffset;
  22134. d += shapesOffset;
  22135. scope.faces.push( new THREE.Face3( a, b, d, null, null, 1 ) );
  22136. scope.faces.push( new THREE.Face3( b, c, d, null, null, 1 ) );
  22137. var uvs = uvgen.generateSideWallUV( scope, a, b, c, d );
  22138. scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] );
  22139. scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] );
  22140. }
  22141. };
  22142. THREE.ExtrudeGeometry.WorldUVGenerator = {
  22143. generateTopUV: function ( geometry, indexA, indexB, indexC ) {
  22144. var vertices = geometry.vertices;
  22145. var a = vertices[ indexA ];
  22146. var b = vertices[ indexB ];
  22147. var c = vertices[ indexC ];
  22148. return [
  22149. new THREE.Vector2( a.x, a.y ),
  22150. new THREE.Vector2( b.x, b.y ),
  22151. new THREE.Vector2( c.x, c.y )
  22152. ];
  22153. },
  22154. generateSideWallUV: function ( geometry, indexA, indexB, indexC, indexD ) {
  22155. var vertices = geometry.vertices;
  22156. var a = vertices[ indexA ];
  22157. var b = vertices[ indexB ];
  22158. var c = vertices[ indexC ];
  22159. var d = vertices[ indexD ];
  22160. if ( Math.abs( a.y - b.y ) < 0.01 ) {
  22161. return [
  22162. new THREE.Vector2( a.x, 1 - a.z ),
  22163. new THREE.Vector2( b.x, 1 - b.z ),
  22164. new THREE.Vector2( c.x, 1 - c.z ),
  22165. new THREE.Vector2( d.x, 1 - d.z )
  22166. ];
  22167. } else {
  22168. return [
  22169. new THREE.Vector2( a.y, 1 - a.z ),
  22170. new THREE.Vector2( b.y, 1 - b.z ),
  22171. new THREE.Vector2( c.y, 1 - c.z ),
  22172. new THREE.Vector2( d.y, 1 - d.z )
  22173. ];
  22174. }
  22175. }
  22176. };
  22177. // File:src/extras/geometries/ShapeGeometry.js
  22178. /**
  22179. * @author jonobr1 / http://jonobr1.com
  22180. *
  22181. * Creates a one-sided polygonal geometry from a path shape. Similar to
  22182. * ExtrudeGeometry.
  22183. *
  22184. * parameters = {
  22185. *
  22186. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  22187. *
  22188. * material: <int> // material index for front and back faces
  22189. * uvGenerator: <Object> // object that provides UV generator functions
  22190. *
  22191. * }
  22192. **/
  22193. THREE.ShapeGeometry = function ( shapes, options ) {
  22194. THREE.Geometry.call( this );
  22195. this.type = 'ShapeGeometry';
  22196. if ( Array.isArray( shapes ) === false ) shapes = [ shapes ];
  22197. this.addShapeList( shapes, options );
  22198. this.computeFaceNormals();
  22199. };
  22200. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  22201. THREE.ShapeGeometry.prototype.constructor = THREE.ShapeGeometry;
  22202. /**
  22203. * Add an array of shapes to THREE.ShapeGeometry.
  22204. */
  22205. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  22206. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  22207. this.addShape( shapes[ i ], options );
  22208. }
  22209. return this;
  22210. };
  22211. /**
  22212. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  22213. */
  22214. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  22215. if ( options === undefined ) options = {};
  22216. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  22217. var material = options.material;
  22218. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  22219. //
  22220. var i, l, hole;
  22221. var shapesOffset = this.vertices.length;
  22222. var shapePoints = shape.extractPoints( curveSegments );
  22223. var vertices = shapePoints.shape;
  22224. var holes = shapePoints.holes;
  22225. var reverse = ! THREE.ShapeUtils.isClockWise( vertices );
  22226. if ( reverse ) {
  22227. vertices = vertices.reverse();
  22228. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  22229. for ( i = 0, l = holes.length; i < l; i ++ ) {
  22230. hole = holes[ i ];
  22231. if ( THREE.ShapeUtils.isClockWise( hole ) ) {
  22232. holes[ i ] = hole.reverse();
  22233. }
  22234. }
  22235. reverse = false;
  22236. }
  22237. var faces = THREE.ShapeUtils.triangulateShape( vertices, holes );
  22238. // Vertices
  22239. for ( i = 0, l = holes.length; i < l; i ++ ) {
  22240. hole = holes[ i ];
  22241. vertices = vertices.concat( hole );
  22242. }
  22243. //
  22244. var vert, vlen = vertices.length;
  22245. var face, flen = faces.length;
  22246. for ( i = 0; i < vlen; i ++ ) {
  22247. vert = vertices[ i ];
  22248. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  22249. }
  22250. for ( i = 0; i < flen; i ++ ) {
  22251. face = faces[ i ];
  22252. var a = face[ 0 ] + shapesOffset;
  22253. var b = face[ 1 ] + shapesOffset;
  22254. var c = face[ 2 ] + shapesOffset;
  22255. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  22256. this.faceVertexUvs[ 0 ].push( uvgen.generateTopUV( this, a, b, c ) );
  22257. }
  22258. };
  22259. // File:src/extras/geometries/LatheBufferGeometry.js
  22260. /**
  22261. * @author Mugen87 / https://github.com/Mugen87
  22262. */
  22263. // points - to create a closed torus, one must use a set of points
  22264. // like so: [ a, b, c, d, a ], see first is the same as last.
  22265. // segments - the number of circumference segments to create
  22266. // phiStart - the starting radian
  22267. // phiLength - the radian (0 to 2PI) range of the lathed section
  22268. // 2PI is a closed lathe, less than 2PI is a portion.
  22269. THREE.LatheBufferGeometry = function ( points, segments, phiStart, phiLength ) {
  22270. THREE.BufferGeometry.call( this );
  22271. this.type = 'LatheBufferGeometry';
  22272. this.parameters = {
  22273. points: points,
  22274. segments: segments,
  22275. phiStart: phiStart,
  22276. phiLength: phiLength
  22277. };
  22278. segments = Math.floor( segments ) || 12;
  22279. phiStart = phiStart || 0;
  22280. phiLength = phiLength || Math.PI * 2;
  22281. // clamp phiLength so it's in range of [ 0, 2PI ]
  22282. phiLength = THREE.Math.clamp( phiLength, 0, Math.PI * 2 );
  22283. // these are used to calculate buffer length
  22284. var vertexCount = ( segments + 1 ) * points.length;
  22285. var indexCount = segments * points.length * 2 * 3;
  22286. // buffers
  22287. var indices = new THREE.BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 );
  22288. var vertices = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  22289. var uvs = new THREE.BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  22290. // helper variables
  22291. var index = 0, indexOffset = 0, base;
  22292. var inversePointLength = 1.0 / ( points.length - 1 );
  22293. var inverseSegments = 1.0 / segments;
  22294. var vertex = new THREE.Vector3();
  22295. var uv = new THREE.Vector2();
  22296. var i, j;
  22297. // generate vertices and uvs
  22298. for ( i = 0; i <= segments; i ++ ) {
  22299. var phi = phiStart + i * inverseSegments * phiLength;
  22300. var sin = Math.sin( phi );
  22301. var cos = Math.cos( phi );
  22302. for ( j = 0; j <= ( points.length - 1 ); j ++ ) {
  22303. // vertex
  22304. vertex.x = points[ j ].x * sin;
  22305. vertex.y = points[ j ].y;
  22306. vertex.z = points[ j ].x * cos;
  22307. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  22308. // uv
  22309. uv.x = i / segments;
  22310. uv.y = j / ( points.length - 1 );
  22311. uvs.setXY( index, uv.x, uv.y );
  22312. // increase index
  22313. index ++;
  22314. }
  22315. }
  22316. // generate indices
  22317. for ( i = 0; i < segments; i ++ ) {
  22318. for ( j = 0; j < ( points.length - 1 ); j ++ ) {
  22319. base = j + i * points.length;
  22320. // indices
  22321. var a = base;
  22322. var b = base + points.length;
  22323. var c = base + points.length + 1;
  22324. var d = base + 1;
  22325. // face one
  22326. indices.setX( indexOffset, a ); indexOffset++;
  22327. indices.setX( indexOffset, b ); indexOffset++;
  22328. indices.setX( indexOffset, d ); indexOffset++;
  22329. // face two
  22330. indices.setX( indexOffset, b ); indexOffset++;
  22331. indices.setX( indexOffset, c ); indexOffset++;
  22332. indices.setX( indexOffset, d ); indexOffset++;
  22333. }
  22334. }
  22335. // build geometry
  22336. this.setIndex( indices );
  22337. this.addAttribute( 'position', vertices );
  22338. this.addAttribute( 'uv', uvs );
  22339. // generate normals
  22340. this.computeVertexNormals();
  22341. // if the geometry is closed, we need to average the normals along the seam.
  22342. // because the corresponding vertices are identical (but still have different UVs).
  22343. if( phiLength === Math.PI * 2 ) {
  22344. var normals = this.attributes.normal.array;
  22345. var n1 = new THREE.Vector3();
  22346. var n2 = new THREE.Vector3();
  22347. var n = new THREE.Vector3();
  22348. // this is the buffer offset for the last line of vertices
  22349. base = segments * points.length * 3;
  22350. for( i = 0, j = 0; i < points.length; i ++, j += 3 ) {
  22351. // select the normal of the vertex in the first line
  22352. n1.x = normals[ j + 0 ];
  22353. n1.y = normals[ j + 1 ];
  22354. n1.z = normals[ j + 2 ];
  22355. // select the normal of the vertex in the last line
  22356. n2.x = normals[ base + j + 0 ];
  22357. n2.y = normals[ base + j + 1 ];
  22358. n2.z = normals[ base + j + 2 ];
  22359. // average normals
  22360. n.addVectors( n1, n2 ).normalize();
  22361. // assign the new values to both normals
  22362. normals[ j + 0 ] = normals[ base + j + 0 ] = n.x;
  22363. normals[ j + 1 ] = normals[ base + j + 1 ] = n.y;
  22364. normals[ j + 2 ] = normals[ base + j + 2 ] = n.z;
  22365. } // next row
  22366. }
  22367. };
  22368. THREE.LatheBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  22369. THREE.LatheBufferGeometry.prototype.constructor = THREE.LatheBufferGeometry;
  22370. // File:src/extras/geometries/LatheGeometry.js
  22371. /**
  22372. * @author astrodud / http://astrodud.isgreat.org/
  22373. * @author zz85 / https://github.com/zz85
  22374. * @author bhouston / http://clara.io
  22375. */
  22376. // points - to create a closed torus, one must use a set of points
  22377. // like so: [ a, b, c, d, a ], see first is the same as last.
  22378. // segments - the number of circumference segments to create
  22379. // phiStart - the starting radian
  22380. // phiLength - the radian (0 to 2PI) range of the lathed section
  22381. // 2PI is a closed lathe, less than 2PI is a portion.
  22382. THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
  22383. THREE.Geometry.call( this );
  22384. this.type = 'LatheGeometry';
  22385. this.parameters = {
  22386. points: points,
  22387. segments: segments,
  22388. phiStart: phiStart,
  22389. phiLength: phiLength
  22390. };
  22391. this.fromBufferGeometry( new THREE.LatheBufferGeometry( points, segments, phiStart, phiLength ) );
  22392. this.mergeVertices();
  22393. };
  22394. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  22395. THREE.LatheGeometry.prototype.constructor = THREE.LatheGeometry;
  22396. // File:src/extras/geometries/PlaneGeometry.js
  22397. /**
  22398. * @author mrdoob / http://mrdoob.com/
  22399. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  22400. */
  22401. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  22402. THREE.Geometry.call( this );
  22403. this.type = 'PlaneGeometry';
  22404. this.parameters = {
  22405. width: width,
  22406. height: height,
  22407. widthSegments: widthSegments,
  22408. heightSegments: heightSegments
  22409. };
  22410. this.fromBufferGeometry( new THREE.PlaneBufferGeometry( width, height, widthSegments, heightSegments ) );
  22411. };
  22412. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  22413. THREE.PlaneGeometry.prototype.constructor = THREE.PlaneGeometry;
  22414. // File:src/extras/geometries/PlaneBufferGeometry.js
  22415. /**
  22416. * @author mrdoob / http://mrdoob.com/
  22417. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  22418. */
  22419. THREE.PlaneBufferGeometry = function ( width, height, widthSegments, heightSegments ) {
  22420. THREE.BufferGeometry.call( this );
  22421. this.type = 'PlaneBufferGeometry';
  22422. this.parameters = {
  22423. width: width,
  22424. height: height,
  22425. widthSegments: widthSegments,
  22426. heightSegments: heightSegments
  22427. };
  22428. var width_half = width / 2;
  22429. var height_half = height / 2;
  22430. var gridX = Math.floor( widthSegments ) || 1;
  22431. var gridY = Math.floor( heightSegments ) || 1;
  22432. var gridX1 = gridX + 1;
  22433. var gridY1 = gridY + 1;
  22434. var segment_width = width / gridX;
  22435. var segment_height = height / gridY;
  22436. var vertices = new Float32Array( gridX1 * gridY1 * 3 );
  22437. var normals = new Float32Array( gridX1 * gridY1 * 3 );
  22438. var uvs = new Float32Array( gridX1 * gridY1 * 2 );
  22439. var offset = 0;
  22440. var offset2 = 0;
  22441. for ( var iy = 0; iy < gridY1; iy ++ ) {
  22442. var y = iy * segment_height - height_half;
  22443. for ( var ix = 0; ix < gridX1; ix ++ ) {
  22444. var x = ix * segment_width - width_half;
  22445. vertices[ offset ] = x;
  22446. vertices[ offset + 1 ] = - y;
  22447. normals[ offset + 2 ] = 1;
  22448. uvs[ offset2 ] = ix / gridX;
  22449. uvs[ offset2 + 1 ] = 1 - ( iy / gridY );
  22450. offset += 3;
  22451. offset2 += 2;
  22452. }
  22453. }
  22454. offset = 0;
  22455. var indices = new ( ( vertices.length / 3 ) > 65535 ? Uint32Array : Uint16Array )( gridX * gridY * 6 );
  22456. for ( var iy = 0; iy < gridY; iy ++ ) {
  22457. for ( var ix = 0; ix < gridX; ix ++ ) {
  22458. var a = ix + gridX1 * iy;
  22459. var b = ix + gridX1 * ( iy + 1 );
  22460. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  22461. var d = ( ix + 1 ) + gridX1 * iy;
  22462. indices[ offset ] = a;
  22463. indices[ offset + 1 ] = b;
  22464. indices[ offset + 2 ] = d;
  22465. indices[ offset + 3 ] = b;
  22466. indices[ offset + 4 ] = c;
  22467. indices[ offset + 5 ] = d;
  22468. offset += 6;
  22469. }
  22470. }
  22471. this.setIndex( new THREE.BufferAttribute( indices, 1 ) );
  22472. this.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  22473. this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
  22474. this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) );
  22475. };
  22476. THREE.PlaneBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  22477. THREE.PlaneBufferGeometry.prototype.constructor = THREE.PlaneBufferGeometry;
  22478. // File:src/extras/geometries/RingBufferGeometry.js
  22479. /**
  22480. * @author Mugen87 / https://github.com/Mugen87
  22481. */
  22482. THREE.RingBufferGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  22483. THREE.BufferGeometry.call( this );
  22484. this.type = 'RingBufferGeometry';
  22485. this.parameters = {
  22486. innerRadius: innerRadius,
  22487. outerRadius: outerRadius,
  22488. thetaSegments: thetaSegments,
  22489. phiSegments: phiSegments,
  22490. thetaStart: thetaStart,
  22491. thetaLength: thetaLength
  22492. };
  22493. innerRadius = innerRadius || 20;
  22494. outerRadius = outerRadius || 50;
  22495. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  22496. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  22497. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  22498. phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 1;
  22499. // these are used to calculate buffer length
  22500. var vertexCount = ( thetaSegments + 1 ) * ( phiSegments + 1 );
  22501. var indexCount = thetaSegments * phiSegments * 2 * 3;
  22502. // buffers
  22503. var indices = new THREE.BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 );
  22504. var vertices = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  22505. var normals = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  22506. var uvs = new THREE.BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  22507. // some helper variables
  22508. var index = 0, indexOffset = 0, segment;
  22509. var radius = innerRadius;
  22510. var radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  22511. var vertex = new THREE.Vector3();
  22512. var uv = new THREE.Vector2();
  22513. var j, i;
  22514. // generate vertices, normals and uvs
  22515. // values are generate from the inside of the ring to the outside
  22516. for ( j = 0; j <= phiSegments; j ++ ) {
  22517. for ( i = 0; i <= thetaSegments; i ++ ) {
  22518. segment = thetaStart + i / thetaSegments * thetaLength;
  22519. // vertex
  22520. vertex.x = radius * Math.cos( segment );
  22521. vertex.y = radius * Math.sin( segment );
  22522. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  22523. // normal
  22524. normals.setXYZ( index, 0, 0, 1 );
  22525. // uv
  22526. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  22527. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  22528. uvs.setXY( index, uv.x, uv.y );
  22529. // increase index
  22530. index++;
  22531. }
  22532. // increase the radius for next row of vertices
  22533. radius += radiusStep;
  22534. }
  22535. // generate indices
  22536. for ( j = 0; j < phiSegments; j ++ ) {
  22537. var thetaSegmentLevel = j * ( thetaSegments + 1 );
  22538. for ( i = 0; i < thetaSegments; i ++ ) {
  22539. segment = i + thetaSegmentLevel;
  22540. // indices
  22541. var a = segment;
  22542. var b = segment + thetaSegments + 1;
  22543. var c = segment + thetaSegments + 2;
  22544. var d = segment + 1;
  22545. // face one
  22546. indices.setX( indexOffset, a ); indexOffset++;
  22547. indices.setX( indexOffset, b ); indexOffset++;
  22548. indices.setX( indexOffset, c ); indexOffset++;
  22549. // face two
  22550. indices.setX( indexOffset, a ); indexOffset++;
  22551. indices.setX( indexOffset, c ); indexOffset++;
  22552. indices.setX( indexOffset, d ); indexOffset++;
  22553. }
  22554. }
  22555. // build geometry
  22556. this.setIndex( indices );
  22557. this.addAttribute( 'position', vertices );
  22558. this.addAttribute( 'normal', normals );
  22559. this.addAttribute( 'uv', uvs );
  22560. };
  22561. THREE.RingBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  22562. THREE.RingBufferGeometry.prototype.constructor = THREE.RingBufferGeometry;
  22563. // File:src/extras/geometries/RingGeometry.js
  22564. /**
  22565. * @author Kaleb Murphy
  22566. */
  22567. THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  22568. THREE.Geometry.call( this );
  22569. this.type = 'RingGeometry';
  22570. this.parameters = {
  22571. innerRadius: innerRadius,
  22572. outerRadius: outerRadius,
  22573. thetaSegments: thetaSegments,
  22574. phiSegments: phiSegments,
  22575. thetaStart: thetaStart,
  22576. thetaLength: thetaLength
  22577. };
  22578. this.fromBufferGeometry( new THREE.RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) );
  22579. };
  22580. THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype );
  22581. THREE.RingGeometry.prototype.constructor = THREE.RingGeometry;
  22582. // File:src/extras/geometries/SphereGeometry.js
  22583. /**
  22584. * @author mrdoob / http://mrdoob.com/
  22585. */
  22586. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  22587. THREE.Geometry.call( this );
  22588. this.type = 'SphereGeometry';
  22589. this.parameters = {
  22590. radius: radius,
  22591. widthSegments: widthSegments,
  22592. heightSegments: heightSegments,
  22593. phiStart: phiStart,
  22594. phiLength: phiLength,
  22595. thetaStart: thetaStart,
  22596. thetaLength: thetaLength
  22597. };
  22598. this.fromBufferGeometry( new THREE.SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) );
  22599. };
  22600. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  22601. THREE.SphereGeometry.prototype.constructor = THREE.SphereGeometry;
  22602. // File:src/extras/geometries/SphereBufferGeometry.js
  22603. /**
  22604. * @author benaadams / https://twitter.com/ben_a_adams
  22605. * based on THREE.SphereGeometry
  22606. */
  22607. THREE.SphereBufferGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  22608. THREE.BufferGeometry.call( this );
  22609. this.type = 'SphereBufferGeometry';
  22610. this.parameters = {
  22611. radius: radius,
  22612. widthSegments: widthSegments,
  22613. heightSegments: heightSegments,
  22614. phiStart: phiStart,
  22615. phiLength: phiLength,
  22616. thetaStart: thetaStart,
  22617. thetaLength: thetaLength
  22618. };
  22619. radius = radius || 50;
  22620. widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  22621. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  22622. phiStart = phiStart !== undefined ? phiStart : 0;
  22623. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  22624. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  22625. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  22626. var thetaEnd = thetaStart + thetaLength;
  22627. var vertexCount = ( ( widthSegments + 1 ) * ( heightSegments + 1 ) );
  22628. var positions = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  22629. var normals = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  22630. var uvs = new THREE.BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  22631. var index = 0, vertices = [], normal = new THREE.Vector3();
  22632. for ( var y = 0; y <= heightSegments; y ++ ) {
  22633. var verticesRow = [];
  22634. var v = y / heightSegments;
  22635. for ( var x = 0; x <= widthSegments; x ++ ) {
  22636. var u = x / widthSegments;
  22637. var px = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  22638. var py = radius * Math.cos( thetaStart + v * thetaLength );
  22639. var pz = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  22640. normal.set( px, py, pz ).normalize();
  22641. positions.setXYZ( index, px, py, pz );
  22642. normals.setXYZ( index, normal.x, normal.y, normal.z );
  22643. uvs.setXY( index, u, 1 - v );
  22644. verticesRow.push( index );
  22645. index ++;
  22646. }
  22647. vertices.push( verticesRow );
  22648. }
  22649. var indices = [];
  22650. for ( var y = 0; y < heightSegments; y ++ ) {
  22651. for ( var x = 0; x < widthSegments; x ++ ) {
  22652. var v1 = vertices[ y ][ x + 1 ];
  22653. var v2 = vertices[ y ][ x ];
  22654. var v3 = vertices[ y + 1 ][ x ];
  22655. var v4 = vertices[ y + 1 ][ x + 1 ];
  22656. if ( y !== 0 || thetaStart > 0 ) indices.push( v1, v2, v4 );
  22657. if ( y !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( v2, v3, v4 );
  22658. }
  22659. }
  22660. this.setIndex( new ( positions.count > 65535 ? THREE.Uint32Attribute : THREE.Uint16Attribute )( indices, 1 ) );
  22661. this.addAttribute( 'position', positions );
  22662. this.addAttribute( 'normal', normals );
  22663. this.addAttribute( 'uv', uvs );
  22664. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  22665. };
  22666. THREE.SphereBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  22667. THREE.SphereBufferGeometry.prototype.constructor = THREE.SphereBufferGeometry;
  22668. // File:src/extras/geometries/TextGeometry.js
  22669. /**
  22670. * @author zz85 / http://www.lab4games.net/zz85/blog
  22671. * @author alteredq / http://alteredqualia.com/
  22672. *
  22673. * Text = 3D Text
  22674. *
  22675. * parameters = {
  22676. * font: <THREE.Font>, // font
  22677. *
  22678. * size: <float>, // size of the text
  22679. * height: <float>, // thickness to extrude text
  22680. * curveSegments: <int>, // number of points on the curves
  22681. *
  22682. * bevelEnabled: <bool>, // turn on bevel
  22683. * bevelThickness: <float>, // how deep into text bevel goes
  22684. * bevelSize: <float> // how far from text outline is bevel
  22685. * }
  22686. */
  22687. THREE.TextGeometry = function ( text, parameters ) {
  22688. parameters = parameters || {};
  22689. var font = parameters.font;
  22690. if ( font instanceof THREE.Font === false ) {
  22691. console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' );
  22692. return new THREE.Geometry();
  22693. }
  22694. var shapes = font.generateShapes( text, parameters.size, parameters.curveSegments );
  22695. // translate parameters to ExtrudeGeometry API
  22696. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  22697. // defaults
  22698. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  22699. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  22700. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  22701. THREE.ExtrudeGeometry.call( this, shapes, parameters );
  22702. this.type = 'TextGeometry';
  22703. };
  22704. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  22705. THREE.TextGeometry.prototype.constructor = THREE.TextGeometry;
  22706. // File:src/extras/geometries/TorusBufferGeometry.js
  22707. /**
  22708. * @author Mugen87 / https://github.com/Mugen87
  22709. */
  22710. THREE.TorusBufferGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  22711. THREE.BufferGeometry.call( this );
  22712. this.type = 'TorusBufferGeometry';
  22713. this.parameters = {
  22714. radius: radius,
  22715. tube: tube,
  22716. radialSegments: radialSegments,
  22717. tubularSegments: tubularSegments,
  22718. arc: arc
  22719. };
  22720. radius = radius || 100;
  22721. tube = tube || 40;
  22722. radialSegments = Math.floor( radialSegments ) || 8;
  22723. tubularSegments = Math.floor( tubularSegments ) || 6;
  22724. arc = arc || Math.PI * 2;
  22725. // used to calculate buffer length
  22726. var vertexCount = ( ( radialSegments + 1 ) * ( tubularSegments + 1 ) );
  22727. var indexCount = radialSegments * tubularSegments * 2 * 3;
  22728. // buffers
  22729. var indices = new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount );
  22730. var vertices = new Float32Array( vertexCount * 3 );
  22731. var normals = new Float32Array( vertexCount * 3 );
  22732. var uvs = new Float32Array( vertexCount * 2 );
  22733. // offset variables
  22734. var vertexBufferOffset = 0;
  22735. var uvBufferOffset = 0;
  22736. var indexBufferOffset = 0;
  22737. // helper variables
  22738. var center = new THREE.Vector3();
  22739. var vertex = new THREE.Vector3();
  22740. var normal = new THREE.Vector3();
  22741. var j, i;
  22742. // generate vertices, normals and uvs
  22743. for ( j = 0; j <= radialSegments; j ++ ) {
  22744. for ( i = 0; i <= tubularSegments; i ++ ) {
  22745. var u = i / tubularSegments * arc;
  22746. var v = j / radialSegments * Math.PI * 2;
  22747. // vertex
  22748. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  22749. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  22750. vertex.z = tube * Math.sin( v );
  22751. vertices[ vertexBufferOffset ] = vertex.x;
  22752. vertices[ vertexBufferOffset + 1 ] = vertex.y;
  22753. vertices[ vertexBufferOffset + 2 ] = vertex.z;
  22754. // this vector is used to calculate the normal
  22755. center.x = radius * Math.cos( u );
  22756. center.y = radius * Math.sin( u );
  22757. // normal
  22758. normal.subVectors( vertex, center ).normalize();
  22759. normals[ vertexBufferOffset ] = normal.x;
  22760. normals[ vertexBufferOffset + 1 ] = normal.y;
  22761. normals[ vertexBufferOffset + 2 ] = normal.z;
  22762. // uv
  22763. uvs[ uvBufferOffset ] = i / tubularSegments;
  22764. uvs[ uvBufferOffset + 1 ] = j / radialSegments;
  22765. // update offsets
  22766. vertexBufferOffset += 3;
  22767. uvBufferOffset += 2;
  22768. }
  22769. }
  22770. // generate indices
  22771. for ( j = 1; j <= radialSegments; j ++ ) {
  22772. for ( i = 1; i <= tubularSegments; i ++ ) {
  22773. // indices
  22774. var a = ( tubularSegments + 1 ) * j + i - 1;
  22775. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  22776. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  22777. var d = ( tubularSegments + 1 ) * j + i;
  22778. // face one
  22779. indices[ indexBufferOffset ] = a;
  22780. indices[ indexBufferOffset + 1 ] = b;
  22781. indices[ indexBufferOffset + 2 ] = d;
  22782. // face two
  22783. indices[ indexBufferOffset + 3 ] = b;
  22784. indices[ indexBufferOffset + 4 ] = c;
  22785. indices[ indexBufferOffset + 5 ] = d;
  22786. // update offset
  22787. indexBufferOffset += 6;
  22788. }
  22789. }
  22790. // build geometry
  22791. this.setIndex( new THREE.BufferAttribute( indices, 1 ) );
  22792. this.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  22793. this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
  22794. this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) );
  22795. };
  22796. THREE.TorusBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  22797. THREE.TorusBufferGeometry.prototype.constructor = THREE.TorusBufferGeometry;
  22798. // File:src/extras/geometries/TorusGeometry.js
  22799. /**
  22800. * @author oosmoxiecode
  22801. * @author mrdoob / http://mrdoob.com/
  22802. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  22803. */
  22804. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  22805. THREE.Geometry.call( this );
  22806. this.type = 'TorusGeometry';
  22807. this.parameters = {
  22808. radius: radius,
  22809. tube: tube,
  22810. radialSegments: radialSegments,
  22811. tubularSegments: tubularSegments,
  22812. arc: arc
  22813. };
  22814. this.fromBufferGeometry( new THREE.TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) );
  22815. };
  22816. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  22817. THREE.TorusGeometry.prototype.constructor = THREE.TorusGeometry;
  22818. // File:src/extras/geometries/TorusKnotBufferGeometry.js
  22819. /**
  22820. * @author Mugen87 / https://github.com/Mugen87
  22821. *
  22822. * see: http://www.blackpawn.com/texts/pqtorus/
  22823. */
  22824. THREE.TorusKnotBufferGeometry = function ( radius, tube, tubularSegments, radialSegments, p, q ) {
  22825. THREE.BufferGeometry.call( this );
  22826. this.type = 'TorusKnotBufferGeometry';
  22827. this.parameters = {
  22828. radius: radius,
  22829. tube: tube,
  22830. tubularSegments: tubularSegments,
  22831. radialSegments: radialSegments,
  22832. p: p,
  22833. q: q
  22834. };
  22835. radius = radius || 100;
  22836. tube = tube || 40;
  22837. tubularSegments = Math.floor( tubularSegments ) || 64;
  22838. radialSegments = Math.floor( radialSegments ) || 8;
  22839. p = p || 2;
  22840. q = q || 3;
  22841. // used to calculate buffer length
  22842. var vertexCount = ( ( radialSegments + 1 ) * ( tubularSegments + 1 ) );
  22843. var indexCount = radialSegments * tubularSegments * 2 * 3;
  22844. // buffers
  22845. var indices = new THREE.BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 );
  22846. var vertices = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  22847. var normals = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  22848. var uvs = new THREE.BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  22849. // helper variables
  22850. var i, j, index = 0, indexOffset = 0;
  22851. var vertex = new THREE.Vector3();
  22852. var normal = new THREE.Vector3();
  22853. var uv = new THREE.Vector2();
  22854. var P1 = new THREE.Vector3();
  22855. var P2 = new THREE.Vector3();
  22856. var B = new THREE.Vector3();
  22857. var T = new THREE.Vector3();
  22858. var N = new THREE.Vector3();
  22859. // generate vertices, normals and uvs
  22860. for ( i = 0; i <= tubularSegments; ++ i ) {
  22861. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  22862. var u = i / tubularSegments * p * Math.PI * 2;
  22863. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  22864. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  22865. calculatePositionOnCurve( u, p, q, radius, P1 );
  22866. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  22867. // calculate orthonormal basis
  22868. T.subVectors( P2, P1 );
  22869. N.addVectors( P2, P1 );
  22870. B.crossVectors( T, N );
  22871. N.crossVectors( B, T );
  22872. // normalize B, N. T can be ignored, we don't use it
  22873. B.normalize();
  22874. N.normalize();
  22875. for ( j = 0; j <= radialSegments; ++ j ) {
  22876. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  22877. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  22878. var v = j / radialSegments * Math.PI * 2;
  22879. var cx = - tube * Math.cos( v );
  22880. var cy = tube * Math.sin( v );
  22881. // now calculate the final vertex position.
  22882. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  22883. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  22884. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  22885. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  22886. // vertex
  22887. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  22888. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  22889. normal.subVectors( vertex, P1 ).normalize();
  22890. normals.setXYZ( index, normal.x, normal.y, normal.z );
  22891. // uv
  22892. uv.x = i / tubularSegments;
  22893. uv.y = j / radialSegments;
  22894. uvs.setXY( index, uv.x, uv.y );
  22895. // increase index
  22896. index ++;
  22897. }
  22898. }
  22899. // generate indices
  22900. for ( j = 1; j <= tubularSegments; j ++ ) {
  22901. for ( i = 1; i <= radialSegments; i ++ ) {
  22902. // indices
  22903. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  22904. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  22905. var c = ( radialSegments + 1 ) * j + i;
  22906. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  22907. // face one
  22908. indices.setX( indexOffset, a ); indexOffset++;
  22909. indices.setX( indexOffset, b ); indexOffset++;
  22910. indices.setX( indexOffset, d ); indexOffset++;
  22911. // face two
  22912. indices.setX( indexOffset, b ); indexOffset++;
  22913. indices.setX( indexOffset, c ); indexOffset++;
  22914. indices.setX( indexOffset, d ); indexOffset++;
  22915. }
  22916. }
  22917. // build geometry
  22918. this.setIndex( indices );
  22919. this.addAttribute( 'position', vertices );
  22920. this.addAttribute( 'normal', normals );
  22921. this.addAttribute( 'uv', uvs );
  22922. // this function calculates the current position on the torus curve
  22923. function calculatePositionOnCurve( u, p, q, radius, position ) {
  22924. var cu = Math.cos( u );
  22925. var su = Math.sin( u );
  22926. var quOverP = q / p * u;
  22927. var cs = Math.cos( quOverP );
  22928. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  22929. position.y = radius * ( 2 + cs ) * su * 0.5;
  22930. position.z = radius * Math.sin( quOverP ) * 0.5;
  22931. }
  22932. };
  22933. THREE.TorusKnotBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  22934. THREE.TorusKnotBufferGeometry.prototype.constructor = THREE.TorusKnotBufferGeometry;
  22935. // File:src/extras/geometries/TorusKnotGeometry.js
  22936. /**
  22937. * @author oosmoxiecode
  22938. */
  22939. THREE.TorusKnotGeometry = function ( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) {
  22940. THREE.Geometry.call( this );
  22941. this.type = 'TorusKnotGeometry';
  22942. this.parameters = {
  22943. radius: radius,
  22944. tube: tube,
  22945. tubularSegments: tubularSegments,
  22946. radialSegments: radialSegments,
  22947. p: p,
  22948. q: q
  22949. };
  22950. if( heightScale !== undefined ) console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' );
  22951. this.fromBufferGeometry( new THREE.TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) );
  22952. this.mergeVertices();
  22953. };
  22954. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  22955. THREE.TorusKnotGeometry.prototype.constructor = THREE.TorusKnotGeometry;
  22956. // File:src/extras/geometries/TubeGeometry.js
  22957. /**
  22958. * @author WestLangley / https://github.com/WestLangley
  22959. * @author zz85 / https://github.com/zz85
  22960. * @author miningold / https://github.com/miningold
  22961. * @author jonobr1 / https://github.com/jonobr1
  22962. *
  22963. * Modified from the TorusKnotGeometry by @oosmoxiecode
  22964. *
  22965. * Creates a tube which extrudes along a 3d spline
  22966. *
  22967. * Uses parallel transport frames as described in
  22968. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  22969. */
  22970. THREE.TubeGeometry = function ( path, segments, radius, radialSegments, closed, taper ) {
  22971. THREE.Geometry.call( this );
  22972. this.type = 'TubeGeometry';
  22973. this.parameters = {
  22974. path: path,
  22975. segments: segments,
  22976. radius: radius,
  22977. radialSegments: radialSegments,
  22978. closed: closed,
  22979. taper: taper
  22980. };
  22981. segments = segments || 64;
  22982. radius = radius || 1;
  22983. radialSegments = radialSegments || 8;
  22984. closed = closed || false;
  22985. taper = taper || THREE.TubeGeometry.NoTaper;
  22986. var grid = [];
  22987. var scope = this,
  22988. tangent,
  22989. normal,
  22990. binormal,
  22991. numpoints = segments + 1,
  22992. u, v, r,
  22993. cx, cy,
  22994. pos, pos2 = new THREE.Vector3(),
  22995. i, j,
  22996. ip, jp,
  22997. a, b, c, d,
  22998. uva, uvb, uvc, uvd;
  22999. var frames = new THREE.TubeGeometry.FrenetFrames( path, segments, closed ),
  23000. tangents = frames.tangents,
  23001. normals = frames.normals,
  23002. binormals = frames.binormals;
  23003. // proxy internals
  23004. this.tangents = tangents;
  23005. this.normals = normals;
  23006. this.binormals = binormals;
  23007. function vert( x, y, z ) {
  23008. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  23009. }
  23010. // construct the grid
  23011. for ( i = 0; i < numpoints; i ++ ) {
  23012. grid[ i ] = [];
  23013. u = i / ( numpoints - 1 );
  23014. pos = path.getPointAt( u );
  23015. tangent = tangents[ i ];
  23016. normal = normals[ i ];
  23017. binormal = binormals[ i ];
  23018. r = radius * taper( u );
  23019. for ( j = 0; j < radialSegments; j ++ ) {
  23020. v = j / radialSegments * 2 * Math.PI;
  23021. cx = - r * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  23022. cy = r * Math.sin( v );
  23023. pos2.copy( pos );
  23024. pos2.x += cx * normal.x + cy * binormal.x;
  23025. pos2.y += cx * normal.y + cy * binormal.y;
  23026. pos2.z += cx * normal.z + cy * binormal.z;
  23027. grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  23028. }
  23029. }
  23030. // construct the mesh
  23031. for ( i = 0; i < segments; i ++ ) {
  23032. for ( j = 0; j < radialSegments; j ++ ) {
  23033. ip = ( closed ) ? ( i + 1 ) % segments : i + 1;
  23034. jp = ( j + 1 ) % radialSegments;
  23035. a = grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  23036. b = grid[ ip ][ j ];
  23037. c = grid[ ip ][ jp ];
  23038. d = grid[ i ][ jp ];
  23039. uva = new THREE.Vector2( i / segments, j / radialSegments );
  23040. uvb = new THREE.Vector2( ( i + 1 ) / segments, j / radialSegments );
  23041. uvc = new THREE.Vector2( ( i + 1 ) / segments, ( j + 1 ) / radialSegments );
  23042. uvd = new THREE.Vector2( i / segments, ( j + 1 ) / radialSegments );
  23043. this.faces.push( new THREE.Face3( a, b, d ) );
  23044. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  23045. this.faces.push( new THREE.Face3( b, c, d ) );
  23046. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  23047. }
  23048. }
  23049. this.computeFaceNormals();
  23050. this.computeVertexNormals();
  23051. };
  23052. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  23053. THREE.TubeGeometry.prototype.constructor = THREE.TubeGeometry;
  23054. THREE.TubeGeometry.NoTaper = function ( u ) {
  23055. return 1;
  23056. };
  23057. THREE.TubeGeometry.SinusoidalTaper = function ( u ) {
  23058. return Math.sin( Math.PI * u );
  23059. };
  23060. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  23061. THREE.TubeGeometry.FrenetFrames = function ( path, segments, closed ) {
  23062. var normal = new THREE.Vector3(),
  23063. tangents = [],
  23064. normals = [],
  23065. binormals = [],
  23066. vec = new THREE.Vector3(),
  23067. mat = new THREE.Matrix4(),
  23068. numpoints = segments + 1,
  23069. theta,
  23070. smallest,
  23071. tx, ty, tz,
  23072. i, u;
  23073. // expose internals
  23074. this.tangents = tangents;
  23075. this.normals = normals;
  23076. this.binormals = binormals;
  23077. // compute the tangent vectors for each segment on the path
  23078. for ( i = 0; i < numpoints; i ++ ) {
  23079. u = i / ( numpoints - 1 );
  23080. tangents[ i ] = path.getTangentAt( u );
  23081. tangents[ i ].normalize();
  23082. }
  23083. initialNormal3();
  23084. /*
  23085. function initialNormal1(lastBinormal) {
  23086. // fixed start binormal. Has dangers of 0 vectors
  23087. normals[ 0 ] = new THREE.Vector3();
  23088. binormals[ 0 ] = new THREE.Vector3();
  23089. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  23090. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  23091. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  23092. }
  23093. function initialNormal2() {
  23094. // This uses the Frenet-Serret formula for deriving binormal
  23095. var t2 = path.getTangentAt( epsilon );
  23096. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  23097. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  23098. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  23099. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  23100. }
  23101. */
  23102. function initialNormal3() {
  23103. // select an initial normal vector perpendicular to the first tangent vector,
  23104. // and in the direction of the smallest tangent xyz component
  23105. normals[ 0 ] = new THREE.Vector3();
  23106. binormals[ 0 ] = new THREE.Vector3();
  23107. smallest = Number.MAX_VALUE;
  23108. tx = Math.abs( tangents[ 0 ].x );
  23109. ty = Math.abs( tangents[ 0 ].y );
  23110. tz = Math.abs( tangents[ 0 ].z );
  23111. if ( tx <= smallest ) {
  23112. smallest = tx;
  23113. normal.set( 1, 0, 0 );
  23114. }
  23115. if ( ty <= smallest ) {
  23116. smallest = ty;
  23117. normal.set( 0, 1, 0 );
  23118. }
  23119. if ( tz <= smallest ) {
  23120. normal.set( 0, 0, 1 );
  23121. }
  23122. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  23123. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  23124. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  23125. }
  23126. // compute the slowly-varying normal and binormal vectors for each segment on the path
  23127. for ( i = 1; i < numpoints; i ++ ) {
  23128. normals[ i ] = normals[ i - 1 ].clone();
  23129. binormals[ i ] = binormals[ i - 1 ].clone();
  23130. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  23131. if ( vec.length() > Number.EPSILON ) {
  23132. vec.normalize();
  23133. theta = Math.acos( THREE.Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  23134. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  23135. }
  23136. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23137. }
  23138. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  23139. if ( closed ) {
  23140. theta = Math.acos( THREE.Math.clamp( normals[ 0 ].dot( normals[ numpoints - 1 ] ), - 1, 1 ) );
  23141. theta /= ( numpoints - 1 );
  23142. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints - 1 ] ) ) > 0 ) {
  23143. theta = - theta;
  23144. }
  23145. for ( i = 1; i < numpoints; i ++ ) {
  23146. // twist a little...
  23147. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  23148. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23149. }
  23150. }
  23151. };
  23152. // File:src/extras/geometries/PolyhedronGeometry.js
  23153. /**
  23154. * @author clockworkgeek / https://github.com/clockworkgeek
  23155. * @author timothypratley / https://github.com/timothypratley
  23156. * @author WestLangley / http://github.com/WestLangley
  23157. */
  23158. THREE.PolyhedronGeometry = function ( vertices, indices, radius, detail ) {
  23159. THREE.Geometry.call( this );
  23160. this.type = 'PolyhedronGeometry';
  23161. this.parameters = {
  23162. vertices: vertices,
  23163. indices: indices,
  23164. radius: radius,
  23165. detail: detail
  23166. };
  23167. radius = radius || 1;
  23168. detail = detail || 0;
  23169. var that = this;
  23170. for ( var i = 0, l = vertices.length; i < l; i += 3 ) {
  23171. prepare( new THREE.Vector3( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] ) );
  23172. }
  23173. var p = this.vertices;
  23174. var faces = [];
  23175. for ( var i = 0, j = 0, l = indices.length; i < l; i += 3, j ++ ) {
  23176. var v1 = p[ indices[ i ] ];
  23177. var v2 = p[ indices[ i + 1 ] ];
  23178. var v3 = p[ indices[ i + 2 ] ];
  23179. faces[ j ] = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ], undefined, j );
  23180. }
  23181. var centroid = new THREE.Vector3();
  23182. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  23183. subdivide( faces[ i ], detail );
  23184. }
  23185. // Handle case when face straddles the seam
  23186. for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) {
  23187. var uvs = this.faceVertexUvs[ 0 ][ i ];
  23188. var x0 = uvs[ 0 ].x;
  23189. var x1 = uvs[ 1 ].x;
  23190. var x2 = uvs[ 2 ].x;
  23191. var max = Math.max( x0, x1, x2 );
  23192. var min = Math.min( x0, x1, x2 );
  23193. if ( max > 0.9 && min < 0.1 ) {
  23194. // 0.9 is somewhat arbitrary
  23195. if ( x0 < 0.2 ) uvs[ 0 ].x += 1;
  23196. if ( x1 < 0.2 ) uvs[ 1 ].x += 1;
  23197. if ( x2 < 0.2 ) uvs[ 2 ].x += 1;
  23198. }
  23199. }
  23200. // Apply radius
  23201. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  23202. this.vertices[ i ].multiplyScalar( radius );
  23203. }
  23204. // Merge vertices
  23205. this.mergeVertices();
  23206. this.computeFaceNormals();
  23207. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  23208. // Project vector onto sphere's surface
  23209. function prepare( vector ) {
  23210. var vertex = vector.normalize().clone();
  23211. vertex.index = that.vertices.push( vertex ) - 1;
  23212. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  23213. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  23214. var v = inclination( vector ) / Math.PI + 0.5;
  23215. vertex.uv = new THREE.Vector2( u, 1 - v );
  23216. return vertex;
  23217. }
  23218. // Approximate a curved face with recursively sub-divided triangles.
  23219. function make( v1, v2, v3, materialIndex ) {
  23220. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ], undefined, materialIndex );
  23221. that.faces.push( face );
  23222. centroid.copy( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  23223. var azi = azimuth( centroid );
  23224. that.faceVertexUvs[ 0 ].push( [
  23225. correctUV( v1.uv, v1, azi ),
  23226. correctUV( v2.uv, v2, azi ),
  23227. correctUV( v3.uv, v3, azi )
  23228. ] );
  23229. }
  23230. // Analytically subdivide a face to the required detail level.
  23231. function subdivide( face, detail ) {
  23232. var cols = Math.pow( 2, detail );
  23233. var a = prepare( that.vertices[ face.a ] );
  23234. var b = prepare( that.vertices[ face.b ] );
  23235. var c = prepare( that.vertices[ face.c ] );
  23236. var v = [];
  23237. var materialIndex = face.materialIndex;
  23238. // Construct all of the vertices for this subdivision.
  23239. for ( var i = 0 ; i <= cols; i ++ ) {
  23240. v[ i ] = [];
  23241. var aj = prepare( a.clone().lerp( c, i / cols ) );
  23242. var bj = prepare( b.clone().lerp( c, i / cols ) );
  23243. var rows = cols - i;
  23244. for ( var j = 0; j <= rows; j ++ ) {
  23245. if ( j === 0 && i === cols ) {
  23246. v[ i ][ j ] = aj;
  23247. } else {
  23248. v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) );
  23249. }
  23250. }
  23251. }
  23252. // Construct all of the faces.
  23253. for ( var i = 0; i < cols ; i ++ ) {
  23254. for ( var j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  23255. var k = Math.floor( j / 2 );
  23256. if ( j % 2 === 0 ) {
  23257. make(
  23258. v[ i ][ k + 1 ],
  23259. v[ i + 1 ][ k ],
  23260. v[ i ][ k ],
  23261. materialIndex
  23262. );
  23263. } else {
  23264. make(
  23265. v[ i ][ k + 1 ],
  23266. v[ i + 1 ][ k + 1 ],
  23267. v[ i + 1 ][ k ],
  23268. materialIndex
  23269. );
  23270. }
  23271. }
  23272. }
  23273. }
  23274. // Angle around the Y axis, counter-clockwise when looking from above.
  23275. function azimuth( vector ) {
  23276. return Math.atan2( vector.z, - vector.x );
  23277. }
  23278. // Angle above the XZ plane.
  23279. function inclination( vector ) {
  23280. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  23281. }
  23282. // Texture fixing helper. Spheres have some odd behaviours.
  23283. function correctUV( uv, vector, azimuth ) {
  23284. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  23285. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  23286. return uv.clone();
  23287. }
  23288. };
  23289. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  23290. THREE.PolyhedronGeometry.prototype.constructor = THREE.PolyhedronGeometry;
  23291. // File:src/extras/geometries/DodecahedronGeometry.js
  23292. /**
  23293. * @author Abe Pazos / https://hamoid.com
  23294. */
  23295. THREE.DodecahedronGeometry = function ( radius, detail ) {
  23296. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  23297. var r = 1 / t;
  23298. var vertices = [
  23299. // (±1, ±1, ±1)
  23300. - 1, - 1, - 1, - 1, - 1, 1,
  23301. - 1, 1, - 1, - 1, 1, 1,
  23302. 1, - 1, - 1, 1, - 1, 1,
  23303. 1, 1, - 1, 1, 1, 1,
  23304. // (0, ±1/φ, ±φ)
  23305. 0, - r, - t, 0, - r, t,
  23306. 0, r, - t, 0, r, t,
  23307. // (±1/φ, ±φ, 0)
  23308. - r, - t, 0, - r, t, 0,
  23309. r, - t, 0, r, t, 0,
  23310. // (±φ, 0, ±1/φ)
  23311. - t, 0, - r, t, 0, - r,
  23312. - t, 0, r, t, 0, r
  23313. ];
  23314. var indices = [
  23315. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  23316. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  23317. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  23318. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  23319. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  23320. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  23321. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  23322. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  23323. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  23324. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  23325. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  23326. 1, 12, 14, 1, 14, 5, 1, 5, 9
  23327. ];
  23328. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  23329. this.type = 'DodecahedronGeometry';
  23330. this.parameters = {
  23331. radius: radius,
  23332. detail: detail
  23333. };
  23334. };
  23335. THREE.DodecahedronGeometry.prototype = Object.create( THREE.PolyhedronGeometry.prototype );
  23336. THREE.DodecahedronGeometry.prototype.constructor = THREE.DodecahedronGeometry;
  23337. // File:src/extras/geometries/IcosahedronGeometry.js
  23338. /**
  23339. * @author timothypratley / https://github.com/timothypratley
  23340. */
  23341. THREE.IcosahedronGeometry = function ( radius, detail ) {
  23342. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  23343. var vertices = [
  23344. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  23345. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  23346. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  23347. ];
  23348. var indices = [
  23349. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  23350. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  23351. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  23352. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  23353. ];
  23354. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  23355. this.type = 'IcosahedronGeometry';
  23356. this.parameters = {
  23357. radius: radius,
  23358. detail: detail
  23359. };
  23360. };
  23361. THREE.IcosahedronGeometry.prototype = Object.create( THREE.PolyhedronGeometry.prototype );
  23362. THREE.IcosahedronGeometry.prototype.constructor = THREE.IcosahedronGeometry;
  23363. // File:src/extras/geometries/OctahedronGeometry.js
  23364. /**
  23365. * @author timothypratley / https://github.com/timothypratley
  23366. */
  23367. THREE.OctahedronGeometry = function ( radius, detail ) {
  23368. var vertices = [
  23369. 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  23370. ];
  23371. var indices = [
  23372. 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2
  23373. ];
  23374. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  23375. this.type = 'OctahedronGeometry';
  23376. this.parameters = {
  23377. radius: radius,
  23378. detail: detail
  23379. };
  23380. };
  23381. THREE.OctahedronGeometry.prototype = Object.create( THREE.PolyhedronGeometry.prototype );
  23382. THREE.OctahedronGeometry.prototype.constructor = THREE.OctahedronGeometry;
  23383. // File:src/extras/geometries/TetrahedronGeometry.js
  23384. /**
  23385. * @author timothypratley / https://github.com/timothypratley
  23386. */
  23387. THREE.TetrahedronGeometry = function ( radius, detail ) {
  23388. var vertices = [
  23389. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  23390. ];
  23391. var indices = [
  23392. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  23393. ];
  23394. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  23395. this.type = 'TetrahedronGeometry';
  23396. this.parameters = {
  23397. radius: radius,
  23398. detail: detail
  23399. };
  23400. };
  23401. THREE.TetrahedronGeometry.prototype = Object.create( THREE.PolyhedronGeometry.prototype );
  23402. THREE.TetrahedronGeometry.prototype.constructor = THREE.TetrahedronGeometry;
  23403. // File:src/extras/geometries/ParametricGeometry.js
  23404. /**
  23405. * @author zz85 / https://github.com/zz85
  23406. * Parametric Surfaces Geometry
  23407. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  23408. *
  23409. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements );
  23410. *
  23411. */
  23412. THREE.ParametricGeometry = function ( func, slices, stacks ) {
  23413. THREE.Geometry.call( this );
  23414. this.type = 'ParametricGeometry';
  23415. this.parameters = {
  23416. func: func,
  23417. slices: slices,
  23418. stacks: stacks
  23419. };
  23420. var verts = this.vertices;
  23421. var faces = this.faces;
  23422. var uvs = this.faceVertexUvs[ 0 ];
  23423. var i, j, p;
  23424. var u, v;
  23425. var sliceCount = slices + 1;
  23426. for ( i = 0; i <= stacks; i ++ ) {
  23427. v = i / stacks;
  23428. for ( j = 0; j <= slices; j ++ ) {
  23429. u = j / slices;
  23430. p = func( u, v );
  23431. verts.push( p );
  23432. }
  23433. }
  23434. var a, b, c, d;
  23435. var uva, uvb, uvc, uvd;
  23436. for ( i = 0; i < stacks; i ++ ) {
  23437. for ( j = 0; j < slices; j ++ ) {
  23438. a = i * sliceCount + j;
  23439. b = i * sliceCount + j + 1;
  23440. c = ( i + 1 ) * sliceCount + j + 1;
  23441. d = ( i + 1 ) * sliceCount + j;
  23442. uva = new THREE.Vector2( j / slices, i / stacks );
  23443. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  23444. uvc = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  23445. uvd = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  23446. faces.push( new THREE.Face3( a, b, d ) );
  23447. uvs.push( [ uva, uvb, uvd ] );
  23448. faces.push( new THREE.Face3( b, c, d ) );
  23449. uvs.push( [ uvb.clone(), uvc, uvd.clone() ] );
  23450. }
  23451. }
  23452. // console.log(this);
  23453. // magic bullet
  23454. // var diff = this.mergeVertices();
  23455. // console.log('removed ', diff, ' vertices by merging');
  23456. this.computeFaceNormals();
  23457. this.computeVertexNormals();
  23458. };
  23459. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  23460. THREE.ParametricGeometry.prototype.constructor = THREE.ParametricGeometry;
  23461. // File:src/extras/geometries/WireframeGeometry.js
  23462. /**
  23463. * @author mrdoob / http://mrdoob.com/
  23464. */
  23465. THREE.WireframeGeometry = function ( geometry ) {
  23466. THREE.BufferGeometry.call( this );
  23467. var edge = [ 0, 0 ], hash = {};
  23468. function sortFunction( a, b ) {
  23469. return a - b;
  23470. }
  23471. var keys = [ 'a', 'b', 'c' ];
  23472. if ( geometry instanceof THREE.Geometry ) {
  23473. var vertices = geometry.vertices;
  23474. var faces = geometry.faces;
  23475. var numEdges = 0;
  23476. // allocate maximal size
  23477. var edges = new Uint32Array( 6 * faces.length );
  23478. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  23479. var face = faces[ i ];
  23480. for ( var j = 0; j < 3; j ++ ) {
  23481. edge[ 0 ] = face[ keys[ j ] ];
  23482. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  23483. edge.sort( sortFunction );
  23484. var key = edge.toString();
  23485. if ( hash[ key ] === undefined ) {
  23486. edges[ 2 * numEdges ] = edge[ 0 ];
  23487. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  23488. hash[ key ] = true;
  23489. numEdges ++;
  23490. }
  23491. }
  23492. }
  23493. var coords = new Float32Array( numEdges * 2 * 3 );
  23494. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  23495. for ( var j = 0; j < 2; j ++ ) {
  23496. var vertex = vertices[ edges [ 2 * i + j ] ];
  23497. var index = 6 * i + 3 * j;
  23498. coords[ index + 0 ] = vertex.x;
  23499. coords[ index + 1 ] = vertex.y;
  23500. coords[ index + 2 ] = vertex.z;
  23501. }
  23502. }
  23503. this.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  23504. } else if ( geometry instanceof THREE.BufferGeometry ) {
  23505. if ( geometry.index !== null ) {
  23506. // Indexed BufferGeometry
  23507. var indices = geometry.index.array;
  23508. var vertices = geometry.attributes.position;
  23509. var groups = geometry.groups;
  23510. var numEdges = 0;
  23511. if ( groups.length === 0 ) {
  23512. geometry.addGroup( 0, indices.length );
  23513. }
  23514. // allocate maximal size
  23515. var edges = new Uint32Array( 2 * indices.length );
  23516. for ( var o = 0, ol = groups.length; o < ol; ++ o ) {
  23517. var group = groups[ o ];
  23518. var start = group.start;
  23519. var count = group.count;
  23520. for ( var i = start, il = start + count; i < il; i += 3 ) {
  23521. for ( var j = 0; j < 3; j ++ ) {
  23522. edge[ 0 ] = indices[ i + j ];
  23523. edge[ 1 ] = indices[ i + ( j + 1 ) % 3 ];
  23524. edge.sort( sortFunction );
  23525. var key = edge.toString();
  23526. if ( hash[ key ] === undefined ) {
  23527. edges[ 2 * numEdges ] = edge[ 0 ];
  23528. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  23529. hash[ key ] = true;
  23530. numEdges ++;
  23531. }
  23532. }
  23533. }
  23534. }
  23535. var coords = new Float32Array( numEdges * 2 * 3 );
  23536. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  23537. for ( var j = 0; j < 2; j ++ ) {
  23538. var index = 6 * i + 3 * j;
  23539. var index2 = edges[ 2 * i + j ];
  23540. coords[ index + 0 ] = vertices.getX( index2 );
  23541. coords[ index + 1 ] = vertices.getY( index2 );
  23542. coords[ index + 2 ] = vertices.getZ( index2 );
  23543. }
  23544. }
  23545. this.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  23546. } else {
  23547. // non-indexed BufferGeometry
  23548. var vertices = geometry.attributes.position.array;
  23549. var numEdges = vertices.length / 3;
  23550. var numTris = numEdges / 3;
  23551. var coords = new Float32Array( numEdges * 2 * 3 );
  23552. for ( var i = 0, l = numTris; i < l; i ++ ) {
  23553. for ( var j = 0; j < 3; j ++ ) {
  23554. var index = 18 * i + 6 * j;
  23555. var index1 = 9 * i + 3 * j;
  23556. coords[ index + 0 ] = vertices[ index1 ];
  23557. coords[ index + 1 ] = vertices[ index1 + 1 ];
  23558. coords[ index + 2 ] = vertices[ index1 + 2 ];
  23559. var index2 = 9 * i + 3 * ( ( j + 1 ) % 3 );
  23560. coords[ index + 3 ] = vertices[ index2 ];
  23561. coords[ index + 4 ] = vertices[ index2 + 1 ];
  23562. coords[ index + 5 ] = vertices[ index2 + 2 ];
  23563. }
  23564. }
  23565. this.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  23566. }
  23567. }
  23568. };
  23569. THREE.WireframeGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  23570. THREE.WireframeGeometry.prototype.constructor = THREE.WireframeGeometry;
  23571. // File:src/extras/helpers/AxisHelper.js
  23572. /**
  23573. * @author sroucheray / http://sroucheray.org/
  23574. * @author mrdoob / http://mrdoob.com/
  23575. */
  23576. THREE.AxisHelper = function ( size ) {
  23577. size = size || 1;
  23578. var vertices = new Float32Array( [
  23579. 0, 0, 0, size, 0, 0,
  23580. 0, 0, 0, 0, size, 0,
  23581. 0, 0, 0, 0, 0, size
  23582. ] );
  23583. var colors = new Float32Array( [
  23584. 1, 0, 0, 1, 0.6, 0,
  23585. 0, 1, 0, 0.6, 1, 0,
  23586. 0, 0, 1, 0, 0.6, 1
  23587. ] );
  23588. var geometry = new THREE.BufferGeometry();
  23589. geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  23590. geometry.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) );
  23591. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  23592. THREE.LineSegments.call( this, geometry, material );
  23593. };
  23594. THREE.AxisHelper.prototype = Object.create( THREE.LineSegments.prototype );
  23595. THREE.AxisHelper.prototype.constructor = THREE.AxisHelper;
  23596. // File:src/extras/helpers/ArrowHelper.js
  23597. /**
  23598. * @author WestLangley / http://github.com/WestLangley
  23599. * @author zz85 / http://github.com/zz85
  23600. * @author bhouston / http://clara.io
  23601. *
  23602. * Creates an arrow for visualizing directions
  23603. *
  23604. * Parameters:
  23605. * dir - Vector3
  23606. * origin - Vector3
  23607. * length - Number
  23608. * color - color in hex value
  23609. * headLength - Number
  23610. * headWidth - Number
  23611. */
  23612. THREE.ArrowHelper = ( function () {
  23613. var lineGeometry = new THREE.Geometry();
  23614. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, 1, 0 ) );
  23615. var coneGeometry = new THREE.CylinderGeometry( 0, 0.5, 1, 5, 1 );
  23616. coneGeometry.translate( 0, - 0.5, 0 );
  23617. return function ArrowHelper( dir, origin, length, color, headLength, headWidth ) {
  23618. // dir is assumed to be normalized
  23619. THREE.Object3D.call( this );
  23620. if ( color === undefined ) color = 0xffff00;
  23621. if ( length === undefined ) length = 1;
  23622. if ( headLength === undefined ) headLength = 0.2 * length;
  23623. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  23624. this.position.copy( origin );
  23625. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: color } ) );
  23626. this.line.matrixAutoUpdate = false;
  23627. this.add( this.line );
  23628. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: color } ) );
  23629. this.cone.matrixAutoUpdate = false;
  23630. this.add( this.cone );
  23631. this.setDirection( dir );
  23632. this.setLength( length, headLength, headWidth );
  23633. }
  23634. }() );
  23635. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  23636. THREE.ArrowHelper.prototype.constructor = THREE.ArrowHelper;
  23637. THREE.ArrowHelper.prototype.setDirection = ( function () {
  23638. var axis = new THREE.Vector3();
  23639. var radians;
  23640. return function setDirection( dir ) {
  23641. // dir is assumed to be normalized
  23642. if ( dir.y > 0.99999 ) {
  23643. this.quaternion.set( 0, 0, 0, 1 );
  23644. } else if ( dir.y < - 0.99999 ) {
  23645. this.quaternion.set( 1, 0, 0, 0 );
  23646. } else {
  23647. axis.set( dir.z, 0, - dir.x ).normalize();
  23648. radians = Math.acos( dir.y );
  23649. this.quaternion.setFromAxisAngle( axis, radians );
  23650. }
  23651. };
  23652. }() );
  23653. THREE.ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  23654. if ( headLength === undefined ) headLength = 0.2 * length;
  23655. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  23656. this.line.scale.set( 1, Math.max( 0, length - headLength ), 1 );
  23657. this.line.updateMatrix();
  23658. this.cone.scale.set( headWidth, headLength, headWidth );
  23659. this.cone.position.y = length;
  23660. this.cone.updateMatrix();
  23661. };
  23662. THREE.ArrowHelper.prototype.setColor = function ( color ) {
  23663. this.line.material.color.set( color );
  23664. this.cone.material.color.set( color );
  23665. };
  23666. // File:src/extras/helpers/BoxHelper.js
  23667. /**
  23668. * @author mrdoob / http://mrdoob.com/
  23669. */
  23670. THREE.BoxHelper = function ( object ) {
  23671. 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 ] );
  23672. var positions = new Float32Array( 8 * 3 );
  23673. var geometry = new THREE.BufferGeometry();
  23674. geometry.setIndex( new THREE.BufferAttribute( indices, 1 ) );
  23675. geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
  23676. THREE.LineSegments.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffff00 } ) );
  23677. if ( object !== undefined ) {
  23678. this.update( object );
  23679. }
  23680. };
  23681. THREE.BoxHelper.prototype = Object.create( THREE.LineSegments.prototype );
  23682. THREE.BoxHelper.prototype.constructor = THREE.BoxHelper;
  23683. THREE.BoxHelper.prototype.update = ( function () {
  23684. var box = new THREE.Box3();
  23685. return function ( object ) {
  23686. box.setFromObject( object );
  23687. if ( box.isEmpty() ) return;
  23688. var min = box.min;
  23689. var max = box.max;
  23690. /*
  23691. 5____4
  23692. 1/___0/|
  23693. | 6__|_7
  23694. 2/___3/
  23695. 0: max.x, max.y, max.z
  23696. 1: min.x, max.y, max.z
  23697. 2: min.x, min.y, max.z
  23698. 3: max.x, min.y, max.z
  23699. 4: max.x, max.y, min.z
  23700. 5: min.x, max.y, min.z
  23701. 6: min.x, min.y, min.z
  23702. 7: max.x, min.y, min.z
  23703. */
  23704. var position = this.geometry.attributes.position;
  23705. var array = position.array;
  23706. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  23707. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  23708. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  23709. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  23710. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  23711. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  23712. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  23713. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  23714. position.needsUpdate = true;
  23715. this.geometry.computeBoundingSphere();
  23716. };
  23717. } )();
  23718. // File:src/extras/helpers/BoundingBoxHelper.js
  23719. /**
  23720. * @author WestLangley / http://github.com/WestLangley
  23721. */
  23722. // a helper to show the world-axis-aligned bounding box for an object
  23723. THREE.BoundingBoxHelper = function ( object, hex ) {
  23724. var color = ( hex !== undefined ) ? hex : 0x888888;
  23725. this.object = object;
  23726. this.box = new THREE.Box3();
  23727. THREE.Mesh.call( this, new THREE.BoxGeometry( 1, 1, 1 ), new THREE.MeshBasicMaterial( { color: color, wireframe: true } ) );
  23728. };
  23729. THREE.BoundingBoxHelper.prototype = Object.create( THREE.Mesh.prototype );
  23730. THREE.BoundingBoxHelper.prototype.constructor = THREE.BoundingBoxHelper;
  23731. THREE.BoundingBoxHelper.prototype.update = function () {
  23732. this.box.setFromObject( this.object );
  23733. this.box.size( this.scale );
  23734. this.box.center( this.position );
  23735. };
  23736. // File:src/extras/helpers/CameraHelper.js
  23737. /**
  23738. * @author alteredq / http://alteredqualia.com/
  23739. *
  23740. * - shows frustum, line of sight and up of the camera
  23741. * - suitable for fast updates
  23742. * - based on frustum visualization in lightgl.js shadowmap example
  23743. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  23744. */
  23745. THREE.CameraHelper = function ( camera ) {
  23746. var geometry = new THREE.Geometry();
  23747. var material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  23748. var pointMap = {};
  23749. // colors
  23750. var hexFrustum = 0xffaa00;
  23751. var hexCone = 0xff0000;
  23752. var hexUp = 0x00aaff;
  23753. var hexTarget = 0xffffff;
  23754. var hexCross = 0x333333;
  23755. // near
  23756. addLine( "n1", "n2", hexFrustum );
  23757. addLine( "n2", "n4", hexFrustum );
  23758. addLine( "n4", "n3", hexFrustum );
  23759. addLine( "n3", "n1", hexFrustum );
  23760. // far
  23761. addLine( "f1", "f2", hexFrustum );
  23762. addLine( "f2", "f4", hexFrustum );
  23763. addLine( "f4", "f3", hexFrustum );
  23764. addLine( "f3", "f1", hexFrustum );
  23765. // sides
  23766. addLine( "n1", "f1", hexFrustum );
  23767. addLine( "n2", "f2", hexFrustum );
  23768. addLine( "n3", "f3", hexFrustum );
  23769. addLine( "n4", "f4", hexFrustum );
  23770. // cone
  23771. addLine( "p", "n1", hexCone );
  23772. addLine( "p", "n2", hexCone );
  23773. addLine( "p", "n3", hexCone );
  23774. addLine( "p", "n4", hexCone );
  23775. // up
  23776. addLine( "u1", "u2", hexUp );
  23777. addLine( "u2", "u3", hexUp );
  23778. addLine( "u3", "u1", hexUp );
  23779. // target
  23780. addLine( "c", "t", hexTarget );
  23781. addLine( "p", "c", hexCross );
  23782. // cross
  23783. addLine( "cn1", "cn2", hexCross );
  23784. addLine( "cn3", "cn4", hexCross );
  23785. addLine( "cf1", "cf2", hexCross );
  23786. addLine( "cf3", "cf4", hexCross );
  23787. function addLine( a, b, hex ) {
  23788. addPoint( a, hex );
  23789. addPoint( b, hex );
  23790. }
  23791. function addPoint( id, hex ) {
  23792. geometry.vertices.push( new THREE.Vector3() );
  23793. geometry.colors.push( new THREE.Color( hex ) );
  23794. if ( pointMap[ id ] === undefined ) {
  23795. pointMap[ id ] = [];
  23796. }
  23797. pointMap[ id ].push( geometry.vertices.length - 1 );
  23798. }
  23799. THREE.LineSegments.call( this, geometry, material );
  23800. this.camera = camera;
  23801. this.camera.updateProjectionMatrix();
  23802. this.matrix = camera.matrixWorld;
  23803. this.matrixAutoUpdate = false;
  23804. this.pointMap = pointMap;
  23805. this.update();
  23806. };
  23807. THREE.CameraHelper.prototype = Object.create( THREE.LineSegments.prototype );
  23808. THREE.CameraHelper.prototype.constructor = THREE.CameraHelper;
  23809. THREE.CameraHelper.prototype.update = function () {
  23810. var geometry, pointMap;
  23811. var vector = new THREE.Vector3();
  23812. var camera = new THREE.Camera();
  23813. function setPoint( point, x, y, z ) {
  23814. vector.set( x, y, z ).unproject( camera );
  23815. var points = pointMap[ point ];
  23816. if ( points !== undefined ) {
  23817. for ( var i = 0, il = points.length; i < il; i ++ ) {
  23818. geometry.vertices[ points[ i ] ].copy( vector );
  23819. }
  23820. }
  23821. }
  23822. return function () {
  23823. geometry = this.geometry;
  23824. pointMap = this.pointMap;
  23825. var w = 1, h = 1;
  23826. // we need just camera projection matrix
  23827. // world matrix must be identity
  23828. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  23829. // center / target
  23830. setPoint( "c", 0, 0, - 1 );
  23831. setPoint( "t", 0, 0, 1 );
  23832. // near
  23833. setPoint( "n1", - w, - h, - 1 );
  23834. setPoint( "n2", w, - h, - 1 );
  23835. setPoint( "n3", - w, h, - 1 );
  23836. setPoint( "n4", w, h, - 1 );
  23837. // far
  23838. setPoint( "f1", - w, - h, 1 );
  23839. setPoint( "f2", w, - h, 1 );
  23840. setPoint( "f3", - w, h, 1 );
  23841. setPoint( "f4", w, h, 1 );
  23842. // up
  23843. setPoint( "u1", w * 0.7, h * 1.1, - 1 );
  23844. setPoint( "u2", - w * 0.7, h * 1.1, - 1 );
  23845. setPoint( "u3", 0, h * 2, - 1 );
  23846. // cross
  23847. setPoint( "cf1", - w, 0, 1 );
  23848. setPoint( "cf2", w, 0, 1 );
  23849. setPoint( "cf3", 0, - h, 1 );
  23850. setPoint( "cf4", 0, h, 1 );
  23851. setPoint( "cn1", - w, 0, - 1 );
  23852. setPoint( "cn2", w, 0, - 1 );
  23853. setPoint( "cn3", 0, - h, - 1 );
  23854. setPoint( "cn4", 0, h, - 1 );
  23855. geometry.verticesNeedUpdate = true;
  23856. };
  23857. }();
  23858. // File:src/extras/helpers/DirectionalLightHelper.js
  23859. /**
  23860. * @author alteredq / http://alteredqualia.com/
  23861. * @author mrdoob / http://mrdoob.com/
  23862. * @author WestLangley / http://github.com/WestLangley
  23863. */
  23864. THREE.DirectionalLightHelper = function ( light, size ) {
  23865. THREE.Object3D.call( this );
  23866. this.light = light;
  23867. this.light.updateMatrixWorld();
  23868. this.matrix = light.matrixWorld;
  23869. this.matrixAutoUpdate = false;
  23870. size = size || 1;
  23871. var geometry = new THREE.Geometry();
  23872. geometry.vertices.push(
  23873. new THREE.Vector3( - size, size, 0 ),
  23874. new THREE.Vector3( size, size, 0 ),
  23875. new THREE.Vector3( size, - size, 0 ),
  23876. new THREE.Vector3( - size, - size, 0 ),
  23877. new THREE.Vector3( - size, size, 0 )
  23878. );
  23879. var material = new THREE.LineBasicMaterial( { fog: false } );
  23880. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  23881. this.lightPlane = new THREE.Line( geometry, material );
  23882. this.add( this.lightPlane );
  23883. geometry = new THREE.Geometry();
  23884. geometry.vertices.push(
  23885. new THREE.Vector3(),
  23886. new THREE.Vector3()
  23887. );
  23888. material = new THREE.LineBasicMaterial( { fog: false } );
  23889. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  23890. this.targetLine = new THREE.Line( geometry, material );
  23891. this.add( this.targetLine );
  23892. this.update();
  23893. };
  23894. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  23895. THREE.DirectionalLightHelper.prototype.constructor = THREE.DirectionalLightHelper;
  23896. THREE.DirectionalLightHelper.prototype.dispose = function () {
  23897. this.lightPlane.geometry.dispose();
  23898. this.lightPlane.material.dispose();
  23899. this.targetLine.geometry.dispose();
  23900. this.targetLine.material.dispose();
  23901. };
  23902. THREE.DirectionalLightHelper.prototype.update = function () {
  23903. var v1 = new THREE.Vector3();
  23904. var v2 = new THREE.Vector3();
  23905. var v3 = new THREE.Vector3();
  23906. return function () {
  23907. v1.setFromMatrixPosition( this.light.matrixWorld );
  23908. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  23909. v3.subVectors( v2, v1 );
  23910. this.lightPlane.lookAt( v3 );
  23911. this.lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  23912. this.targetLine.geometry.vertices[ 1 ].copy( v3 );
  23913. this.targetLine.geometry.verticesNeedUpdate = true;
  23914. this.targetLine.material.color.copy( this.lightPlane.material.color );
  23915. };
  23916. }();
  23917. // File:src/extras/helpers/EdgesHelper.js
  23918. /**
  23919. * @author WestLangley / http://github.com/WestLangley
  23920. * @param object THREE.Mesh whose geometry will be used
  23921. * @param hex line color
  23922. * @param thresholdAngle the minimum angle (in degrees),
  23923. * between the face normals of adjacent faces,
  23924. * that is required to render an edge. A value of 10 means
  23925. * an edge is only rendered if the angle is at least 10 degrees.
  23926. */
  23927. THREE.EdgesHelper = function ( object, hex, thresholdAngle ) {
  23928. var color = ( hex !== undefined ) ? hex : 0xffffff;
  23929. THREE.LineSegments.call( this, new THREE.EdgesGeometry( object.geometry, thresholdAngle ), new THREE.LineBasicMaterial( { color: color } ) );
  23930. this.matrix = object.matrixWorld;
  23931. this.matrixAutoUpdate = false;
  23932. };
  23933. THREE.EdgesHelper.prototype = Object.create( THREE.LineSegments.prototype );
  23934. THREE.EdgesHelper.prototype.constructor = THREE.EdgesHelper;
  23935. // File:src/extras/helpers/FaceNormalsHelper.js
  23936. /**
  23937. * @author mrdoob / http://mrdoob.com/
  23938. * @author WestLangley / http://github.com/WestLangley
  23939. */
  23940. THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) {
  23941. // FaceNormalsHelper only supports THREE.Geometry
  23942. this.object = object;
  23943. this.size = ( size !== undefined ) ? size : 1;
  23944. var color = ( hex !== undefined ) ? hex : 0xffff00;
  23945. var width = ( linewidth !== undefined ) ? linewidth : 1;
  23946. //
  23947. var nNormals = 0;
  23948. var objGeometry = this.object.geometry;
  23949. if ( objGeometry instanceof THREE.Geometry ) {
  23950. nNormals = objGeometry.faces.length;
  23951. } else {
  23952. console.warn( 'THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.' );
  23953. }
  23954. //
  23955. var geometry = new THREE.BufferGeometry();
  23956. var positions = new THREE.Float32Attribute( nNormals * 2 * 3, 3 );
  23957. geometry.addAttribute( 'position', positions );
  23958. THREE.LineSegments.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ) );
  23959. //
  23960. this.matrixAutoUpdate = false;
  23961. this.update();
  23962. };
  23963. THREE.FaceNormalsHelper.prototype = Object.create( THREE.LineSegments.prototype );
  23964. THREE.FaceNormalsHelper.prototype.constructor = THREE.FaceNormalsHelper;
  23965. THREE.FaceNormalsHelper.prototype.update = ( function () {
  23966. var v1 = new THREE.Vector3();
  23967. var v2 = new THREE.Vector3();
  23968. var normalMatrix = new THREE.Matrix3();
  23969. return function update() {
  23970. this.object.updateMatrixWorld( true );
  23971. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  23972. var matrixWorld = this.object.matrixWorld;
  23973. var position = this.geometry.attributes.position;
  23974. //
  23975. var objGeometry = this.object.geometry;
  23976. var vertices = objGeometry.vertices;
  23977. var faces = objGeometry.faces;
  23978. var idx = 0;
  23979. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  23980. var face = faces[ i ];
  23981. var normal = face.normal;
  23982. v1.copy( vertices[ face.a ] )
  23983. .add( vertices[ face.b ] )
  23984. .add( vertices[ face.c ] )
  23985. .divideScalar( 3 )
  23986. .applyMatrix4( matrixWorld );
  23987. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  23988. position.setXYZ( idx, v1.x, v1.y, v1.z );
  23989. idx = idx + 1;
  23990. position.setXYZ( idx, v2.x, v2.y, v2.z );
  23991. idx = idx + 1;
  23992. }
  23993. position.needsUpdate = true;
  23994. return this;
  23995. }
  23996. }() );
  23997. // File:src/extras/helpers/GridHelper.js
  23998. /**
  23999. * @author mrdoob / http://mrdoob.com/
  24000. */
  24001. THREE.GridHelper = function ( size, step ) {
  24002. var geometry = new THREE.Geometry();
  24003. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  24004. this.color1 = new THREE.Color( 0x444444 );
  24005. this.color2 = new THREE.Color( 0x888888 );
  24006. for ( var i = - size; i <= size; i += step ) {
  24007. geometry.vertices.push(
  24008. new THREE.Vector3( - size, 0, i ), new THREE.Vector3( size, 0, i ),
  24009. new THREE.Vector3( i, 0, - size ), new THREE.Vector3( i, 0, size )
  24010. );
  24011. var color = i === 0 ? this.color1 : this.color2;
  24012. geometry.colors.push( color, color, color, color );
  24013. }
  24014. THREE.LineSegments.call( this, geometry, material );
  24015. };
  24016. THREE.GridHelper.prototype = Object.create( THREE.LineSegments.prototype );
  24017. THREE.GridHelper.prototype.constructor = THREE.GridHelper;
  24018. THREE.GridHelper.prototype.setColors = function( colorCenterLine, colorGrid ) {
  24019. this.color1.set( colorCenterLine );
  24020. this.color2.set( colorGrid );
  24021. this.geometry.colorsNeedUpdate = true;
  24022. };
  24023. // File:src/extras/helpers/HemisphereLightHelper.js
  24024. /**
  24025. * @author alteredq / http://alteredqualia.com/
  24026. * @author mrdoob / http://mrdoob.com/
  24027. */
  24028. THREE.HemisphereLightHelper = function ( light, sphereSize ) {
  24029. THREE.Object3D.call( this );
  24030. this.light = light;
  24031. this.light.updateMatrixWorld();
  24032. this.matrix = light.matrixWorld;
  24033. this.matrixAutoUpdate = false;
  24034. this.colors = [ new THREE.Color(), new THREE.Color() ];
  24035. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  24036. geometry.rotateX( - Math.PI / 2 );
  24037. for ( var i = 0, il = 8; i < il; i ++ ) {
  24038. geometry.faces[ i ].color = this.colors[ i < 4 ? 0 : 1 ];
  24039. }
  24040. var material = new THREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors, wireframe: true } );
  24041. this.lightSphere = new THREE.Mesh( geometry, material );
  24042. this.add( this.lightSphere );
  24043. this.update();
  24044. };
  24045. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  24046. THREE.HemisphereLightHelper.prototype.constructor = THREE.HemisphereLightHelper;
  24047. THREE.HemisphereLightHelper.prototype.dispose = function () {
  24048. this.lightSphere.geometry.dispose();
  24049. this.lightSphere.material.dispose();
  24050. };
  24051. THREE.HemisphereLightHelper.prototype.update = function () {
  24052. var vector = new THREE.Vector3();
  24053. return function () {
  24054. this.colors[ 0 ].copy( this.light.color ).multiplyScalar( this.light.intensity );
  24055. this.colors[ 1 ].copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  24056. this.lightSphere.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  24057. this.lightSphere.geometry.colorsNeedUpdate = true;
  24058. }
  24059. }();
  24060. // File:src/extras/helpers/PointLightHelper.js
  24061. /**
  24062. * @author alteredq / http://alteredqualia.com/
  24063. * @author mrdoob / http://mrdoob.com/
  24064. */
  24065. THREE.PointLightHelper = function ( light, sphereSize ) {
  24066. this.light = light;
  24067. this.light.updateMatrixWorld();
  24068. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  24069. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  24070. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  24071. THREE.Mesh.call( this, geometry, material );
  24072. this.matrix = this.light.matrixWorld;
  24073. this.matrixAutoUpdate = false;
  24074. /*
  24075. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  24076. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  24077. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  24078. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  24079. var d = light.distance;
  24080. if ( d === 0.0 ) {
  24081. this.lightDistance.visible = false;
  24082. } else {
  24083. this.lightDistance.scale.set( d, d, d );
  24084. }
  24085. this.add( this.lightDistance );
  24086. */
  24087. };
  24088. THREE.PointLightHelper.prototype = Object.create( THREE.Mesh.prototype );
  24089. THREE.PointLightHelper.prototype.constructor = THREE.PointLightHelper;
  24090. THREE.PointLightHelper.prototype.dispose = function () {
  24091. this.geometry.dispose();
  24092. this.material.dispose();
  24093. };
  24094. THREE.PointLightHelper.prototype.update = function () {
  24095. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  24096. /*
  24097. var d = this.light.distance;
  24098. if ( d === 0.0 ) {
  24099. this.lightDistance.visible = false;
  24100. } else {
  24101. this.lightDistance.visible = true;
  24102. this.lightDistance.scale.set( d, d, d );
  24103. }
  24104. */
  24105. };
  24106. // File:src/extras/helpers/SkeletonHelper.js
  24107. /**
  24108. * @author Sean Griffin / http://twitter.com/sgrif
  24109. * @author Michael Guerrero / http://realitymeltdown.com
  24110. * @author mrdoob / http://mrdoob.com/
  24111. * @author ikerr / http://verold.com
  24112. */
  24113. THREE.SkeletonHelper = function ( object ) {
  24114. this.bones = this.getBoneList( object );
  24115. var geometry = new THREE.Geometry();
  24116. for ( var i = 0; i < this.bones.length; i ++ ) {
  24117. var bone = this.bones[ i ];
  24118. if ( bone.parent instanceof THREE.Bone ) {
  24119. geometry.vertices.push( new THREE.Vector3() );
  24120. geometry.vertices.push( new THREE.Vector3() );
  24121. geometry.colors.push( new THREE.Color( 0, 0, 1 ) );
  24122. geometry.colors.push( new THREE.Color( 0, 1, 0 ) );
  24123. }
  24124. }
  24125. geometry.dynamic = true;
  24126. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors, depthTest: false, depthWrite: false, transparent: true } );
  24127. THREE.LineSegments.call( this, geometry, material );
  24128. this.root = object;
  24129. this.matrix = object.matrixWorld;
  24130. this.matrixAutoUpdate = false;
  24131. this.update();
  24132. };
  24133. THREE.SkeletonHelper.prototype = Object.create( THREE.LineSegments.prototype );
  24134. THREE.SkeletonHelper.prototype.constructor = THREE.SkeletonHelper;
  24135. THREE.SkeletonHelper.prototype.getBoneList = function( object ) {
  24136. var boneList = [];
  24137. if ( object instanceof THREE.Bone ) {
  24138. boneList.push( object );
  24139. }
  24140. for ( var i = 0; i < object.children.length; i ++ ) {
  24141. boneList.push.apply( boneList, this.getBoneList( object.children[ i ] ) );
  24142. }
  24143. return boneList;
  24144. };
  24145. THREE.SkeletonHelper.prototype.update = function () {
  24146. var geometry = this.geometry;
  24147. var matrixWorldInv = new THREE.Matrix4().getInverse( this.root.matrixWorld );
  24148. var boneMatrix = new THREE.Matrix4();
  24149. var j = 0;
  24150. for ( var i = 0; i < this.bones.length; i ++ ) {
  24151. var bone = this.bones[ i ];
  24152. if ( bone.parent instanceof THREE.Bone ) {
  24153. boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld );
  24154. geometry.vertices[ j ].setFromMatrixPosition( boneMatrix );
  24155. boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld );
  24156. geometry.vertices[ j + 1 ].setFromMatrixPosition( boneMatrix );
  24157. j += 2;
  24158. }
  24159. }
  24160. geometry.verticesNeedUpdate = true;
  24161. geometry.computeBoundingSphere();
  24162. };
  24163. // File:src/extras/helpers/SpotLightHelper.js
  24164. /**
  24165. * @author alteredq / http://alteredqualia.com/
  24166. * @author mrdoob / http://mrdoob.com/
  24167. * @author WestLangley / http://github.com/WestLangley
  24168. */
  24169. THREE.SpotLightHelper = function ( light ) {
  24170. THREE.Object3D.call( this );
  24171. this.light = light;
  24172. this.light.updateMatrixWorld();
  24173. this.matrix = light.matrixWorld;
  24174. this.matrixAutoUpdate = false;
  24175. var geometry = new THREE.CylinderGeometry( 0, 1, 1, 8, 1, true );
  24176. geometry.translate( 0, - 0.5, 0 );
  24177. geometry.rotateX( - Math.PI / 2 );
  24178. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  24179. this.cone = new THREE.Mesh( geometry, material );
  24180. this.add( this.cone );
  24181. this.update();
  24182. };
  24183. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  24184. THREE.SpotLightHelper.prototype.constructor = THREE.SpotLightHelper;
  24185. THREE.SpotLightHelper.prototype.dispose = function () {
  24186. this.cone.geometry.dispose();
  24187. this.cone.material.dispose();
  24188. };
  24189. THREE.SpotLightHelper.prototype.update = function () {
  24190. var vector = new THREE.Vector3();
  24191. var vector2 = new THREE.Vector3();
  24192. return function () {
  24193. var coneLength = this.light.distance ? this.light.distance : 10000;
  24194. var coneWidth = coneLength * Math.tan( this.light.angle );
  24195. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  24196. vector.setFromMatrixPosition( this.light.matrixWorld );
  24197. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  24198. this.cone.lookAt( vector2.sub( vector ) );
  24199. this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  24200. };
  24201. }();
  24202. // File:src/extras/helpers/VertexNormalsHelper.js
  24203. /**
  24204. * @author mrdoob / http://mrdoob.com/
  24205. * @author WestLangley / http://github.com/WestLangley
  24206. */
  24207. THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) {
  24208. this.object = object;
  24209. this.size = ( size !== undefined ) ? size : 1;
  24210. var color = ( hex !== undefined ) ? hex : 0xff0000;
  24211. var width = ( linewidth !== undefined ) ? linewidth : 1;
  24212. //
  24213. var nNormals = 0;
  24214. var objGeometry = this.object.geometry;
  24215. if ( objGeometry instanceof THREE.Geometry ) {
  24216. nNormals = objGeometry.faces.length * 3;
  24217. } else if ( objGeometry instanceof THREE.BufferGeometry ) {
  24218. nNormals = objGeometry.attributes.normal.count
  24219. }
  24220. //
  24221. var geometry = new THREE.BufferGeometry();
  24222. var positions = new THREE.Float32Attribute( nNormals * 2 * 3, 3 );
  24223. geometry.addAttribute( 'position', positions );
  24224. THREE.LineSegments.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ) );
  24225. //
  24226. this.matrixAutoUpdate = false;
  24227. this.update();
  24228. };
  24229. THREE.VertexNormalsHelper.prototype = Object.create( THREE.LineSegments.prototype );
  24230. THREE.VertexNormalsHelper.prototype.constructor = THREE.VertexNormalsHelper;
  24231. THREE.VertexNormalsHelper.prototype.update = ( function () {
  24232. var v1 = new THREE.Vector3();
  24233. var v2 = new THREE.Vector3();
  24234. var normalMatrix = new THREE.Matrix3();
  24235. return function update() {
  24236. var keys = [ 'a', 'b', 'c' ];
  24237. this.object.updateMatrixWorld( true );
  24238. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  24239. var matrixWorld = this.object.matrixWorld;
  24240. var position = this.geometry.attributes.position;
  24241. //
  24242. var objGeometry = this.object.geometry;
  24243. if ( objGeometry instanceof THREE.Geometry ) {
  24244. var vertices = objGeometry.vertices;
  24245. var faces = objGeometry.faces;
  24246. var idx = 0;
  24247. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  24248. var face = faces[ i ];
  24249. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  24250. var vertex = vertices[ face[ keys[ j ] ] ];
  24251. var normal = face.vertexNormals[ j ];
  24252. v1.copy( vertex ).applyMatrix4( matrixWorld );
  24253. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  24254. position.setXYZ( idx, v1.x, v1.y, v1.z );
  24255. idx = idx + 1;
  24256. position.setXYZ( idx, v2.x, v2.y, v2.z );
  24257. idx = idx + 1;
  24258. }
  24259. }
  24260. } else if ( objGeometry instanceof THREE.BufferGeometry ) {
  24261. var objPos = objGeometry.attributes.position;
  24262. var objNorm = objGeometry.attributes.normal;
  24263. var idx = 0;
  24264. // for simplicity, ignore index and drawcalls, and render every normal
  24265. for ( var j = 0, jl = objPos.count; j < jl; j ++ ) {
  24266. v1.set( objPos.getX( j ), objPos.getY( j ), objPos.getZ( j ) ).applyMatrix4( matrixWorld );
  24267. v2.set( objNorm.getX( j ), objNorm.getY( j ), objNorm.getZ( j ) );
  24268. v2.applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  24269. position.setXYZ( idx, v1.x, v1.y, v1.z );
  24270. idx = idx + 1;
  24271. position.setXYZ( idx, v2.x, v2.y, v2.z );
  24272. idx = idx + 1;
  24273. }
  24274. }
  24275. position.needsUpdate = true;
  24276. return this;
  24277. }
  24278. }() );
  24279. // File:src/extras/helpers/WireframeHelper.js
  24280. /**
  24281. * @author mrdoob / http://mrdoob.com/
  24282. */
  24283. THREE.WireframeHelper = function ( object, hex ) {
  24284. var color = ( hex !== undefined ) ? hex : 0xffffff;
  24285. THREE.LineSegments.call( this, new THREE.WireframeGeometry( object.geometry ), new THREE.LineBasicMaterial( { color: color } ) );
  24286. this.matrix = object.matrixWorld;
  24287. this.matrixAutoUpdate = false;
  24288. };
  24289. THREE.WireframeHelper.prototype = Object.create( THREE.LineSegments.prototype );
  24290. THREE.WireframeHelper.prototype.constructor = THREE.WireframeHelper;
  24291. // File:src/extras/objects/ImmediateRenderObject.js
  24292. /**
  24293. * @author alteredq / http://alteredqualia.com/
  24294. */
  24295. THREE.ImmediateRenderObject = function ( material ) {
  24296. THREE.Object3D.call( this );
  24297. this.material = material;
  24298. this.render = function ( renderCallback ) {};
  24299. };
  24300. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  24301. THREE.ImmediateRenderObject.prototype.constructor = THREE.ImmediateRenderObject;
  24302. // File:src/extras/objects/MorphBlendMesh.js
  24303. /**
  24304. * @author alteredq / http://alteredqualia.com/
  24305. */
  24306. THREE.MorphBlendMesh = function( geometry, material ) {
  24307. THREE.Mesh.call( this, geometry, material );
  24308. this.animationsMap = {};
  24309. this.animationsList = [];
  24310. // prepare default animation
  24311. // (all frames played together in 1 second)
  24312. var numFrames = this.geometry.morphTargets.length;
  24313. var name = "__default";
  24314. var startFrame = 0;
  24315. var endFrame = numFrames - 1;
  24316. var fps = numFrames / 1;
  24317. this.createAnimation( name, startFrame, endFrame, fps );
  24318. this.setAnimationWeight( name, 1 );
  24319. };
  24320. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  24321. THREE.MorphBlendMesh.prototype.constructor = THREE.MorphBlendMesh;
  24322. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  24323. var animation = {
  24324. start: start,
  24325. end: end,
  24326. length: end - start + 1,
  24327. fps: fps,
  24328. duration: ( end - start ) / fps,
  24329. lastFrame: 0,
  24330. currentFrame: 0,
  24331. active: false,
  24332. time: 0,
  24333. direction: 1,
  24334. weight: 1,
  24335. directionBackwards: false,
  24336. mirroredLoop: false
  24337. };
  24338. this.animationsMap[ name ] = animation;
  24339. this.animationsList.push( animation );
  24340. };
  24341. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  24342. var pattern = /([a-z]+)_?(\d+)/i;
  24343. var firstAnimation, frameRanges = {};
  24344. var geometry = this.geometry;
  24345. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  24346. var morph = geometry.morphTargets[ i ];
  24347. var chunks = morph.name.match( pattern );
  24348. if ( chunks && chunks.length > 1 ) {
  24349. var name = chunks[ 1 ];
  24350. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: - Infinity };
  24351. var range = frameRanges[ name ];
  24352. if ( i < range.start ) range.start = i;
  24353. if ( i > range.end ) range.end = i;
  24354. if ( ! firstAnimation ) firstAnimation = name;
  24355. }
  24356. }
  24357. for ( var name in frameRanges ) {
  24358. var range = frameRanges[ name ];
  24359. this.createAnimation( name, range.start, range.end, fps );
  24360. }
  24361. this.firstAnimation = firstAnimation;
  24362. };
  24363. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  24364. var animation = this.animationsMap[ name ];
  24365. if ( animation ) {
  24366. animation.direction = 1;
  24367. animation.directionBackwards = false;
  24368. }
  24369. };
  24370. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  24371. var animation = this.animationsMap[ name ];
  24372. if ( animation ) {
  24373. animation.direction = - 1;
  24374. animation.directionBackwards = true;
  24375. }
  24376. };
  24377. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  24378. var animation = this.animationsMap[ name ];
  24379. if ( animation ) {
  24380. animation.fps = fps;
  24381. animation.duration = ( animation.end - animation.start ) / animation.fps;
  24382. }
  24383. };
  24384. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  24385. var animation = this.animationsMap[ name ];
  24386. if ( animation ) {
  24387. animation.duration = duration;
  24388. animation.fps = ( animation.end - animation.start ) / animation.duration;
  24389. }
  24390. };
  24391. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  24392. var animation = this.animationsMap[ name ];
  24393. if ( animation ) {
  24394. animation.weight = weight;
  24395. }
  24396. };
  24397. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  24398. var animation = this.animationsMap[ name ];
  24399. if ( animation ) {
  24400. animation.time = time;
  24401. }
  24402. };
  24403. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  24404. var time = 0;
  24405. var animation = this.animationsMap[ name ];
  24406. if ( animation ) {
  24407. time = animation.time;
  24408. }
  24409. return time;
  24410. };
  24411. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  24412. var duration = - 1;
  24413. var animation = this.animationsMap[ name ];
  24414. if ( animation ) {
  24415. duration = animation.duration;
  24416. }
  24417. return duration;
  24418. };
  24419. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  24420. var animation = this.animationsMap[ name ];
  24421. if ( animation ) {
  24422. animation.time = 0;
  24423. animation.active = true;
  24424. } else {
  24425. console.warn( "THREE.MorphBlendMesh: animation[" + name + "] undefined in .playAnimation()" );
  24426. }
  24427. };
  24428. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  24429. var animation = this.animationsMap[ name ];
  24430. if ( animation ) {
  24431. animation.active = false;
  24432. }
  24433. };
  24434. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  24435. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  24436. var animation = this.animationsList[ i ];
  24437. if ( ! animation.active ) continue;
  24438. var frameTime = animation.duration / animation.length;
  24439. animation.time += animation.direction * delta;
  24440. if ( animation.mirroredLoop ) {
  24441. if ( animation.time > animation.duration || animation.time < 0 ) {
  24442. animation.direction *= - 1;
  24443. if ( animation.time > animation.duration ) {
  24444. animation.time = animation.duration;
  24445. animation.directionBackwards = true;
  24446. }
  24447. if ( animation.time < 0 ) {
  24448. animation.time = 0;
  24449. animation.directionBackwards = false;
  24450. }
  24451. }
  24452. } else {
  24453. animation.time = animation.time % animation.duration;
  24454. if ( animation.time < 0 ) animation.time += animation.duration;
  24455. }
  24456. var keyframe = animation.start + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  24457. var weight = animation.weight;
  24458. if ( keyframe !== animation.currentFrame ) {
  24459. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  24460. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  24461. this.morphTargetInfluences[ keyframe ] = 0;
  24462. animation.lastFrame = animation.currentFrame;
  24463. animation.currentFrame = keyframe;
  24464. }
  24465. var mix = ( animation.time % frameTime ) / frameTime;
  24466. if ( animation.directionBackwards ) mix = 1 - mix;
  24467. if ( animation.currentFrame !== animation.lastFrame ) {
  24468. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  24469. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  24470. } else {
  24471. this.morphTargetInfluences[ animation.currentFrame ] = weight;
  24472. }
  24473. }
  24474. };