three.js 876 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079
  1. // File:src/Three.js
  2. /**
  3. * @author mrdoob / http://mrdoob.com/
  4. */
  5. var THREE = { REVISION: '74dev' };
  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. // polyfills
  13. if ( self.requestAnimationFrame === undefined || self.cancelAnimationFrame === undefined ) {
  14. // Missing in Android stock browser.
  15. ( function () {
  16. var lastTime = 0;
  17. var vendors = [ 'ms', 'moz', 'webkit', 'o' ];
  18. for ( var x = 0; x < vendors.length && ! self.requestAnimationFrame; ++ x ) {
  19. self.requestAnimationFrame = self[ vendors[ x ] + 'RequestAnimationFrame' ];
  20. self.cancelAnimationFrame = self[ vendors[ x ] + 'CancelAnimationFrame' ] || self[ vendors[ x ] + 'CancelRequestAnimationFrame' ];
  21. }
  22. if ( self.requestAnimationFrame === undefined && self.setTimeout !== undefined ) {
  23. self.requestAnimationFrame = function ( callback ) {
  24. var currTime = Date.now(), timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
  25. var id = self.setTimeout( function () {
  26. callback( currTime + timeToCall );
  27. }, timeToCall );
  28. lastTime = currTime + timeToCall;
  29. return id;
  30. };
  31. }
  32. if ( self.cancelAnimationFrame === undefined && self.clearTimeout !== undefined ) {
  33. self.cancelAnimationFrame = function ( id ) {
  34. self.clearTimeout( id );
  35. };
  36. }
  37. } )();
  38. }
  39. //
  40. if ( self.performance === undefined ) {
  41. self.performance = {};
  42. }
  43. if ( self.performance.now === undefined ) {
  44. ( function () {
  45. var start = Date.now();
  46. self.performance.now = function () {
  47. return Date.now() - start;
  48. }
  49. } )();
  50. }
  51. //
  52. if ( Number.EPSILON === undefined ) {
  53. Number.EPSILON = Math.pow( 2, - 52 );
  54. }
  55. //
  56. if ( Math.sign === undefined ) {
  57. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
  58. Math.sign = function ( x ) {
  59. return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : + x;
  60. };
  61. }
  62. if ( Function.prototype.name === undefined && Object.defineProperty !== undefined ) {
  63. // Missing in IE9-11.
  64. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
  65. Object.defineProperty( Function.prototype, 'name', {
  66. get: function () {
  67. return this.toString().match( /^\s*function\s*(\S*)\s*\(/ )[ 1 ];
  68. }
  69. } );
  70. }
  71. if ( Object.assign === undefined ) {
  72. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
  73. Object.defineProperty( Object, 'assign', {
  74. writable: true,
  75. configurable: true,
  76. value: function ( target ) {
  77. 'use strict';
  78. if ( target === undefined || target === null ) {
  79. throw new TypeError( "Cannot convert first argument to object" );
  80. }
  81. var to = Object( target );
  82. for ( var i = 1, n = arguments.length; i !== n; ++ i ) {
  83. var nextSource = arguments[ i ];
  84. if ( nextSource === undefined || nextSource === null ) continue;
  85. nextSource = Object( nextSource );
  86. var keysArray = Object.keys( nextSource );
  87. for ( var nextIndex = 0, len = keysArray.length; nextIndex !== len; ++ nextIndex ) {
  88. var nextKey = keysArray[ nextIndex ];
  89. var desc = Object.getOwnPropertyDescriptor( nextSource, nextKey );
  90. if ( desc !== undefined && desc.enumerable ) {
  91. to[ nextKey ] = nextSource[ nextKey ];
  92. }
  93. }
  94. }
  95. return to;
  96. }
  97. } );
  98. }
  99. // https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent.button
  100. THREE.MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2 };
  101. // GL STATE CONSTANTS
  102. THREE.CullFaceNone = 0;
  103. THREE.CullFaceBack = 1;
  104. THREE.CullFaceFront = 2;
  105. THREE.CullFaceFrontBack = 3;
  106. THREE.FrontFaceDirectionCW = 0;
  107. THREE.FrontFaceDirectionCCW = 1;
  108. // SHADOWING TYPES
  109. THREE.BasicShadowMap = 0;
  110. THREE.PCFShadowMap = 1;
  111. THREE.PCFSoftShadowMap = 2;
  112. // MATERIAL CONSTANTS
  113. // side
  114. THREE.FrontSide = 0;
  115. THREE.BackSide = 1;
  116. THREE.DoubleSide = 2;
  117. // shading
  118. THREE.FlatShading = 1;
  119. THREE.SmoothShading = 2;
  120. // colors
  121. THREE.NoColors = 0;
  122. THREE.FaceColors = 1;
  123. THREE.VertexColors = 2;
  124. // blending modes
  125. THREE.NoBlending = 0;
  126. THREE.NormalBlending = 1;
  127. THREE.AdditiveBlending = 2;
  128. THREE.SubtractiveBlending = 3;
  129. THREE.MultiplyBlending = 4;
  130. THREE.CustomBlending = 5;
  131. // custom blending equations
  132. // (numbers start from 100 not to clash with other
  133. // mappings to OpenGL constants defined in Texture.js)
  134. THREE.AddEquation = 100;
  135. THREE.SubtractEquation = 101;
  136. THREE.ReverseSubtractEquation = 102;
  137. THREE.MinEquation = 103;
  138. THREE.MaxEquation = 104;
  139. // custom blending destination factors
  140. THREE.ZeroFactor = 200;
  141. THREE.OneFactor = 201;
  142. THREE.SrcColorFactor = 202;
  143. THREE.OneMinusSrcColorFactor = 203;
  144. THREE.SrcAlphaFactor = 204;
  145. THREE.OneMinusSrcAlphaFactor = 205;
  146. THREE.DstAlphaFactor = 206;
  147. THREE.OneMinusDstAlphaFactor = 207;
  148. // custom blending source factors
  149. //THREE.ZeroFactor = 200;
  150. //THREE.OneFactor = 201;
  151. //THREE.SrcAlphaFactor = 204;
  152. //THREE.OneMinusSrcAlphaFactor = 205;
  153. //THREE.DstAlphaFactor = 206;
  154. //THREE.OneMinusDstAlphaFactor = 207;
  155. THREE.DstColorFactor = 208;
  156. THREE.OneMinusDstColorFactor = 209;
  157. THREE.SrcAlphaSaturateFactor = 210;
  158. // depth modes
  159. THREE.NeverDepth = 0;
  160. THREE.AlwaysDepth = 1;
  161. THREE.LessDepth = 2;
  162. THREE.LessEqualDepth = 3;
  163. THREE.EqualDepth = 4;
  164. THREE.GreaterEqualDepth = 5;
  165. THREE.GreaterDepth = 6;
  166. THREE.NotEqualDepth = 7;
  167. // TEXTURE CONSTANTS
  168. THREE.MultiplyOperation = 0;
  169. THREE.MixOperation = 1;
  170. THREE.AddOperation = 2;
  171. // Mapping modes
  172. THREE.UVMapping = 300;
  173. THREE.CubeReflectionMapping = 301;
  174. THREE.CubeRefractionMapping = 302;
  175. THREE.EquirectangularReflectionMapping = 303;
  176. THREE.EquirectangularRefractionMapping = 304;
  177. THREE.SphericalReflectionMapping = 305;
  178. // Wrapping modes
  179. THREE.RepeatWrapping = 1000;
  180. THREE.ClampToEdgeWrapping = 1001;
  181. THREE.MirroredRepeatWrapping = 1002;
  182. // Filters
  183. THREE.NearestFilter = 1003;
  184. THREE.NearestMipMapNearestFilter = 1004;
  185. THREE.NearestMipMapLinearFilter = 1005;
  186. THREE.LinearFilter = 1006;
  187. THREE.LinearMipMapNearestFilter = 1007;
  188. THREE.LinearMipMapLinearFilter = 1008;
  189. // Data types
  190. THREE.UnsignedByteType = 1009;
  191. THREE.ByteType = 1010;
  192. THREE.ShortType = 1011;
  193. THREE.UnsignedShortType = 1012;
  194. THREE.IntType = 1013;
  195. THREE.UnsignedIntType = 1014;
  196. THREE.FloatType = 1015;
  197. THREE.HalfFloatType = 1025;
  198. // Pixel types
  199. //THREE.UnsignedByteType = 1009;
  200. THREE.UnsignedShort4444Type = 1016;
  201. THREE.UnsignedShort5551Type = 1017;
  202. THREE.UnsignedShort565Type = 1018;
  203. // Pixel formats
  204. THREE.AlphaFormat = 1019;
  205. THREE.RGBFormat = 1020;
  206. THREE.RGBAFormat = 1021;
  207. THREE.LuminanceFormat = 1022;
  208. THREE.LuminanceAlphaFormat = 1023;
  209. // THREE.RGBEFormat handled as THREE.RGBAFormat in shaders
  210. THREE.RGBEFormat = THREE.RGBAFormat; //1024;
  211. // DDS / ST3C Compressed texture formats
  212. THREE.RGB_S3TC_DXT1_Format = 2001;
  213. THREE.RGBA_S3TC_DXT1_Format = 2002;
  214. THREE.RGBA_S3TC_DXT3_Format = 2003;
  215. THREE.RGBA_S3TC_DXT5_Format = 2004;
  216. // PVRTC compressed texture formats
  217. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  218. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  219. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  220. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  221. // Loop styles for AnimationAction
  222. THREE.LoopOnce = 2200;
  223. THREE.LoopRepeat = 2201;
  224. THREE.LoopPingPong = 2202;
  225. // Interpolation
  226. THREE.InterpolateDiscrete = 2300;
  227. THREE.InterpolateLinear = 2301;
  228. THREE.InterpolateSmooth = 2302;
  229. // Interpolant ending modes
  230. THREE.ZeroCurvatureEnding = 2400;
  231. THREE.ZeroSlopeEnding = 2401;
  232. THREE.WrapAroundEnding = 2402;
  233. // Triangle Draw modes
  234. THREE.TrianglesDrawMode = 0;
  235. THREE.TriangleStripDrawMode = 1;
  236. THREE.TriangleFanDrawMode = 2;
  237. // File:src/math/Color.js
  238. /**
  239. * @author mrdoob / http://mrdoob.com/
  240. */
  241. THREE.Color = function ( color ) {
  242. if ( arguments.length === 3 ) {
  243. return this.fromArray( arguments );
  244. }
  245. return this.set( color );
  246. };
  247. THREE.Color.prototype = {
  248. constructor: THREE.Color,
  249. r: 1, g: 1, b: 1,
  250. set: function ( value ) {
  251. if ( value instanceof THREE.Color ) {
  252. this.copy( value );
  253. } else if ( typeof value === 'number' ) {
  254. this.setHex( value );
  255. } else if ( typeof value === 'string' ) {
  256. this.setStyle( value );
  257. }
  258. return this;
  259. },
  260. setScalar: function ( scalar ) {
  261. this.r = scalar;
  262. this.g = scalar;
  263. this.b = scalar;
  264. },
  265. setHex: function ( hex ) {
  266. hex = Math.floor( hex );
  267. this.r = ( hex >> 16 & 255 ) / 255;
  268. this.g = ( hex >> 8 & 255 ) / 255;
  269. this.b = ( hex & 255 ) / 255;
  270. return this;
  271. },
  272. setRGB: function ( r, g, b ) {
  273. this.r = r;
  274. this.g = g;
  275. this.b = b;
  276. return this;
  277. },
  278. setHSL: function () {
  279. function hue2rgb( p, q, t ) {
  280. if ( t < 0 ) t += 1;
  281. if ( t > 1 ) t -= 1;
  282. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  283. if ( t < 1 / 2 ) return q;
  284. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  285. return p;
  286. }
  287. return function ( h, s, l ) {
  288. // h,s,l ranges are in 0.0 - 1.0
  289. h = THREE.Math.euclideanModulo( h, 1 );
  290. s = THREE.Math.clamp( s, 0, 1 );
  291. l = THREE.Math.clamp( l, 0, 1 );
  292. if ( s === 0 ) {
  293. this.r = this.g = this.b = l;
  294. } else {
  295. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  296. var q = ( 2 * l ) - p;
  297. this.r = hue2rgb( q, p, h + 1 / 3 );
  298. this.g = hue2rgb( q, p, h );
  299. this.b = hue2rgb( q, p, h - 1 / 3 );
  300. }
  301. return this;
  302. };
  303. }(),
  304. setStyle: function ( style ) {
  305. function handleAlpha( string ) {
  306. if ( string === undefined ) return;
  307. if ( parseFloat( string ) < 1 ) {
  308. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  309. }
  310. }
  311. var m;
  312. if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) {
  313. // rgb / hsl
  314. var color;
  315. var name = m[ 1 ];
  316. var components = m[ 2 ];
  317. switch ( name ) {
  318. case 'rgb':
  319. case 'rgba':
  320. if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  321. // rgb(255,0,0) rgba(255,0,0,0.5)
  322. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  323. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  324. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  325. handleAlpha( color[ 5 ] );
  326. return this;
  327. }
  328. if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  329. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  330. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  331. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  332. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  333. handleAlpha( color[ 5 ] );
  334. return this;
  335. }
  336. break;
  337. case 'hsl':
  338. case 'hsla':
  339. if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  340. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  341. var h = parseFloat( color[ 1 ] ) / 360;
  342. var s = parseInt( color[ 2 ], 10 ) / 100;
  343. var l = parseInt( color[ 3 ], 10 ) / 100;
  344. handleAlpha( color[ 5 ] );
  345. return this.setHSL( h, s, l );
  346. }
  347. break;
  348. }
  349. } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) {
  350. // hex color
  351. var hex = m[ 1 ];
  352. var size = hex.length;
  353. if ( size === 3 ) {
  354. // #ff0
  355. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  356. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  357. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  358. return this;
  359. } else if ( size === 6 ) {
  360. // #ff0000
  361. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  362. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  363. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  364. return this;
  365. }
  366. }
  367. if ( style && style.length > 0 ) {
  368. // color keywords
  369. var hex = THREE.ColorKeywords[ style ];
  370. if ( hex !== undefined ) {
  371. // red
  372. this.setHex( hex );
  373. } else {
  374. // unknown color
  375. console.warn( 'THREE.Color: Unknown color ' + style );
  376. }
  377. }
  378. return this;
  379. },
  380. clone: function () {
  381. return new this.constructor( this.r, this.g, this.b );
  382. },
  383. copy: function ( color ) {
  384. this.r = color.r;
  385. this.g = color.g;
  386. this.b = color.b;
  387. return this;
  388. },
  389. copyGammaToLinear: function ( color, gammaFactor ) {
  390. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  391. this.r = Math.pow( color.r, gammaFactor );
  392. this.g = Math.pow( color.g, gammaFactor );
  393. this.b = Math.pow( color.b, gammaFactor );
  394. return this;
  395. },
  396. copyLinearToGamma: function ( color, gammaFactor ) {
  397. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  398. var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  399. this.r = Math.pow( color.r, safeInverse );
  400. this.g = Math.pow( color.g, safeInverse );
  401. this.b = Math.pow( color.b, safeInverse );
  402. return this;
  403. },
  404. convertGammaToLinear: function () {
  405. var r = this.r, g = this.g, b = this.b;
  406. this.r = r * r;
  407. this.g = g * g;
  408. this.b = b * b;
  409. return this;
  410. },
  411. convertLinearToGamma: function () {
  412. this.r = Math.sqrt( this.r );
  413. this.g = Math.sqrt( this.g );
  414. this.b = Math.sqrt( this.b );
  415. return this;
  416. },
  417. getHex: function () {
  418. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  419. },
  420. getHexString: function () {
  421. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  422. },
  423. getHSL: function ( optionalTarget ) {
  424. // h,s,l ranges are in 0.0 - 1.0
  425. var hsl = optionalTarget || { h: 0, s: 0, l: 0 };
  426. var r = this.r, g = this.g, b = this.b;
  427. var max = Math.max( r, g, b );
  428. var min = Math.min( r, g, b );
  429. var hue, saturation;
  430. var lightness = ( min + max ) / 2.0;
  431. if ( min === max ) {
  432. hue = 0;
  433. saturation = 0;
  434. } else {
  435. var delta = max - min;
  436. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  437. switch ( max ) {
  438. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  439. case g: hue = ( b - r ) / delta + 2; break;
  440. case b: hue = ( r - g ) / delta + 4; break;
  441. }
  442. hue /= 6;
  443. }
  444. hsl.h = hue;
  445. hsl.s = saturation;
  446. hsl.l = lightness;
  447. return hsl;
  448. },
  449. getStyle: function () {
  450. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  451. },
  452. offsetHSL: function ( h, s, l ) {
  453. var hsl = this.getHSL();
  454. hsl.h += h; hsl.s += s; hsl.l += l;
  455. this.setHSL( hsl.h, hsl.s, hsl.l );
  456. return this;
  457. },
  458. add: function ( color ) {
  459. this.r += color.r;
  460. this.g += color.g;
  461. this.b += color.b;
  462. return this;
  463. },
  464. addColors: function ( color1, color2 ) {
  465. this.r = color1.r + color2.r;
  466. this.g = color1.g + color2.g;
  467. this.b = color1.b + color2.b;
  468. return this;
  469. },
  470. addScalar: function ( s ) {
  471. this.r += s;
  472. this.g += s;
  473. this.b += s;
  474. return this;
  475. },
  476. multiply: function ( color ) {
  477. this.r *= color.r;
  478. this.g *= color.g;
  479. this.b *= color.b;
  480. return this;
  481. },
  482. multiplyScalar: function ( s ) {
  483. this.r *= s;
  484. this.g *= s;
  485. this.b *= s;
  486. return this;
  487. },
  488. lerp: function ( color, alpha ) {
  489. this.r += ( color.r - this.r ) * alpha;
  490. this.g += ( color.g - this.g ) * alpha;
  491. this.b += ( color.b - this.b ) * alpha;
  492. return this;
  493. },
  494. equals: function ( c ) {
  495. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  496. },
  497. fromArray: function ( array, offset ) {
  498. if ( offset === undefined ) offset = 0;
  499. this.r = array[ offset ];
  500. this.g = array[ offset + 1 ];
  501. this.b = array[ offset + 2 ];
  502. return this;
  503. },
  504. toArray: function ( array, offset ) {
  505. if ( array === undefined ) array = [];
  506. if ( offset === undefined ) offset = 0;
  507. array[ offset ] = this.r;
  508. array[ offset + 1 ] = this.g;
  509. array[ offset + 2 ] = this.b;
  510. return array;
  511. }
  512. };
  513. THREE.ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  514. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  515. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  516. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  517. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  518. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  519. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  520. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  521. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  522. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  523. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  524. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  525. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  526. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  527. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  528. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  529. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  530. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  531. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  532. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  533. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  534. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  535. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  536. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  537. // File:src/math/Quaternion.js
  538. /**
  539. * @author mikael emtinger / http://gomo.se/
  540. * @author alteredq / http://alteredqualia.com/
  541. * @author WestLangley / http://github.com/WestLangley
  542. * @author bhouston / http://clara.io
  543. */
  544. THREE.Quaternion = function ( x, y, z, w ) {
  545. this._x = x || 0;
  546. this._y = y || 0;
  547. this._z = z || 0;
  548. this._w = ( w !== undefined ) ? w : 1;
  549. };
  550. THREE.Quaternion.prototype = {
  551. constructor: THREE.Quaternion,
  552. get x () {
  553. return this._x;
  554. },
  555. set x ( value ) {
  556. this._x = value;
  557. this.onChangeCallback();
  558. },
  559. get y () {
  560. return this._y;
  561. },
  562. set y ( value ) {
  563. this._y = value;
  564. this.onChangeCallback();
  565. },
  566. get z () {
  567. return this._z;
  568. },
  569. set z ( value ) {
  570. this._z = value;
  571. this.onChangeCallback();
  572. },
  573. get w () {
  574. return this._w;
  575. },
  576. set w ( value ) {
  577. this._w = value;
  578. this.onChangeCallback();
  579. },
  580. set: function ( x, y, z, w ) {
  581. this._x = x;
  582. this._y = y;
  583. this._z = z;
  584. this._w = w;
  585. this.onChangeCallback();
  586. return this;
  587. },
  588. clone: function () {
  589. return new this.constructor( this._x, this._y, this._z, this._w );
  590. },
  591. copy: function ( quaternion ) {
  592. this._x = quaternion.x;
  593. this._y = quaternion.y;
  594. this._z = quaternion.z;
  595. this._w = quaternion.w;
  596. this.onChangeCallback();
  597. return this;
  598. },
  599. setFromEuler: function ( euler, update ) {
  600. if ( euler instanceof THREE.Euler === false ) {
  601. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  602. }
  603. // http://www.mathworks.com/matlabcentral/fileexchange/
  604. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  605. // content/SpinCalc.m
  606. var c1 = Math.cos( euler._x / 2 );
  607. var c2 = Math.cos( euler._y / 2 );
  608. var c3 = Math.cos( euler._z / 2 );
  609. var s1 = Math.sin( euler._x / 2 );
  610. var s2 = Math.sin( euler._y / 2 );
  611. var s3 = Math.sin( euler._z / 2 );
  612. var order = euler.order;
  613. if ( order === 'XYZ' ) {
  614. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  615. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  616. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  617. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  618. } else if ( order === 'YXZ' ) {
  619. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  620. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  621. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  622. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  623. } else if ( order === 'ZXY' ) {
  624. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  625. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  626. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  627. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  628. } else if ( order === 'ZYX' ) {
  629. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  630. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  631. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  632. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  633. } else if ( order === 'YZX' ) {
  634. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  635. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  636. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  637. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  638. } else if ( order === 'XZY' ) {
  639. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  640. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  641. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  642. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  643. }
  644. if ( update !== false ) this.onChangeCallback();
  645. return this;
  646. },
  647. setFromAxisAngle: function ( axis, angle ) {
  648. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  649. // assumes axis is normalized
  650. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  651. this._x = axis.x * s;
  652. this._y = axis.y * s;
  653. this._z = axis.z * s;
  654. this._w = Math.cos( halfAngle );
  655. this.onChangeCallback();
  656. return this;
  657. },
  658. setFromRotationMatrix: function ( m ) {
  659. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  660. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  661. var te = m.elements,
  662. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  663. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  664. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  665. trace = m11 + m22 + m33,
  666. s;
  667. if ( trace > 0 ) {
  668. s = 0.5 / Math.sqrt( trace + 1.0 );
  669. this._w = 0.25 / s;
  670. this._x = ( m32 - m23 ) * s;
  671. this._y = ( m13 - m31 ) * s;
  672. this._z = ( m21 - m12 ) * s;
  673. } else if ( m11 > m22 && m11 > m33 ) {
  674. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  675. this._w = ( m32 - m23 ) / s;
  676. this._x = 0.25 * s;
  677. this._y = ( m12 + m21 ) / s;
  678. this._z = ( m13 + m31 ) / s;
  679. } else if ( m22 > m33 ) {
  680. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  681. this._w = ( m13 - m31 ) / s;
  682. this._x = ( m12 + m21 ) / s;
  683. this._y = 0.25 * s;
  684. this._z = ( m23 + m32 ) / s;
  685. } else {
  686. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  687. this._w = ( m21 - m12 ) / s;
  688. this._x = ( m13 + m31 ) / s;
  689. this._y = ( m23 + m32 ) / s;
  690. this._z = 0.25 * s;
  691. }
  692. this.onChangeCallback();
  693. return this;
  694. },
  695. setFromUnitVectors: function () {
  696. // http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final
  697. // assumes direction vectors vFrom and vTo are normalized
  698. var v1, r;
  699. var EPS = 0.000001;
  700. return function ( vFrom, vTo ) {
  701. if ( v1 === undefined ) v1 = new THREE.Vector3();
  702. r = vFrom.dot( vTo ) + 1;
  703. if ( r < EPS ) {
  704. r = 0;
  705. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  706. v1.set( - vFrom.y, vFrom.x, 0 );
  707. } else {
  708. v1.set( 0, - vFrom.z, vFrom.y );
  709. }
  710. } else {
  711. v1.crossVectors( vFrom, vTo );
  712. }
  713. this._x = v1.x;
  714. this._y = v1.y;
  715. this._z = v1.z;
  716. this._w = r;
  717. this.normalize();
  718. return this;
  719. };
  720. }(),
  721. inverse: function () {
  722. this.conjugate().normalize();
  723. return this;
  724. },
  725. conjugate: function () {
  726. this._x *= - 1;
  727. this._y *= - 1;
  728. this._z *= - 1;
  729. this.onChangeCallback();
  730. return this;
  731. },
  732. dot: function ( v ) {
  733. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  734. },
  735. lengthSq: function () {
  736. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  737. },
  738. length: function () {
  739. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  740. },
  741. normalize: function () {
  742. var l = this.length();
  743. if ( l === 0 ) {
  744. this._x = 0;
  745. this._y = 0;
  746. this._z = 0;
  747. this._w = 1;
  748. } else {
  749. l = 1 / l;
  750. this._x = this._x * l;
  751. this._y = this._y * l;
  752. this._z = this._z * l;
  753. this._w = this._w * l;
  754. }
  755. this.onChangeCallback();
  756. return this;
  757. },
  758. multiply: function ( q, p ) {
  759. if ( p !== undefined ) {
  760. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  761. return this.multiplyQuaternions( q, p );
  762. }
  763. return this.multiplyQuaternions( this, q );
  764. },
  765. multiplyQuaternions: function ( a, b ) {
  766. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  767. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  768. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  769. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  770. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  771. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  772. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  773. this.onChangeCallback();
  774. return this;
  775. },
  776. slerp: function ( qb, t ) {
  777. if ( t === 0 ) return this;
  778. if ( t === 1 ) return this.copy( qb );
  779. var x = this._x, y = this._y, z = this._z, w = this._w;
  780. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  781. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  782. if ( cosHalfTheta < 0 ) {
  783. this._w = - qb._w;
  784. this._x = - qb._x;
  785. this._y = - qb._y;
  786. this._z = - qb._z;
  787. cosHalfTheta = - cosHalfTheta;
  788. } else {
  789. this.copy( qb );
  790. }
  791. if ( cosHalfTheta >= 1.0 ) {
  792. this._w = w;
  793. this._x = x;
  794. this._y = y;
  795. this._z = z;
  796. return this;
  797. }
  798. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  799. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  800. this._w = 0.5 * ( w + this._w );
  801. this._x = 0.5 * ( x + this._x );
  802. this._y = 0.5 * ( y + this._y );
  803. this._z = 0.5 * ( z + this._z );
  804. return this;
  805. }
  806. var halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  807. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  808. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  809. this._w = ( w * ratioA + this._w * ratioB );
  810. this._x = ( x * ratioA + this._x * ratioB );
  811. this._y = ( y * ratioA + this._y * ratioB );
  812. this._z = ( z * ratioA + this._z * ratioB );
  813. this.onChangeCallback();
  814. return this;
  815. },
  816. equals: function ( quaternion ) {
  817. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  818. },
  819. fromArray: function ( array, offset ) {
  820. if ( offset === undefined ) offset = 0;
  821. this._x = array[ offset ];
  822. this._y = array[ offset + 1 ];
  823. this._z = array[ offset + 2 ];
  824. this._w = array[ offset + 3 ];
  825. this.onChangeCallback();
  826. return this;
  827. },
  828. toArray: function ( array, offset ) {
  829. if ( array === undefined ) array = [];
  830. if ( offset === undefined ) offset = 0;
  831. array[ offset ] = this._x;
  832. array[ offset + 1 ] = this._y;
  833. array[ offset + 2 ] = this._z;
  834. array[ offset + 3 ] = this._w;
  835. return array;
  836. },
  837. onChange: function ( callback ) {
  838. this.onChangeCallback = callback;
  839. return this;
  840. },
  841. onChangeCallback: function () {}
  842. };
  843. Object.assign( THREE.Quaternion, {
  844. slerp: function( qa, qb, qm, t ) {
  845. return qm.copy( qa ).slerp( qb, t );
  846. },
  847. slerpFlat: function(
  848. dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  849. // fuzz-free, array-based Quaternion SLERP operation
  850. var x0 = src0[ srcOffset0 + 0 ],
  851. y0 = src0[ srcOffset0 + 1 ],
  852. z0 = src0[ srcOffset0 + 2 ],
  853. w0 = src0[ srcOffset0 + 3 ],
  854. x1 = src1[ srcOffset1 + 0 ],
  855. y1 = src1[ srcOffset1 + 1 ],
  856. z1 = src1[ srcOffset1 + 2 ],
  857. w1 = src1[ srcOffset1 + 3 ];
  858. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  859. var s = 1 - t,
  860. cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  861. dir = ( cos >= 0 ? 1 : - 1 ),
  862. sqrSin = 1 - cos * cos;
  863. // Skip the Slerp for tiny steps to avoid numeric problems:
  864. if ( sqrSin > Number.EPSILON ) {
  865. var sin = Math.sqrt( sqrSin ),
  866. len = Math.atan2( sin, cos * dir );
  867. s = Math.sin( s * len ) / sin;
  868. t = Math.sin( t * len ) / sin;
  869. }
  870. var tDir = t * dir;
  871. x0 = x0 * s + x1 * tDir;
  872. y0 = y0 * s + y1 * tDir;
  873. z0 = z0 * s + z1 * tDir;
  874. w0 = w0 * s + w1 * tDir;
  875. // Normalize in case we just did a lerp:
  876. if ( s === 1 - t ) {
  877. var f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  878. x0 *= f;
  879. y0 *= f;
  880. z0 *= f;
  881. w0 *= f;
  882. }
  883. }
  884. dst[ dstOffset ] = x0;
  885. dst[ dstOffset + 1 ] = y0;
  886. dst[ dstOffset + 2 ] = z0;
  887. dst[ dstOffset + 3 ] = w0;
  888. }
  889. } );
  890. // File:src/math/Vector2.js
  891. /**
  892. * @author mrdoob / http://mrdoob.com/
  893. * @author philogb / http://blog.thejit.org/
  894. * @author egraether / http://egraether.com/
  895. * @author zz85 / http://www.lab4games.net/zz85/blog
  896. */
  897. THREE.Vector2 = function ( x, y ) {
  898. this.x = x || 0;
  899. this.y = y || 0;
  900. };
  901. THREE.Vector2.prototype = {
  902. constructor: THREE.Vector2,
  903. get width() {
  904. return this.x;
  905. },
  906. set width( value ) {
  907. this.x = value;
  908. },
  909. get height() {
  910. return this.y;
  911. },
  912. set height( value ) {
  913. this.y = value;
  914. },
  915. //
  916. set: function ( x, y ) {
  917. this.x = x;
  918. this.y = y;
  919. return this;
  920. },
  921. setScalar: function ( scalar ) {
  922. this.x = scalar;
  923. this.y = scalar;
  924. return this;
  925. },
  926. setX: function ( x ) {
  927. this.x = x;
  928. return this;
  929. },
  930. setY: function ( y ) {
  931. this.y = y;
  932. return this;
  933. },
  934. setComponent: function ( index, value ) {
  935. switch ( index ) {
  936. case 0: this.x = value; break;
  937. case 1: this.y = value; break;
  938. default: throw new Error( 'index is out of range: ' + index );
  939. }
  940. },
  941. getComponent: function ( index ) {
  942. switch ( index ) {
  943. case 0: return this.x;
  944. case 1: return this.y;
  945. default: throw new Error( 'index is out of range: ' + index );
  946. }
  947. },
  948. clone: function () {
  949. return new this.constructor( this.x, this.y );
  950. },
  951. copy: function ( v ) {
  952. this.x = v.x;
  953. this.y = v.y;
  954. return this;
  955. },
  956. add: function ( v, w ) {
  957. if ( w !== undefined ) {
  958. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  959. return this.addVectors( v, w );
  960. }
  961. this.x += v.x;
  962. this.y += v.y;
  963. return this;
  964. },
  965. addScalar: function ( s ) {
  966. this.x += s;
  967. this.y += s;
  968. return this;
  969. },
  970. addVectors: function ( a, b ) {
  971. this.x = a.x + b.x;
  972. this.y = a.y + b.y;
  973. return this;
  974. },
  975. addScaledVector: function ( v, s ) {
  976. this.x += v.x * s;
  977. this.y += v.y * s;
  978. return this;
  979. },
  980. sub: function ( v, w ) {
  981. if ( w !== undefined ) {
  982. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  983. return this.subVectors( v, w );
  984. }
  985. this.x -= v.x;
  986. this.y -= v.y;
  987. return this;
  988. },
  989. subScalar: function ( s ) {
  990. this.x -= s;
  991. this.y -= s;
  992. return this;
  993. },
  994. subVectors: function ( a, b ) {
  995. this.x = a.x - b.x;
  996. this.y = a.y - b.y;
  997. return this;
  998. },
  999. multiply: function ( v ) {
  1000. this.x *= v.x;
  1001. this.y *= v.y;
  1002. return this;
  1003. },
  1004. multiplyScalar: function ( scalar ) {
  1005. if ( isFinite( scalar ) ) {
  1006. this.x *= scalar;
  1007. this.y *= scalar;
  1008. } else {
  1009. this.x = 0;
  1010. this.y = 0;
  1011. }
  1012. return this;
  1013. },
  1014. divide: function ( v ) {
  1015. this.x /= v.x;
  1016. this.y /= v.y;
  1017. return this;
  1018. },
  1019. divideScalar: function ( scalar ) {
  1020. return this.multiplyScalar( 1 / scalar );
  1021. },
  1022. min: function ( v ) {
  1023. this.x = Math.min( this.x, v.x );
  1024. this.y = Math.min( this.y, v.y );
  1025. return this;
  1026. },
  1027. max: function ( v ) {
  1028. this.x = Math.max( this.x, v.x );
  1029. this.y = Math.max( this.y, v.y );
  1030. return this;
  1031. },
  1032. clamp: function ( min, max ) {
  1033. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1034. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1035. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1036. return this;
  1037. },
  1038. clampScalar: function () {
  1039. var min, max;
  1040. return function clampScalar( minVal, maxVal ) {
  1041. if ( min === undefined ) {
  1042. min = new THREE.Vector2();
  1043. max = new THREE.Vector2();
  1044. }
  1045. min.set( minVal, minVal );
  1046. max.set( maxVal, maxVal );
  1047. return this.clamp( min, max );
  1048. };
  1049. }(),
  1050. clampLength: function ( min, max ) {
  1051. var length = this.length();
  1052. this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length );
  1053. return this;
  1054. },
  1055. floor: function () {
  1056. this.x = Math.floor( this.x );
  1057. this.y = Math.floor( this.y );
  1058. return this;
  1059. },
  1060. ceil: function () {
  1061. this.x = Math.ceil( this.x );
  1062. this.y = Math.ceil( this.y );
  1063. return this;
  1064. },
  1065. round: function () {
  1066. this.x = Math.round( this.x );
  1067. this.y = Math.round( this.y );
  1068. return this;
  1069. },
  1070. roundToZero: function () {
  1071. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1072. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1073. return this;
  1074. },
  1075. negate: function () {
  1076. this.x = - this.x;
  1077. this.y = - this.y;
  1078. return this;
  1079. },
  1080. dot: function ( v ) {
  1081. return this.x * v.x + this.y * v.y;
  1082. },
  1083. lengthSq: function () {
  1084. return this.x * this.x + this.y * this.y;
  1085. },
  1086. length: function () {
  1087. return Math.sqrt( this.x * this.x + this.y * this.y );
  1088. },
  1089. lengthManhattan: function() {
  1090. return Math.abs( this.x ) + Math.abs( this.y );
  1091. },
  1092. normalize: function () {
  1093. return this.divideScalar( this.length() );
  1094. },
  1095. distanceTo: function ( v ) {
  1096. return Math.sqrt( this.distanceToSquared( v ) );
  1097. },
  1098. distanceToSquared: function ( v ) {
  1099. var dx = this.x - v.x, dy = this.y - v.y;
  1100. return dx * dx + dy * dy;
  1101. },
  1102. setLength: function ( length ) {
  1103. return this.multiplyScalar( length / this.length() );
  1104. },
  1105. lerp: function ( v, alpha ) {
  1106. this.x += ( v.x - this.x ) * alpha;
  1107. this.y += ( v.y - this.y ) * alpha;
  1108. return this;
  1109. },
  1110. lerpVectors: function ( v1, v2, alpha ) {
  1111. this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1112. return this;
  1113. },
  1114. equals: function ( v ) {
  1115. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  1116. },
  1117. fromArray: function ( array, offset ) {
  1118. if ( offset === undefined ) offset = 0;
  1119. this.x = array[ offset ];
  1120. this.y = array[ offset + 1 ];
  1121. return this;
  1122. },
  1123. toArray: function ( array, offset ) {
  1124. if ( array === undefined ) array = [];
  1125. if ( offset === undefined ) offset = 0;
  1126. array[ offset ] = this.x;
  1127. array[ offset + 1 ] = this.y;
  1128. return array;
  1129. },
  1130. fromAttribute: function ( attribute, index, offset ) {
  1131. if ( offset === undefined ) offset = 0;
  1132. index = index * attribute.itemSize + offset;
  1133. this.x = attribute.array[ index ];
  1134. this.y = attribute.array[ index + 1 ];
  1135. return this;
  1136. },
  1137. rotateAround: function ( center, angle ) {
  1138. var c = Math.cos( angle ), s = Math.sin( angle );
  1139. var x = this.x - center.x;
  1140. var y = this.y - center.y;
  1141. this.x = x * c - y * s + center.x;
  1142. this.y = x * s + y * c + center.y;
  1143. return this;
  1144. }
  1145. };
  1146. // File:src/math/Vector3.js
  1147. /**
  1148. * @author mrdoob / http://mrdoob.com/
  1149. * @author *kile / http://kile.stravaganza.org/
  1150. * @author philogb / http://blog.thejit.org/
  1151. * @author mikael emtinger / http://gomo.se/
  1152. * @author egraether / http://egraether.com/
  1153. * @author WestLangley / http://github.com/WestLangley
  1154. */
  1155. THREE.Vector3 = function ( x, y, z ) {
  1156. this.x = x || 0;
  1157. this.y = y || 0;
  1158. this.z = z || 0;
  1159. };
  1160. THREE.Vector3.prototype = {
  1161. constructor: THREE.Vector3,
  1162. set: function ( x, y, z ) {
  1163. this.x = x;
  1164. this.y = y;
  1165. this.z = z;
  1166. return this;
  1167. },
  1168. setScalar: function ( scalar ) {
  1169. this.x = scalar;
  1170. this.y = scalar;
  1171. this.z = scalar;
  1172. return this;
  1173. },
  1174. setX: function ( x ) {
  1175. this.x = x;
  1176. return this;
  1177. },
  1178. setY: function ( y ) {
  1179. this.y = y;
  1180. return this;
  1181. },
  1182. setZ: function ( z ) {
  1183. this.z = z;
  1184. return this;
  1185. },
  1186. setComponent: function ( index, value ) {
  1187. switch ( index ) {
  1188. case 0: this.x = value; break;
  1189. case 1: this.y = value; break;
  1190. case 2: this.z = value; break;
  1191. default: throw new Error( 'index is out of range: ' + index );
  1192. }
  1193. },
  1194. getComponent: function ( index ) {
  1195. switch ( index ) {
  1196. case 0: return this.x;
  1197. case 1: return this.y;
  1198. case 2: return this.z;
  1199. default: throw new Error( 'index is out of range: ' + index );
  1200. }
  1201. },
  1202. clone: function () {
  1203. return new this.constructor( this.x, this.y, this.z );
  1204. },
  1205. copy: function ( v ) {
  1206. this.x = v.x;
  1207. this.y = v.y;
  1208. this.z = v.z;
  1209. return this;
  1210. },
  1211. add: function ( v, w ) {
  1212. if ( w !== undefined ) {
  1213. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1214. return this.addVectors( v, w );
  1215. }
  1216. this.x += v.x;
  1217. this.y += v.y;
  1218. this.z += v.z;
  1219. return this;
  1220. },
  1221. addScalar: function ( s ) {
  1222. this.x += s;
  1223. this.y += s;
  1224. this.z += s;
  1225. return this;
  1226. },
  1227. addVectors: function ( a, b ) {
  1228. this.x = a.x + b.x;
  1229. this.y = a.y + b.y;
  1230. this.z = a.z + b.z;
  1231. return this;
  1232. },
  1233. addScaledVector: function ( v, s ) {
  1234. this.x += v.x * s;
  1235. this.y += v.y * s;
  1236. this.z += v.z * s;
  1237. return this;
  1238. },
  1239. sub: function ( v, w ) {
  1240. if ( w !== undefined ) {
  1241. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1242. return this.subVectors( v, w );
  1243. }
  1244. this.x -= v.x;
  1245. this.y -= v.y;
  1246. this.z -= v.z;
  1247. return this;
  1248. },
  1249. subScalar: function ( s ) {
  1250. this.x -= s;
  1251. this.y -= s;
  1252. this.z -= s;
  1253. return this;
  1254. },
  1255. subVectors: function ( a, b ) {
  1256. this.x = a.x - b.x;
  1257. this.y = a.y - b.y;
  1258. this.z = a.z - b.z;
  1259. return this;
  1260. },
  1261. multiply: function ( v, w ) {
  1262. if ( w !== undefined ) {
  1263. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  1264. return this.multiplyVectors( v, w );
  1265. }
  1266. this.x *= v.x;
  1267. this.y *= v.y;
  1268. this.z *= v.z;
  1269. return this;
  1270. },
  1271. multiplyScalar: function ( scalar ) {
  1272. if ( isFinite( scalar ) ) {
  1273. this.x *= scalar;
  1274. this.y *= scalar;
  1275. this.z *= scalar;
  1276. } else {
  1277. this.x = 0;
  1278. this.y = 0;
  1279. this.z = 0;
  1280. }
  1281. return this;
  1282. },
  1283. multiplyVectors: function ( a, b ) {
  1284. this.x = a.x * b.x;
  1285. this.y = a.y * b.y;
  1286. this.z = a.z * b.z;
  1287. return this;
  1288. },
  1289. applyEuler: function () {
  1290. var quaternion;
  1291. return function applyEuler( euler ) {
  1292. if ( euler instanceof THREE.Euler === false ) {
  1293. console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  1294. }
  1295. if ( quaternion === undefined ) quaternion = new THREE.Quaternion();
  1296. this.applyQuaternion( quaternion.setFromEuler( euler ) );
  1297. return this;
  1298. };
  1299. }(),
  1300. applyAxisAngle: function () {
  1301. var quaternion;
  1302. return function applyAxisAngle( axis, angle ) {
  1303. if ( quaternion === undefined ) quaternion = new THREE.Quaternion();
  1304. this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  1305. return this;
  1306. };
  1307. }(),
  1308. applyMatrix3: function ( m ) {
  1309. var x = this.x;
  1310. var y = this.y;
  1311. var z = this.z;
  1312. var e = m.elements;
  1313. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  1314. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  1315. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  1316. return this;
  1317. },
  1318. applyMatrix4: function ( m ) {
  1319. // input: THREE.Matrix4 affine matrix
  1320. var x = this.x, y = this.y, z = this.z;
  1321. var e = m.elements;
  1322. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ];
  1323. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ];
  1324. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ];
  1325. return this;
  1326. },
  1327. applyProjection: function ( m ) {
  1328. // input: THREE.Matrix4 projection matrix
  1329. var x = this.x, y = this.y, z = this.z;
  1330. var e = m.elements;
  1331. var d = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] ); // perspective divide
  1332. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * d;
  1333. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * d;
  1334. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * d;
  1335. return this;
  1336. },
  1337. applyQuaternion: function ( q ) {
  1338. var x = this.x;
  1339. var y = this.y;
  1340. var z = this.z;
  1341. var qx = q.x;
  1342. var qy = q.y;
  1343. var qz = q.z;
  1344. var qw = q.w;
  1345. // calculate quat * vector
  1346. var ix = qw * x + qy * z - qz * y;
  1347. var iy = qw * y + qz * x - qx * z;
  1348. var iz = qw * z + qx * y - qy * x;
  1349. var iw = - qx * x - qy * y - qz * z;
  1350. // calculate result * inverse quat
  1351. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  1352. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  1353. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  1354. return this;
  1355. },
  1356. project: function () {
  1357. var matrix;
  1358. return function project( camera ) {
  1359. if ( matrix === undefined ) matrix = new THREE.Matrix4();
  1360. matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) );
  1361. return this.applyProjection( matrix );
  1362. };
  1363. }(),
  1364. unproject: function () {
  1365. var matrix;
  1366. return function unproject( camera ) {
  1367. if ( matrix === undefined ) matrix = new THREE.Matrix4();
  1368. matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) );
  1369. return this.applyProjection( matrix );
  1370. };
  1371. }(),
  1372. transformDirection: function ( m ) {
  1373. // input: THREE.Matrix4 affine matrix
  1374. // vector interpreted as a direction
  1375. var x = this.x, y = this.y, z = this.z;
  1376. var e = m.elements;
  1377. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  1378. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  1379. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  1380. this.normalize();
  1381. return this;
  1382. },
  1383. divide: function ( v ) {
  1384. this.x /= v.x;
  1385. this.y /= v.y;
  1386. this.z /= v.z;
  1387. return this;
  1388. },
  1389. divideScalar: function ( scalar ) {
  1390. return this.multiplyScalar( 1 / scalar );
  1391. },
  1392. min: function ( v ) {
  1393. this.x = Math.min( this.x, v.x );
  1394. this.y = Math.min( this.y, v.y );
  1395. this.z = Math.min( this.z, v.z );
  1396. return this;
  1397. },
  1398. max: function ( v ) {
  1399. this.x = Math.max( this.x, v.x );
  1400. this.y = Math.max( this.y, v.y );
  1401. this.z = Math.max( this.z, v.z );
  1402. return this;
  1403. },
  1404. clamp: function ( min, max ) {
  1405. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1406. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1407. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1408. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1409. return this;
  1410. },
  1411. clampScalar: function () {
  1412. var min, max;
  1413. return function clampScalar( minVal, maxVal ) {
  1414. if ( min === undefined ) {
  1415. min = new THREE.Vector3();
  1416. max = new THREE.Vector3();
  1417. }
  1418. min.set( minVal, minVal, minVal );
  1419. max.set( maxVal, maxVal, maxVal );
  1420. return this.clamp( min, max );
  1421. };
  1422. }(),
  1423. clampLength: function ( min, max ) {
  1424. var length = this.length();
  1425. this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length );
  1426. return this;
  1427. },
  1428. floor: function () {
  1429. this.x = Math.floor( this.x );
  1430. this.y = Math.floor( this.y );
  1431. this.z = Math.floor( this.z );
  1432. return this;
  1433. },
  1434. ceil: function () {
  1435. this.x = Math.ceil( this.x );
  1436. this.y = Math.ceil( this.y );
  1437. this.z = Math.ceil( this.z );
  1438. return this;
  1439. },
  1440. round: function () {
  1441. this.x = Math.round( this.x );
  1442. this.y = Math.round( this.y );
  1443. this.z = Math.round( this.z );
  1444. return this;
  1445. },
  1446. roundToZero: function () {
  1447. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1448. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1449. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1450. return this;
  1451. },
  1452. negate: function () {
  1453. this.x = - this.x;
  1454. this.y = - this.y;
  1455. this.z = - this.z;
  1456. return this;
  1457. },
  1458. dot: function ( v ) {
  1459. return this.x * v.x + this.y * v.y + this.z * v.z;
  1460. },
  1461. lengthSq: function () {
  1462. return this.x * this.x + this.y * this.y + this.z * this.z;
  1463. },
  1464. length: function () {
  1465. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1466. },
  1467. lengthManhattan: function () {
  1468. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1469. },
  1470. normalize: function () {
  1471. return this.divideScalar( this.length() );
  1472. },
  1473. setLength: function ( length ) {
  1474. return this.multiplyScalar( length / this.length() );
  1475. },
  1476. lerp: function ( v, alpha ) {
  1477. this.x += ( v.x - this.x ) * alpha;
  1478. this.y += ( v.y - this.y ) * alpha;
  1479. this.z += ( v.z - this.z ) * alpha;
  1480. return this;
  1481. },
  1482. lerpVectors: function ( v1, v2, alpha ) {
  1483. this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1484. return this;
  1485. },
  1486. cross: function ( v, w ) {
  1487. if ( w !== undefined ) {
  1488. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1489. return this.crossVectors( v, w );
  1490. }
  1491. var x = this.x, y = this.y, z = this.z;
  1492. this.x = y * v.z - z * v.y;
  1493. this.y = z * v.x - x * v.z;
  1494. this.z = x * v.y - y * v.x;
  1495. return this;
  1496. },
  1497. crossVectors: function ( a, b ) {
  1498. var ax = a.x, ay = a.y, az = a.z;
  1499. var bx = b.x, by = b.y, bz = b.z;
  1500. this.x = ay * bz - az * by;
  1501. this.y = az * bx - ax * bz;
  1502. this.z = ax * by - ay * bx;
  1503. return this;
  1504. },
  1505. projectOnVector: function () {
  1506. var v1, dot;
  1507. return function projectOnVector( vector ) {
  1508. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1509. v1.copy( vector ).normalize();
  1510. dot = this.dot( v1 );
  1511. return this.copy( v1 ).multiplyScalar( dot );
  1512. };
  1513. }(),
  1514. projectOnPlane: function () {
  1515. var v1;
  1516. return function projectOnPlane( planeNormal ) {
  1517. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1518. v1.copy( this ).projectOnVector( planeNormal );
  1519. return this.sub( v1 );
  1520. }
  1521. }(),
  1522. reflect: function () {
  1523. // reflect incident vector off plane orthogonal to normal
  1524. // normal is assumed to have unit length
  1525. var v1;
  1526. return function reflect( normal ) {
  1527. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1528. return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  1529. }
  1530. }(),
  1531. angleTo: function ( v ) {
  1532. var theta = this.dot( v ) / ( Math.sqrt( this.lengthSq() * v.lengthSq() ) );
  1533. // clamp, to handle numerical problems
  1534. return Math.acos( THREE.Math.clamp( theta, - 1, 1 ) );
  1535. },
  1536. distanceTo: function ( v ) {
  1537. return Math.sqrt( this.distanceToSquared( v ) );
  1538. },
  1539. distanceToSquared: function ( v ) {
  1540. var dx = this.x - v.x;
  1541. var dy = this.y - v.y;
  1542. var dz = this.z - v.z;
  1543. return dx * dx + dy * dy + dz * dz;
  1544. },
  1545. setFromMatrixPosition: function ( m ) {
  1546. this.x = m.elements[ 12 ];
  1547. this.y = m.elements[ 13 ];
  1548. this.z = m.elements[ 14 ];
  1549. return this;
  1550. },
  1551. setFromMatrixScale: function ( m ) {
  1552. var sx = this.set( m.elements[ 0 ], m.elements[ 1 ], m.elements[ 2 ] ).length();
  1553. var sy = this.set( m.elements[ 4 ], m.elements[ 5 ], m.elements[ 6 ] ).length();
  1554. var sz = this.set( m.elements[ 8 ], m.elements[ 9 ], m.elements[ 10 ] ).length();
  1555. this.x = sx;
  1556. this.y = sy;
  1557. this.z = sz;
  1558. return this;
  1559. },
  1560. setFromMatrixColumn: function ( index, matrix ) {
  1561. var offset = index * 4;
  1562. var me = matrix.elements;
  1563. this.x = me[ offset ];
  1564. this.y = me[ offset + 1 ];
  1565. this.z = me[ offset + 2 ];
  1566. return this;
  1567. },
  1568. equals: function ( v ) {
  1569. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1570. },
  1571. fromArray: function ( array, offset ) {
  1572. if ( offset === undefined ) offset = 0;
  1573. this.x = array[ offset ];
  1574. this.y = array[ offset + 1 ];
  1575. this.z = array[ offset + 2 ];
  1576. return this;
  1577. },
  1578. toArray: function ( array, offset ) {
  1579. if ( array === undefined ) array = [];
  1580. if ( offset === undefined ) offset = 0;
  1581. array[ offset ] = this.x;
  1582. array[ offset + 1 ] = this.y;
  1583. array[ offset + 2 ] = this.z;
  1584. return array;
  1585. },
  1586. fromAttribute: function ( attribute, index, offset ) {
  1587. if ( offset === undefined ) offset = 0;
  1588. index = index * attribute.itemSize + offset;
  1589. this.x = attribute.array[ index ];
  1590. this.y = attribute.array[ index + 1 ];
  1591. this.z = attribute.array[ index + 2 ];
  1592. return this;
  1593. }
  1594. };
  1595. // File:src/math/Vector4.js
  1596. /**
  1597. * @author supereggbert / http://www.paulbrunt.co.uk/
  1598. * @author philogb / http://blog.thejit.org/
  1599. * @author mikael emtinger / http://gomo.se/
  1600. * @author egraether / http://egraether.com/
  1601. * @author WestLangley / http://github.com/WestLangley
  1602. */
  1603. THREE.Vector4 = function ( x, y, z, w ) {
  1604. this.x = x || 0;
  1605. this.y = y || 0;
  1606. this.z = z || 0;
  1607. this.w = ( w !== undefined ) ? w : 1;
  1608. };
  1609. THREE.Vector4.prototype = {
  1610. constructor: THREE.Vector4,
  1611. set: function ( x, y, z, w ) {
  1612. this.x = x;
  1613. this.y = y;
  1614. this.z = z;
  1615. this.w = w;
  1616. return this;
  1617. },
  1618. setScalar: function ( scalar ) {
  1619. this.x = scalar;
  1620. this.y = scalar;
  1621. this.z = scalar;
  1622. this.w = scalar;
  1623. return this;
  1624. },
  1625. setX: function ( x ) {
  1626. this.x = x;
  1627. return this;
  1628. },
  1629. setY: function ( y ) {
  1630. this.y = y;
  1631. return this;
  1632. },
  1633. setZ: function ( z ) {
  1634. this.z = z;
  1635. return this;
  1636. },
  1637. setW: function ( w ) {
  1638. this.w = w;
  1639. return this;
  1640. },
  1641. setComponent: function ( index, value ) {
  1642. switch ( index ) {
  1643. case 0: this.x = value; break;
  1644. case 1: this.y = value; break;
  1645. case 2: this.z = value; break;
  1646. case 3: this.w = value; break;
  1647. default: throw new Error( 'index is out of range: ' + index );
  1648. }
  1649. },
  1650. getComponent: function ( index ) {
  1651. switch ( index ) {
  1652. case 0: return this.x;
  1653. case 1: return this.y;
  1654. case 2: return this.z;
  1655. case 3: return this.w;
  1656. default: throw new Error( 'index is out of range: ' + index );
  1657. }
  1658. },
  1659. clone: function () {
  1660. return new this.constructor( this.x, this.y, this.z, this.w );
  1661. },
  1662. copy: function ( v ) {
  1663. this.x = v.x;
  1664. this.y = v.y;
  1665. this.z = v.z;
  1666. this.w = ( v.w !== undefined ) ? v.w : 1;
  1667. return this;
  1668. },
  1669. add: function ( v, w ) {
  1670. if ( w !== undefined ) {
  1671. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1672. return this.addVectors( v, w );
  1673. }
  1674. this.x += v.x;
  1675. this.y += v.y;
  1676. this.z += v.z;
  1677. this.w += v.w;
  1678. return this;
  1679. },
  1680. addScalar: function ( s ) {
  1681. this.x += s;
  1682. this.y += s;
  1683. this.z += s;
  1684. this.w += s;
  1685. return this;
  1686. },
  1687. addVectors: function ( a, b ) {
  1688. this.x = a.x + b.x;
  1689. this.y = a.y + b.y;
  1690. this.z = a.z + b.z;
  1691. this.w = a.w + b.w;
  1692. return this;
  1693. },
  1694. addScaledVector: function ( v, s ) {
  1695. this.x += v.x * s;
  1696. this.y += v.y * s;
  1697. this.z += v.z * s;
  1698. this.w += v.w * s;
  1699. return this;
  1700. },
  1701. sub: function ( v, w ) {
  1702. if ( w !== undefined ) {
  1703. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1704. return this.subVectors( v, w );
  1705. }
  1706. this.x -= v.x;
  1707. this.y -= v.y;
  1708. this.z -= v.z;
  1709. this.w -= v.w;
  1710. return this;
  1711. },
  1712. subScalar: function ( s ) {
  1713. this.x -= s;
  1714. this.y -= s;
  1715. this.z -= s;
  1716. this.w -= s;
  1717. return this;
  1718. },
  1719. subVectors: function ( a, b ) {
  1720. this.x = a.x - b.x;
  1721. this.y = a.y - b.y;
  1722. this.z = a.z - b.z;
  1723. this.w = a.w - b.w;
  1724. return this;
  1725. },
  1726. multiplyScalar: function ( scalar ) {
  1727. if ( isFinite( scalar ) ) {
  1728. this.x *= scalar;
  1729. this.y *= scalar;
  1730. this.z *= scalar;
  1731. this.w *= scalar;
  1732. } else {
  1733. this.x = 0;
  1734. this.y = 0;
  1735. this.z = 0;
  1736. this.w = 0;
  1737. }
  1738. return this;
  1739. },
  1740. applyMatrix4: function ( m ) {
  1741. var x = this.x;
  1742. var y = this.y;
  1743. var z = this.z;
  1744. var w = this.w;
  1745. var e = m.elements;
  1746. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1747. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1748. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1749. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1750. return this;
  1751. },
  1752. divideScalar: function ( scalar ) {
  1753. return this.multiplyScalar( 1 / scalar );
  1754. },
  1755. setAxisAngleFromQuaternion: function ( q ) {
  1756. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1757. // q is assumed to be normalized
  1758. this.w = 2 * Math.acos( q.w );
  1759. var s = Math.sqrt( 1 - q.w * q.w );
  1760. if ( s < 0.0001 ) {
  1761. this.x = 1;
  1762. this.y = 0;
  1763. this.z = 0;
  1764. } else {
  1765. this.x = q.x / s;
  1766. this.y = q.y / s;
  1767. this.z = q.z / s;
  1768. }
  1769. return this;
  1770. },
  1771. setAxisAngleFromRotationMatrix: function ( m ) {
  1772. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1773. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1774. var angle, x, y, z, // variables for result
  1775. epsilon = 0.01, // margin to allow for rounding errors
  1776. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1777. te = m.elements,
  1778. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1779. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1780. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1781. if ( ( Math.abs( m12 - m21 ) < epsilon )
  1782. && ( Math.abs( m13 - m31 ) < epsilon )
  1783. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1784. // singularity found
  1785. // first check for identity matrix which must have +1 for all terms
  1786. // in leading diagonal and zero in other terms
  1787. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  1788. && ( Math.abs( m13 + m31 ) < epsilon2 )
  1789. && ( Math.abs( m23 + m32 ) < epsilon2 )
  1790. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1791. // this singularity is identity matrix so angle = 0
  1792. this.set( 1, 0, 0, 0 );
  1793. return this; // zero angle, arbitrary axis
  1794. }
  1795. // otherwise this singularity is angle = 180
  1796. angle = Math.PI;
  1797. var xx = ( m11 + 1 ) / 2;
  1798. var yy = ( m22 + 1 ) / 2;
  1799. var zz = ( m33 + 1 ) / 2;
  1800. var xy = ( m12 + m21 ) / 4;
  1801. var xz = ( m13 + m31 ) / 4;
  1802. var yz = ( m23 + m32 ) / 4;
  1803. if ( ( xx > yy ) && ( xx > zz ) ) {
  1804. // m11 is the largest diagonal term
  1805. if ( xx < epsilon ) {
  1806. x = 0;
  1807. y = 0.707106781;
  1808. z = 0.707106781;
  1809. } else {
  1810. x = Math.sqrt( xx );
  1811. y = xy / x;
  1812. z = xz / x;
  1813. }
  1814. } else if ( yy > zz ) {
  1815. // m22 is the largest diagonal term
  1816. if ( yy < epsilon ) {
  1817. x = 0.707106781;
  1818. y = 0;
  1819. z = 0.707106781;
  1820. } else {
  1821. y = Math.sqrt( yy );
  1822. x = xy / y;
  1823. z = yz / y;
  1824. }
  1825. } else {
  1826. // m33 is the largest diagonal term so base result on this
  1827. if ( zz < epsilon ) {
  1828. x = 0.707106781;
  1829. y = 0.707106781;
  1830. z = 0;
  1831. } else {
  1832. z = Math.sqrt( zz );
  1833. x = xz / z;
  1834. y = yz / z;
  1835. }
  1836. }
  1837. this.set( x, y, z, angle );
  1838. return this; // return 180 deg rotation
  1839. }
  1840. // as we have reached here there are no singularities so we can handle normally
  1841. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  1842. + ( m13 - m31 ) * ( m13 - m31 )
  1843. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1844. if ( Math.abs( s ) < 0.001 ) s = 1;
  1845. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1846. // caught by singularity test above, but I've left it in just in case
  1847. this.x = ( m32 - m23 ) / s;
  1848. this.y = ( m13 - m31 ) / s;
  1849. this.z = ( m21 - m12 ) / s;
  1850. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1851. return this;
  1852. },
  1853. min: function ( v ) {
  1854. this.x = Math.min( this.x, v.x );
  1855. this.y = Math.min( this.y, v.y );
  1856. this.z = Math.min( this.z, v.z );
  1857. this.w = Math.min( this.w, v.w );
  1858. return this;
  1859. },
  1860. max: function ( v ) {
  1861. this.x = Math.max( this.x, v.x );
  1862. this.y = Math.max( this.y, v.y );
  1863. this.z = Math.max( this.z, v.z );
  1864. this.w = Math.max( this.w, v.w );
  1865. return this;
  1866. },
  1867. clamp: function ( min, max ) {
  1868. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1869. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1870. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1871. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1872. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1873. return this;
  1874. },
  1875. clampScalar: function () {
  1876. var min, max;
  1877. return function clampScalar( minVal, maxVal ) {
  1878. if ( min === undefined ) {
  1879. min = new THREE.Vector4();
  1880. max = new THREE.Vector4();
  1881. }
  1882. min.set( minVal, minVal, minVal, minVal );
  1883. max.set( maxVal, maxVal, maxVal, maxVal );
  1884. return this.clamp( min, max );
  1885. };
  1886. }(),
  1887. floor: function () {
  1888. this.x = Math.floor( this.x );
  1889. this.y = Math.floor( this.y );
  1890. this.z = Math.floor( this.z );
  1891. this.w = Math.floor( this.w );
  1892. return this;
  1893. },
  1894. ceil: function () {
  1895. this.x = Math.ceil( this.x );
  1896. this.y = Math.ceil( this.y );
  1897. this.z = Math.ceil( this.z );
  1898. this.w = Math.ceil( this.w );
  1899. return this;
  1900. },
  1901. round: function () {
  1902. this.x = Math.round( this.x );
  1903. this.y = Math.round( this.y );
  1904. this.z = Math.round( this.z );
  1905. this.w = Math.round( this.w );
  1906. return this;
  1907. },
  1908. roundToZero: function () {
  1909. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1910. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1911. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1912. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1913. return this;
  1914. },
  1915. negate: function () {
  1916. this.x = - this.x;
  1917. this.y = - this.y;
  1918. this.z = - this.z;
  1919. this.w = - this.w;
  1920. return this;
  1921. },
  1922. dot: function ( v ) {
  1923. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1924. },
  1925. lengthSq: function () {
  1926. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1927. },
  1928. length: function () {
  1929. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1930. },
  1931. lengthManhattan: function () {
  1932. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1933. },
  1934. normalize: function () {
  1935. return this.divideScalar( this.length() );
  1936. },
  1937. setLength: function ( length ) {
  1938. return this.multiplyScalar( length / this.length() );
  1939. },
  1940. lerp: function ( v, alpha ) {
  1941. this.x += ( v.x - this.x ) * alpha;
  1942. this.y += ( v.y - this.y ) * alpha;
  1943. this.z += ( v.z - this.z ) * alpha;
  1944. this.w += ( v.w - this.w ) * alpha;
  1945. return this;
  1946. },
  1947. lerpVectors: function ( v1, v2, alpha ) {
  1948. this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1949. return this;
  1950. },
  1951. equals: function ( v ) {
  1952. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1953. },
  1954. fromArray: function ( array, offset ) {
  1955. if ( offset === undefined ) offset = 0;
  1956. this.x = array[ offset ];
  1957. this.y = array[ offset + 1 ];
  1958. this.z = array[ offset + 2 ];
  1959. this.w = array[ offset + 3 ];
  1960. return this;
  1961. },
  1962. toArray: function ( array, offset ) {
  1963. if ( array === undefined ) array = [];
  1964. if ( offset === undefined ) offset = 0;
  1965. array[ offset ] = this.x;
  1966. array[ offset + 1 ] = this.y;
  1967. array[ offset + 2 ] = this.z;
  1968. array[ offset + 3 ] = this.w;
  1969. return array;
  1970. },
  1971. fromAttribute: function ( attribute, index, offset ) {
  1972. if ( offset === undefined ) offset = 0;
  1973. index = index * attribute.itemSize + offset;
  1974. this.x = attribute.array[ index ];
  1975. this.y = attribute.array[ index + 1 ];
  1976. this.z = attribute.array[ index + 2 ];
  1977. this.w = attribute.array[ index + 3 ];
  1978. return this;
  1979. }
  1980. };
  1981. // File:src/math/Euler.js
  1982. /**
  1983. * @author mrdoob / http://mrdoob.com/
  1984. * @author WestLangley / http://github.com/WestLangley
  1985. * @author bhouston / http://clara.io
  1986. */
  1987. THREE.Euler = function ( x, y, z, order ) {
  1988. this._x = x || 0;
  1989. this._y = y || 0;
  1990. this._z = z || 0;
  1991. this._order = order || THREE.Euler.DefaultOrder;
  1992. };
  1993. THREE.Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  1994. THREE.Euler.DefaultOrder = 'XYZ';
  1995. THREE.Euler.prototype = {
  1996. constructor: THREE.Euler,
  1997. get x () {
  1998. return this._x;
  1999. },
  2000. set x ( value ) {
  2001. this._x = value;
  2002. this.onChangeCallback();
  2003. },
  2004. get y () {
  2005. return this._y;
  2006. },
  2007. set y ( value ) {
  2008. this._y = value;
  2009. this.onChangeCallback();
  2010. },
  2011. get z () {
  2012. return this._z;
  2013. },
  2014. set z ( value ) {
  2015. this._z = value;
  2016. this.onChangeCallback();
  2017. },
  2018. get order () {
  2019. return this._order;
  2020. },
  2021. set order ( value ) {
  2022. this._order = value;
  2023. this.onChangeCallback();
  2024. },
  2025. set: function ( x, y, z, order ) {
  2026. this._x = x;
  2027. this._y = y;
  2028. this._z = z;
  2029. this._order = order || this._order;
  2030. this.onChangeCallback();
  2031. return this;
  2032. },
  2033. clone: function () {
  2034. return new this.constructor( this._x, this._y, this._z, this._order );
  2035. },
  2036. copy: function ( euler ) {
  2037. this._x = euler._x;
  2038. this._y = euler._y;
  2039. this._z = euler._z;
  2040. this._order = euler._order;
  2041. this.onChangeCallback();
  2042. return this;
  2043. },
  2044. setFromRotationMatrix: function ( m, order, update ) {
  2045. var clamp = THREE.Math.clamp;
  2046. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2047. var te = m.elements;
  2048. var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  2049. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  2050. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  2051. order = order || this._order;
  2052. if ( order === 'XYZ' ) {
  2053. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  2054. if ( Math.abs( m13 ) < 0.99999 ) {
  2055. this._x = Math.atan2( - m23, m33 );
  2056. this._z = Math.atan2( - m12, m11 );
  2057. } else {
  2058. this._x = Math.atan2( m32, m22 );
  2059. this._z = 0;
  2060. }
  2061. } else if ( order === 'YXZ' ) {
  2062. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  2063. if ( Math.abs( m23 ) < 0.99999 ) {
  2064. this._y = Math.atan2( m13, m33 );
  2065. this._z = Math.atan2( m21, m22 );
  2066. } else {
  2067. this._y = Math.atan2( - m31, m11 );
  2068. this._z = 0;
  2069. }
  2070. } else if ( order === 'ZXY' ) {
  2071. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  2072. if ( Math.abs( m32 ) < 0.99999 ) {
  2073. this._y = Math.atan2( - m31, m33 );
  2074. this._z = Math.atan2( - m12, m22 );
  2075. } else {
  2076. this._y = 0;
  2077. this._z = Math.atan2( m21, m11 );
  2078. }
  2079. } else if ( order === 'ZYX' ) {
  2080. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  2081. if ( Math.abs( m31 ) < 0.99999 ) {
  2082. this._x = Math.atan2( m32, m33 );
  2083. this._z = Math.atan2( m21, m11 );
  2084. } else {
  2085. this._x = 0;
  2086. this._z = Math.atan2( - m12, m22 );
  2087. }
  2088. } else if ( order === 'YZX' ) {
  2089. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  2090. if ( Math.abs( m21 ) < 0.99999 ) {
  2091. this._x = Math.atan2( - m23, m22 );
  2092. this._y = Math.atan2( - m31, m11 );
  2093. } else {
  2094. this._x = 0;
  2095. this._y = Math.atan2( m13, m33 );
  2096. }
  2097. } else if ( order === 'XZY' ) {
  2098. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  2099. if ( Math.abs( m12 ) < 0.99999 ) {
  2100. this._x = Math.atan2( m32, m22 );
  2101. this._y = Math.atan2( m13, m11 );
  2102. } else {
  2103. this._x = Math.atan2( - m23, m33 );
  2104. this._y = 0;
  2105. }
  2106. } else {
  2107. console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order )
  2108. }
  2109. this._order = order;
  2110. if ( update !== false ) this.onChangeCallback();
  2111. return this;
  2112. },
  2113. setFromQuaternion: function () {
  2114. var matrix;
  2115. return function ( q, order, update ) {
  2116. if ( matrix === undefined ) matrix = new THREE.Matrix4();
  2117. matrix.makeRotationFromQuaternion( q );
  2118. this.setFromRotationMatrix( matrix, order, update );
  2119. return this;
  2120. };
  2121. }(),
  2122. setFromVector3: function ( v, order ) {
  2123. return this.set( v.x, v.y, v.z, order || this._order );
  2124. },
  2125. reorder: function () {
  2126. // WARNING: this discards revolution information -bhouston
  2127. var q = new THREE.Quaternion();
  2128. return function ( newOrder ) {
  2129. q.setFromEuler( this );
  2130. this.setFromQuaternion( q, newOrder );
  2131. };
  2132. }(),
  2133. equals: function ( euler ) {
  2134. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  2135. },
  2136. fromArray: function ( array ) {
  2137. this._x = array[ 0 ];
  2138. this._y = array[ 1 ];
  2139. this._z = array[ 2 ];
  2140. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  2141. this.onChangeCallback();
  2142. return this;
  2143. },
  2144. toArray: function ( array, offset ) {
  2145. if ( array === undefined ) array = [];
  2146. if ( offset === undefined ) offset = 0;
  2147. array[ offset ] = this._x;
  2148. array[ offset + 1 ] = this._y;
  2149. array[ offset + 2 ] = this._z;
  2150. array[ offset + 3 ] = this._order;
  2151. return array;
  2152. },
  2153. toVector3: function ( optionalResult ) {
  2154. if ( optionalResult ) {
  2155. return optionalResult.set( this._x, this._y, this._z );
  2156. } else {
  2157. return new THREE.Vector3( this._x, this._y, this._z );
  2158. }
  2159. },
  2160. onChange: function ( callback ) {
  2161. this.onChangeCallback = callback;
  2162. return this;
  2163. },
  2164. onChangeCallback: function () {}
  2165. };
  2166. // File:src/math/Line3.js
  2167. /**
  2168. * @author bhouston / http://clara.io
  2169. */
  2170. THREE.Line3 = function ( start, end ) {
  2171. this.start = ( start !== undefined ) ? start : new THREE.Vector3();
  2172. this.end = ( end !== undefined ) ? end : new THREE.Vector3();
  2173. };
  2174. THREE.Line3.prototype = {
  2175. constructor: THREE.Line3,
  2176. set: function ( start, end ) {
  2177. this.start.copy( start );
  2178. this.end.copy( end );
  2179. return this;
  2180. },
  2181. clone: function () {
  2182. return new this.constructor().copy( this );
  2183. },
  2184. copy: function ( line ) {
  2185. this.start.copy( line.start );
  2186. this.end.copy( line.end );
  2187. return this;
  2188. },
  2189. center: function ( optionalTarget ) {
  2190. var result = optionalTarget || new THREE.Vector3();
  2191. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  2192. },
  2193. delta: function ( optionalTarget ) {
  2194. var result = optionalTarget || new THREE.Vector3();
  2195. return result.subVectors( this.end, this.start );
  2196. },
  2197. distanceSq: function () {
  2198. return this.start.distanceToSquared( this.end );
  2199. },
  2200. distance: function () {
  2201. return this.start.distanceTo( this.end );
  2202. },
  2203. at: function ( t, optionalTarget ) {
  2204. var result = optionalTarget || new THREE.Vector3();
  2205. return this.delta( result ).multiplyScalar( t ).add( this.start );
  2206. },
  2207. closestPointToPointParameter: function () {
  2208. var startP = new THREE.Vector3();
  2209. var startEnd = new THREE.Vector3();
  2210. return function ( point, clampToLine ) {
  2211. startP.subVectors( point, this.start );
  2212. startEnd.subVectors( this.end, this.start );
  2213. var startEnd2 = startEnd.dot( startEnd );
  2214. var startEnd_startP = startEnd.dot( startP );
  2215. var t = startEnd_startP / startEnd2;
  2216. if ( clampToLine ) {
  2217. t = THREE.Math.clamp( t, 0, 1 );
  2218. }
  2219. return t;
  2220. };
  2221. }(),
  2222. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  2223. var t = this.closestPointToPointParameter( point, clampToLine );
  2224. var result = optionalTarget || new THREE.Vector3();
  2225. return this.delta( result ).multiplyScalar( t ).add( this.start );
  2226. },
  2227. applyMatrix4: function ( matrix ) {
  2228. this.start.applyMatrix4( matrix );
  2229. this.end.applyMatrix4( matrix );
  2230. return this;
  2231. },
  2232. equals: function ( line ) {
  2233. return line.start.equals( this.start ) && line.end.equals( this.end );
  2234. }
  2235. };
  2236. // File:src/math/Box2.js
  2237. /**
  2238. * @author bhouston / http://clara.io
  2239. */
  2240. THREE.Box2 = function ( min, max ) {
  2241. this.min = ( min !== undefined ) ? min : new THREE.Vector2( Infinity, Infinity );
  2242. this.max = ( max !== undefined ) ? max : new THREE.Vector2( - Infinity, - Infinity );
  2243. };
  2244. THREE.Box2.prototype = {
  2245. constructor: THREE.Box2,
  2246. set: function ( min, max ) {
  2247. this.min.copy( min );
  2248. this.max.copy( max );
  2249. return this;
  2250. },
  2251. setFromPoints: function ( points ) {
  2252. this.makeEmpty();
  2253. for ( var i = 0, il = points.length; i < il; i ++ ) {
  2254. this.expandByPoint( points[ i ] );
  2255. }
  2256. return this;
  2257. },
  2258. setFromCenterAndSize: function () {
  2259. var v1 = new THREE.Vector2();
  2260. return function ( center, size ) {
  2261. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2262. this.min.copy( center ).sub( halfSize );
  2263. this.max.copy( center ).add( halfSize );
  2264. return this;
  2265. };
  2266. }(),
  2267. clone: function () {
  2268. return new this.constructor().copy( this );
  2269. },
  2270. copy: function ( box ) {
  2271. this.min.copy( box.min );
  2272. this.max.copy( box.max );
  2273. return this;
  2274. },
  2275. makeEmpty: function () {
  2276. this.min.x = this.min.y = Infinity;
  2277. this.max.x = this.max.y = - Infinity;
  2278. return this;
  2279. },
  2280. empty: function () {
  2281. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2282. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  2283. },
  2284. center: function ( optionalTarget ) {
  2285. var result = optionalTarget || new THREE.Vector2();
  2286. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2287. },
  2288. size: function ( optionalTarget ) {
  2289. var result = optionalTarget || new THREE.Vector2();
  2290. return result.subVectors( this.max, this.min );
  2291. },
  2292. expandByPoint: function ( point ) {
  2293. this.min.min( point );
  2294. this.max.max( point );
  2295. return this;
  2296. },
  2297. expandByVector: function ( vector ) {
  2298. this.min.sub( vector );
  2299. this.max.add( vector );
  2300. return this;
  2301. },
  2302. expandByScalar: function ( scalar ) {
  2303. this.min.addScalar( - scalar );
  2304. this.max.addScalar( scalar );
  2305. return this;
  2306. },
  2307. containsPoint: function ( point ) {
  2308. if ( point.x < this.min.x || point.x > this.max.x ||
  2309. point.y < this.min.y || point.y > this.max.y ) {
  2310. return false;
  2311. }
  2312. return true;
  2313. },
  2314. containsBox: function ( box ) {
  2315. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2316. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  2317. return true;
  2318. }
  2319. return false;
  2320. },
  2321. getParameter: function ( point, optionalTarget ) {
  2322. // This can potentially have a divide by zero if the box
  2323. // has a size dimension of 0.
  2324. var result = optionalTarget || new THREE.Vector2();
  2325. return result.set(
  2326. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2327. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  2328. );
  2329. },
  2330. intersectsBox: function ( box ) {
  2331. // using 6 splitting planes to rule out intersections.
  2332. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2333. box.max.y < this.min.y || box.min.y > this.max.y ) {
  2334. return false;
  2335. }
  2336. return true;
  2337. },
  2338. clampPoint: function ( point, optionalTarget ) {
  2339. var result = optionalTarget || new THREE.Vector2();
  2340. return result.copy( point ).clamp( this.min, this.max );
  2341. },
  2342. distanceToPoint: function () {
  2343. var v1 = new THREE.Vector2();
  2344. return function ( point ) {
  2345. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2346. return clampedPoint.sub( point ).length();
  2347. };
  2348. }(),
  2349. intersect: function ( box ) {
  2350. this.min.max( box.min );
  2351. this.max.min( box.max );
  2352. return this;
  2353. },
  2354. union: function ( box ) {
  2355. this.min.min( box.min );
  2356. this.max.max( box.max );
  2357. return this;
  2358. },
  2359. translate: function ( offset ) {
  2360. this.min.add( offset );
  2361. this.max.add( offset );
  2362. return this;
  2363. },
  2364. equals: function ( box ) {
  2365. return box.min.equals( this.min ) && box.max.equals( this.max );
  2366. }
  2367. };
  2368. // File:src/math/Box3.js
  2369. /**
  2370. * @author bhouston / http://clara.io
  2371. * @author WestLangley / http://github.com/WestLangley
  2372. */
  2373. THREE.Box3 = function ( min, max ) {
  2374. this.min = ( min !== undefined ) ? min : new THREE.Vector3( Infinity, Infinity, Infinity );
  2375. this.max = ( max !== undefined ) ? max : new THREE.Vector3( - Infinity, - Infinity, - Infinity );
  2376. };
  2377. THREE.Box3.prototype = {
  2378. constructor: THREE.Box3,
  2379. set: function ( min, max ) {
  2380. this.min.copy( min );
  2381. this.max.copy( max );
  2382. return this;
  2383. },
  2384. setFromPoints: function ( points ) {
  2385. this.makeEmpty();
  2386. for ( var i = 0, il = points.length; i < il; i ++ ) {
  2387. this.expandByPoint( points[ i ] );
  2388. }
  2389. return this;
  2390. },
  2391. setFromCenterAndSize: function () {
  2392. var v1 = new THREE.Vector3();
  2393. return function ( center, size ) {
  2394. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2395. this.min.copy( center ).sub( halfSize );
  2396. this.max.copy( center ).add( halfSize );
  2397. return this;
  2398. };
  2399. }(),
  2400. setFromObject: function () {
  2401. // Computes the world-axis-aligned bounding box of an object (including its children),
  2402. // accounting for both the object's, and children's, world transforms
  2403. var box;
  2404. return function ( object ) {
  2405. if ( box === undefined ) box = new THREE.Box3();
  2406. var scope = this;
  2407. this.makeEmpty();
  2408. object.updateMatrixWorld( true );
  2409. object.traverse( function ( node ) {
  2410. var geometry = node.geometry;
  2411. if ( geometry !== undefined ) {
  2412. if ( geometry.boundingBox === null ) {
  2413. geometry.computeBoundingBox();
  2414. }
  2415. box.copy( geometry.boundingBox );
  2416. box.applyMatrix4( node.matrixWorld );
  2417. scope.union( box );
  2418. }
  2419. } );
  2420. return this;
  2421. };
  2422. }(),
  2423. clone: function () {
  2424. return new this.constructor().copy( this );
  2425. },
  2426. copy: function ( box ) {
  2427. this.min.copy( box.min );
  2428. this.max.copy( box.max );
  2429. return this;
  2430. },
  2431. makeEmpty: function () {
  2432. this.min.x = this.min.y = this.min.z = Infinity;
  2433. this.max.x = this.max.y = this.max.z = - Infinity;
  2434. return this;
  2435. },
  2436. empty: function () {
  2437. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2438. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2439. },
  2440. center: function ( optionalTarget ) {
  2441. var result = optionalTarget || new THREE.Vector3();
  2442. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2443. },
  2444. size: function ( optionalTarget ) {
  2445. var result = optionalTarget || new THREE.Vector3();
  2446. return result.subVectors( this.max, this.min );
  2447. },
  2448. expandByPoint: function ( point ) {
  2449. this.min.min( point );
  2450. this.max.max( point );
  2451. return this;
  2452. },
  2453. expandByVector: function ( vector ) {
  2454. this.min.sub( vector );
  2455. this.max.add( vector );
  2456. return this;
  2457. },
  2458. expandByScalar: function ( scalar ) {
  2459. this.min.addScalar( - scalar );
  2460. this.max.addScalar( scalar );
  2461. return this;
  2462. },
  2463. containsPoint: function ( point ) {
  2464. if ( point.x < this.min.x || point.x > this.max.x ||
  2465. point.y < this.min.y || point.y > this.max.y ||
  2466. point.z < this.min.z || point.z > this.max.z ) {
  2467. return false;
  2468. }
  2469. return true;
  2470. },
  2471. containsBox: function ( box ) {
  2472. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2473. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  2474. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  2475. return true;
  2476. }
  2477. return false;
  2478. },
  2479. getParameter: function ( point, optionalTarget ) {
  2480. // This can potentially have a divide by zero if the box
  2481. // has a size dimension of 0.
  2482. var result = optionalTarget || new THREE.Vector3();
  2483. return result.set(
  2484. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2485. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2486. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2487. );
  2488. },
  2489. intersectsBox: function ( box ) {
  2490. // using 6 splitting planes to rule out intersections.
  2491. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2492. box.max.y < this.min.y || box.min.y > this.max.y ||
  2493. box.max.z < this.min.z || box.min.z > this.max.z ) {
  2494. return false;
  2495. }
  2496. return true;
  2497. },
  2498. intersectsSphere: ( function () {
  2499. var closestPoint;
  2500. return function intersectsSphere( sphere ) {
  2501. if ( closestPoint === undefined ) closestPoint = new THREE.Vector3();
  2502. // Find the point on the AABB closest to the sphere center.
  2503. this.clampPoint( sphere.center, closestPoint );
  2504. // If that point is inside the sphere, the AABB and sphere intersect.
  2505. return closestPoint.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  2506. };
  2507. } )(),
  2508. intersectsPlane: function ( plane ) {
  2509. // We compute the minimum and maximum dot product values. If those values
  2510. // are on the same side (back or front) of the plane, then there is no intersection.
  2511. var min, max;
  2512. if( plane.normal.x > 0 ) {
  2513. min = plane.normal.x * this.min.x;
  2514. max = plane.normal.x * this.max.x;
  2515. } else {
  2516. min = plane.normal.x * this.max.x;
  2517. max = plane.normal.x * this.min.x;
  2518. }
  2519. if( plane.normal.y > 0 ) {
  2520. min += plane.normal.y * this.min.y;
  2521. max += plane.normal.y * this.max.y;
  2522. } else {
  2523. min += plane.normal.y * this.max.y;
  2524. max += plane.normal.y * this.min.y;
  2525. }
  2526. if( plane.normal.z > 0 ) {
  2527. min += plane.normal.z * this.min.z;
  2528. max += plane.normal.z * this.max.z;
  2529. } else {
  2530. min += plane.normal.z * this.max.z;
  2531. max += plane.normal.z * this.min.z;
  2532. }
  2533. return ( min <= plane.constant && max >= plane.constant );
  2534. },
  2535. clampPoint: function ( point, optionalTarget ) {
  2536. var result = optionalTarget || new THREE.Vector3();
  2537. return result.copy( point ).clamp( this.min, this.max );
  2538. },
  2539. distanceToPoint: function () {
  2540. var v1 = new THREE.Vector3();
  2541. return function ( point ) {
  2542. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2543. return clampedPoint.sub( point ).length();
  2544. };
  2545. }(),
  2546. getBoundingSphere: function () {
  2547. var v1 = new THREE.Vector3();
  2548. return function ( optionalTarget ) {
  2549. var result = optionalTarget || new THREE.Sphere();
  2550. result.center = this.center();
  2551. result.radius = this.size( v1 ).length() * 0.5;
  2552. return result;
  2553. };
  2554. }(),
  2555. intersect: function ( box ) {
  2556. this.min.max( box.min );
  2557. this.max.min( box.max );
  2558. return this;
  2559. },
  2560. union: function ( box ) {
  2561. this.min.min( box.min );
  2562. this.max.max( box.max );
  2563. return this;
  2564. },
  2565. applyMatrix4: function () {
  2566. var points = [
  2567. new THREE.Vector3(),
  2568. new THREE.Vector3(),
  2569. new THREE.Vector3(),
  2570. new THREE.Vector3(),
  2571. new THREE.Vector3(),
  2572. new THREE.Vector3(),
  2573. new THREE.Vector3(),
  2574. new THREE.Vector3()
  2575. ];
  2576. return function ( matrix ) {
  2577. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2578. points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2579. points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2580. points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2581. points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2582. points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2583. points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2584. points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2585. points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2586. this.makeEmpty();
  2587. this.setFromPoints( points );
  2588. return this;
  2589. };
  2590. }(),
  2591. translate: function ( offset ) {
  2592. this.min.add( offset );
  2593. this.max.add( offset );
  2594. return this;
  2595. },
  2596. equals: function ( box ) {
  2597. return box.min.equals( this.min ) && box.max.equals( this.max );
  2598. }
  2599. };
  2600. // File:src/math/Matrix3.js
  2601. /**
  2602. * @author alteredq / http://alteredqualia.com/
  2603. * @author WestLangley / http://github.com/WestLangley
  2604. * @author bhouston / http://clara.io
  2605. */
  2606. THREE.Matrix3 = function () {
  2607. this.elements = new Float32Array( [
  2608. 1, 0, 0,
  2609. 0, 1, 0,
  2610. 0, 0, 1
  2611. ] );
  2612. if ( arguments.length > 0 ) {
  2613. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  2614. }
  2615. };
  2616. THREE.Matrix3.prototype = {
  2617. constructor: THREE.Matrix3,
  2618. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2619. var te = this.elements;
  2620. te[ 0 ] = n11; te[ 3 ] = n12; te[ 6 ] = n13;
  2621. te[ 1 ] = n21; te[ 4 ] = n22; te[ 7 ] = n23;
  2622. te[ 2 ] = n31; te[ 5 ] = n32; te[ 8 ] = n33;
  2623. return this;
  2624. },
  2625. identity: function () {
  2626. this.set(
  2627. 1, 0, 0,
  2628. 0, 1, 0,
  2629. 0, 0, 1
  2630. );
  2631. return this;
  2632. },
  2633. clone: function () {
  2634. return new this.constructor().fromArray( this.elements );
  2635. },
  2636. copy: function ( m ) {
  2637. var me = m.elements;
  2638. this.set(
  2639. me[ 0 ], me[ 3 ], me[ 6 ],
  2640. me[ 1 ], me[ 4 ], me[ 7 ],
  2641. me[ 2 ], me[ 5 ], me[ 8 ]
  2642. );
  2643. return this;
  2644. },
  2645. applyToVector3Array: function () {
  2646. var v1;
  2647. return function ( array, offset, length ) {
  2648. if ( v1 === undefined ) v1 = new THREE.Vector3();
  2649. if ( offset === undefined ) offset = 0;
  2650. if ( length === undefined ) length = array.length;
  2651. for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) {
  2652. v1.fromArray( array, j );
  2653. v1.applyMatrix3( this );
  2654. v1.toArray( array, j );
  2655. }
  2656. return array;
  2657. };
  2658. }(),
  2659. applyToBuffer: function () {
  2660. var v1;
  2661. return function applyToBuffer( buffer, offset, length ) {
  2662. if ( v1 === undefined ) v1 = new THREE.Vector3();
  2663. if ( offset === undefined ) offset = 0;
  2664. if ( length === undefined ) length = buffer.length / buffer.itemSize;
  2665. for ( var i = 0, j = offset; i < length; i ++, j ++ ) {
  2666. v1.x = buffer.getX( j );
  2667. v1.y = buffer.getY( j );
  2668. v1.z = buffer.getZ( j );
  2669. v1.applyMatrix3( this );
  2670. buffer.setXYZ( v1.x, v1.y, v1.z );
  2671. }
  2672. return buffer;
  2673. };
  2674. }(),
  2675. multiplyScalar: function ( s ) {
  2676. var te = this.elements;
  2677. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  2678. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  2679. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  2680. return this;
  2681. },
  2682. determinant: function () {
  2683. var te = this.elements;
  2684. var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  2685. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  2686. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  2687. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  2688. },
  2689. getInverse: function ( matrix, throwOnDegenerate ) {
  2690. // input: THREE.Matrix4
  2691. // ( based on http://code.google.com/p/webgl-mjs/ )
  2692. var me = matrix.elements;
  2693. var te = this.elements;
  2694. te[ 0 ] = me[ 10 ] * me[ 5 ] - me[ 6 ] * me[ 9 ];
  2695. te[ 1 ] = - me[ 10 ] * me[ 1 ] + me[ 2 ] * me[ 9 ];
  2696. te[ 2 ] = me[ 6 ] * me[ 1 ] - me[ 2 ] * me[ 5 ];
  2697. te[ 3 ] = - me[ 10 ] * me[ 4 ] + me[ 6 ] * me[ 8 ];
  2698. te[ 4 ] = me[ 10 ] * me[ 0 ] - me[ 2 ] * me[ 8 ];
  2699. te[ 5 ] = - me[ 6 ] * me[ 0 ] + me[ 2 ] * me[ 4 ];
  2700. te[ 6 ] = me[ 9 ] * me[ 4 ] - me[ 5 ] * me[ 8 ];
  2701. te[ 7 ] = - me[ 9 ] * me[ 0 ] + me[ 1 ] * me[ 8 ];
  2702. te[ 8 ] = me[ 5 ] * me[ 0 ] - me[ 1 ] * me[ 4 ];
  2703. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ];
  2704. // no inverse
  2705. if ( det === 0 ) {
  2706. var msg = "THREE.Matrix3.getInverse(): can't invert matrix, determinant is 0";
  2707. if ( throwOnDegenerate || false ) {
  2708. throw new Error( msg );
  2709. } else {
  2710. console.warn( msg );
  2711. }
  2712. this.identity();
  2713. return this;
  2714. }
  2715. this.multiplyScalar( 1.0 / det );
  2716. return this;
  2717. },
  2718. transpose: function () {
  2719. var tmp, m = this.elements;
  2720. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  2721. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  2722. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  2723. return this;
  2724. },
  2725. flattenToArrayOffset: function ( array, offset ) {
  2726. var te = this.elements;
  2727. array[ offset ] = te[ 0 ];
  2728. array[ offset + 1 ] = te[ 1 ];
  2729. array[ offset + 2 ] = te[ 2 ];
  2730. array[ offset + 3 ] = te[ 3 ];
  2731. array[ offset + 4 ] = te[ 4 ];
  2732. array[ offset + 5 ] = te[ 5 ];
  2733. array[ offset + 6 ] = te[ 6 ];
  2734. array[ offset + 7 ] = te[ 7 ];
  2735. array[ offset + 8 ] = te[ 8 ];
  2736. return array;
  2737. },
  2738. getNormalMatrix: function ( m ) {
  2739. // input: THREE.Matrix4
  2740. this.getInverse( m ).transpose();
  2741. return this;
  2742. },
  2743. transposeIntoArray: function ( r ) {
  2744. var m = this.elements;
  2745. r[ 0 ] = m[ 0 ];
  2746. r[ 1 ] = m[ 3 ];
  2747. r[ 2 ] = m[ 6 ];
  2748. r[ 3 ] = m[ 1 ];
  2749. r[ 4 ] = m[ 4 ];
  2750. r[ 5 ] = m[ 7 ];
  2751. r[ 6 ] = m[ 2 ];
  2752. r[ 7 ] = m[ 5 ];
  2753. r[ 8 ] = m[ 8 ];
  2754. return this;
  2755. },
  2756. fromArray: function ( array ) {
  2757. this.elements.set( array );
  2758. return this;
  2759. },
  2760. toArray: function () {
  2761. var te = this.elements;
  2762. return [
  2763. te[ 0 ], te[ 1 ], te[ 2 ],
  2764. te[ 3 ], te[ 4 ], te[ 5 ],
  2765. te[ 6 ], te[ 7 ], te[ 8 ]
  2766. ];
  2767. }
  2768. };
  2769. // File:src/math/Matrix4.js
  2770. /**
  2771. * @author mrdoob / http://mrdoob.com/
  2772. * @author supereggbert / http://www.paulbrunt.co.uk/
  2773. * @author philogb / http://blog.thejit.org/
  2774. * @author jordi_ros / http://plattsoft.com
  2775. * @author D1plo1d / http://github.com/D1plo1d
  2776. * @author alteredq / http://alteredqualia.com/
  2777. * @author mikael emtinger / http://gomo.se/
  2778. * @author timknip / http://www.floorplanner.com/
  2779. * @author bhouston / http://clara.io
  2780. * @author WestLangley / http://github.com/WestLangley
  2781. */
  2782. THREE.Matrix4 = function () {
  2783. this.elements = new Float32Array( [
  2784. 1, 0, 0, 0,
  2785. 0, 1, 0, 0,
  2786. 0, 0, 1, 0,
  2787. 0, 0, 0, 1
  2788. ] );
  2789. if ( arguments.length > 0 ) {
  2790. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  2791. }
  2792. };
  2793. THREE.Matrix4.prototype = {
  2794. constructor: THREE.Matrix4,
  2795. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2796. var te = this.elements;
  2797. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  2798. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  2799. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  2800. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  2801. return this;
  2802. },
  2803. identity: function () {
  2804. this.set(
  2805. 1, 0, 0, 0,
  2806. 0, 1, 0, 0,
  2807. 0, 0, 1, 0,
  2808. 0, 0, 0, 1
  2809. );
  2810. return this;
  2811. },
  2812. clone: function () {
  2813. return new THREE.Matrix4().fromArray( this.elements );
  2814. },
  2815. copy: function ( m ) {
  2816. this.elements.set( m.elements );
  2817. return this;
  2818. },
  2819. copyPosition: function ( m ) {
  2820. var te = this.elements;
  2821. var me = m.elements;
  2822. te[ 12 ] = me[ 12 ];
  2823. te[ 13 ] = me[ 13 ];
  2824. te[ 14 ] = me[ 14 ];
  2825. return this;
  2826. },
  2827. extractBasis: function ( xAxis, yAxis, zAxis ) {
  2828. var te = this.elements;
  2829. xAxis.set( te[ 0 ], te[ 1 ], te[ 2 ] );
  2830. yAxis.set( te[ 4 ], te[ 5 ], te[ 6 ] );
  2831. zAxis.set( te[ 8 ], te[ 9 ], te[ 10 ] );
  2832. return this;
  2833. },
  2834. makeBasis: function ( xAxis, yAxis, zAxis ) {
  2835. this.set(
  2836. xAxis.x, yAxis.x, zAxis.x, 0,
  2837. xAxis.y, yAxis.y, zAxis.y, 0,
  2838. xAxis.z, yAxis.z, zAxis.z, 0,
  2839. 0, 0, 0, 1
  2840. );
  2841. return this;
  2842. },
  2843. extractRotation: function () {
  2844. var v1;
  2845. return function ( m ) {
  2846. if ( v1 === undefined ) v1 = new THREE.Vector3();
  2847. var te = this.elements;
  2848. var me = m.elements;
  2849. var scaleX = 1 / v1.set( me[ 0 ], me[ 1 ], me[ 2 ] ).length();
  2850. var scaleY = 1 / v1.set( me[ 4 ], me[ 5 ], me[ 6 ] ).length();
  2851. var scaleZ = 1 / v1.set( me[ 8 ], me[ 9 ], me[ 10 ] ).length();
  2852. te[ 0 ] = me[ 0 ] * scaleX;
  2853. te[ 1 ] = me[ 1 ] * scaleX;
  2854. te[ 2 ] = me[ 2 ] * scaleX;
  2855. te[ 4 ] = me[ 4 ] * scaleY;
  2856. te[ 5 ] = me[ 5 ] * scaleY;
  2857. te[ 6 ] = me[ 6 ] * scaleY;
  2858. te[ 8 ] = me[ 8 ] * scaleZ;
  2859. te[ 9 ] = me[ 9 ] * scaleZ;
  2860. te[ 10 ] = me[ 10 ] * scaleZ;
  2861. return this;
  2862. };
  2863. }(),
  2864. makeRotationFromEuler: function ( euler ) {
  2865. if ( euler instanceof THREE.Euler === false ) {
  2866. console.error( 'THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  2867. }
  2868. var te = this.elements;
  2869. var x = euler.x, y = euler.y, z = euler.z;
  2870. var a = Math.cos( x ), b = Math.sin( x );
  2871. var c = Math.cos( y ), d = Math.sin( y );
  2872. var e = Math.cos( z ), f = Math.sin( z );
  2873. if ( euler.order === 'XYZ' ) {
  2874. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2875. te[ 0 ] = c * e;
  2876. te[ 4 ] = - c * f;
  2877. te[ 8 ] = d;
  2878. te[ 1 ] = af + be * d;
  2879. te[ 5 ] = ae - bf * d;
  2880. te[ 9 ] = - b * c;
  2881. te[ 2 ] = bf - ae * d;
  2882. te[ 6 ] = be + af * d;
  2883. te[ 10 ] = a * c;
  2884. } else if ( euler.order === 'YXZ' ) {
  2885. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2886. te[ 0 ] = ce + df * b;
  2887. te[ 4 ] = de * b - cf;
  2888. te[ 8 ] = a * d;
  2889. te[ 1 ] = a * f;
  2890. te[ 5 ] = a * e;
  2891. te[ 9 ] = - b;
  2892. te[ 2 ] = cf * b - de;
  2893. te[ 6 ] = df + ce * b;
  2894. te[ 10 ] = a * c;
  2895. } else if ( euler.order === 'ZXY' ) {
  2896. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2897. te[ 0 ] = ce - df * b;
  2898. te[ 4 ] = - a * f;
  2899. te[ 8 ] = de + cf * b;
  2900. te[ 1 ] = cf + de * b;
  2901. te[ 5 ] = a * e;
  2902. te[ 9 ] = df - ce * b;
  2903. te[ 2 ] = - a * d;
  2904. te[ 6 ] = b;
  2905. te[ 10 ] = a * c;
  2906. } else if ( euler.order === 'ZYX' ) {
  2907. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2908. te[ 0 ] = c * e;
  2909. te[ 4 ] = be * d - af;
  2910. te[ 8 ] = ae * d + bf;
  2911. te[ 1 ] = c * f;
  2912. te[ 5 ] = bf * d + ae;
  2913. te[ 9 ] = af * d - be;
  2914. te[ 2 ] = - d;
  2915. te[ 6 ] = b * c;
  2916. te[ 10 ] = a * c;
  2917. } else if ( euler.order === 'YZX' ) {
  2918. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2919. te[ 0 ] = c * e;
  2920. te[ 4 ] = bd - ac * f;
  2921. te[ 8 ] = bc * f + ad;
  2922. te[ 1 ] = f;
  2923. te[ 5 ] = a * e;
  2924. te[ 9 ] = - b * e;
  2925. te[ 2 ] = - d * e;
  2926. te[ 6 ] = ad * f + bc;
  2927. te[ 10 ] = ac - bd * f;
  2928. } else if ( euler.order === 'XZY' ) {
  2929. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2930. te[ 0 ] = c * e;
  2931. te[ 4 ] = - f;
  2932. te[ 8 ] = d * e;
  2933. te[ 1 ] = ac * f + bd;
  2934. te[ 5 ] = a * e;
  2935. te[ 9 ] = ad * f - bc;
  2936. te[ 2 ] = bc * f - ad;
  2937. te[ 6 ] = b * e;
  2938. te[ 10 ] = bd * f + ac;
  2939. }
  2940. // last column
  2941. te[ 3 ] = 0;
  2942. te[ 7 ] = 0;
  2943. te[ 11 ] = 0;
  2944. // bottom row
  2945. te[ 12 ] = 0;
  2946. te[ 13 ] = 0;
  2947. te[ 14 ] = 0;
  2948. te[ 15 ] = 1;
  2949. return this;
  2950. },
  2951. makeRotationFromQuaternion: function ( q ) {
  2952. var te = this.elements;
  2953. var x = q.x, y = q.y, z = q.z, w = q.w;
  2954. var x2 = x + x, y2 = y + y, z2 = z + z;
  2955. var xx = x * x2, xy = x * y2, xz = x * z2;
  2956. var yy = y * y2, yz = y * z2, zz = z * z2;
  2957. var wx = w * x2, wy = w * y2, wz = w * z2;
  2958. te[ 0 ] = 1 - ( yy + zz );
  2959. te[ 4 ] = xy - wz;
  2960. te[ 8 ] = xz + wy;
  2961. te[ 1 ] = xy + wz;
  2962. te[ 5 ] = 1 - ( xx + zz );
  2963. te[ 9 ] = yz - wx;
  2964. te[ 2 ] = xz - wy;
  2965. te[ 6 ] = yz + wx;
  2966. te[ 10 ] = 1 - ( xx + yy );
  2967. // last column
  2968. te[ 3 ] = 0;
  2969. te[ 7 ] = 0;
  2970. te[ 11 ] = 0;
  2971. // bottom row
  2972. te[ 12 ] = 0;
  2973. te[ 13 ] = 0;
  2974. te[ 14 ] = 0;
  2975. te[ 15 ] = 1;
  2976. return this;
  2977. },
  2978. lookAt: function () {
  2979. var x, y, z;
  2980. return function ( eye, target, up ) {
  2981. if ( x === undefined ) x = new THREE.Vector3();
  2982. if ( y === undefined ) y = new THREE.Vector3();
  2983. if ( z === undefined ) z = new THREE.Vector3();
  2984. var te = this.elements;
  2985. z.subVectors( eye, target ).normalize();
  2986. if ( z.lengthSq() === 0 ) {
  2987. z.z = 1;
  2988. }
  2989. x.crossVectors( up, z ).normalize();
  2990. if ( x.lengthSq() === 0 ) {
  2991. z.x += 0.0001;
  2992. x.crossVectors( up, z ).normalize();
  2993. }
  2994. y.crossVectors( z, x );
  2995. te[ 0 ] = x.x; te[ 4 ] = y.x; te[ 8 ] = z.x;
  2996. te[ 1 ] = x.y; te[ 5 ] = y.y; te[ 9 ] = z.y;
  2997. te[ 2 ] = x.z; te[ 6 ] = y.z; te[ 10 ] = z.z;
  2998. return this;
  2999. };
  3000. }(),
  3001. multiply: function ( m, n ) {
  3002. if ( n !== undefined ) {
  3003. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  3004. return this.multiplyMatrices( m, n );
  3005. }
  3006. return this.multiplyMatrices( this, m );
  3007. },
  3008. multiplyMatrices: function ( a, b ) {
  3009. var ae = a.elements;
  3010. var be = b.elements;
  3011. var te = this.elements;
  3012. var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  3013. var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  3014. var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  3015. var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  3016. var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  3017. var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  3018. var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  3019. var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  3020. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3021. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3022. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3023. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3024. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3025. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3026. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3027. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3028. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3029. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3030. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3031. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3032. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3033. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3034. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3035. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3036. return this;
  3037. },
  3038. multiplyToArray: function ( a, b, r ) {
  3039. var te = this.elements;
  3040. this.multiplyMatrices( a, b );
  3041. r[ 0 ] = te[ 0 ]; r[ 1 ] = te[ 1 ]; r[ 2 ] = te[ 2 ]; r[ 3 ] = te[ 3 ];
  3042. r[ 4 ] = te[ 4 ]; r[ 5 ] = te[ 5 ]; r[ 6 ] = te[ 6 ]; r[ 7 ] = te[ 7 ];
  3043. r[ 8 ] = te[ 8 ]; r[ 9 ] = te[ 9 ]; r[ 10 ] = te[ 10 ]; r[ 11 ] = te[ 11 ];
  3044. r[ 12 ] = te[ 12 ]; r[ 13 ] = te[ 13 ]; r[ 14 ] = te[ 14 ]; r[ 15 ] = te[ 15 ];
  3045. return this;
  3046. },
  3047. multiplyScalar: function ( s ) {
  3048. var te = this.elements;
  3049. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  3050. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  3051. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  3052. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  3053. return this;
  3054. },
  3055. applyToVector3Array: function () {
  3056. var v1;
  3057. return function ( array, offset, length ) {
  3058. if ( v1 === undefined ) v1 = new THREE.Vector3();
  3059. if ( offset === undefined ) offset = 0;
  3060. if ( length === undefined ) length = array.length;
  3061. for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) {
  3062. v1.fromArray( array, j );
  3063. v1.applyMatrix4( this );
  3064. v1.toArray( array, j );
  3065. }
  3066. return array;
  3067. };
  3068. }(),
  3069. applyToBuffer: function () {
  3070. var v1;
  3071. return function applyToBuffer( buffer, offset, length ) {
  3072. if ( v1 === undefined ) v1 = new THREE.Vector3();
  3073. if ( offset === undefined ) offset = 0;
  3074. if ( length === undefined ) length = buffer.length / buffer.itemSize;
  3075. for ( var i = 0, j = offset; i < length; i ++, j ++ ) {
  3076. v1.x = buffer.getX( j );
  3077. v1.y = buffer.getY( j );
  3078. v1.z = buffer.getZ( j );
  3079. v1.applyMatrix4( this );
  3080. buffer.setXYZ( v1.x, v1.y, v1.z );
  3081. }
  3082. return buffer;
  3083. };
  3084. }(),
  3085. determinant: function () {
  3086. var te = this.elements;
  3087. var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  3088. var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  3089. var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  3090. var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  3091. //TODO: make this more efficient
  3092. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3093. return (
  3094. n41 * (
  3095. + n14 * n23 * n32
  3096. - n13 * n24 * n32
  3097. - n14 * n22 * n33
  3098. + n12 * n24 * n33
  3099. + n13 * n22 * n34
  3100. - n12 * n23 * n34
  3101. ) +
  3102. n42 * (
  3103. + n11 * n23 * n34
  3104. - n11 * n24 * n33
  3105. + n14 * n21 * n33
  3106. - n13 * n21 * n34
  3107. + n13 * n24 * n31
  3108. - n14 * n23 * n31
  3109. ) +
  3110. n43 * (
  3111. + n11 * n24 * n32
  3112. - n11 * n22 * n34
  3113. - n14 * n21 * n32
  3114. + n12 * n21 * n34
  3115. + n14 * n22 * n31
  3116. - n12 * n24 * n31
  3117. ) +
  3118. n44 * (
  3119. - n13 * n22 * n31
  3120. - n11 * n23 * n32
  3121. + n11 * n22 * n33
  3122. + n13 * n21 * n32
  3123. - n12 * n21 * n33
  3124. + n12 * n23 * n31
  3125. )
  3126. );
  3127. },
  3128. transpose: function () {
  3129. var te = this.elements;
  3130. var tmp;
  3131. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  3132. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  3133. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  3134. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  3135. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  3136. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  3137. return this;
  3138. },
  3139. flattenToArrayOffset: function ( array, offset ) {
  3140. var te = this.elements;
  3141. array[ offset ] = te[ 0 ];
  3142. array[ offset + 1 ] = te[ 1 ];
  3143. array[ offset + 2 ] = te[ 2 ];
  3144. array[ offset + 3 ] = te[ 3 ];
  3145. array[ offset + 4 ] = te[ 4 ];
  3146. array[ offset + 5 ] = te[ 5 ];
  3147. array[ offset + 6 ] = te[ 6 ];
  3148. array[ offset + 7 ] = te[ 7 ];
  3149. array[ offset + 8 ] = te[ 8 ];
  3150. array[ offset + 9 ] = te[ 9 ];
  3151. array[ offset + 10 ] = te[ 10 ];
  3152. array[ offset + 11 ] = te[ 11 ];
  3153. array[ offset + 12 ] = te[ 12 ];
  3154. array[ offset + 13 ] = te[ 13 ];
  3155. array[ offset + 14 ] = te[ 14 ];
  3156. array[ offset + 15 ] = te[ 15 ];
  3157. return array;
  3158. },
  3159. getPosition: function () {
  3160. var v1;
  3161. return function () {
  3162. if ( v1 === undefined ) v1 = new THREE.Vector3();
  3163. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  3164. var te = this.elements;
  3165. return v1.set( te[ 12 ], te[ 13 ], te[ 14 ] );
  3166. };
  3167. }(),
  3168. setPosition: function ( v ) {
  3169. var te = this.elements;
  3170. te[ 12 ] = v.x;
  3171. te[ 13 ] = v.y;
  3172. te[ 14 ] = v.z;
  3173. return this;
  3174. },
  3175. getInverse: function ( m, throwOnInvertible ) {
  3176. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3177. var te = this.elements;
  3178. var me = m.elements;
  3179. var n11 = me[ 0 ], n12 = me[ 4 ], n13 = me[ 8 ], n14 = me[ 12 ];
  3180. var n21 = me[ 1 ], n22 = me[ 5 ], n23 = me[ 9 ], n24 = me[ 13 ];
  3181. var n31 = me[ 2 ], n32 = me[ 6 ], n33 = me[ 10 ], n34 = me[ 14 ];
  3182. var n41 = me[ 3 ], n42 = me[ 7 ], n43 = me[ 11 ], n44 = me[ 15 ];
  3183. te[ 0 ] = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44;
  3184. te[ 4 ] = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44;
  3185. te[ 8 ] = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44;
  3186. te[ 12 ] = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3187. te[ 1 ] = n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44;
  3188. te[ 5 ] = n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44;
  3189. te[ 9 ] = n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44;
  3190. te[ 13 ] = n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34;
  3191. te[ 2 ] = n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44;
  3192. te[ 6 ] = n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44;
  3193. te[ 10 ] = n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44;
  3194. te[ 14 ] = n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34;
  3195. te[ 3 ] = n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43;
  3196. te[ 7 ] = n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43;
  3197. te[ 11 ] = n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43;
  3198. te[ 15 ] = n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33;
  3199. var det = n11 * te[ 0 ] + n21 * te[ 4 ] + n31 * te[ 8 ] + n41 * te[ 12 ];
  3200. if ( det === 0 ) {
  3201. var msg = "THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0";
  3202. if ( throwOnInvertible || false ) {
  3203. throw new Error( msg );
  3204. } else {
  3205. console.warn( msg );
  3206. }
  3207. this.identity();
  3208. return this;
  3209. }
  3210. this.multiplyScalar( 1 / det );
  3211. return this;
  3212. },
  3213. scale: function ( v ) {
  3214. var te = this.elements;
  3215. var x = v.x, y = v.y, z = v.z;
  3216. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  3217. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  3218. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  3219. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  3220. return this;
  3221. },
  3222. getMaxScaleOnAxis: function () {
  3223. var te = this.elements;
  3224. var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  3225. var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  3226. var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  3227. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  3228. },
  3229. makeTranslation: function ( x, y, z ) {
  3230. this.set(
  3231. 1, 0, 0, x,
  3232. 0, 1, 0, y,
  3233. 0, 0, 1, z,
  3234. 0, 0, 0, 1
  3235. );
  3236. return this;
  3237. },
  3238. makeRotationX: function ( theta ) {
  3239. var c = Math.cos( theta ), s = Math.sin( theta );
  3240. this.set(
  3241. 1, 0, 0, 0,
  3242. 0, c, - s, 0,
  3243. 0, s, c, 0,
  3244. 0, 0, 0, 1
  3245. );
  3246. return this;
  3247. },
  3248. makeRotationY: function ( theta ) {
  3249. var c = Math.cos( theta ), s = Math.sin( theta );
  3250. this.set(
  3251. c, 0, s, 0,
  3252. 0, 1, 0, 0,
  3253. - s, 0, c, 0,
  3254. 0, 0, 0, 1
  3255. );
  3256. return this;
  3257. },
  3258. makeRotationZ: function ( theta ) {
  3259. var c = Math.cos( theta ), s = Math.sin( theta );
  3260. this.set(
  3261. c, - s, 0, 0,
  3262. s, c, 0, 0,
  3263. 0, 0, 1, 0,
  3264. 0, 0, 0, 1
  3265. );
  3266. return this;
  3267. },
  3268. makeRotationAxis: function ( axis, angle ) {
  3269. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3270. var c = Math.cos( angle );
  3271. var s = Math.sin( angle );
  3272. var t = 1 - c;
  3273. var x = axis.x, y = axis.y, z = axis.z;
  3274. var tx = t * x, ty = t * y;
  3275. this.set(
  3276. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  3277. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3278. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3279. 0, 0, 0, 1
  3280. );
  3281. return this;
  3282. },
  3283. makeScale: function ( x, y, z ) {
  3284. this.set(
  3285. x, 0, 0, 0,
  3286. 0, y, 0, 0,
  3287. 0, 0, z, 0,
  3288. 0, 0, 0, 1
  3289. );
  3290. return this;
  3291. },
  3292. compose: function ( position, quaternion, scale ) {
  3293. this.makeRotationFromQuaternion( quaternion );
  3294. this.scale( scale );
  3295. this.setPosition( position );
  3296. return this;
  3297. },
  3298. decompose: function () {
  3299. var vector, matrix;
  3300. return function ( position, quaternion, scale ) {
  3301. if ( vector === undefined ) vector = new THREE.Vector3();
  3302. if ( matrix === undefined ) matrix = new THREE.Matrix4();
  3303. var te = this.elements;
  3304. var sx = vector.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  3305. var sy = vector.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  3306. var sz = vector.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  3307. // if determine is negative, we need to invert one scale
  3308. var det = this.determinant();
  3309. if ( det < 0 ) {
  3310. sx = - sx;
  3311. }
  3312. position.x = te[ 12 ];
  3313. position.y = te[ 13 ];
  3314. position.z = te[ 14 ];
  3315. // scale the rotation part
  3316. matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy()
  3317. var invSX = 1 / sx;
  3318. var invSY = 1 / sy;
  3319. var invSZ = 1 / sz;
  3320. matrix.elements[ 0 ] *= invSX;
  3321. matrix.elements[ 1 ] *= invSX;
  3322. matrix.elements[ 2 ] *= invSX;
  3323. matrix.elements[ 4 ] *= invSY;
  3324. matrix.elements[ 5 ] *= invSY;
  3325. matrix.elements[ 6 ] *= invSY;
  3326. matrix.elements[ 8 ] *= invSZ;
  3327. matrix.elements[ 9 ] *= invSZ;
  3328. matrix.elements[ 10 ] *= invSZ;
  3329. quaternion.setFromRotationMatrix( matrix );
  3330. scale.x = sx;
  3331. scale.y = sy;
  3332. scale.z = sz;
  3333. return this;
  3334. };
  3335. }(),
  3336. makeFrustum: function ( left, right, bottom, top, near, far ) {
  3337. var te = this.elements;
  3338. var x = 2 * near / ( right - left );
  3339. var y = 2 * near / ( top - bottom );
  3340. var a = ( right + left ) / ( right - left );
  3341. var b = ( top + bottom ) / ( top - bottom );
  3342. var c = - ( far + near ) / ( far - near );
  3343. var d = - 2 * far * near / ( far - near );
  3344. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  3345. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  3346. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  3347. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  3348. return this;
  3349. },
  3350. makePerspective: function ( fov, aspect, near, far ) {
  3351. var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) );
  3352. var ymin = - ymax;
  3353. var xmin = ymin * aspect;
  3354. var xmax = ymax * aspect;
  3355. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  3356. },
  3357. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  3358. var te = this.elements;
  3359. var w = right - left;
  3360. var h = top - bottom;
  3361. var p = far - near;
  3362. var x = ( right + left ) / w;
  3363. var y = ( top + bottom ) / h;
  3364. var z = ( far + near ) / p;
  3365. te[ 0 ] = 2 / w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  3366. te[ 1 ] = 0; te[ 5 ] = 2 / h; te[ 9 ] = 0; te[ 13 ] = - y;
  3367. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 / p; te[ 14 ] = - z;
  3368. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  3369. return this;
  3370. },
  3371. equals: function ( matrix ) {
  3372. var te = this.elements;
  3373. var me = matrix.elements;
  3374. for ( var i = 0; i < 16; i ++ ) {
  3375. if ( te[ i ] !== me[ i ] ) return false;
  3376. }
  3377. return true;
  3378. },
  3379. fromArray: function ( array ) {
  3380. this.elements.set( array );
  3381. return this;
  3382. },
  3383. toArray: function () {
  3384. var te = this.elements;
  3385. return [
  3386. te[ 0 ], te[ 1 ], te[ 2 ], te[ 3 ],
  3387. te[ 4 ], te[ 5 ], te[ 6 ], te[ 7 ],
  3388. te[ 8 ], te[ 9 ], te[ 10 ], te[ 11 ],
  3389. te[ 12 ], te[ 13 ], te[ 14 ], te[ 15 ]
  3390. ];
  3391. }
  3392. };
  3393. // File:src/math/Ray.js
  3394. /**
  3395. * @author bhouston / http://clara.io
  3396. */
  3397. THREE.Ray = function ( origin, direction ) {
  3398. this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3();
  3399. this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3();
  3400. };
  3401. THREE.Ray.prototype = {
  3402. constructor: THREE.Ray,
  3403. set: function ( origin, direction ) {
  3404. this.origin.copy( origin );
  3405. this.direction.copy( direction );
  3406. return this;
  3407. },
  3408. clone: function () {
  3409. return new this.constructor().copy( this );
  3410. },
  3411. copy: function ( ray ) {
  3412. this.origin.copy( ray.origin );
  3413. this.direction.copy( ray.direction );
  3414. return this;
  3415. },
  3416. at: function ( t, optionalTarget ) {
  3417. var result = optionalTarget || new THREE.Vector3();
  3418. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  3419. },
  3420. recast: function () {
  3421. var v1 = new THREE.Vector3();
  3422. return function ( t ) {
  3423. this.origin.copy( this.at( t, v1 ) );
  3424. return this;
  3425. };
  3426. }(),
  3427. closestPointToPoint: function ( point, optionalTarget ) {
  3428. var result = optionalTarget || new THREE.Vector3();
  3429. result.subVectors( point, this.origin );
  3430. var directionDistance = result.dot( this.direction );
  3431. if ( directionDistance < 0 ) {
  3432. return result.copy( this.origin );
  3433. }
  3434. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3435. },
  3436. distanceToPoint: function ( point ) {
  3437. return Math.sqrt( this.distanceSqToPoint( point ) );
  3438. },
  3439. distanceSqToPoint: function () {
  3440. var v1 = new THREE.Vector3();
  3441. return function ( point ) {
  3442. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  3443. // point behind the ray
  3444. if ( directionDistance < 0 ) {
  3445. return this.origin.distanceToSquared( point );
  3446. }
  3447. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3448. return v1.distanceToSquared( point );
  3449. };
  3450. }(),
  3451. distanceSqToSegment: function () {
  3452. var segCenter = new THREE.Vector3();
  3453. var segDir = new THREE.Vector3();
  3454. var diff = new THREE.Vector3();
  3455. return function ( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3456. // from http://www.geometrictools.com/LibMathematics/Distance/Wm5DistRay3Segment3.cpp
  3457. // It returns the min distance between the ray and the segment
  3458. // defined by v0 and v1
  3459. // It can also set two optional targets :
  3460. // - The closest point on the ray
  3461. // - The closest point on the segment
  3462. segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3463. segDir.copy( v1 ).sub( v0 ).normalize();
  3464. diff.copy( this.origin ).sub( segCenter );
  3465. var segExtent = v0.distanceTo( v1 ) * 0.5;
  3466. var a01 = - this.direction.dot( segDir );
  3467. var b0 = diff.dot( this.direction );
  3468. var b1 = - diff.dot( segDir );
  3469. var c = diff.lengthSq();
  3470. var det = Math.abs( 1 - a01 * a01 );
  3471. var s0, s1, sqrDist, extDet;
  3472. if ( det > 0 ) {
  3473. // The ray and segment are not parallel.
  3474. s0 = a01 * b1 - b0;
  3475. s1 = a01 * b0 - b1;
  3476. extDet = segExtent * det;
  3477. if ( s0 >= 0 ) {
  3478. if ( s1 >= - extDet ) {
  3479. if ( s1 <= extDet ) {
  3480. // region 0
  3481. // Minimum at interior points of ray and segment.
  3482. var invDet = 1 / det;
  3483. s0 *= invDet;
  3484. s1 *= invDet;
  3485. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3486. } else {
  3487. // region 1
  3488. s1 = segExtent;
  3489. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3490. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3491. }
  3492. } else {
  3493. // region 5
  3494. s1 = - segExtent;
  3495. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3496. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3497. }
  3498. } else {
  3499. if ( s1 <= - extDet ) {
  3500. // region 4
  3501. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3502. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3503. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3504. } else if ( s1 <= extDet ) {
  3505. // region 3
  3506. s0 = 0;
  3507. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3508. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3509. } else {
  3510. // region 2
  3511. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3512. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3513. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3514. }
  3515. }
  3516. } else {
  3517. // Ray and segment are parallel.
  3518. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3519. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3520. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3521. }
  3522. if ( optionalPointOnRay ) {
  3523. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  3524. }
  3525. if ( optionalPointOnSegment ) {
  3526. optionalPointOnSegment.copy( segDir ).multiplyScalar( s1 ).add( segCenter );
  3527. }
  3528. return sqrDist;
  3529. };
  3530. }(),
  3531. intersectSphere: function () {
  3532. var v1 = new THREE.Vector3();
  3533. return function ( sphere, optionalTarget ) {
  3534. v1.subVectors( sphere.center, this.origin );
  3535. var tca = v1.dot( this.direction );
  3536. var d2 = v1.dot( v1 ) - tca * tca;
  3537. var radius2 = sphere.radius * sphere.radius;
  3538. if ( d2 > radius2 ) return null;
  3539. var thc = Math.sqrt( radius2 - d2 );
  3540. // t0 = first intersect point - entrance on front of sphere
  3541. var t0 = tca - thc;
  3542. // t1 = second intersect point - exit point on back of sphere
  3543. var t1 = tca + thc;
  3544. // test to see if both t0 and t1 are behind the ray - if so, return null
  3545. if ( t0 < 0 && t1 < 0 ) return null;
  3546. // test to see if t0 is behind the ray:
  3547. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3548. // in order to always return an intersect point that is in front of the ray.
  3549. if ( t0 < 0 ) return this.at( t1, optionalTarget );
  3550. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3551. return this.at( t0, optionalTarget );
  3552. }
  3553. }(),
  3554. intersectsSphere: function ( sphere ) {
  3555. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  3556. },
  3557. distanceToPlane: function ( plane ) {
  3558. var denominator = plane.normal.dot( this.direction );
  3559. if ( denominator === 0 ) {
  3560. // line is coplanar, return origin
  3561. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3562. return 0;
  3563. }
  3564. // Null is preferable to undefined since undefined means.... it is undefined
  3565. return null;
  3566. }
  3567. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3568. // Return if the ray never intersects the plane
  3569. return t >= 0 ? t : null;
  3570. },
  3571. intersectPlane: function ( plane, optionalTarget ) {
  3572. var t = this.distanceToPlane( plane );
  3573. if ( t === null ) {
  3574. return null;
  3575. }
  3576. return this.at( t, optionalTarget );
  3577. },
  3578. intersectsPlane: function ( plane ) {
  3579. // check if the ray lies on the plane first
  3580. var distToPoint = plane.distanceToPoint( this.origin );
  3581. if ( distToPoint === 0 ) {
  3582. return true;
  3583. }
  3584. var denominator = plane.normal.dot( this.direction );
  3585. if ( denominator * distToPoint < 0 ) {
  3586. return true;
  3587. }
  3588. // ray origin is behind the plane (and is pointing behind it)
  3589. return false;
  3590. },
  3591. intersectBox: function ( box, optionalTarget ) {
  3592. var tmin, tmax, tymin, tymax, tzmin, tzmax;
  3593. var invdirx = 1 / this.direction.x,
  3594. invdiry = 1 / this.direction.y,
  3595. invdirz = 1 / this.direction.z;
  3596. var origin = this.origin;
  3597. if ( invdirx >= 0 ) {
  3598. tmin = ( box.min.x - origin.x ) * invdirx;
  3599. tmax = ( box.max.x - origin.x ) * invdirx;
  3600. } else {
  3601. tmin = ( box.max.x - origin.x ) * invdirx;
  3602. tmax = ( box.min.x - origin.x ) * invdirx;
  3603. }
  3604. if ( invdiry >= 0 ) {
  3605. tymin = ( box.min.y - origin.y ) * invdiry;
  3606. tymax = ( box.max.y - origin.y ) * invdiry;
  3607. } else {
  3608. tymin = ( box.max.y - origin.y ) * invdiry;
  3609. tymax = ( box.min.y - origin.y ) * invdiry;
  3610. }
  3611. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3612. // These lines also handle the case where tmin or tmax is NaN
  3613. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3614. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  3615. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  3616. if ( invdirz >= 0 ) {
  3617. tzmin = ( box.min.z - origin.z ) * invdirz;
  3618. tzmax = ( box.max.z - origin.z ) * invdirz;
  3619. } else {
  3620. tzmin = ( box.max.z - origin.z ) * invdirz;
  3621. tzmax = ( box.min.z - origin.z ) * invdirz;
  3622. }
  3623. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3624. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3625. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3626. //return point closest to the ray (positive side)
  3627. if ( tmax < 0 ) return null;
  3628. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  3629. },
  3630. intersectsBox: ( function () {
  3631. var v = new THREE.Vector3();
  3632. return function ( box ) {
  3633. return this.intersectBox( box, v ) !== null;
  3634. };
  3635. } )(),
  3636. intersectTriangle: function () {
  3637. // Compute the offset origin, edges, and normal.
  3638. var diff = new THREE.Vector3();
  3639. var edge1 = new THREE.Vector3();
  3640. var edge2 = new THREE.Vector3();
  3641. var normal = new THREE.Vector3();
  3642. return function ( a, b, c, backfaceCulling, optionalTarget ) {
  3643. // from http://www.geometrictools.com/LibMathematics/Intersection/Wm5IntrRay3Triangle3.cpp
  3644. edge1.subVectors( b, a );
  3645. edge2.subVectors( c, a );
  3646. normal.crossVectors( edge1, edge2 );
  3647. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3648. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3649. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3650. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3651. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3652. var DdN = this.direction.dot( normal );
  3653. var sign;
  3654. if ( DdN > 0 ) {
  3655. if ( backfaceCulling ) return null;
  3656. sign = 1;
  3657. } else if ( DdN < 0 ) {
  3658. sign = - 1;
  3659. DdN = - DdN;
  3660. } else {
  3661. return null;
  3662. }
  3663. diff.subVectors( this.origin, a );
  3664. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  3665. // b1 < 0, no intersection
  3666. if ( DdQxE2 < 0 ) {
  3667. return null;
  3668. }
  3669. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  3670. // b2 < 0, no intersection
  3671. if ( DdE1xQ < 0 ) {
  3672. return null;
  3673. }
  3674. // b1+b2 > 1, no intersection
  3675. if ( DdQxE2 + DdE1xQ > DdN ) {
  3676. return null;
  3677. }
  3678. // Line intersects triangle, check if ray does.
  3679. var QdN = - sign * diff.dot( normal );
  3680. // t < 0, no intersection
  3681. if ( QdN < 0 ) {
  3682. return null;
  3683. }
  3684. // Ray intersects triangle.
  3685. return this.at( QdN / DdN, optionalTarget );
  3686. };
  3687. }(),
  3688. applyMatrix4: function ( matrix4 ) {
  3689. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  3690. this.origin.applyMatrix4( matrix4 );
  3691. this.direction.sub( this.origin );
  3692. this.direction.normalize();
  3693. return this;
  3694. },
  3695. equals: function ( ray ) {
  3696. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3697. }
  3698. };
  3699. // File:src/math/Sphere.js
  3700. /**
  3701. * @author bhouston / http://clara.io
  3702. * @author mrdoob / http://mrdoob.com/
  3703. */
  3704. THREE.Sphere = function ( center, radius ) {
  3705. this.center = ( center !== undefined ) ? center : new THREE.Vector3();
  3706. this.radius = ( radius !== undefined ) ? radius : 0;
  3707. };
  3708. THREE.Sphere.prototype = {
  3709. constructor: THREE.Sphere,
  3710. set: function ( center, radius ) {
  3711. this.center.copy( center );
  3712. this.radius = radius;
  3713. return this;
  3714. },
  3715. setFromPoints: function () {
  3716. var box = new THREE.Box3();
  3717. return function ( points, optionalCenter ) {
  3718. var center = this.center;
  3719. if ( optionalCenter !== undefined ) {
  3720. center.copy( optionalCenter );
  3721. } else {
  3722. box.setFromPoints( points ).center( center );
  3723. }
  3724. var maxRadiusSq = 0;
  3725. for ( var i = 0, il = points.length; i < il; i ++ ) {
  3726. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3727. }
  3728. this.radius = Math.sqrt( maxRadiusSq );
  3729. return this;
  3730. };
  3731. }(),
  3732. clone: function () {
  3733. return new this.constructor().copy( this );
  3734. },
  3735. copy: function ( sphere ) {
  3736. this.center.copy( sphere.center );
  3737. this.radius = sphere.radius;
  3738. return this;
  3739. },
  3740. empty: function () {
  3741. return ( this.radius <= 0 );
  3742. },
  3743. containsPoint: function ( point ) {
  3744. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3745. },
  3746. distanceToPoint: function ( point ) {
  3747. return ( point.distanceTo( this.center ) - this.radius );
  3748. },
  3749. intersectsSphere: function ( sphere ) {
  3750. var radiusSum = this.radius + sphere.radius;
  3751. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3752. },
  3753. intersectsBox: function ( box ) {
  3754. return box.intersectsSphere( this );
  3755. },
  3756. intersectsPlane: function ( plane ) {
  3757. // We use the following equation to compute the signed distance from
  3758. // the center of the sphere to the plane.
  3759. //
  3760. // distance = q * n - d
  3761. //
  3762. // If this distance is greater than the radius of the sphere,
  3763. // then there is no intersection.
  3764. return Math.abs( this.center.dot( plane.normal ) - plane.constant ) <= this.radius;
  3765. },
  3766. clampPoint: function ( point, optionalTarget ) {
  3767. var deltaLengthSq = this.center.distanceToSquared( point );
  3768. var result = optionalTarget || new THREE.Vector3();
  3769. result.copy( point );
  3770. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3771. result.sub( this.center ).normalize();
  3772. result.multiplyScalar( this.radius ).add( this.center );
  3773. }
  3774. return result;
  3775. },
  3776. getBoundingBox: function ( optionalTarget ) {
  3777. var box = optionalTarget || new THREE.Box3();
  3778. box.set( this.center, this.center );
  3779. box.expandByScalar( this.radius );
  3780. return box;
  3781. },
  3782. applyMatrix4: function ( matrix ) {
  3783. this.center.applyMatrix4( matrix );
  3784. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3785. return this;
  3786. },
  3787. translate: function ( offset ) {
  3788. this.center.add( offset );
  3789. return this;
  3790. },
  3791. equals: function ( sphere ) {
  3792. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3793. }
  3794. };
  3795. // File:src/math/Frustum.js
  3796. /**
  3797. * @author mrdoob / http://mrdoob.com/
  3798. * @author alteredq / http://alteredqualia.com/
  3799. * @author bhouston / http://clara.io
  3800. */
  3801. THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) {
  3802. this.planes = [
  3803. ( p0 !== undefined ) ? p0 : new THREE.Plane(),
  3804. ( p1 !== undefined ) ? p1 : new THREE.Plane(),
  3805. ( p2 !== undefined ) ? p2 : new THREE.Plane(),
  3806. ( p3 !== undefined ) ? p3 : new THREE.Plane(),
  3807. ( p4 !== undefined ) ? p4 : new THREE.Plane(),
  3808. ( p5 !== undefined ) ? p5 : new THREE.Plane()
  3809. ];
  3810. };
  3811. THREE.Frustum.prototype = {
  3812. constructor: THREE.Frustum,
  3813. set: function ( p0, p1, p2, p3, p4, p5 ) {
  3814. var planes = this.planes;
  3815. planes[ 0 ].copy( p0 );
  3816. planes[ 1 ].copy( p1 );
  3817. planes[ 2 ].copy( p2 );
  3818. planes[ 3 ].copy( p3 );
  3819. planes[ 4 ].copy( p4 );
  3820. planes[ 5 ].copy( p5 );
  3821. return this;
  3822. },
  3823. clone: function () {
  3824. return new this.constructor().copy( this );
  3825. },
  3826. copy: function ( frustum ) {
  3827. var planes = this.planes;
  3828. for ( var i = 0; i < 6; i ++ ) {
  3829. planes[ i ].copy( frustum.planes[ i ] );
  3830. }
  3831. return this;
  3832. },
  3833. setFromMatrix: function ( m ) {
  3834. var planes = this.planes;
  3835. var me = m.elements;
  3836. var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  3837. var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  3838. var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  3839. var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  3840. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  3841. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  3842. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  3843. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  3844. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  3845. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  3846. return this;
  3847. },
  3848. intersectsObject: function () {
  3849. var sphere = new THREE.Sphere();
  3850. return function ( object ) {
  3851. var geometry = object.geometry;
  3852. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  3853. sphere.copy( geometry.boundingSphere );
  3854. sphere.applyMatrix4( object.matrixWorld );
  3855. return this.intersectsSphere( sphere );
  3856. };
  3857. }(),
  3858. intersectsSphere: function ( sphere ) {
  3859. var planes = this.planes;
  3860. var center = sphere.center;
  3861. var negRadius = - sphere.radius;
  3862. for ( var i = 0; i < 6; i ++ ) {
  3863. var distance = planes[ i ].distanceToPoint( center );
  3864. if ( distance < negRadius ) {
  3865. return false;
  3866. }
  3867. }
  3868. return true;
  3869. },
  3870. intersectsBox: function () {
  3871. var p1 = new THREE.Vector3(),
  3872. p2 = new THREE.Vector3();
  3873. return function ( box ) {
  3874. var planes = this.planes;
  3875. for ( var i = 0; i < 6 ; i ++ ) {
  3876. var plane = planes[ i ];
  3877. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  3878. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  3879. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  3880. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  3881. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  3882. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  3883. var d1 = plane.distanceToPoint( p1 );
  3884. var d2 = plane.distanceToPoint( p2 );
  3885. // if both outside plane, no intersection
  3886. if ( d1 < 0 && d2 < 0 ) {
  3887. return false;
  3888. }
  3889. }
  3890. return true;
  3891. };
  3892. }(),
  3893. containsPoint: function ( point ) {
  3894. var planes = this.planes;
  3895. for ( var i = 0; i < 6; i ++ ) {
  3896. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  3897. return false;
  3898. }
  3899. }
  3900. return true;
  3901. }
  3902. };
  3903. // File:src/math/Plane.js
  3904. /**
  3905. * @author bhouston / http://clara.io
  3906. */
  3907. THREE.Plane = function ( normal, constant ) {
  3908. this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 );
  3909. this.constant = ( constant !== undefined ) ? constant : 0;
  3910. };
  3911. THREE.Plane.prototype = {
  3912. constructor: THREE.Plane,
  3913. set: function ( normal, constant ) {
  3914. this.normal.copy( normal );
  3915. this.constant = constant;
  3916. return this;
  3917. },
  3918. setComponents: function ( x, y, z, w ) {
  3919. this.normal.set( x, y, z );
  3920. this.constant = w;
  3921. return this;
  3922. },
  3923. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  3924. this.normal.copy( normal );
  3925. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  3926. return this;
  3927. },
  3928. setFromCoplanarPoints: function () {
  3929. var v1 = new THREE.Vector3();
  3930. var v2 = new THREE.Vector3();
  3931. return function ( a, b, c ) {
  3932. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  3933. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  3934. this.setFromNormalAndCoplanarPoint( normal, a );
  3935. return this;
  3936. };
  3937. }(),
  3938. clone: function () {
  3939. return new this.constructor().copy( this );
  3940. },
  3941. copy: function ( plane ) {
  3942. this.normal.copy( plane.normal );
  3943. this.constant = plane.constant;
  3944. return this;
  3945. },
  3946. normalize: function () {
  3947. // Note: will lead to a divide by zero if the plane is invalid.
  3948. var inverseNormalLength = 1.0 / this.normal.length();
  3949. this.normal.multiplyScalar( inverseNormalLength );
  3950. this.constant *= inverseNormalLength;
  3951. return this;
  3952. },
  3953. negate: function () {
  3954. this.constant *= - 1;
  3955. this.normal.negate();
  3956. return this;
  3957. },
  3958. distanceToPoint: function ( point ) {
  3959. return this.normal.dot( point ) + this.constant;
  3960. },
  3961. distanceToSphere: function ( sphere ) {
  3962. return this.distanceToPoint( sphere.center ) - sphere.radius;
  3963. },
  3964. projectPoint: function ( point, optionalTarget ) {
  3965. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  3966. },
  3967. orthoPoint: function ( point, optionalTarget ) {
  3968. var perpendicularMagnitude = this.distanceToPoint( point );
  3969. var result = optionalTarget || new THREE.Vector3();
  3970. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  3971. },
  3972. intersectLine: function () {
  3973. var v1 = new THREE.Vector3();
  3974. return function ( line, optionalTarget ) {
  3975. var result = optionalTarget || new THREE.Vector3();
  3976. var direction = line.delta( v1 );
  3977. var denominator = this.normal.dot( direction );
  3978. if ( denominator === 0 ) {
  3979. // line is coplanar, return origin
  3980. if ( this.distanceToPoint( line.start ) === 0 ) {
  3981. return result.copy( line.start );
  3982. }
  3983. // Unsure if this is the correct method to handle this case.
  3984. return undefined;
  3985. }
  3986. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  3987. if ( t < 0 || t > 1 ) {
  3988. return undefined;
  3989. }
  3990. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  3991. };
  3992. }(),
  3993. intersectsLine: function ( line ) {
  3994. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  3995. var startSign = this.distanceToPoint( line.start );
  3996. var endSign = this.distanceToPoint( line.end );
  3997. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  3998. },
  3999. intersectsBox: function ( box ) {
  4000. return box.intersectsPlane( this );
  4001. },
  4002. intersectsSphere: function ( sphere ) {
  4003. return sphere.intersectsPlane( this );
  4004. },
  4005. coplanarPoint: function ( optionalTarget ) {
  4006. var result = optionalTarget || new THREE.Vector3();
  4007. return result.copy( this.normal ).multiplyScalar( - this.constant );
  4008. },
  4009. applyMatrix4: function () {
  4010. var v1 = new THREE.Vector3();
  4011. var v2 = new THREE.Vector3();
  4012. var m1 = new THREE.Matrix3();
  4013. return function ( matrix, optionalNormalMatrix ) {
  4014. // compute new normal based on theory here:
  4015. // http://www.songho.ca/opengl/gl_normaltransform.html
  4016. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  4017. var newNormal = v1.copy( this.normal ).applyMatrix3( normalMatrix );
  4018. var newCoplanarPoint = this.coplanarPoint( v2 );
  4019. newCoplanarPoint.applyMatrix4( matrix );
  4020. this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint );
  4021. return this;
  4022. };
  4023. }(),
  4024. translate: function ( offset ) {
  4025. this.constant = this.constant - offset.dot( this.normal );
  4026. return this;
  4027. },
  4028. equals: function ( plane ) {
  4029. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  4030. }
  4031. };
  4032. // File:src/math/Math.js
  4033. /**
  4034. * @author alteredq / http://alteredqualia.com/
  4035. * @author mrdoob / http://mrdoob.com/
  4036. */
  4037. THREE.Math = {
  4038. generateUUID: function () {
  4039. // http://www.broofa.com/Tools/Math.uuid.htm
  4040. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split( '' );
  4041. var uuid = new Array( 36 );
  4042. var rnd = 0, r;
  4043. return function () {
  4044. for ( var i = 0; i < 36; i ++ ) {
  4045. if ( i === 8 || i === 13 || i === 18 || i === 23 ) {
  4046. uuid[ i ] = '-';
  4047. } else if ( i === 14 ) {
  4048. uuid[ i ] = '4';
  4049. } else {
  4050. if ( rnd <= 0x02 ) rnd = 0x2000000 + ( Math.random() * 0x1000000 ) | 0;
  4051. r = rnd & 0xf;
  4052. rnd = rnd >> 4;
  4053. uuid[ i ] = chars[ ( i === 19 ) ? ( r & 0x3 ) | 0x8 : r ];
  4054. }
  4055. }
  4056. return uuid.join( '' );
  4057. };
  4058. }(),
  4059. clamp: function ( value, min, max ) {
  4060. return Math.max( min, Math.min( max, value ) );
  4061. },
  4062. // compute euclidian modulo of m % n
  4063. // https://en.wikipedia.org/wiki/Modulo_operation
  4064. euclideanModulo: function ( n, m ) {
  4065. return ( ( n % m ) + m ) % m;
  4066. },
  4067. // Linear mapping from range <a1, a2> to range <b1, b2>
  4068. mapLinear: function ( x, a1, a2, b1, b2 ) {
  4069. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  4070. },
  4071. // http://en.wikipedia.org/wiki/Smoothstep
  4072. smoothstep: function ( x, min, max ) {
  4073. if ( x <= min ) return 0;
  4074. if ( x >= max ) return 1;
  4075. x = ( x - min ) / ( max - min );
  4076. return x * x * ( 3 - 2 * x );
  4077. },
  4078. smootherstep: function ( x, min, max ) {
  4079. if ( x <= min ) return 0;
  4080. if ( x >= max ) return 1;
  4081. x = ( x - min ) / ( max - min );
  4082. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  4083. },
  4084. random16: function () {
  4085. console.warn( 'THREE.Math.random16() has been deprecated. Use Math.random() instead.' );
  4086. return Math.random();
  4087. },
  4088. // Random integer from <low, high> interval
  4089. randInt: function ( low, high ) {
  4090. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  4091. },
  4092. // Random float from <low, high> interval
  4093. randFloat: function ( low, high ) {
  4094. return low + Math.random() * ( high - low );
  4095. },
  4096. // Random float from <-range/2, range/2> interval
  4097. randFloatSpread: function ( range ) {
  4098. return range * ( 0.5 - Math.random() );
  4099. },
  4100. degToRad: function () {
  4101. var degreeToRadiansFactor = Math.PI / 180;
  4102. return function ( degrees ) {
  4103. return degrees * degreeToRadiansFactor;
  4104. };
  4105. }(),
  4106. radToDeg: function () {
  4107. var radianToDegreesFactor = 180 / Math.PI;
  4108. return function ( radians ) {
  4109. return radians * radianToDegreesFactor;
  4110. };
  4111. }(),
  4112. isPowerOfTwo: function ( value ) {
  4113. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  4114. },
  4115. nearestPowerOfTwo: function ( value ) {
  4116. return Math.pow( 2, Math.round( Math.log( value ) / Math.LN2 ) );
  4117. },
  4118. nextPowerOfTwo: function ( value ) {
  4119. value --;
  4120. value |= value >> 1;
  4121. value |= value >> 2;
  4122. value |= value >> 4;
  4123. value |= value >> 8;
  4124. value |= value >> 16;
  4125. value ++;
  4126. return value;
  4127. }
  4128. };
  4129. // File:src/math/Rectangle.js
  4130. /**
  4131. * @author mrdoob / http://mrdoob.com/
  4132. */
  4133. THREE.Rectangle = function ( x, y, width, height ) {
  4134. this.set( x, y, width, height );
  4135. };
  4136. THREE.Rectangle.prototype = {
  4137. constructor: THREE.Rectangle,
  4138. set: function ( x, y, width, height ) {
  4139. this.x = x;
  4140. this.y = y;
  4141. this.width = width;
  4142. this.height = height;
  4143. return this;
  4144. },
  4145. copy: function ( source ) {
  4146. this.x = source.x;
  4147. this.y = source.y;
  4148. this.width = source.width;
  4149. this.height = source.height;
  4150. return this;
  4151. }
  4152. };
  4153. // File:src/math/Spline.js
  4154. /**
  4155. * Spline from Tween.js, slightly optimized (and trashed)
  4156. * http://sole.github.com/tween.js/examples/05_spline.html
  4157. *
  4158. * @author mrdoob / http://mrdoob.com/
  4159. * @author alteredq / http://alteredqualia.com/
  4160. */
  4161. THREE.Spline = function ( points ) {
  4162. this.points = points;
  4163. var c = [], v3 = { x: 0, y: 0, z: 0 },
  4164. point, intPoint, weight, w2, w3,
  4165. pa, pb, pc, pd;
  4166. this.initFromArray = function ( a ) {
  4167. this.points = [];
  4168. for ( var i = 0; i < a.length; i ++ ) {
  4169. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  4170. }
  4171. };
  4172. this.getPoint = function ( k ) {
  4173. point = ( this.points.length - 1 ) * k;
  4174. intPoint = Math.floor( point );
  4175. weight = point - intPoint;
  4176. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  4177. c[ 1 ] = intPoint;
  4178. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  4179. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  4180. pa = this.points[ c[ 0 ] ];
  4181. pb = this.points[ c[ 1 ] ];
  4182. pc = this.points[ c[ 2 ] ];
  4183. pd = this.points[ c[ 3 ] ];
  4184. w2 = weight * weight;
  4185. w3 = weight * w2;
  4186. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  4187. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  4188. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  4189. return v3;
  4190. };
  4191. this.getControlPointsArray = function () {
  4192. var i, p, l = this.points.length,
  4193. coords = [];
  4194. for ( i = 0; i < l; i ++ ) {
  4195. p = this.points[ i ];
  4196. coords[ i ] = [ p.x, p.y, p.z ];
  4197. }
  4198. return coords;
  4199. };
  4200. // approximate length by summing linear segments
  4201. this.getLength = function ( nSubDivisions ) {
  4202. var i, index, nSamples, position,
  4203. point = 0, intPoint = 0, oldIntPoint = 0,
  4204. oldPosition = new THREE.Vector3(),
  4205. tmpVec = new THREE.Vector3(),
  4206. chunkLengths = [],
  4207. totalLength = 0;
  4208. // first point has 0 length
  4209. chunkLengths[ 0 ] = 0;
  4210. if ( ! nSubDivisions ) nSubDivisions = 100;
  4211. nSamples = this.points.length * nSubDivisions;
  4212. oldPosition.copy( this.points[ 0 ] );
  4213. for ( i = 1; i < nSamples; i ++ ) {
  4214. index = i / nSamples;
  4215. position = this.getPoint( index );
  4216. tmpVec.copy( position );
  4217. totalLength += tmpVec.distanceTo( oldPosition );
  4218. oldPosition.copy( position );
  4219. point = ( this.points.length - 1 ) * index;
  4220. intPoint = Math.floor( point );
  4221. if ( intPoint !== oldIntPoint ) {
  4222. chunkLengths[ intPoint ] = totalLength;
  4223. oldIntPoint = intPoint;
  4224. }
  4225. }
  4226. // last point ends with total length
  4227. chunkLengths[ chunkLengths.length ] = totalLength;
  4228. return { chunks: chunkLengths, total: totalLength };
  4229. };
  4230. this.reparametrizeByArcLength = function ( samplingCoef ) {
  4231. var i, j,
  4232. index, indexCurrent, indexNext,
  4233. realDistance,
  4234. sampling, position,
  4235. newpoints = [],
  4236. tmpVec = new THREE.Vector3(),
  4237. sl = this.getLength();
  4238. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  4239. for ( i = 1; i < this.points.length; i ++ ) {
  4240. //tmpVec.copy( this.points[ i - 1 ] );
  4241. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  4242. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  4243. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  4244. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  4245. indexNext = i / ( this.points.length - 1 );
  4246. for ( j = 1; j < sampling - 1; j ++ ) {
  4247. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  4248. position = this.getPoint( index );
  4249. newpoints.push( tmpVec.copy( position ).clone() );
  4250. }
  4251. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  4252. }
  4253. this.points = newpoints;
  4254. };
  4255. // Catmull-Rom
  4256. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  4257. var v0 = ( p2 - p0 ) * 0.5,
  4258. v1 = ( p3 - p1 ) * 0.5;
  4259. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  4260. }
  4261. };
  4262. // File:src/math/Triangle.js
  4263. /**
  4264. * @author bhouston / http://clara.io
  4265. * @author mrdoob / http://mrdoob.com/
  4266. */
  4267. THREE.Triangle = function ( a, b, c ) {
  4268. this.a = ( a !== undefined ) ? a : new THREE.Vector3();
  4269. this.b = ( b !== undefined ) ? b : new THREE.Vector3();
  4270. this.c = ( c !== undefined ) ? c : new THREE.Vector3();
  4271. };
  4272. THREE.Triangle.normal = function () {
  4273. var v0 = new THREE.Vector3();
  4274. return function ( a, b, c, optionalTarget ) {
  4275. var result = optionalTarget || new THREE.Vector3();
  4276. result.subVectors( c, b );
  4277. v0.subVectors( a, b );
  4278. result.cross( v0 );
  4279. var resultLengthSq = result.lengthSq();
  4280. if ( resultLengthSq > 0 ) {
  4281. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  4282. }
  4283. return result.set( 0, 0, 0 );
  4284. };
  4285. }();
  4286. // static/instance method to calculate barycentric coordinates
  4287. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4288. THREE.Triangle.barycoordFromPoint = function () {
  4289. var v0 = new THREE.Vector3();
  4290. var v1 = new THREE.Vector3();
  4291. var v2 = new THREE.Vector3();
  4292. return function ( point, a, b, c, optionalTarget ) {
  4293. v0.subVectors( c, a );
  4294. v1.subVectors( b, a );
  4295. v2.subVectors( point, a );
  4296. var dot00 = v0.dot( v0 );
  4297. var dot01 = v0.dot( v1 );
  4298. var dot02 = v0.dot( v2 );
  4299. var dot11 = v1.dot( v1 );
  4300. var dot12 = v1.dot( v2 );
  4301. var denom = ( dot00 * dot11 - dot01 * dot01 );
  4302. var result = optionalTarget || new THREE.Vector3();
  4303. // collinear or singular triangle
  4304. if ( denom === 0 ) {
  4305. // arbitrary location outside of triangle?
  4306. // not sure if this is the best idea, maybe should be returning undefined
  4307. return result.set( - 2, - 1, - 1 );
  4308. }
  4309. var invDenom = 1 / denom;
  4310. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  4311. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  4312. // barycentric coordinates must always sum to 1
  4313. return result.set( 1 - u - v, v, u );
  4314. };
  4315. }();
  4316. THREE.Triangle.containsPoint = function () {
  4317. var v1 = new THREE.Vector3();
  4318. return function ( point, a, b, c ) {
  4319. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 );
  4320. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  4321. };
  4322. }();
  4323. THREE.Triangle.prototype = {
  4324. constructor: THREE.Triangle,
  4325. set: function ( a, b, c ) {
  4326. this.a.copy( a );
  4327. this.b.copy( b );
  4328. this.c.copy( c );
  4329. return this;
  4330. },
  4331. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  4332. this.a.copy( points[ i0 ] );
  4333. this.b.copy( points[ i1 ] );
  4334. this.c.copy( points[ i2 ] );
  4335. return this;
  4336. },
  4337. clone: function () {
  4338. return new this.constructor().copy( this );
  4339. },
  4340. copy: function ( triangle ) {
  4341. this.a.copy( triangle.a );
  4342. this.b.copy( triangle.b );
  4343. this.c.copy( triangle.c );
  4344. return this;
  4345. },
  4346. area: function () {
  4347. var v0 = new THREE.Vector3();
  4348. var v1 = new THREE.Vector3();
  4349. return function () {
  4350. v0.subVectors( this.c, this.b );
  4351. v1.subVectors( this.a, this.b );
  4352. return v0.cross( v1 ).length() * 0.5;
  4353. };
  4354. }(),
  4355. midpoint: function ( optionalTarget ) {
  4356. var result = optionalTarget || new THREE.Vector3();
  4357. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  4358. },
  4359. normal: function ( optionalTarget ) {
  4360. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  4361. },
  4362. plane: function ( optionalTarget ) {
  4363. var result = optionalTarget || new THREE.Plane();
  4364. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  4365. },
  4366. barycoordFromPoint: function ( point, optionalTarget ) {
  4367. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  4368. },
  4369. containsPoint: function ( point ) {
  4370. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  4371. },
  4372. equals: function ( triangle ) {
  4373. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  4374. }
  4375. };
  4376. // File:src/math/Interpolant.js
  4377. /**
  4378. * Abstract base class of interpolants over parametric samples.
  4379. *
  4380. * The parameter domain is one dimensional, typically the time or a path
  4381. * along a curve defined by the data.
  4382. *
  4383. * The sample values can have any dimensionality and derived classes may
  4384. * apply special interpretations to the data.
  4385. *
  4386. * This class provides the interval seek in a Template Method, deferring
  4387. * the actual interpolation to derived classes.
  4388. *
  4389. * Time complexity is O(1) for linear access crossing at most two points
  4390. * and O(log N) for random access, where N is the number of positions.
  4391. *
  4392. * References:
  4393. *
  4394. * http://www.oodesign.com/template-method-pattern.html
  4395. *
  4396. * @author tschw
  4397. */
  4398. THREE.Interpolant = function(
  4399. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  4400. this.parameterPositions = parameterPositions;
  4401. this._cachedIndex = 0;
  4402. this.resultBuffer = resultBuffer !== undefined ?
  4403. resultBuffer : new sampleValues.constructor( sampleSize );
  4404. this.sampleValues = sampleValues;
  4405. this.valueSize = sampleSize;
  4406. };
  4407. THREE.Interpolant.prototype = {
  4408. constructor: THREE.Intepolant,
  4409. evaluate: function( t ) {
  4410. var pp = this.parameterPositions,
  4411. i1 = this._cachedIndex,
  4412. t1 = pp[ i1 ],
  4413. t0 = pp[ i1 - 1 ];
  4414. validate_interval: {
  4415. seek: {
  4416. var right;
  4417. linear_scan: {
  4418. //- See http://jsperf.com/comparison-to-undefined/3
  4419. //- slower code:
  4420. //-
  4421. //- if ( t >= t1 || t1 === undefined ) {
  4422. forward_scan: if ( ! ( t < t1 ) ) {
  4423. for ( var giveUpAt = i1 + 2; ;) {
  4424. if ( t1 === undefined ) {
  4425. if ( t < t0 ) break forward_scan;
  4426. // after end
  4427. i1 = pp.length;
  4428. this._cachedIndex = i1;
  4429. return this.afterEnd_( i1 - 1, t, t0 );
  4430. }
  4431. if ( i1 === giveUpAt ) break; // this loop
  4432. t0 = t1;
  4433. t1 = pp[ ++ i1 ];
  4434. if ( t < t1 ) {
  4435. // we have arrived at the sought interval
  4436. break seek;
  4437. }
  4438. }
  4439. // prepare binary search on the right side of the index
  4440. right = pp.length;
  4441. break linear_scan;
  4442. }
  4443. //- slower code:
  4444. //- if ( t < t0 || t0 === undefined ) {
  4445. if ( ! ( t >= t0 ) ) {
  4446. // looping?
  4447. var t1global = pp[ 1 ];
  4448. if ( t < t1global ) {
  4449. i1 = 2; // + 1, using the scan for the details
  4450. t0 = t1global;
  4451. }
  4452. // linear reverse scan
  4453. for ( var giveUpAt = i1 - 2; ;) {
  4454. if ( t0 === undefined ) {
  4455. // before start
  4456. this._cachedIndex = 0;
  4457. return this.beforeStart_( 0, t, t1 );
  4458. }
  4459. if ( i1 === giveUpAt ) break; // this loop
  4460. t1 = t0;
  4461. t0 = pp[ -- i1 - 1 ];
  4462. if ( t >= t0 ) {
  4463. // we have arrived at the sought interval
  4464. break seek;
  4465. }
  4466. }
  4467. // prepare binary search on the left side of the index
  4468. right = i1;
  4469. i1 = 0;
  4470. break linear_scan;
  4471. }
  4472. // the interval is valid
  4473. break validate_interval;
  4474. } // linear scan
  4475. // binary search
  4476. while ( i1 < right ) {
  4477. var mid = ( i1 + right ) >>> 1;
  4478. if ( t < pp[ mid ] ) {
  4479. right = mid;
  4480. } else {
  4481. i1 = mid + 1;
  4482. }
  4483. }
  4484. t1 = pp[ i1 ];
  4485. t0 = pp[ i1 - 1 ];
  4486. // check boundary cases, again
  4487. if ( t0 === undefined ) {
  4488. this._cachedIndex = 0;
  4489. return this.beforeStart_( 0, t, t1 );
  4490. }
  4491. if ( t1 === undefined ) {
  4492. i1 = pp.length;
  4493. this._cachedIndex = i1;
  4494. return this.afterEnd_( i1 - 1, t0, t );
  4495. }
  4496. } // seek
  4497. this._cachedIndex = i1;
  4498. this.intervalChanged_( i1, t0, t1 );
  4499. } // validate_interval
  4500. return this.interpolate_( i1, t0, t, t1 );
  4501. },
  4502. settings: null, // optional, subclass-specific settings structure
  4503. // Note: The indirection allows central control of many interpolants.
  4504. // --- Protected interface
  4505. DefaultSettings_: {},
  4506. getSettings_: function() {
  4507. return this.settings || this.DefaultSettings_;
  4508. },
  4509. copySampleValue_: function( index ) {
  4510. // copies a sample value to the result buffer
  4511. var result = this.resultBuffer,
  4512. values = this.sampleValues,
  4513. stride = this.valueSize,
  4514. offset = index * stride;
  4515. for ( var i = 0; i !== stride; ++ i ) {
  4516. result[ i ] = values[ offset + i ];
  4517. }
  4518. return result;
  4519. },
  4520. // Template methods for derived classes:
  4521. interpolate_: function( i1, t0, t, t1 ) {
  4522. throw new Error( "call to abstract method" );
  4523. // implementations shall return this.resultBuffer
  4524. },
  4525. intervalChanged_: function( i1, t0, t1 ) {
  4526. // empty
  4527. }
  4528. };
  4529. Object.assign( THREE.Interpolant.prototype, {
  4530. beforeStart_: //( 0, t, t0 ), returns this.resultBuffer
  4531. THREE.Interpolant.prototype.copySampleValue_,
  4532. afterEnd_: //( N-1, tN-1, t ), returns this.resultBuffer
  4533. THREE.Interpolant.prototype.copySampleValue_
  4534. } );
  4535. // File:src/math/interpolants/CubicInterpolant.js
  4536. /**
  4537. * Fast and simple cubic spline interpolant.
  4538. *
  4539. * It was derived from a Hermitian construction setting the first derivative
  4540. * at each sample position to the linear slope between neighboring positions
  4541. * over their parameter interval.
  4542. *
  4543. * @author tschw
  4544. */
  4545. THREE.CubicInterpolant = function(
  4546. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  4547. THREE.Interpolant.call(
  4548. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  4549. this._weightPrev = -0;
  4550. this._offsetPrev = -0;
  4551. this._weightNext = -0;
  4552. this._offsetNext = -0;
  4553. };
  4554. THREE.CubicInterpolant.prototype =
  4555. Object.assign( Object.create( THREE.Interpolant.prototype ), {
  4556. constructor: THREE.CubicInterpolant,
  4557. DefaultSettings_: {
  4558. endingStart: THREE.ZeroCurvatureEnding,
  4559. endingEnd: THREE.ZeroCurvatureEnding
  4560. },
  4561. intervalChanged_: function( i1, t0, t1 ) {
  4562. var pp = this.parameterPositions,
  4563. iPrev = i1 - 2,
  4564. iNext = i1 + 1,
  4565. tPrev = pp[ iPrev ],
  4566. tNext = pp[ iNext ];
  4567. if ( tPrev === undefined ) {
  4568. switch ( this.getSettings_().endingStart ) {
  4569. case THREE.ZeroSlopeEnding:
  4570. // f'(t0) = 0
  4571. iPrev = i1;
  4572. tPrev = 2 * t0 - t1;
  4573. break;
  4574. case THREE.WrapAroundEnding:
  4575. // use the other end of the curve
  4576. iPrev = pp.length - 2;
  4577. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  4578. break;
  4579. default: // ZeroCurvatureEnding
  4580. // f''(t0) = 0 a.k.a. Natural Spline
  4581. iPrev = i1;
  4582. tPrev = t1;
  4583. }
  4584. }
  4585. if ( tNext === undefined ) {
  4586. switch ( this.getSettings_().endingEnd ) {
  4587. case THREE.ZeroSlopeEnding:
  4588. // f'(tN) = 0
  4589. iNext = i1;
  4590. tNext = 2 * t1 - t0;
  4591. break;
  4592. case THREE.WrapAroundEnding:
  4593. // use the other end of the curve
  4594. iNext = 1;
  4595. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  4596. break;
  4597. default: // ZeroCurvatureEnding
  4598. // f''(tN) = 0, a.k.a. Natural Spline
  4599. iNext = i1 - 1;
  4600. tNext = t0;
  4601. }
  4602. }
  4603. var halfDt = ( t1 - t0 ) * 0.5,
  4604. stride = this.valueSize;
  4605. this._weightPrev = halfDt / ( t0 - tPrev );
  4606. this._weightNext = halfDt / ( tNext - t1 );
  4607. this._offsetPrev = iPrev * stride;
  4608. this._offsetNext = iNext * stride;
  4609. },
  4610. interpolate_: function( i1, t0, t, t1 ) {
  4611. var result = this.resultBuffer,
  4612. values = this.sampleValues,
  4613. stride = this.valueSize,
  4614. o1 = i1 * stride, o0 = o1 - stride,
  4615. oP = this._offsetPrev, oN = this._offsetNext,
  4616. wP = this._weightPrev, wN = this._weightNext,
  4617. p = ( t - t0 ) / ( t1 - t0 ),
  4618. pp = p * p,
  4619. ppp = pp * p;
  4620. // evaluate polynomials
  4621. var sP = - wP * ppp + 2 * wP * pp - wP * p;
  4622. var s0 = ( 1 + wP ) * ppp + (-1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  4623. var s1 = (-1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  4624. var sN = wN * ppp - wN * pp;
  4625. // combine data linearly
  4626. for ( var i = 0; i !== stride; ++ i ) {
  4627. result[ i ] =
  4628. sP * values[ oP + i ] +
  4629. s0 * values[ o0 + i ] +
  4630. s1 * values[ o1 + i ] +
  4631. sN * values[ oN + i ];
  4632. }
  4633. return result;
  4634. }
  4635. } );
  4636. // File:src/math/interpolants/DiscreteInterpolant.js
  4637. /**
  4638. *
  4639. * Interpolant that evaluates to the sample value at the position preceeding
  4640. * the parameter.
  4641. *
  4642. * @author tschw
  4643. */
  4644. THREE.DiscreteInterpolant = function(
  4645. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  4646. THREE.Interpolant.call(
  4647. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  4648. };
  4649. THREE.DiscreteInterpolant.prototype =
  4650. Object.assign( Object.create( THREE.Interpolant.prototype ), {
  4651. constructor: THREE.DiscreteInterpolant,
  4652. interpolate_: function( i1, t0, t, t1 ) {
  4653. return this.copySampleValue_( i1 - 1 );
  4654. }
  4655. } );
  4656. // File:src/math/interpolants/LinearInterpolant.js
  4657. /**
  4658. * @author tschw
  4659. */
  4660. THREE.LinearInterpolant = function(
  4661. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  4662. THREE.Interpolant.call(
  4663. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  4664. };
  4665. THREE.LinearInterpolant.prototype =
  4666. Object.assign( Object.create( THREE.Interpolant.prototype ), {
  4667. constructor: THREE.LinearInterpolant,
  4668. interpolate_: function( i1, t0, t, t1 ) {
  4669. var result = this.resultBuffer,
  4670. values = this.sampleValues,
  4671. stride = this.valueSize,
  4672. offset1 = i1 * stride,
  4673. offset0 = offset1 - stride,
  4674. weight1 = ( t - t0 ) / ( t1 - t0 ),
  4675. weight0 = 1 - weight1;
  4676. for ( var i = 0; i !== stride; ++ i ) {
  4677. result[ i ] =
  4678. values[ offset0 + i ] * weight0 +
  4679. values[ offset1 + i ] * weight1;
  4680. }
  4681. return result;
  4682. }
  4683. } );
  4684. // File:src/math/interpolants/QuaternionLinearInterpolant.js
  4685. /**
  4686. * Spherical linear unit quaternion interpolant.
  4687. *
  4688. * @author tschw
  4689. */
  4690. THREE.QuaternionLinearInterpolant = function(
  4691. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  4692. THREE.Interpolant.call(
  4693. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  4694. };
  4695. THREE.QuaternionLinearInterpolant.prototype =
  4696. Object.assign( Object.create( THREE.Interpolant.prototype ), {
  4697. constructor: THREE.QuaternionLinearInterpolant,
  4698. interpolate_: function( i1, t0, t, t1 ) {
  4699. var result = this.resultBuffer,
  4700. values = this.sampleValues,
  4701. stride = this.valueSize,
  4702. offset = i1 * stride,
  4703. alpha = ( t - t0 ) / ( t1 - t0 );
  4704. for ( var end = offset + stride; offset !== end; offset += 4 ) {
  4705. THREE.Quaternion.slerpFlat( result, 0,
  4706. values, offset - stride, values, offset, alpha );
  4707. }
  4708. return result;
  4709. }
  4710. } );
  4711. // File:src/core/Clock.js
  4712. /**
  4713. * @author alteredq / http://alteredqualia.com/
  4714. */
  4715. THREE.Clock = function ( autoStart ) {
  4716. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  4717. this.startTime = 0;
  4718. this.oldTime = 0;
  4719. this.elapsedTime = 0;
  4720. this.running = false;
  4721. };
  4722. THREE.Clock.prototype = {
  4723. constructor: THREE.Clock,
  4724. start: function () {
  4725. this.startTime = self.performance.now();
  4726. this.oldTime = this.startTime;
  4727. this.running = true;
  4728. },
  4729. stop: function () {
  4730. this.getElapsedTime();
  4731. this.running = false;
  4732. },
  4733. getElapsedTime: function () {
  4734. this.getDelta();
  4735. return this.elapsedTime;
  4736. },
  4737. getDelta: function () {
  4738. var diff = 0;
  4739. if ( this.autoStart && ! this.running ) {
  4740. this.start();
  4741. }
  4742. if ( this.running ) {
  4743. var newTime = self.performance.now();
  4744. diff = 0.001 * ( newTime - this.oldTime );
  4745. this.oldTime = newTime;
  4746. this.elapsedTime += diff;
  4747. }
  4748. return diff;
  4749. }
  4750. };
  4751. // File:src/core/EventDispatcher.js
  4752. /**
  4753. * https://github.com/mrdoob/eventdispatcher.js/
  4754. */
  4755. THREE.EventDispatcher = function () {};
  4756. THREE.EventDispatcher.prototype = {
  4757. constructor: THREE.EventDispatcher,
  4758. apply: function ( object ) {
  4759. object.addEventListener = THREE.EventDispatcher.prototype.addEventListener;
  4760. object.hasEventListener = THREE.EventDispatcher.prototype.hasEventListener;
  4761. object.removeEventListener = THREE.EventDispatcher.prototype.removeEventListener;
  4762. object.dispatchEvent = THREE.EventDispatcher.prototype.dispatchEvent;
  4763. },
  4764. addEventListener: function ( type, listener ) {
  4765. if ( this._listeners === undefined ) this._listeners = {};
  4766. var listeners = this._listeners;
  4767. if ( listeners[ type ] === undefined ) {
  4768. listeners[ type ] = [];
  4769. }
  4770. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  4771. listeners[ type ].push( listener );
  4772. }
  4773. },
  4774. hasEventListener: function ( type, listener ) {
  4775. if ( this._listeners === undefined ) return false;
  4776. var listeners = this._listeners;
  4777. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  4778. return true;
  4779. }
  4780. return false;
  4781. },
  4782. removeEventListener: function ( type, listener ) {
  4783. if ( this._listeners === undefined ) return;
  4784. var listeners = this._listeners;
  4785. var listenerArray = listeners[ type ];
  4786. if ( listenerArray !== undefined ) {
  4787. var index = listenerArray.indexOf( listener );
  4788. if ( index !== - 1 ) {
  4789. listenerArray.splice( index, 1 );
  4790. }
  4791. }
  4792. },
  4793. dispatchEvent: function ( event ) {
  4794. if ( this._listeners === undefined ) return;
  4795. var listeners = this._listeners;
  4796. var listenerArray = listeners[ event.type ];
  4797. if ( listenerArray !== undefined ) {
  4798. event.target = this;
  4799. var array = [];
  4800. var length = listenerArray.length;
  4801. for ( var i = 0; i < length; i ++ ) {
  4802. array[ i ] = listenerArray[ i ];
  4803. }
  4804. for ( var i = 0; i < length; i ++ ) {
  4805. array[ i ].call( this, event );
  4806. }
  4807. }
  4808. }
  4809. };
  4810. // File:src/core/Layers.js
  4811. /**
  4812. * @author mrdoob / http://mrdoob.com/
  4813. */
  4814. THREE.Layers = function () {
  4815. this.mask = 1;
  4816. };
  4817. THREE.Layers.prototype = {
  4818. constructor: THREE.Layers,
  4819. set: function ( channel ) {
  4820. this.mask = 1 << channel;
  4821. },
  4822. enable: function ( channel ) {
  4823. this.mask |= 1 << channel;
  4824. },
  4825. toggle: function ( channel ) {
  4826. this.mask ^= 1 << channel;
  4827. },
  4828. disable: function ( channel ) {
  4829. this.mask &= ~ ( 1 << channel );
  4830. },
  4831. test: function ( layers ) {
  4832. return ( this.mask & layers.mask ) !== 0;
  4833. }
  4834. };
  4835. // File:src/core/Raycaster.js
  4836. /**
  4837. * @author mrdoob / http://mrdoob.com/
  4838. * @author bhouston / http://clara.io/
  4839. * @author stephomi / http://stephaneginier.com/
  4840. */
  4841. ( function ( THREE ) {
  4842. THREE.Raycaster = function ( origin, direction, near, far ) {
  4843. this.ray = new THREE.Ray( origin, direction );
  4844. // direction is assumed to be normalized (for accurate distance calculations)
  4845. this.near = near || 0;
  4846. this.far = far || Infinity;
  4847. this.params = {
  4848. Mesh: {},
  4849. Line: {},
  4850. LOD: {},
  4851. Points: { threshold: 1 },
  4852. Sprite: {}
  4853. };
  4854. Object.defineProperties( this.params, {
  4855. PointCloud: {
  4856. get: function () {
  4857. console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' );
  4858. return this.Points;
  4859. }
  4860. }
  4861. } );
  4862. };
  4863. function ascSort( a, b ) {
  4864. return a.distance - b.distance;
  4865. }
  4866. function intersectObject( object, raycaster, intersects, recursive ) {
  4867. if ( object.visible === false ) return;
  4868. object.raycast( raycaster, intersects );
  4869. if ( recursive === true ) {
  4870. var children = object.children;
  4871. for ( var i = 0, l = children.length; i < l; i ++ ) {
  4872. intersectObject( children[ i ], raycaster, intersects, true );
  4873. }
  4874. }
  4875. }
  4876. //
  4877. THREE.Raycaster.prototype = {
  4878. constructor: THREE.Raycaster,
  4879. linePrecision: 1,
  4880. set: function ( origin, direction ) {
  4881. // direction is assumed to be normalized (for accurate distance calculations)
  4882. this.ray.set( origin, direction );
  4883. },
  4884. setFromCamera: function ( coords, camera ) {
  4885. if ( camera instanceof THREE.PerspectiveCamera ) {
  4886. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  4887. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  4888. } else if ( camera instanceof THREE.OrthographicCamera ) {
  4889. this.ray.origin.set( coords.x, coords.y, - 1 ).unproject( camera );
  4890. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  4891. } else {
  4892. console.error( 'THREE.Raycaster: Unsupported camera type.' );
  4893. }
  4894. },
  4895. intersectObject: function ( object, recursive ) {
  4896. var intersects = [];
  4897. intersectObject( object, this, intersects, recursive );
  4898. intersects.sort( ascSort );
  4899. return intersects;
  4900. },
  4901. intersectObjects: function ( objects, recursive ) {
  4902. var intersects = [];
  4903. if ( Array.isArray( objects ) === false ) {
  4904. console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
  4905. return intersects;
  4906. }
  4907. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  4908. intersectObject( objects[ i ], this, intersects, recursive );
  4909. }
  4910. intersects.sort( ascSort );
  4911. return intersects;
  4912. }
  4913. };
  4914. }( THREE ) );
  4915. // File:src/core/Object3D.js
  4916. /**
  4917. * @author mrdoob / http://mrdoob.com/
  4918. * @author mikael emtinger / http://gomo.se/
  4919. * @author alteredq / http://alteredqualia.com/
  4920. * @author WestLangley / http://github.com/WestLangley
  4921. * @author elephantatwork / www.elephantatwork.ch
  4922. */
  4923. THREE.Object3D = function () {
  4924. Object.defineProperty( this, 'id', { value: THREE.Object3DIdCount ++ } );
  4925. this.uuid = THREE.Math.generateUUID();
  4926. this.name = '';
  4927. this.type = 'Object3D';
  4928. this.parent = null;
  4929. this.children = [];
  4930. this.up = THREE.Object3D.DefaultUp.clone();
  4931. var position = new THREE.Vector3();
  4932. var rotation = new THREE.Euler();
  4933. var quaternion = new THREE.Quaternion();
  4934. var scale = new THREE.Vector3( 1, 1, 1 );
  4935. function onRotationChange() {
  4936. quaternion.setFromEuler( rotation, false );
  4937. }
  4938. function onQuaternionChange() {
  4939. rotation.setFromQuaternion( quaternion, undefined, false );
  4940. }
  4941. rotation.onChange( onRotationChange );
  4942. quaternion.onChange( onQuaternionChange );
  4943. Object.defineProperties( this, {
  4944. position: {
  4945. enumerable: true,
  4946. value: position
  4947. },
  4948. rotation: {
  4949. enumerable: true,
  4950. value: rotation
  4951. },
  4952. quaternion: {
  4953. enumerable: true,
  4954. value: quaternion
  4955. },
  4956. scale: {
  4957. enumerable: true,
  4958. value: scale
  4959. },
  4960. modelViewMatrix: {
  4961. value: new THREE.Matrix4()
  4962. },
  4963. normalMatrix: {
  4964. value: new THREE.Matrix3()
  4965. }
  4966. } );
  4967. this.rotationAutoUpdate = true;
  4968. this.matrix = new THREE.Matrix4();
  4969. this.matrixWorld = new THREE.Matrix4();
  4970. this.matrixAutoUpdate = THREE.Object3D.DefaultMatrixAutoUpdate;
  4971. this.matrixWorldNeedsUpdate = false;
  4972. this.layers = new THREE.Layers();
  4973. this.visible = true;
  4974. this.castShadow = false;
  4975. this.receiveShadow = false;
  4976. this.frustumCulled = true;
  4977. this.renderOrder = 0;
  4978. this.userData = {};
  4979. };
  4980. THREE.Object3D.DefaultUp = new THREE.Vector3( 0, 1, 0 );
  4981. THREE.Object3D.DefaultMatrixAutoUpdate = true;
  4982. THREE.Object3D.prototype = {
  4983. constructor: THREE.Object3D,
  4984. applyMatrix: function ( matrix ) {
  4985. this.matrix.multiplyMatrices( matrix, this.matrix );
  4986. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4987. },
  4988. setRotationFromAxisAngle: function ( axis, angle ) {
  4989. // assumes axis is normalized
  4990. this.quaternion.setFromAxisAngle( axis, angle );
  4991. },
  4992. setRotationFromEuler: function ( euler ) {
  4993. this.quaternion.setFromEuler( euler, true );
  4994. },
  4995. setRotationFromMatrix: function ( m ) {
  4996. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4997. this.quaternion.setFromRotationMatrix( m );
  4998. },
  4999. setRotationFromQuaternion: function ( q ) {
  5000. // assumes q is normalized
  5001. this.quaternion.copy( q );
  5002. },
  5003. rotateOnAxis: function () {
  5004. // rotate object on axis in object space
  5005. // axis is assumed to be normalized
  5006. var q1 = new THREE.Quaternion();
  5007. return function ( axis, angle ) {
  5008. q1.setFromAxisAngle( axis, angle );
  5009. this.quaternion.multiply( q1 );
  5010. return this;
  5011. };
  5012. }(),
  5013. rotateX: function () {
  5014. var v1 = new THREE.Vector3( 1, 0, 0 );
  5015. return function ( angle ) {
  5016. return this.rotateOnAxis( v1, angle );
  5017. };
  5018. }(),
  5019. rotateY: function () {
  5020. var v1 = new THREE.Vector3( 0, 1, 0 );
  5021. return function ( angle ) {
  5022. return this.rotateOnAxis( v1, angle );
  5023. };
  5024. }(),
  5025. rotateZ: function () {
  5026. var v1 = new THREE.Vector3( 0, 0, 1 );
  5027. return function ( angle ) {
  5028. return this.rotateOnAxis( v1, angle );
  5029. };
  5030. }(),
  5031. translateOnAxis: function () {
  5032. // translate object by distance along axis in object space
  5033. // axis is assumed to be normalized
  5034. var v1 = new THREE.Vector3();
  5035. return function ( axis, distance ) {
  5036. v1.copy( axis ).applyQuaternion( this.quaternion );
  5037. this.position.add( v1.multiplyScalar( distance ) );
  5038. return this;
  5039. };
  5040. }(),
  5041. translateX: function () {
  5042. var v1 = new THREE.Vector3( 1, 0, 0 );
  5043. return function ( distance ) {
  5044. return this.translateOnAxis( v1, distance );
  5045. };
  5046. }(),
  5047. translateY: function () {
  5048. var v1 = new THREE.Vector3( 0, 1, 0 );
  5049. return function ( distance ) {
  5050. return this.translateOnAxis( v1, distance );
  5051. };
  5052. }(),
  5053. translateZ: function () {
  5054. var v1 = new THREE.Vector3( 0, 0, 1 );
  5055. return function ( distance ) {
  5056. return this.translateOnAxis( v1, distance );
  5057. };
  5058. }(),
  5059. localToWorld: function ( vector ) {
  5060. return vector.applyMatrix4( this.matrixWorld );
  5061. },
  5062. worldToLocal: function () {
  5063. var m1 = new THREE.Matrix4();
  5064. return function ( vector ) {
  5065. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  5066. };
  5067. }(),
  5068. lookAt: function () {
  5069. // This routine does not support objects with rotated and/or translated parent(s)
  5070. var m1 = new THREE.Matrix4();
  5071. return function ( vector ) {
  5072. m1.lookAt( vector, this.position, this.up );
  5073. this.quaternion.setFromRotationMatrix( m1 );
  5074. };
  5075. }(),
  5076. add: function ( object ) {
  5077. if ( arguments.length > 1 ) {
  5078. for ( var i = 0; i < arguments.length; i ++ ) {
  5079. this.add( arguments[ i ] );
  5080. }
  5081. return this;
  5082. }
  5083. if ( object === this ) {
  5084. console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object );
  5085. return this;
  5086. }
  5087. if ( object instanceof THREE.Object3D ) {
  5088. if ( object.parent !== null ) {
  5089. object.parent.remove( object );
  5090. }
  5091. object.parent = this;
  5092. object.dispatchEvent( { type: 'added' } );
  5093. this.children.push( object );
  5094. } else {
  5095. console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object );
  5096. }
  5097. return this;
  5098. },
  5099. remove: function ( object ) {
  5100. if ( arguments.length > 1 ) {
  5101. for ( var i = 0; i < arguments.length; i ++ ) {
  5102. this.remove( arguments[ i ] );
  5103. }
  5104. }
  5105. var index = this.children.indexOf( object );
  5106. if ( index !== - 1 ) {
  5107. object.parent = null;
  5108. object.dispatchEvent( { type: 'removed' } );
  5109. this.children.splice( index, 1 );
  5110. }
  5111. },
  5112. getObjectById: function ( id ) {
  5113. return this.getObjectByProperty( 'id', id );
  5114. },
  5115. getObjectByName: function ( name ) {
  5116. return this.getObjectByProperty( 'name', name );
  5117. },
  5118. getObjectByProperty: function ( name, value ) {
  5119. if ( this[ name ] === value ) return this;
  5120. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  5121. var child = this.children[ i ];
  5122. var object = child.getObjectByProperty( name, value );
  5123. if ( object !== undefined ) {
  5124. return object;
  5125. }
  5126. }
  5127. return undefined;
  5128. },
  5129. getWorldPosition: function ( optionalTarget ) {
  5130. var result = optionalTarget || new THREE.Vector3();
  5131. this.updateMatrixWorld( true );
  5132. return result.setFromMatrixPosition( this.matrixWorld );
  5133. },
  5134. getWorldQuaternion: function () {
  5135. var position = new THREE.Vector3();
  5136. var scale = new THREE.Vector3();
  5137. return function ( optionalTarget ) {
  5138. var result = optionalTarget || new THREE.Quaternion();
  5139. this.updateMatrixWorld( true );
  5140. this.matrixWorld.decompose( position, result, scale );
  5141. return result;
  5142. };
  5143. }(),
  5144. getWorldRotation: function () {
  5145. var quaternion = new THREE.Quaternion();
  5146. return function ( optionalTarget ) {
  5147. var result = optionalTarget || new THREE.Euler();
  5148. this.getWorldQuaternion( quaternion );
  5149. return result.setFromQuaternion( quaternion, this.rotation.order, false );
  5150. };
  5151. }(),
  5152. getWorldScale: function () {
  5153. var position = new THREE.Vector3();
  5154. var quaternion = new THREE.Quaternion();
  5155. return function ( optionalTarget ) {
  5156. var result = optionalTarget || new THREE.Vector3();
  5157. this.updateMatrixWorld( true );
  5158. this.matrixWorld.decompose( position, quaternion, result );
  5159. return result;
  5160. };
  5161. }(),
  5162. getWorldDirection: function () {
  5163. var quaternion = new THREE.Quaternion();
  5164. return function ( optionalTarget ) {
  5165. var result = optionalTarget || new THREE.Vector3();
  5166. this.getWorldQuaternion( quaternion );
  5167. return result.set( 0, 0, 1 ).applyQuaternion( quaternion );
  5168. };
  5169. }(),
  5170. raycast: function () {},
  5171. traverse: function ( callback ) {
  5172. callback( this );
  5173. var children = this.children;
  5174. for ( var i = 0, l = children.length; i < l; i ++ ) {
  5175. children[ i ].traverse( callback );
  5176. }
  5177. },
  5178. traverseVisible: function ( callback ) {
  5179. if ( this.visible === false ) return;
  5180. callback( this );
  5181. var children = this.children;
  5182. for ( var i = 0, l = children.length; i < l; i ++ ) {
  5183. children[ i ].traverseVisible( callback );
  5184. }
  5185. },
  5186. traverseAncestors: function ( callback ) {
  5187. var parent = this.parent;
  5188. if ( parent !== null ) {
  5189. callback( parent );
  5190. parent.traverseAncestors( callback );
  5191. }
  5192. },
  5193. updateMatrix: function () {
  5194. this.matrix.compose( this.position, this.quaternion, this.scale );
  5195. this.matrixWorldNeedsUpdate = true;
  5196. },
  5197. updateMatrixWorld: function ( force ) {
  5198. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  5199. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  5200. if ( this.parent === null ) {
  5201. this.matrixWorld.copy( this.matrix );
  5202. } else {
  5203. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  5204. }
  5205. this.matrixWorldNeedsUpdate = false;
  5206. force = true;
  5207. }
  5208. // update children
  5209. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  5210. this.children[ i ].updateMatrixWorld( force );
  5211. }
  5212. },
  5213. toJSON: function ( meta ) {
  5214. var isRootObject = ( meta === undefined );
  5215. var output = {};
  5216. // meta is a hash used to collect geometries, materials.
  5217. // not providing it implies that this is the root object
  5218. // being serialized.
  5219. if ( isRootObject ) {
  5220. // initialize meta obj
  5221. meta = {
  5222. geometries: {},
  5223. materials: {},
  5224. textures: {},
  5225. images: {}
  5226. };
  5227. output.metadata = {
  5228. version: 4.4,
  5229. type: 'Object',
  5230. generator: 'Object3D.toJSON'
  5231. };
  5232. }
  5233. // standard Object3D serialization
  5234. var object = {};
  5235. object.uuid = this.uuid;
  5236. object.type = this.type;
  5237. if ( this.name !== '' ) object.name = this.name;
  5238. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  5239. if ( this.castShadow === true ) object.castShadow = true;
  5240. if ( this.receiveShadow === true ) object.receiveShadow = true;
  5241. if ( this.visible === false ) object.visible = false;
  5242. object.matrix = this.matrix.toArray();
  5243. //
  5244. if ( this.geometry !== undefined ) {
  5245. if ( meta.geometries[ this.geometry.uuid ] === undefined ) {
  5246. meta.geometries[ this.geometry.uuid ] = this.geometry.toJSON( meta );
  5247. }
  5248. object.geometry = this.geometry.uuid;
  5249. }
  5250. if ( this.material !== undefined ) {
  5251. if ( meta.materials[ this.material.uuid ] === undefined ) {
  5252. meta.materials[ this.material.uuid ] = this.material.toJSON( meta );
  5253. }
  5254. object.material = this.material.uuid;
  5255. }
  5256. //
  5257. if ( this.children.length > 0 ) {
  5258. object.children = [];
  5259. for ( var i = 0; i < this.children.length; i ++ ) {
  5260. object.children.push( this.children[ i ].toJSON( meta ).object );
  5261. }
  5262. }
  5263. if ( isRootObject ) {
  5264. var geometries = extractFromCache( meta.geometries );
  5265. var materials = extractFromCache( meta.materials );
  5266. var textures = extractFromCache( meta.textures );
  5267. var images = extractFromCache( meta.images );
  5268. if ( geometries.length > 0 ) output.geometries = geometries;
  5269. if ( materials.length > 0 ) output.materials = materials;
  5270. if ( textures.length > 0 ) output.textures = textures;
  5271. if ( images.length > 0 ) output.images = images;
  5272. }
  5273. output.object = object;
  5274. return output;
  5275. // extract data from the cache hash
  5276. // remove metadata on each item
  5277. // and return as array
  5278. function extractFromCache ( cache ) {
  5279. var values = [];
  5280. for ( var key in cache ) {
  5281. var data = cache[ key ];
  5282. delete data.metadata;
  5283. values.push( data );
  5284. }
  5285. return values;
  5286. }
  5287. },
  5288. clone: function ( recursive ) {
  5289. return new this.constructor().copy( this, recursive );
  5290. },
  5291. copy: function ( source, recursive ) {
  5292. if ( recursive === undefined ) recursive = true;
  5293. this.name = source.name;
  5294. this.up.copy( source.up );
  5295. this.position.copy( source.position );
  5296. this.quaternion.copy( source.quaternion );
  5297. this.scale.copy( source.scale );
  5298. this.rotationAutoUpdate = source.rotationAutoUpdate;
  5299. this.matrix.copy( source.matrix );
  5300. this.matrixWorld.copy( source.matrixWorld );
  5301. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5302. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  5303. this.visible = source.visible;
  5304. this.castShadow = source.castShadow;
  5305. this.receiveShadow = source.receiveShadow;
  5306. this.frustumCulled = source.frustumCulled;
  5307. this.renderOrder = source.renderOrder;
  5308. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5309. if ( recursive === true ) {
  5310. for ( var i = 0; i < source.children.length; i ++ ) {
  5311. var child = source.children[ i ];
  5312. this.add( child.clone() );
  5313. }
  5314. }
  5315. return this;
  5316. }
  5317. };
  5318. THREE.EventDispatcher.prototype.apply( THREE.Object3D.prototype );
  5319. THREE.Object3DIdCount = 0;
  5320. // File:src/core/Face3.js
  5321. /**
  5322. * @author mrdoob / http://mrdoob.com/
  5323. * @author alteredq / http://alteredqualia.com/
  5324. */
  5325. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  5326. this.a = a;
  5327. this.b = b;
  5328. this.c = c;
  5329. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  5330. this.vertexNormals = Array.isArray( normal ) ? normal : [];
  5331. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  5332. this.vertexColors = Array.isArray( color ) ? color : [];
  5333. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  5334. };
  5335. THREE.Face3.prototype = {
  5336. constructor: THREE.Face3,
  5337. clone: function () {
  5338. return new this.constructor().copy( this );
  5339. },
  5340. copy: function ( source ) {
  5341. this.a = source.a;
  5342. this.b = source.b;
  5343. this.c = source.c;
  5344. this.normal.copy( source.normal );
  5345. this.color.copy( source.color );
  5346. this.materialIndex = source.materialIndex;
  5347. for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) {
  5348. this.vertexNormals[ i ] = source.vertexNormals[ i ].clone();
  5349. }
  5350. for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) {
  5351. this.vertexColors[ i ] = source.vertexColors[ i ].clone();
  5352. }
  5353. return this;
  5354. }
  5355. };
  5356. // File:src/core/Face4.js
  5357. /**
  5358. * @author mrdoob / http://mrdoob.com/
  5359. */
  5360. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  5361. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' );
  5362. return new THREE.Face3( a, b, c, normal, color, materialIndex );
  5363. };
  5364. // File:src/core/BufferAttribute.js
  5365. /**
  5366. * @author mrdoob / http://mrdoob.com/
  5367. */
  5368. THREE.BufferAttribute = function ( array, itemSize ) {
  5369. this.uuid = THREE.Math.generateUUID();
  5370. this.array = array;
  5371. this.itemSize = itemSize;
  5372. this.dynamic = false;
  5373. this.updateRange = { offset: 0, count: - 1 };
  5374. this.version = 0;
  5375. };
  5376. THREE.BufferAttribute.prototype = {
  5377. constructor: THREE.BufferAttribute,
  5378. get count() {
  5379. return this.array.length / this.itemSize;
  5380. },
  5381. set needsUpdate( value ) {
  5382. if ( value === true ) this.version ++;
  5383. },
  5384. setDynamic: function ( value ) {
  5385. this.dynamic = value;
  5386. return this;
  5387. },
  5388. copy: function ( source ) {
  5389. this.array = new source.array.constructor( source.array );
  5390. this.itemSize = source.itemSize;
  5391. this.dynamic = source.dynamic;
  5392. return this;
  5393. },
  5394. copyAt: function ( index1, attribute, index2 ) {
  5395. index1 *= this.itemSize;
  5396. index2 *= attribute.itemSize;
  5397. for ( var i = 0, l = this.itemSize; i < l; i ++ ) {
  5398. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5399. }
  5400. return this;
  5401. },
  5402. copyArray: function ( array ) {
  5403. this.array.set( array );
  5404. return this;
  5405. },
  5406. copyColorsArray: function ( colors ) {
  5407. var array = this.array, offset = 0;
  5408. for ( var i = 0, l = colors.length; i < l; i ++ ) {
  5409. var color = colors[ i ];
  5410. if ( color === undefined ) {
  5411. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  5412. color = new THREE.Color();
  5413. }
  5414. array[ offset ++ ] = color.r;
  5415. array[ offset ++ ] = color.g;
  5416. array[ offset ++ ] = color.b;
  5417. }
  5418. return this;
  5419. },
  5420. copyIndicesArray: function ( indices ) {
  5421. var array = this.array, offset = 0;
  5422. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  5423. var index = indices[ i ];
  5424. array[ offset ++ ] = index.a;
  5425. array[ offset ++ ] = index.b;
  5426. array[ offset ++ ] = index.c;
  5427. }
  5428. return this;
  5429. },
  5430. copyVector2sArray: function ( vectors ) {
  5431. var array = this.array, offset = 0;
  5432. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  5433. var vector = vectors[ i ];
  5434. if ( vector === undefined ) {
  5435. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  5436. vector = new THREE.Vector2();
  5437. }
  5438. array[ offset ++ ] = vector.x;
  5439. array[ offset ++ ] = vector.y;
  5440. }
  5441. return this;
  5442. },
  5443. copyVector3sArray: function ( vectors ) {
  5444. var array = this.array, offset = 0;
  5445. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  5446. var vector = vectors[ i ];
  5447. if ( vector === undefined ) {
  5448. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  5449. vector = new THREE.Vector3();
  5450. }
  5451. array[ offset ++ ] = vector.x;
  5452. array[ offset ++ ] = vector.y;
  5453. array[ offset ++ ] = vector.z;
  5454. }
  5455. return this;
  5456. },
  5457. copyVector4sArray: function ( vectors ) {
  5458. var array = this.array, offset = 0;
  5459. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  5460. var vector = vectors[ i ];
  5461. if ( vector === undefined ) {
  5462. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  5463. vector = new THREE.Vector4();
  5464. }
  5465. array[ offset ++ ] = vector.x;
  5466. array[ offset ++ ] = vector.y;
  5467. array[ offset ++ ] = vector.z;
  5468. array[ offset ++ ] = vector.w;
  5469. }
  5470. return this;
  5471. },
  5472. set: function ( value, offset ) {
  5473. if ( offset === undefined ) offset = 0;
  5474. this.array.set( value, offset );
  5475. return this;
  5476. },
  5477. getX: function ( index ) {
  5478. return this.array[ index * this.itemSize ];
  5479. },
  5480. setX: function ( index, x ) {
  5481. this.array[ index * this.itemSize ] = x;
  5482. return this;
  5483. },
  5484. getY: function ( index ) {
  5485. return this.array[ index * this.itemSize + 1 ];
  5486. },
  5487. setY: function ( index, y ) {
  5488. this.array[ index * this.itemSize + 1 ] = y;
  5489. return this;
  5490. },
  5491. getZ: function ( index ) {
  5492. return this.array[ index * this.itemSize + 2 ];
  5493. },
  5494. setZ: function ( index, z ) {
  5495. this.array[ index * this.itemSize + 2 ] = z;
  5496. return this;
  5497. },
  5498. getW: function ( index ) {
  5499. return this.array[ index * this.itemSize + 3 ];
  5500. },
  5501. setW: function ( index, w ) {
  5502. this.array[ index * this.itemSize + 3 ] = w;
  5503. return this;
  5504. },
  5505. setXY: function ( index, x, y ) {
  5506. index *= this.itemSize;
  5507. this.array[ index + 0 ] = x;
  5508. this.array[ index + 1 ] = y;
  5509. return this;
  5510. },
  5511. setXYZ: function ( index, x, y, z ) {
  5512. index *= this.itemSize;
  5513. this.array[ index + 0 ] = x;
  5514. this.array[ index + 1 ] = y;
  5515. this.array[ index + 2 ] = z;
  5516. return this;
  5517. },
  5518. setXYZW: function ( index, x, y, z, w ) {
  5519. index *= this.itemSize;
  5520. this.array[ index + 0 ] = x;
  5521. this.array[ index + 1 ] = y;
  5522. this.array[ index + 2 ] = z;
  5523. this.array[ index + 3 ] = w;
  5524. return this;
  5525. },
  5526. clone: function () {
  5527. return new this.constructor().copy( this );
  5528. }
  5529. };
  5530. //
  5531. THREE.Int8Attribute = function ( array, itemSize ) {
  5532. return new THREE.BufferAttribute( new Int8Array( array ), itemSize );
  5533. };
  5534. THREE.Uint8Attribute = function ( array, itemSize ) {
  5535. return new THREE.BufferAttribute( new Uint8Array( array ), itemSize );
  5536. };
  5537. THREE.Uint8ClampedAttribute = function ( array, itemSize ) {
  5538. return new THREE.BufferAttribute( new Uint8ClampedArray( array ), itemSize );
  5539. };
  5540. THREE.Int16Attribute = function ( array, itemSize ) {
  5541. return new THREE.BufferAttribute( new Int16Array( array ), itemSize );
  5542. };
  5543. THREE.Uint16Attribute = function ( array, itemSize ) {
  5544. return new THREE.BufferAttribute( new Uint16Array( array ), itemSize );
  5545. };
  5546. THREE.Int32Attribute = function ( array, itemSize ) {
  5547. return new THREE.BufferAttribute( new Int32Array( array ), itemSize );
  5548. };
  5549. THREE.Uint32Attribute = function ( array, itemSize ) {
  5550. return new THREE.BufferAttribute( new Uint32Array( array ), itemSize );
  5551. };
  5552. THREE.Float32Attribute = function ( array, itemSize ) {
  5553. return new THREE.BufferAttribute( new Float32Array( array ), itemSize );
  5554. };
  5555. THREE.Float64Attribute = function ( array, itemSize ) {
  5556. return new THREE.BufferAttribute( new Float64Array( array ), itemSize );
  5557. };
  5558. // Deprecated
  5559. THREE.DynamicBufferAttribute = function ( array, itemSize ) {
  5560. console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.' );
  5561. return new THREE.BufferAttribute( array, itemSize ).setDynamic( true );
  5562. };
  5563. // File:src/core/InstancedBufferAttribute.js
  5564. /**
  5565. * @author benaadams / https://twitter.com/ben_a_adams
  5566. */
  5567. THREE.InstancedBufferAttribute = function ( array, itemSize, meshPerAttribute ) {
  5568. THREE.BufferAttribute.call( this, array, itemSize );
  5569. this.meshPerAttribute = meshPerAttribute || 1;
  5570. };
  5571. THREE.InstancedBufferAttribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5572. THREE.InstancedBufferAttribute.prototype.constructor = THREE.InstancedBufferAttribute;
  5573. THREE.InstancedBufferAttribute.prototype.copy = function ( source ) {
  5574. THREE.BufferAttribute.prototype.copy.call( this, source );
  5575. this.meshPerAttribute = source.meshPerAttribute;
  5576. return this;
  5577. };
  5578. // File:src/core/InterleavedBuffer.js
  5579. /**
  5580. * @author benaadams / https://twitter.com/ben_a_adams
  5581. */
  5582. THREE.InterleavedBuffer = function ( array, stride ) {
  5583. this.uuid = THREE.Math.generateUUID();
  5584. this.array = array;
  5585. this.stride = stride;
  5586. this.dynamic = false;
  5587. this.updateRange = { offset: 0, count: - 1 };
  5588. this.version = 0;
  5589. };
  5590. THREE.InterleavedBuffer.prototype = {
  5591. constructor: THREE.InterleavedBuffer,
  5592. get length () {
  5593. return this.array.length;
  5594. },
  5595. get count () {
  5596. return this.array.length / this.stride;
  5597. },
  5598. set needsUpdate( value ) {
  5599. if ( value === true ) this.version ++;
  5600. },
  5601. setDynamic: function ( value ) {
  5602. this.dynamic = value;
  5603. return this;
  5604. },
  5605. copy: function ( source ) {
  5606. this.array = new source.array.constructor( source.array );
  5607. this.stride = source.stride;
  5608. this.dynamic = source.dynamic;
  5609. return this;
  5610. },
  5611. copyAt: function ( index1, attribute, index2 ) {
  5612. index1 *= this.stride;
  5613. index2 *= attribute.stride;
  5614. for ( var i = 0, l = this.stride; i < l; i ++ ) {
  5615. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5616. }
  5617. return this;
  5618. },
  5619. set: function ( value, offset ) {
  5620. if ( offset === undefined ) offset = 0;
  5621. this.array.set( value, offset );
  5622. return this;
  5623. },
  5624. clone: function () {
  5625. return new this.constructor().copy( this );
  5626. }
  5627. };
  5628. // File:src/core/InstancedInterleavedBuffer.js
  5629. /**
  5630. * @author benaadams / https://twitter.com/ben_a_adams
  5631. */
  5632. THREE.InstancedInterleavedBuffer = function ( array, stride, meshPerAttribute ) {
  5633. THREE.InterleavedBuffer.call( this, array, stride );
  5634. this.meshPerAttribute = meshPerAttribute || 1;
  5635. };
  5636. THREE.InstancedInterleavedBuffer.prototype = Object.create( THREE.InterleavedBuffer.prototype );
  5637. THREE.InstancedInterleavedBuffer.prototype.constructor = THREE.InstancedInterleavedBuffer;
  5638. THREE.InstancedInterleavedBuffer.prototype.copy = function ( source ) {
  5639. THREE.InterleavedBuffer.prototype.copy.call( this, source );
  5640. this.meshPerAttribute = source.meshPerAttribute;
  5641. return this;
  5642. };
  5643. // File:src/core/InterleavedBufferAttribute.js
  5644. /**
  5645. * @author benaadams / https://twitter.com/ben_a_adams
  5646. */
  5647. THREE.InterleavedBufferAttribute = function ( interleavedBuffer, itemSize, offset ) {
  5648. this.uuid = THREE.Math.generateUUID();
  5649. this.data = interleavedBuffer;
  5650. this.itemSize = itemSize;
  5651. this.offset = offset;
  5652. };
  5653. THREE.InterleavedBufferAttribute.prototype = {
  5654. constructor: THREE.InterleavedBufferAttribute,
  5655. get length() {
  5656. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Please use .count.' );
  5657. return this.array.length;
  5658. },
  5659. get count() {
  5660. return this.data.count;
  5661. },
  5662. setX: function ( index, x ) {
  5663. this.data.array[ index * this.data.stride + this.offset ] = x;
  5664. return this;
  5665. },
  5666. setY: function ( index, y ) {
  5667. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  5668. return this;
  5669. },
  5670. setZ: function ( index, z ) {
  5671. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  5672. return this;
  5673. },
  5674. setW: function ( index, w ) {
  5675. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  5676. return this;
  5677. },
  5678. getX: function ( index ) {
  5679. return this.data.array[ index * this.data.stride + this.offset ];
  5680. },
  5681. getY: function ( index ) {
  5682. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  5683. },
  5684. getZ: function ( index ) {
  5685. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  5686. },
  5687. getW: function ( index ) {
  5688. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  5689. },
  5690. setXY: function ( index, x, y ) {
  5691. index = index * this.data.stride + this.offset;
  5692. this.data.array[ index + 0 ] = x;
  5693. this.data.array[ index + 1 ] = y;
  5694. return this;
  5695. },
  5696. setXYZ: function ( index, x, y, z ) {
  5697. index = index * this.data.stride + this.offset;
  5698. this.data.array[ index + 0 ] = x;
  5699. this.data.array[ index + 1 ] = y;
  5700. this.data.array[ index + 2 ] = z;
  5701. return this;
  5702. },
  5703. setXYZW: function ( index, x, y, z, w ) {
  5704. index = index * this.data.stride + this.offset;
  5705. this.data.array[ index + 0 ] = x;
  5706. this.data.array[ index + 1 ] = y;
  5707. this.data.array[ index + 2 ] = z;
  5708. this.data.array[ index + 3 ] = w;
  5709. return this;
  5710. }
  5711. };
  5712. // File:src/core/Geometry.js
  5713. /**
  5714. * @author mrdoob / http://mrdoob.com/
  5715. * @author kile / http://kile.stravaganza.org/
  5716. * @author alteredq / http://alteredqualia.com/
  5717. * @author mikael emtinger / http://gomo.se/
  5718. * @author zz85 / http://www.lab4games.net/zz85/blog
  5719. * @author bhouston / http://clara.io
  5720. */
  5721. THREE.Geometry = function () {
  5722. Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } );
  5723. this.uuid = THREE.Math.generateUUID();
  5724. this.name = '';
  5725. this.type = 'Geometry';
  5726. this.vertices = [];
  5727. this.colors = [];
  5728. this.faces = [];
  5729. this.faceVertexUvs = [ [] ];
  5730. this.morphTargets = [];
  5731. this.morphNormals = [];
  5732. this.skinWeights = [];
  5733. this.skinIndices = [];
  5734. this.lineDistances = [];
  5735. this.boundingBox = null;
  5736. this.boundingSphere = null;
  5737. // update flags
  5738. this.verticesNeedUpdate = false;
  5739. this.elementsNeedUpdate = false;
  5740. this.uvsNeedUpdate = false;
  5741. this.normalsNeedUpdate = false;
  5742. this.colorsNeedUpdate = false;
  5743. this.lineDistancesNeedUpdate = false;
  5744. this.groupsNeedUpdate = false;
  5745. };
  5746. THREE.Geometry.prototype = {
  5747. constructor: THREE.Geometry,
  5748. applyMatrix: function ( matrix ) {
  5749. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5750. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  5751. var vertex = this.vertices[ i ];
  5752. vertex.applyMatrix4( matrix );
  5753. }
  5754. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  5755. var face = this.faces[ i ];
  5756. face.normal.applyMatrix3( normalMatrix ).normalize();
  5757. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  5758. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  5759. }
  5760. }
  5761. if ( this.boundingBox !== null ) {
  5762. this.computeBoundingBox();
  5763. }
  5764. if ( this.boundingSphere !== null ) {
  5765. this.computeBoundingSphere();
  5766. }
  5767. this.verticesNeedUpdate = true;
  5768. this.normalsNeedUpdate = true;
  5769. },
  5770. rotateX: function () {
  5771. // rotate geometry around world x-axis
  5772. var m1;
  5773. return function rotateX( angle ) {
  5774. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  5775. m1.makeRotationX( angle );
  5776. this.applyMatrix( m1 );
  5777. return this;
  5778. };
  5779. }(),
  5780. rotateY: function () {
  5781. // rotate geometry around world y-axis
  5782. var m1;
  5783. return function rotateY( angle ) {
  5784. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  5785. m1.makeRotationY( angle );
  5786. this.applyMatrix( m1 );
  5787. return this;
  5788. };
  5789. }(),
  5790. rotateZ: function () {
  5791. // rotate geometry around world z-axis
  5792. var m1;
  5793. return function rotateZ( angle ) {
  5794. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  5795. m1.makeRotationZ( angle );
  5796. this.applyMatrix( m1 );
  5797. return this;
  5798. };
  5799. }(),
  5800. translate: function () {
  5801. // translate geometry
  5802. var m1;
  5803. return function translate( x, y, z ) {
  5804. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  5805. m1.makeTranslation( x, y, z );
  5806. this.applyMatrix( m1 );
  5807. return this;
  5808. };
  5809. }(),
  5810. scale: function () {
  5811. // scale geometry
  5812. var m1;
  5813. return function scale( x, y, z ) {
  5814. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  5815. m1.makeScale( x, y, z );
  5816. this.applyMatrix( m1 );
  5817. return this;
  5818. };
  5819. }(),
  5820. lookAt: function () {
  5821. var obj;
  5822. return function lookAt( vector ) {
  5823. if ( obj === undefined ) obj = new THREE.Object3D();
  5824. obj.lookAt( vector );
  5825. obj.updateMatrix();
  5826. this.applyMatrix( obj.matrix );
  5827. };
  5828. }(),
  5829. fromBufferGeometry: function ( geometry ) {
  5830. var scope = this;
  5831. var indices = geometry.index !== null ? geometry.index.array : undefined;
  5832. var attributes = geometry.attributes;
  5833. var positions = attributes.position.array;
  5834. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  5835. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  5836. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  5837. var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;
  5838. if ( uvs2 !== undefined ) this.faceVertexUvs[ 1 ] = [];
  5839. var tempNormals = [];
  5840. var tempUVs = [];
  5841. var tempUVs2 = [];
  5842. for ( var i = 0, j = 0; i < positions.length; i += 3, j += 2 ) {
  5843. scope.vertices.push( new THREE.Vector3( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ) );
  5844. if ( normals !== undefined ) {
  5845. tempNormals.push( new THREE.Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) );
  5846. }
  5847. if ( colors !== undefined ) {
  5848. scope.colors.push( new THREE.Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) );
  5849. }
  5850. if ( uvs !== undefined ) {
  5851. tempUVs.push( new THREE.Vector2( uvs[ j ], uvs[ j + 1 ] ) );
  5852. }
  5853. if ( uvs2 !== undefined ) {
  5854. tempUVs2.push( new THREE.Vector2( uvs2[ j ], uvs2[ j + 1 ] ) );
  5855. }
  5856. }
  5857. function addFace( a, b, c ) {
  5858. var vertexNormals = normals !== undefined ? [ tempNormals[ a ].clone(), tempNormals[ b ].clone(), tempNormals[ c ].clone() ] : [];
  5859. var vertexColors = colors !== undefined ? [ scope.colors[ a ].clone(), scope.colors[ b ].clone(), scope.colors[ c ].clone() ] : [];
  5860. var face = new THREE.Face3( a, b, c, vertexNormals, vertexColors );
  5861. scope.faces.push( face );
  5862. if ( uvs !== undefined ) {
  5863. scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] );
  5864. }
  5865. if ( uvs2 !== undefined ) {
  5866. scope.faceVertexUvs[ 1 ].push( [ tempUVs2[ a ].clone(), tempUVs2[ b ].clone(), tempUVs2[ c ].clone() ] );
  5867. }
  5868. }
  5869. if ( indices !== undefined ) {
  5870. var groups = geometry.groups;
  5871. if ( groups.length > 0 ) {
  5872. for ( var i = 0; i < groups.length; i ++ ) {
  5873. var group = groups[ i ];
  5874. var start = group.start;
  5875. var count = group.count;
  5876. for ( var j = start, jl = start + count; j < jl; j += 3 ) {
  5877. addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ] );
  5878. }
  5879. }
  5880. } else {
  5881. for ( var i = 0; i < indices.length; i += 3 ) {
  5882. addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  5883. }
  5884. }
  5885. } else {
  5886. for ( var i = 0; i < positions.length / 3; i += 3 ) {
  5887. addFace( i, i + 1, i + 2 );
  5888. }
  5889. }
  5890. this.computeFaceNormals();
  5891. if ( geometry.boundingBox !== null ) {
  5892. this.boundingBox = geometry.boundingBox.clone();
  5893. }
  5894. if ( geometry.boundingSphere !== null ) {
  5895. this.boundingSphere = geometry.boundingSphere.clone();
  5896. }
  5897. return this;
  5898. },
  5899. center: function () {
  5900. this.computeBoundingBox();
  5901. var offset = this.boundingBox.center().negate();
  5902. this.translate( offset.x, offset.y, offset.z );
  5903. return offset;
  5904. },
  5905. normalize: function () {
  5906. this.computeBoundingSphere();
  5907. var center = this.boundingSphere.center;
  5908. var radius = this.boundingSphere.radius;
  5909. var s = radius === 0 ? 1 : 1.0 / radius;
  5910. var matrix = new THREE.Matrix4();
  5911. matrix.set(
  5912. s, 0, 0, - s * center.x,
  5913. 0, s, 0, - s * center.y,
  5914. 0, 0, s, - s * center.z,
  5915. 0, 0, 0, 1
  5916. );
  5917. this.applyMatrix( matrix );
  5918. return this;
  5919. },
  5920. computeFaceNormals: function () {
  5921. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  5922. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5923. var face = this.faces[ f ];
  5924. var vA = this.vertices[ face.a ];
  5925. var vB = this.vertices[ face.b ];
  5926. var vC = this.vertices[ face.c ];
  5927. cb.subVectors( vC, vB );
  5928. ab.subVectors( vA, vB );
  5929. cb.cross( ab );
  5930. cb.normalize();
  5931. face.normal.copy( cb );
  5932. }
  5933. },
  5934. computeVertexNormals: function ( areaWeighted ) {
  5935. var v, vl, f, fl, face, vertices;
  5936. vertices = new Array( this.vertices.length );
  5937. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5938. vertices[ v ] = new THREE.Vector3();
  5939. }
  5940. if ( areaWeighted ) {
  5941. // vertex normals weighted by triangle areas
  5942. // http://www.iquilezles.org/www/articles/normals/normals.htm
  5943. var vA, vB, vC;
  5944. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  5945. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5946. face = this.faces[ f ];
  5947. vA = this.vertices[ face.a ];
  5948. vB = this.vertices[ face.b ];
  5949. vC = this.vertices[ face.c ];
  5950. cb.subVectors( vC, vB );
  5951. ab.subVectors( vA, vB );
  5952. cb.cross( ab );
  5953. vertices[ face.a ].add( cb );
  5954. vertices[ face.b ].add( cb );
  5955. vertices[ face.c ].add( cb );
  5956. }
  5957. } else {
  5958. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5959. face = this.faces[ f ];
  5960. vertices[ face.a ].add( face.normal );
  5961. vertices[ face.b ].add( face.normal );
  5962. vertices[ face.c ].add( face.normal );
  5963. }
  5964. }
  5965. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5966. vertices[ v ].normalize();
  5967. }
  5968. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5969. face = this.faces[ f ];
  5970. var vertexNormals = face.vertexNormals;
  5971. if ( vertexNormals.length === 3 ) {
  5972. vertexNormals[ 0 ].copy( vertices[ face.a ] );
  5973. vertexNormals[ 1 ].copy( vertices[ face.b ] );
  5974. vertexNormals[ 2 ].copy( vertices[ face.c ] );
  5975. } else {
  5976. vertexNormals[ 0 ] = vertices[ face.a ].clone();
  5977. vertexNormals[ 1 ] = vertices[ face.b ].clone();
  5978. vertexNormals[ 2 ] = vertices[ face.c ].clone();
  5979. }
  5980. }
  5981. },
  5982. computeMorphNormals: function () {
  5983. var i, il, f, fl, face;
  5984. // save original normals
  5985. // - create temp variables on first access
  5986. // otherwise just copy (for faster repeated calls)
  5987. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5988. face = this.faces[ f ];
  5989. if ( ! face.__originalFaceNormal ) {
  5990. face.__originalFaceNormal = face.normal.clone();
  5991. } else {
  5992. face.__originalFaceNormal.copy( face.normal );
  5993. }
  5994. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  5995. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  5996. if ( ! face.__originalVertexNormals[ i ] ) {
  5997. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  5998. } else {
  5999. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  6000. }
  6001. }
  6002. }
  6003. // use temp geometry to compute face and vertex normals for each morph
  6004. var tmpGeo = new THREE.Geometry();
  6005. tmpGeo.faces = this.faces;
  6006. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  6007. // create on first access
  6008. if ( ! this.morphNormals[ i ] ) {
  6009. this.morphNormals[ i ] = {};
  6010. this.morphNormals[ i ].faceNormals = [];
  6011. this.morphNormals[ i ].vertexNormals = [];
  6012. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  6013. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  6014. var faceNormal, vertexNormals;
  6015. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6016. faceNormal = new THREE.Vector3();
  6017. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  6018. dstNormalsFace.push( faceNormal );
  6019. dstNormalsVertex.push( vertexNormals );
  6020. }
  6021. }
  6022. var morphNormals = this.morphNormals[ i ];
  6023. // set vertices to morph target
  6024. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  6025. // compute morph normals
  6026. tmpGeo.computeFaceNormals();
  6027. tmpGeo.computeVertexNormals();
  6028. // store morph normals
  6029. var faceNormal, vertexNormals;
  6030. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6031. face = this.faces[ f ];
  6032. faceNormal = morphNormals.faceNormals[ f ];
  6033. vertexNormals = morphNormals.vertexNormals[ f ];
  6034. faceNormal.copy( face.normal );
  6035. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  6036. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  6037. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  6038. }
  6039. }
  6040. // restore original normals
  6041. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6042. face = this.faces[ f ];
  6043. face.normal = face.__originalFaceNormal;
  6044. face.vertexNormals = face.__originalVertexNormals;
  6045. }
  6046. },
  6047. computeTangents: function () {
  6048. console.warn( 'THREE.Geometry: .computeTangents() has been removed.' );
  6049. },
  6050. computeLineDistances: function () {
  6051. var d = 0;
  6052. var vertices = this.vertices;
  6053. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  6054. if ( i > 0 ) {
  6055. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  6056. }
  6057. this.lineDistances[ i ] = d;
  6058. }
  6059. },
  6060. computeBoundingBox: function () {
  6061. if ( this.boundingBox === null ) {
  6062. this.boundingBox = new THREE.Box3();
  6063. }
  6064. this.boundingBox.setFromPoints( this.vertices );
  6065. },
  6066. computeBoundingSphere: function () {
  6067. if ( this.boundingSphere === null ) {
  6068. this.boundingSphere = new THREE.Sphere();
  6069. }
  6070. this.boundingSphere.setFromPoints( this.vertices );
  6071. },
  6072. merge: function ( geometry, matrix, materialIndexOffset ) {
  6073. if ( geometry instanceof THREE.Geometry === false ) {
  6074. console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  6075. return;
  6076. }
  6077. var normalMatrix,
  6078. vertexOffset = this.vertices.length,
  6079. vertices1 = this.vertices,
  6080. vertices2 = geometry.vertices,
  6081. faces1 = this.faces,
  6082. faces2 = geometry.faces,
  6083. uvs1 = this.faceVertexUvs[ 0 ],
  6084. uvs2 = geometry.faceVertexUvs[ 0 ];
  6085. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  6086. if ( matrix !== undefined ) {
  6087. normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  6088. }
  6089. // vertices
  6090. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  6091. var vertex = vertices2[ i ];
  6092. var vertexCopy = vertex.clone();
  6093. if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
  6094. vertices1.push( vertexCopy );
  6095. }
  6096. // faces
  6097. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  6098. var face = faces2[ i ], faceCopy, normal, color,
  6099. faceVertexNormals = face.vertexNormals,
  6100. faceVertexColors = face.vertexColors;
  6101. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  6102. faceCopy.normal.copy( face.normal );
  6103. if ( normalMatrix !== undefined ) {
  6104. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  6105. }
  6106. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  6107. normal = faceVertexNormals[ j ].clone();
  6108. if ( normalMatrix !== undefined ) {
  6109. normal.applyMatrix3( normalMatrix ).normalize();
  6110. }
  6111. faceCopy.vertexNormals.push( normal );
  6112. }
  6113. faceCopy.color.copy( face.color );
  6114. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  6115. color = faceVertexColors[ j ];
  6116. faceCopy.vertexColors.push( color.clone() );
  6117. }
  6118. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  6119. faces1.push( faceCopy );
  6120. }
  6121. // uvs
  6122. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  6123. var uv = uvs2[ i ], uvCopy = [];
  6124. if ( uv === undefined ) {
  6125. continue;
  6126. }
  6127. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  6128. uvCopy.push( uv[ j ].clone() );
  6129. }
  6130. uvs1.push( uvCopy );
  6131. }
  6132. },
  6133. mergeMesh: function ( mesh ) {
  6134. if ( mesh instanceof THREE.Mesh === false ) {
  6135. console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
  6136. return;
  6137. }
  6138. mesh.matrixAutoUpdate && mesh.updateMatrix();
  6139. this.merge( mesh.geometry, mesh.matrix );
  6140. },
  6141. /*
  6142. * Checks for duplicate vertices with hashmap.
  6143. * Duplicated vertices are removed
  6144. * and faces' vertices are updated.
  6145. */
  6146. mergeVertices: function () {
  6147. var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  6148. var unique = [], changes = [];
  6149. var v, key;
  6150. var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
  6151. var precision = Math.pow( 10, precisionPoints );
  6152. var i, il, face;
  6153. var indices, j, jl;
  6154. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  6155. v = this.vertices[ i ];
  6156. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  6157. if ( verticesMap[ key ] === undefined ) {
  6158. verticesMap[ key ] = i;
  6159. unique.push( this.vertices[ i ] );
  6160. changes[ i ] = unique.length - 1;
  6161. } else {
  6162. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  6163. changes[ i ] = changes[ verticesMap[ key ] ];
  6164. }
  6165. }
  6166. // if faces are completely degenerate after merging vertices, we
  6167. // have to remove them from the geometry.
  6168. var faceIndicesToRemove = [];
  6169. for ( i = 0, il = this.faces.length; i < il; i ++ ) {
  6170. face = this.faces[ i ];
  6171. face.a = changes[ face.a ];
  6172. face.b = changes[ face.b ];
  6173. face.c = changes[ face.c ];
  6174. indices = [ face.a, face.b, face.c ];
  6175. var dupIndex = - 1;
  6176. // if any duplicate vertices are found in a Face3
  6177. // we have to remove the face as nothing can be saved
  6178. for ( var n = 0; n < 3; n ++ ) {
  6179. if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) {
  6180. dupIndex = n;
  6181. faceIndicesToRemove.push( i );
  6182. break;
  6183. }
  6184. }
  6185. }
  6186. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  6187. var idx = faceIndicesToRemove[ i ];
  6188. this.faces.splice( idx, 1 );
  6189. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  6190. this.faceVertexUvs[ j ].splice( idx, 1 );
  6191. }
  6192. }
  6193. // Use unique set of vertices
  6194. var diff = this.vertices.length - unique.length;
  6195. this.vertices = unique;
  6196. return diff;
  6197. },
  6198. sortFacesByMaterialIndex: function () {
  6199. var faces = this.faces;
  6200. var length = faces.length;
  6201. // tag faces
  6202. for ( var i = 0; i < length; i ++ ) {
  6203. faces[ i ]._id = i;
  6204. }
  6205. // sort faces
  6206. function materialIndexSort( a, b ) {
  6207. return a.materialIndex - b.materialIndex;
  6208. }
  6209. faces.sort( materialIndexSort );
  6210. // sort uvs
  6211. var uvs1 = this.faceVertexUvs[ 0 ];
  6212. var uvs2 = this.faceVertexUvs[ 1 ];
  6213. var newUvs1, newUvs2;
  6214. if ( uvs1 && uvs1.length === length ) newUvs1 = [];
  6215. if ( uvs2 && uvs2.length === length ) newUvs2 = [];
  6216. for ( var i = 0; i < length; i ++ ) {
  6217. var id = faces[ i ]._id;
  6218. if ( newUvs1 ) newUvs1.push( uvs1[ id ] );
  6219. if ( newUvs2 ) newUvs2.push( uvs2[ id ] );
  6220. }
  6221. if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1;
  6222. if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2;
  6223. },
  6224. toJSON: function () {
  6225. var data = {
  6226. metadata: {
  6227. version: 4.4,
  6228. type: 'Geometry',
  6229. generator: 'Geometry.toJSON'
  6230. }
  6231. };
  6232. // standard Geometry serialization
  6233. data.uuid = this.uuid;
  6234. data.type = this.type;
  6235. if ( this.name !== '' ) data.name = this.name;
  6236. if ( this.parameters !== undefined ) {
  6237. var parameters = this.parameters;
  6238. for ( var key in parameters ) {
  6239. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6240. }
  6241. return data;
  6242. }
  6243. var vertices = [];
  6244. for ( var i = 0; i < this.vertices.length; i ++ ) {
  6245. var vertex = this.vertices[ i ];
  6246. vertices.push( vertex.x, vertex.y, vertex.z );
  6247. }
  6248. var faces = [];
  6249. var normals = [];
  6250. var normalsHash = {};
  6251. var colors = [];
  6252. var colorsHash = {};
  6253. var uvs = [];
  6254. var uvsHash = {};
  6255. for ( var i = 0; i < this.faces.length; i ++ ) {
  6256. var face = this.faces[ i ];
  6257. var hasMaterial = true;
  6258. var hasFaceUv = false; // deprecated
  6259. var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined;
  6260. var hasFaceNormal = face.normal.length() > 0;
  6261. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  6262. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  6263. var hasFaceVertexColor = face.vertexColors.length > 0;
  6264. var faceType = 0;
  6265. faceType = setBit( faceType, 0, 0 ); // isQuad
  6266. faceType = setBit( faceType, 1, hasMaterial );
  6267. faceType = setBit( faceType, 2, hasFaceUv );
  6268. faceType = setBit( faceType, 3, hasFaceVertexUv );
  6269. faceType = setBit( faceType, 4, hasFaceNormal );
  6270. faceType = setBit( faceType, 5, hasFaceVertexNormal );
  6271. faceType = setBit( faceType, 6, hasFaceColor );
  6272. faceType = setBit( faceType, 7, hasFaceVertexColor );
  6273. faces.push( faceType );
  6274. faces.push( face.a, face.b, face.c );
  6275. faces.push( face.materialIndex );
  6276. if ( hasFaceVertexUv ) {
  6277. var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ];
  6278. faces.push(
  6279. getUvIndex( faceVertexUvs[ 0 ] ),
  6280. getUvIndex( faceVertexUvs[ 1 ] ),
  6281. getUvIndex( faceVertexUvs[ 2 ] )
  6282. );
  6283. }
  6284. if ( hasFaceNormal ) {
  6285. faces.push( getNormalIndex( face.normal ) );
  6286. }
  6287. if ( hasFaceVertexNormal ) {
  6288. var vertexNormals = face.vertexNormals;
  6289. faces.push(
  6290. getNormalIndex( vertexNormals[ 0 ] ),
  6291. getNormalIndex( vertexNormals[ 1 ] ),
  6292. getNormalIndex( vertexNormals[ 2 ] )
  6293. );
  6294. }
  6295. if ( hasFaceColor ) {
  6296. faces.push( getColorIndex( face.color ) );
  6297. }
  6298. if ( hasFaceVertexColor ) {
  6299. var vertexColors = face.vertexColors;
  6300. faces.push(
  6301. getColorIndex( vertexColors[ 0 ] ),
  6302. getColorIndex( vertexColors[ 1 ] ),
  6303. getColorIndex( vertexColors[ 2 ] )
  6304. );
  6305. }
  6306. }
  6307. function setBit( value, position, enabled ) {
  6308. return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) );
  6309. }
  6310. function getNormalIndex( normal ) {
  6311. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  6312. if ( normalsHash[ hash ] !== undefined ) {
  6313. return normalsHash[ hash ];
  6314. }
  6315. normalsHash[ hash ] = normals.length / 3;
  6316. normals.push( normal.x, normal.y, normal.z );
  6317. return normalsHash[ hash ];
  6318. }
  6319. function getColorIndex( color ) {
  6320. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  6321. if ( colorsHash[ hash ] !== undefined ) {
  6322. return colorsHash[ hash ];
  6323. }
  6324. colorsHash[ hash ] = colors.length;
  6325. colors.push( color.getHex() );
  6326. return colorsHash[ hash ];
  6327. }
  6328. function getUvIndex( uv ) {
  6329. var hash = uv.x.toString() + uv.y.toString();
  6330. if ( uvsHash[ hash ] !== undefined ) {
  6331. return uvsHash[ hash ];
  6332. }
  6333. uvsHash[ hash ] = uvs.length / 2;
  6334. uvs.push( uv.x, uv.y );
  6335. return uvsHash[ hash ];
  6336. }
  6337. data.data = {};
  6338. data.data.vertices = vertices;
  6339. data.data.normals = normals;
  6340. if ( colors.length > 0 ) data.data.colors = colors;
  6341. if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility
  6342. data.data.faces = faces;
  6343. return data;
  6344. },
  6345. clone: function () {
  6346. /*
  6347. // Handle primitives
  6348. var parameters = this.parameters;
  6349. if ( parameters !== undefined ) {
  6350. var values = [];
  6351. for ( var key in parameters ) {
  6352. values.push( parameters[ key ] );
  6353. }
  6354. var geometry = Object.create( this.constructor.prototype );
  6355. this.constructor.apply( geometry, values );
  6356. return geometry;
  6357. }
  6358. return new this.constructor().copy( this );
  6359. */
  6360. return new THREE.Geometry().copy( this );
  6361. },
  6362. copy: function ( source ) {
  6363. this.vertices = [];
  6364. this.faces = [];
  6365. this.faceVertexUvs = [ [] ];
  6366. var vertices = source.vertices;
  6367. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  6368. this.vertices.push( vertices[ i ].clone() );
  6369. }
  6370. var faces = source.faces;
  6371. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  6372. this.faces.push( faces[ i ].clone() );
  6373. }
  6374. for ( var i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) {
  6375. var faceVertexUvs = source.faceVertexUvs[ i ];
  6376. if ( this.faceVertexUvs[ i ] === undefined ) {
  6377. this.faceVertexUvs[ i ] = [];
  6378. }
  6379. for ( var j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {
  6380. var uvs = faceVertexUvs[ j ], uvsCopy = [];
  6381. for ( var k = 0, kl = uvs.length; k < kl; k ++ ) {
  6382. var uv = uvs[ k ];
  6383. uvsCopy.push( uv.clone() );
  6384. }
  6385. this.faceVertexUvs[ i ].push( uvsCopy );
  6386. }
  6387. }
  6388. return this;
  6389. },
  6390. dispose: function () {
  6391. this.dispatchEvent( { type: 'dispose' } );
  6392. }
  6393. };
  6394. THREE.EventDispatcher.prototype.apply( THREE.Geometry.prototype );
  6395. THREE.GeometryIdCount = 0;
  6396. // File:src/core/DirectGeometry.js
  6397. /**
  6398. * @author mrdoob / http://mrdoob.com/
  6399. */
  6400. THREE.DirectGeometry = function () {
  6401. Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } );
  6402. this.uuid = THREE.Math.generateUUID();
  6403. this.name = '';
  6404. this.type = 'DirectGeometry';
  6405. this.indices = [];
  6406. this.vertices = [];
  6407. this.normals = [];
  6408. this.colors = [];
  6409. this.uvs = [];
  6410. this.uvs2 = [];
  6411. this.groups = [];
  6412. this.morphTargets = {};
  6413. this.skinWeights = [];
  6414. this.skinIndices = [];
  6415. // this.lineDistances = [];
  6416. this.boundingBox = null;
  6417. this.boundingSphere = null;
  6418. // update flags
  6419. this.verticesNeedUpdate = false;
  6420. this.normalsNeedUpdate = false;
  6421. this.colorsNeedUpdate = false;
  6422. this.uvsNeedUpdate = false;
  6423. this.groupsNeedUpdate = false;
  6424. };
  6425. THREE.DirectGeometry.prototype = {
  6426. constructor: THREE.DirectGeometry,
  6427. computeBoundingBox: THREE.Geometry.prototype.computeBoundingBox,
  6428. computeBoundingSphere: THREE.Geometry.prototype.computeBoundingSphere,
  6429. computeFaceNormals: function () {
  6430. console.warn( 'THREE.DirectGeometry: computeFaceNormals() is not a method of this type of geometry.' );
  6431. },
  6432. computeVertexNormals: function () {
  6433. console.warn( 'THREE.DirectGeometry: computeVertexNormals() is not a method of this type of geometry.' );
  6434. },
  6435. computeGroups: function ( geometry ) {
  6436. var group;
  6437. var groups = [];
  6438. var materialIndex;
  6439. var faces = geometry.faces;
  6440. for ( var i = 0; i < faces.length; i ++ ) {
  6441. var face = faces[ i ];
  6442. // materials
  6443. if ( face.materialIndex !== materialIndex ) {
  6444. materialIndex = face.materialIndex;
  6445. if ( group !== undefined ) {
  6446. group.count = ( i * 3 ) - group.start;
  6447. groups.push( group );
  6448. }
  6449. group = {
  6450. start: i * 3,
  6451. materialIndex: materialIndex
  6452. };
  6453. }
  6454. }
  6455. if ( group !== undefined ) {
  6456. group.count = ( i * 3 ) - group.start;
  6457. groups.push( group );
  6458. }
  6459. this.groups = groups;
  6460. },
  6461. fromGeometry: function ( geometry ) {
  6462. var faces = geometry.faces;
  6463. var vertices = geometry.vertices;
  6464. var faceVertexUvs = geometry.faceVertexUvs;
  6465. var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0;
  6466. var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0;
  6467. // morphs
  6468. var morphTargets = geometry.morphTargets;
  6469. var morphTargetsLength = morphTargets.length;
  6470. var morphTargetsPosition;
  6471. if ( morphTargetsLength > 0 ) {
  6472. morphTargetsPosition = [];
  6473. for ( var i = 0; i < morphTargetsLength; i ++ ) {
  6474. morphTargetsPosition[ i ] = [];
  6475. }
  6476. this.morphTargets.position = morphTargetsPosition;
  6477. }
  6478. var morphNormals = geometry.morphNormals;
  6479. var morphNormalsLength = morphNormals.length;
  6480. var morphTargetsNormal;
  6481. if ( morphNormalsLength > 0 ) {
  6482. morphTargetsNormal = [];
  6483. for ( var i = 0; i < morphNormalsLength; i ++ ) {
  6484. morphTargetsNormal[ i ] = [];
  6485. }
  6486. this.morphTargets.normal = morphTargetsNormal;
  6487. }
  6488. // skins
  6489. var skinIndices = geometry.skinIndices;
  6490. var skinWeights = geometry.skinWeights;
  6491. var hasSkinIndices = skinIndices.length === vertices.length;
  6492. var hasSkinWeights = skinWeights.length === vertices.length;
  6493. //
  6494. for ( var i = 0; i < faces.length; i ++ ) {
  6495. var face = faces[ i ];
  6496. this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] );
  6497. var vertexNormals = face.vertexNormals;
  6498. if ( vertexNormals.length === 3 ) {
  6499. this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] );
  6500. } else {
  6501. var normal = face.normal;
  6502. this.normals.push( normal, normal, normal );
  6503. }
  6504. var vertexColors = face.vertexColors;
  6505. if ( vertexColors.length === 3 ) {
  6506. this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] );
  6507. } else {
  6508. var color = face.color;
  6509. this.colors.push( color, color, color );
  6510. }
  6511. if ( hasFaceVertexUv === true ) {
  6512. var vertexUvs = faceVertexUvs[ 0 ][ i ];
  6513. if ( vertexUvs !== undefined ) {
  6514. this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  6515. } else {
  6516. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i );
  6517. this.uvs.push( new THREE.Vector2(), new THREE.Vector2(), new THREE.Vector2() );
  6518. }
  6519. }
  6520. if ( hasFaceVertexUv2 === true ) {
  6521. var vertexUvs = faceVertexUvs[ 1 ][ i ];
  6522. if ( vertexUvs !== undefined ) {
  6523. this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  6524. } else {
  6525. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i );
  6526. this.uvs2.push( new THREE.Vector2(), new THREE.Vector2(), new THREE.Vector2() );
  6527. }
  6528. }
  6529. // morphs
  6530. for ( var j = 0; j < morphTargetsLength; j ++ ) {
  6531. var morphTarget = morphTargets[ j ].vertices;
  6532. morphTargetsPosition[ j ].push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] );
  6533. }
  6534. for ( var j = 0; j < morphNormalsLength; j ++ ) {
  6535. var morphNormal = morphNormals[ j ].vertexNormals[ i ];
  6536. morphTargetsNormal[ j ].push( morphNormal.a, morphNormal.b, morphNormal.c );
  6537. }
  6538. // skins
  6539. if ( hasSkinIndices ) {
  6540. this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] );
  6541. }
  6542. if ( hasSkinWeights ) {
  6543. this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] );
  6544. }
  6545. }
  6546. this.computeGroups( geometry );
  6547. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  6548. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  6549. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  6550. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  6551. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  6552. return this;
  6553. },
  6554. dispose: function () {
  6555. this.dispatchEvent( { type: 'dispose' } );
  6556. }
  6557. };
  6558. THREE.EventDispatcher.prototype.apply( THREE.DirectGeometry.prototype );
  6559. // File:src/core/BufferGeometry.js
  6560. /**
  6561. * @author alteredq / http://alteredqualia.com/
  6562. * @author mrdoob / http://mrdoob.com/
  6563. */
  6564. THREE.BufferGeometry = function () {
  6565. Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } );
  6566. this.uuid = THREE.Math.generateUUID();
  6567. this.name = '';
  6568. this.type = 'BufferGeometry';
  6569. this.index = null;
  6570. this.attributes = {};
  6571. this.morphAttributes = {};
  6572. this.groups = [];
  6573. this.boundingBox = null;
  6574. this.boundingSphere = null;
  6575. this.drawRange = { start: 0, count: Infinity };
  6576. };
  6577. THREE.BufferGeometry.prototype = {
  6578. constructor: THREE.BufferGeometry,
  6579. addIndex: function ( index ) {
  6580. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  6581. this.setIndex( index );
  6582. },
  6583. getIndex: function () {
  6584. return this.index;
  6585. },
  6586. setIndex: function ( index ) {
  6587. this.index = index;
  6588. },
  6589. addAttribute: function ( name, attribute ) {
  6590. if ( attribute instanceof THREE.BufferAttribute === false && attribute instanceof THREE.InterleavedBufferAttribute === false ) {
  6591. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  6592. this.addAttribute( name, new THREE.BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  6593. return;
  6594. }
  6595. if ( name === 'index' ) {
  6596. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  6597. this.setIndex( attribute );
  6598. return;
  6599. }
  6600. this.attributes[ name ] = attribute;
  6601. },
  6602. getAttribute: function ( name ) {
  6603. return this.attributes[ name ];
  6604. },
  6605. removeAttribute: function ( name ) {
  6606. delete this.attributes[ name ];
  6607. },
  6608. get drawcalls() {
  6609. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  6610. return this.groups;
  6611. },
  6612. get offsets() {
  6613. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  6614. return this.groups;
  6615. },
  6616. addDrawCall: function ( start, count, indexOffset ) {
  6617. if ( indexOffset !== undefined ) {
  6618. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  6619. }
  6620. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  6621. this.addGroup( start, count );
  6622. },
  6623. clearDrawCalls: function () {
  6624. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  6625. this.clearGroups();
  6626. },
  6627. addGroup: function ( start, count, materialIndex ) {
  6628. this.groups.push( {
  6629. start: start,
  6630. count: count,
  6631. materialIndex: materialIndex !== undefined ? materialIndex : 0
  6632. } );
  6633. },
  6634. clearGroups: function () {
  6635. this.groups = [];
  6636. },
  6637. setDrawRange: function ( start, count ) {
  6638. this.drawRange.start = start;
  6639. this.drawRange.count = count;
  6640. },
  6641. applyMatrix: function ( matrix ) {
  6642. var position = this.attributes.position;
  6643. if ( position !== undefined ) {
  6644. matrix.applyToVector3Array( position.array );
  6645. position.needsUpdate = true;
  6646. }
  6647. var normal = this.attributes.normal;
  6648. if ( normal !== undefined ) {
  6649. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  6650. normalMatrix.applyToVector3Array( normal.array );
  6651. normal.needsUpdate = true;
  6652. }
  6653. if ( this.boundingBox !== null ) {
  6654. this.computeBoundingBox();
  6655. }
  6656. if ( this.boundingSphere !== null ) {
  6657. this.computeBoundingSphere();
  6658. }
  6659. },
  6660. rotateX: function () {
  6661. // rotate geometry around world x-axis
  6662. var m1;
  6663. return function rotateX( angle ) {
  6664. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  6665. m1.makeRotationX( angle );
  6666. this.applyMatrix( m1 );
  6667. return this;
  6668. };
  6669. }(),
  6670. rotateY: function () {
  6671. // rotate geometry around world y-axis
  6672. var m1;
  6673. return function rotateY( angle ) {
  6674. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  6675. m1.makeRotationY( angle );
  6676. this.applyMatrix( m1 );
  6677. return this;
  6678. };
  6679. }(),
  6680. rotateZ: function () {
  6681. // rotate geometry around world z-axis
  6682. var m1;
  6683. return function rotateZ( angle ) {
  6684. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  6685. m1.makeRotationZ( angle );
  6686. this.applyMatrix( m1 );
  6687. return this;
  6688. };
  6689. }(),
  6690. translate: function () {
  6691. // translate geometry
  6692. var m1;
  6693. return function translate( x, y, z ) {
  6694. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  6695. m1.makeTranslation( x, y, z );
  6696. this.applyMatrix( m1 );
  6697. return this;
  6698. };
  6699. }(),
  6700. scale: function () {
  6701. // scale geometry
  6702. var m1;
  6703. return function scale( x, y, z ) {
  6704. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  6705. m1.makeScale( x, y, z );
  6706. this.applyMatrix( m1 );
  6707. return this;
  6708. };
  6709. }(),
  6710. lookAt: function () {
  6711. var obj;
  6712. return function lookAt( vector ) {
  6713. if ( obj === undefined ) obj = new THREE.Object3D();
  6714. obj.lookAt( vector );
  6715. obj.updateMatrix();
  6716. this.applyMatrix( obj.matrix );
  6717. };
  6718. }(),
  6719. center: function () {
  6720. this.computeBoundingBox();
  6721. var offset = this.boundingBox.center().negate();
  6722. this.translate( offset.x, offset.y, offset.z );
  6723. return offset;
  6724. },
  6725. setFromObject: function ( object ) {
  6726. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  6727. var geometry = object.geometry;
  6728. if ( object instanceof THREE.Points || object instanceof THREE.Line ) {
  6729. var positions = new THREE.Float32Attribute( geometry.vertices.length * 3, 3 );
  6730. var colors = new THREE.Float32Attribute( geometry.colors.length * 3, 3 );
  6731. this.addAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) );
  6732. this.addAttribute( 'color', colors.copyColorsArray( geometry.colors ) );
  6733. if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) {
  6734. var lineDistances = new THREE.Float32Attribute( geometry.lineDistances.length, 1 );
  6735. this.addAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) );
  6736. }
  6737. if ( geometry.boundingSphere !== null ) {
  6738. this.boundingSphere = geometry.boundingSphere.clone();
  6739. }
  6740. if ( geometry.boundingBox !== null ) {
  6741. this.boundingBox = geometry.boundingBox.clone();
  6742. }
  6743. } else if ( object instanceof THREE.Mesh ) {
  6744. if ( geometry instanceof THREE.Geometry ) {
  6745. this.fromGeometry( geometry );
  6746. }
  6747. }
  6748. return this;
  6749. },
  6750. updateFromObject: function ( object ) {
  6751. var geometry = object.geometry;
  6752. if ( object instanceof THREE.Mesh ) {
  6753. var direct = geometry.__directGeometry;
  6754. if ( direct === undefined ) {
  6755. return this.fromGeometry( geometry );
  6756. }
  6757. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  6758. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  6759. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  6760. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  6761. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  6762. geometry.verticesNeedUpdate = false;
  6763. geometry.normalsNeedUpdate = false;
  6764. geometry.colorsNeedUpdate = false;
  6765. geometry.uvsNeedUpdate = false;
  6766. geometry.groupsNeedUpdate = false;
  6767. geometry = direct;
  6768. }
  6769. if ( geometry.verticesNeedUpdate === true ) {
  6770. var attribute = this.attributes.position;
  6771. if ( attribute !== undefined ) {
  6772. attribute.copyVector3sArray( geometry.vertices );
  6773. attribute.needsUpdate = true;
  6774. }
  6775. geometry.verticesNeedUpdate = false;
  6776. }
  6777. if ( geometry.normalsNeedUpdate === true ) {
  6778. var attribute = this.attributes.normal;
  6779. if ( attribute !== undefined ) {
  6780. attribute.copyVector3sArray( geometry.normals );
  6781. attribute.needsUpdate = true;
  6782. }
  6783. geometry.normalsNeedUpdate = false;
  6784. }
  6785. if ( geometry.colorsNeedUpdate === true ) {
  6786. var attribute = this.attributes.color;
  6787. if ( attribute !== undefined ) {
  6788. attribute.copyColorsArray( geometry.colors );
  6789. attribute.needsUpdate = true;
  6790. }
  6791. geometry.colorsNeedUpdate = false;
  6792. }
  6793. if ( geometry.uvsNeedUpdate ) {
  6794. var attribute = this.attributes.uv;
  6795. if ( attribute !== undefined ) {
  6796. attribute.copyVector2sArray( geometry.uvs );
  6797. attribute.needsUpdate = true;
  6798. }
  6799. geometry.uvsNeedUpdate = false;
  6800. }
  6801. if ( geometry.lineDistancesNeedUpdate ) {
  6802. var attribute = this.attributes.lineDistance;
  6803. if ( attribute !== undefined ) {
  6804. attribute.copyArray( geometry.lineDistances );
  6805. attribute.needsUpdate = true;
  6806. }
  6807. geometry.lineDistancesNeedUpdate = false;
  6808. }
  6809. if ( geometry.groupsNeedUpdate ) {
  6810. geometry.computeGroups( object.geometry );
  6811. this.groups = geometry.groups;
  6812. geometry.groupsNeedUpdate = false;
  6813. }
  6814. return this;
  6815. },
  6816. fromGeometry: function ( geometry ) {
  6817. geometry.__directGeometry = new THREE.DirectGeometry().fromGeometry( geometry );
  6818. return this.fromDirectGeometry( geometry.__directGeometry );
  6819. },
  6820. fromDirectGeometry: function ( geometry ) {
  6821. var positions = new Float32Array( geometry.vertices.length * 3 );
  6822. this.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) );
  6823. if ( geometry.normals.length > 0 ) {
  6824. var normals = new Float32Array( geometry.normals.length * 3 );
  6825. this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) );
  6826. }
  6827. if ( geometry.colors.length > 0 ) {
  6828. var colors = new Float32Array( geometry.colors.length * 3 );
  6829. this.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) );
  6830. }
  6831. if ( geometry.uvs.length > 0 ) {
  6832. var uvs = new Float32Array( geometry.uvs.length * 2 );
  6833. this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) );
  6834. }
  6835. if ( geometry.uvs2.length > 0 ) {
  6836. var uvs2 = new Float32Array( geometry.uvs2.length * 2 );
  6837. this.addAttribute( 'uv2', new THREE.BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) );
  6838. }
  6839. if ( geometry.indices.length > 0 ) {
  6840. var TypeArray = geometry.vertices.length > 65535 ? Uint32Array : Uint16Array;
  6841. var indices = new TypeArray( geometry.indices.length * 3 );
  6842. this.setIndex( new THREE.BufferAttribute( indices, 1 ).copyIndicesArray( geometry.indices ) );
  6843. }
  6844. // groups
  6845. this.groups = geometry.groups;
  6846. // morphs
  6847. for ( var name in geometry.morphTargets ) {
  6848. var array = [];
  6849. var morphTargets = geometry.morphTargets[ name ];
  6850. for ( var i = 0, l = morphTargets.length; i < l; i ++ ) {
  6851. var morphTarget = morphTargets[ i ];
  6852. var attribute = new THREE.Float32Attribute( morphTarget.length * 3, 3 );
  6853. array.push( attribute.copyVector3sArray( morphTarget ) );
  6854. }
  6855. this.morphAttributes[ name ] = array;
  6856. }
  6857. // skinning
  6858. if ( geometry.skinIndices.length > 0 ) {
  6859. var skinIndices = new THREE.Float32Attribute( geometry.skinIndices.length * 4, 4 );
  6860. this.addAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) );
  6861. }
  6862. if ( geometry.skinWeights.length > 0 ) {
  6863. var skinWeights = new THREE.Float32Attribute( geometry.skinWeights.length * 4, 4 );
  6864. this.addAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) );
  6865. }
  6866. //
  6867. if ( geometry.boundingSphere !== null ) {
  6868. this.boundingSphere = geometry.boundingSphere.clone();
  6869. }
  6870. if ( geometry.boundingBox !== null ) {
  6871. this.boundingBox = geometry.boundingBox.clone();
  6872. }
  6873. return this;
  6874. },
  6875. computeBoundingBox: function () {
  6876. var vector = new THREE.Vector3();
  6877. return function () {
  6878. if ( this.boundingBox === null ) {
  6879. this.boundingBox = new THREE.Box3();
  6880. }
  6881. var positions = this.attributes.position.array;
  6882. if ( positions ) {
  6883. var bb = this.boundingBox;
  6884. bb.makeEmpty();
  6885. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  6886. vector.fromArray( positions, i );
  6887. bb.expandByPoint( vector );
  6888. }
  6889. }
  6890. if ( positions === undefined || positions.length === 0 ) {
  6891. this.boundingBox.min.set( 0, 0, 0 );
  6892. this.boundingBox.max.set( 0, 0, 0 );
  6893. }
  6894. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  6895. console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6896. }
  6897. };
  6898. }(),
  6899. computeBoundingSphere: function () {
  6900. var box = new THREE.Box3();
  6901. var vector = new THREE.Vector3();
  6902. return function () {
  6903. if ( this.boundingSphere === null ) {
  6904. this.boundingSphere = new THREE.Sphere();
  6905. }
  6906. var positions = this.attributes.position.array;
  6907. if ( positions ) {
  6908. box.makeEmpty();
  6909. var center = this.boundingSphere.center;
  6910. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  6911. vector.fromArray( positions, i );
  6912. box.expandByPoint( vector );
  6913. }
  6914. box.center( center );
  6915. // hoping to find a boundingSphere with a radius smaller than the
  6916. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6917. var maxRadiusSq = 0;
  6918. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  6919. vector.fromArray( positions, i );
  6920. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  6921. }
  6922. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6923. if ( isNaN( this.boundingSphere.radius ) ) {
  6924. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6925. }
  6926. }
  6927. };
  6928. }(),
  6929. computeFaceNormals: function () {
  6930. // backwards compatibility
  6931. },
  6932. computeVertexNormals: function () {
  6933. var index = this.index;
  6934. var attributes = this.attributes;
  6935. var groups = this.groups;
  6936. if ( attributes.position ) {
  6937. var positions = attributes.position.array;
  6938. if ( attributes.normal === undefined ) {
  6939. this.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( positions.length ), 3 ) );
  6940. } else {
  6941. // reset existing normals to zero
  6942. var array = attributes.normal.array;
  6943. for ( var i = 0, il = array.length; i < il; i ++ ) {
  6944. array[ i ] = 0;
  6945. }
  6946. }
  6947. var normals = attributes.normal.array;
  6948. var vA, vB, vC,
  6949. pA = new THREE.Vector3(),
  6950. pB = new THREE.Vector3(),
  6951. pC = new THREE.Vector3(),
  6952. cb = new THREE.Vector3(),
  6953. ab = new THREE.Vector3();
  6954. // indexed elements
  6955. if ( index ) {
  6956. var indices = index.array;
  6957. if ( groups.length === 0 ) {
  6958. this.addGroup( 0, indices.length );
  6959. }
  6960. for ( var j = 0, jl = groups.length; j < jl; ++ j ) {
  6961. var group = groups[ j ];
  6962. var start = group.start;
  6963. var count = group.count;
  6964. for ( var i = start, il = start + count; i < il; i += 3 ) {
  6965. vA = indices[ i + 0 ] * 3;
  6966. vB = indices[ i + 1 ] * 3;
  6967. vC = indices[ i + 2 ] * 3;
  6968. pA.fromArray( positions, vA );
  6969. pB.fromArray( positions, vB );
  6970. pC.fromArray( positions, vC );
  6971. cb.subVectors( pC, pB );
  6972. ab.subVectors( pA, pB );
  6973. cb.cross( ab );
  6974. normals[ vA ] += cb.x;
  6975. normals[ vA + 1 ] += cb.y;
  6976. normals[ vA + 2 ] += cb.z;
  6977. normals[ vB ] += cb.x;
  6978. normals[ vB + 1 ] += cb.y;
  6979. normals[ vB + 2 ] += cb.z;
  6980. normals[ vC ] += cb.x;
  6981. normals[ vC + 1 ] += cb.y;
  6982. normals[ vC + 2 ] += cb.z;
  6983. }
  6984. }
  6985. } else {
  6986. // non-indexed elements (unconnected triangle soup)
  6987. for ( var i = 0, il = positions.length; i < il; i += 9 ) {
  6988. pA.fromArray( positions, i );
  6989. pB.fromArray( positions, i + 3 );
  6990. pC.fromArray( positions, i + 6 );
  6991. cb.subVectors( pC, pB );
  6992. ab.subVectors( pA, pB );
  6993. cb.cross( ab );
  6994. normals[ i ] = cb.x;
  6995. normals[ i + 1 ] = cb.y;
  6996. normals[ i + 2 ] = cb.z;
  6997. normals[ i + 3 ] = cb.x;
  6998. normals[ i + 4 ] = cb.y;
  6999. normals[ i + 5 ] = cb.z;
  7000. normals[ i + 6 ] = cb.x;
  7001. normals[ i + 7 ] = cb.y;
  7002. normals[ i + 8 ] = cb.z;
  7003. }
  7004. }
  7005. this.normalizeNormals();
  7006. attributes.normal.needsUpdate = true;
  7007. }
  7008. },
  7009. computeTangents: function () {
  7010. console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' );
  7011. },
  7012. computeOffsets: function ( size ) {
  7013. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );
  7014. },
  7015. merge: function ( geometry, offset ) {
  7016. if ( geometry instanceof THREE.BufferGeometry === false ) {
  7017. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  7018. return;
  7019. }
  7020. if ( offset === undefined ) offset = 0;
  7021. var attributes = this.attributes;
  7022. for ( var key in attributes ) {
  7023. if ( geometry.attributes[ key ] === undefined ) continue;
  7024. var attribute1 = attributes[ key ];
  7025. var attributeArray1 = attribute1.array;
  7026. var attribute2 = geometry.attributes[ key ];
  7027. var attributeArray2 = attribute2.array;
  7028. var attributeSize = attribute2.itemSize;
  7029. for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) {
  7030. attributeArray1[ j ] = attributeArray2[ i ];
  7031. }
  7032. }
  7033. return this;
  7034. },
  7035. normalizeNormals: function () {
  7036. var normals = this.attributes.normal.array;
  7037. var x, y, z, n;
  7038. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  7039. x = normals[ i ];
  7040. y = normals[ i + 1 ];
  7041. z = normals[ i + 2 ];
  7042. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  7043. normals[ i ] *= n;
  7044. normals[ i + 1 ] *= n;
  7045. normals[ i + 2 ] *= n;
  7046. }
  7047. },
  7048. toJSON: function () {
  7049. var data = {
  7050. metadata: {
  7051. version: 4.4,
  7052. type: 'BufferGeometry',
  7053. generator: 'BufferGeometry.toJSON'
  7054. }
  7055. };
  7056. // standard BufferGeometry serialization
  7057. data.uuid = this.uuid;
  7058. data.type = this.type;
  7059. if ( this.name !== '' ) data.name = this.name;
  7060. if ( this.parameters !== undefined ) {
  7061. var parameters = this.parameters;
  7062. for ( var key in parameters ) {
  7063. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  7064. }
  7065. return data;
  7066. }
  7067. data.data = { attributes: {} };
  7068. var index = this.index;
  7069. if ( index !== null ) {
  7070. var array = Array.prototype.slice.call( index.array );
  7071. data.data.index = {
  7072. type: index.array.constructor.name,
  7073. array: array
  7074. };
  7075. }
  7076. var attributes = this.attributes;
  7077. for ( var key in attributes ) {
  7078. var attribute = attributes[ key ];
  7079. var array = Array.prototype.slice.call( attribute.array );
  7080. data.data.attributes[ key ] = {
  7081. itemSize: attribute.itemSize,
  7082. type: attribute.array.constructor.name,
  7083. array: array
  7084. };
  7085. }
  7086. var groups = this.groups;
  7087. if ( groups.length > 0 ) {
  7088. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  7089. }
  7090. var boundingSphere = this.boundingSphere;
  7091. if ( boundingSphere !== null ) {
  7092. data.data.boundingSphere = {
  7093. center: boundingSphere.center.toArray(),
  7094. radius: boundingSphere.radius
  7095. };
  7096. }
  7097. return data;
  7098. },
  7099. clone: function () {
  7100. /*
  7101. // Handle primitives
  7102. var parameters = this.parameters;
  7103. if ( parameters !== undefined ) {
  7104. var values = [];
  7105. for ( var key in parameters ) {
  7106. values.push( parameters[ key ] );
  7107. }
  7108. var geometry = Object.create( this.constructor.prototype );
  7109. this.constructor.apply( geometry, values );
  7110. return geometry;
  7111. }
  7112. return new this.constructor().copy( this );
  7113. */
  7114. return new THREE.BufferGeometry().copy( this );
  7115. },
  7116. copy: function ( source ) {
  7117. var index = source.index;
  7118. if ( index !== null ) {
  7119. this.setIndex( index.clone() );
  7120. }
  7121. var attributes = source.attributes;
  7122. for ( var name in attributes ) {
  7123. var attribute = attributes[ name ];
  7124. this.addAttribute( name, attribute.clone() );
  7125. }
  7126. var groups = source.groups;
  7127. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  7128. var group = groups[ i ];
  7129. this.addGroup( group.start, group.count );
  7130. }
  7131. return this;
  7132. },
  7133. dispose: function () {
  7134. this.dispatchEvent( { type: 'dispose' } );
  7135. }
  7136. };
  7137. THREE.EventDispatcher.prototype.apply( THREE.BufferGeometry.prototype );
  7138. THREE.BufferGeometry.MaxIndex = 65535;
  7139. // File:src/core/InstancedBufferGeometry.js
  7140. /**
  7141. * @author benaadams / https://twitter.com/ben_a_adams
  7142. */
  7143. THREE.InstancedBufferGeometry = function () {
  7144. THREE.BufferGeometry.call( this );
  7145. this.type = 'InstancedBufferGeometry';
  7146. this.maxInstancedCount = undefined;
  7147. };
  7148. THREE.InstancedBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  7149. THREE.InstancedBufferGeometry.prototype.constructor = THREE.InstancedBufferGeometry;
  7150. THREE.InstancedBufferGeometry.prototype.addGroup = function ( start, count, instances ) {
  7151. this.groups.push( {
  7152. start: start,
  7153. count: count,
  7154. instances: instances
  7155. } );
  7156. };
  7157. THREE.InstancedBufferGeometry.prototype.copy = function ( source ) {
  7158. var index = source.index;
  7159. if ( index !== null ) {
  7160. this.setIndex( index.clone() );
  7161. }
  7162. var attributes = source.attributes;
  7163. for ( var name in attributes ) {
  7164. var attribute = attributes[ name ];
  7165. this.addAttribute( name, attribute.clone() );
  7166. }
  7167. var groups = source.groups;
  7168. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  7169. var group = groups[ i ];
  7170. this.addGroup( group.start, group.count, group.instances );
  7171. }
  7172. return this;
  7173. };
  7174. THREE.EventDispatcher.prototype.apply( THREE.InstancedBufferGeometry.prototype );
  7175. // File:src/core/Uniform.js
  7176. /**
  7177. * @author mrdoob / http://mrdoob.com/
  7178. */
  7179. THREE.Uniform = function ( type, value ) {
  7180. this.type = type;
  7181. this.value = value;
  7182. this.dynamic = false;
  7183. };
  7184. THREE.Uniform.prototype = {
  7185. constructor: THREE.Uniform,
  7186. onUpdate: function ( callback ) {
  7187. this.dynamic = true;
  7188. this.onUpdateCallback = callback;
  7189. return this;
  7190. }
  7191. };
  7192. // File:src/animation/AnimationClip.js
  7193. /**
  7194. *
  7195. * Reusable set of Tracks that represent an animation.
  7196. *
  7197. * @author Ben Houston / http://clara.io/
  7198. * @author David Sarno / http://lighthaus.us/
  7199. */
  7200. THREE.AnimationClip = function ( name, duration, tracks ) {
  7201. this.name = name || THREE.Math.generateUUID();
  7202. this.tracks = tracks;
  7203. this.duration = ( duration !== undefined ) ? duration : -1;
  7204. // this means it should figure out its duration by scanning the tracks
  7205. if ( this.duration < 0 ) {
  7206. this.resetDuration();
  7207. }
  7208. // maybe only do these on demand, as doing them here could potentially slow down loading
  7209. // but leaving these here during development as this ensures a lot of testing of these functions
  7210. this.trim();
  7211. this.optimize();
  7212. };
  7213. THREE.AnimationClip.prototype = {
  7214. constructor: THREE.AnimationClip,
  7215. resetDuration: function() {
  7216. var tracks = this.tracks,
  7217. duration = 0;
  7218. for ( var i = 0, n = tracks.length; i !== n; ++ i ) {
  7219. var track = this.tracks[ i ];
  7220. duration = Math.max(
  7221. duration, track.times[ track.times.length - 1 ] );
  7222. }
  7223. this.duration = duration;
  7224. },
  7225. trim: function() {
  7226. for ( var i = 0; i < this.tracks.length; i ++ ) {
  7227. this.tracks[ i ].trim( 0, this.duration );
  7228. }
  7229. return this;
  7230. },
  7231. optimize: function() {
  7232. for ( var i = 0; i < this.tracks.length; i ++ ) {
  7233. this.tracks[ i ].optimize();
  7234. }
  7235. return this;
  7236. }
  7237. };
  7238. // Static methods:
  7239. Object.assign( THREE.AnimationClip, {
  7240. parse: function( json ) {
  7241. var tracks = [],
  7242. jsonTracks = json.tracks,
  7243. frameTime = 1.0 / ( json.fps || 1.0 );
  7244. for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  7245. tracks.push( THREE.KeyframeTrack.parse( jsonTracks[ i ] ).scale( frameTime ) );
  7246. }
  7247. return new THREE.AnimationClip( json.name, json.duration, tracks );
  7248. },
  7249. toJSON: function( clip ) {
  7250. var tracks = [],
  7251. clipTracks = clip.tracks;
  7252. var json = {
  7253. 'name': clip.name,
  7254. 'duration': clip.duration,
  7255. 'tracks': tracks
  7256. };
  7257. for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) {
  7258. tracks.push( THREE.KeyframeTrack.toJSON( clipTracks[ i ] ) );
  7259. }
  7260. return json;
  7261. },
  7262. CreateFromMorphTargetSequence: function( name, morphTargetSequence, fps ) {
  7263. var numMorphTargets = morphTargetSequence.length;
  7264. var tracks = [];
  7265. for ( var i = 0; i < numMorphTargets; i ++ ) {
  7266. var times = [];
  7267. var values = [];
  7268. times.push(
  7269. ( i + numMorphTargets - 1 ) % numMorphTargets,
  7270. i,
  7271. ( i + 1 ) % numMorphTargets );
  7272. values.push( 0, 1, 0 );
  7273. var order = THREE.AnimationUtils.getKeyframeOrder( times );
  7274. times = THREE.AnimationUtils.sortedArray( times, 1, order );
  7275. values = THREE.AnimationUtils.sortedArray( values, 1, order );
  7276. // if there is a key at the first frame, duplicate it as the
  7277. // last frame as well for perfect loop.
  7278. if ( times[ 0 ] === 0 ) {
  7279. times.push( numMorphTargets );
  7280. values.push( values[ 0 ] );
  7281. }
  7282. tracks.push(
  7283. new THREE.NumberKeyframeTrack(
  7284. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  7285. times, values
  7286. ).scale( 1.0 / fps ) );
  7287. }
  7288. return new THREE.AnimationClip( name, -1, tracks );
  7289. },
  7290. findByName: function( clipArray, name ) {
  7291. for ( var i = 0; i < clipArray.length; i ++ ) {
  7292. if ( clipArray[ i ].name === name ) {
  7293. return clipArray[ i ];
  7294. }
  7295. }
  7296. return null;
  7297. },
  7298. CreateClipsFromMorphTargetSequences: function( morphTargets, fps ) {
  7299. var animationToMorphTargets = {};
  7300. // tested with https://regex101.com/ on trick sequences
  7301. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  7302. var pattern = /^([\w-]*?)([\d]+)$/;
  7303. // sort morph target names into animation groups based
  7304. // patterns like Walk_001, Walk_002, Run_001, Run_002
  7305. for ( var i = 0, il = morphTargets.length; i < il; i ++ ) {
  7306. var morphTarget = morphTargets[ i ];
  7307. var parts = morphTarget.name.match( pattern );
  7308. if ( parts && parts.length > 1 ) {
  7309. var name = parts[ 1 ];
  7310. var animationMorphTargets = animationToMorphTargets[ name ];
  7311. if ( ! animationMorphTargets ) {
  7312. animationToMorphTargets[ name ] = animationMorphTargets = [];
  7313. }
  7314. animationMorphTargets.push( morphTarget );
  7315. }
  7316. }
  7317. var clips = [];
  7318. for ( var name in animationToMorphTargets ) {
  7319. clips.push( THREE.AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps ) );
  7320. }
  7321. return clips;
  7322. },
  7323. // parse the animation.hierarchy format
  7324. parseAnimation: function( animation, bones, nodeName ) {
  7325. if ( ! animation ) {
  7326. console.error( " no animation in JSONLoader data" );
  7327. return null;
  7328. }
  7329. var addNonemptyTrack = function(
  7330. trackType, trackName, animationKeys, propertyName, destTracks ) {
  7331. // only return track if there are actually keys.
  7332. if ( animationKeys.length !== 0 ) {
  7333. var times = [];
  7334. var values = [];
  7335. THREE.AnimationUtils.flattenJSON(
  7336. animationKeys, times, values, propertyName );
  7337. // empty keys are filtered out, so check again
  7338. if ( times.length !== 0 ) {
  7339. destTracks.push( new trackType( trackName, times, values ) );
  7340. }
  7341. }
  7342. };
  7343. var tracks = [];
  7344. var clipName = animation.name || 'default';
  7345. // automatic length determination in AnimationClip.
  7346. var duration = animation.length || -1;
  7347. var fps = animation.fps || 30;
  7348. var hierarchyTracks = animation.hierarchy || [];
  7349. for ( var h = 0; h < hierarchyTracks.length; h ++ ) {
  7350. var animationKeys = hierarchyTracks[ h ].keys;
  7351. // skip empty tracks
  7352. if ( ! animationKeys || animationKeys.length == 0 ) continue;
  7353. // process morph targets in a way exactly compatible
  7354. // with AnimationHandler.init( animation )
  7355. if ( animationKeys[0].morphTargets ) {
  7356. // figure out all morph targets used in this track
  7357. var morphTargetNames = {};
  7358. for ( var k = 0; k < animationKeys.length; k ++ ) {
  7359. if ( animationKeys[k].morphTargets ) {
  7360. for ( var m = 0; m < animationKeys[k].morphTargets.length; m ++ ) {
  7361. morphTargetNames[ animationKeys[k].morphTargets[m] ] = -1;
  7362. }
  7363. }
  7364. }
  7365. // create a track for each morph target with all zero
  7366. // morphTargetInfluences except for the keys in which
  7367. // the morphTarget is named.
  7368. for ( var morphTargetName in morphTargetNames ) {
  7369. var times = [];
  7370. var values = [];
  7371. for ( var m = 0;
  7372. m !== animationKeys[k].morphTargets.length; ++ m ) {
  7373. var animationKey = animationKeys[k];
  7374. times.push( animationKey.time );
  7375. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 )
  7376. }
  7377. tracks.push( new THREE.NumberKeyframeTrack(
  7378. '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  7379. }
  7380. duration = morphTargetNames.length * ( fps || 1.0 );
  7381. } else {
  7382. // ...assume skeletal animation
  7383. var boneName = '.bones[' + bones[ h ].name + ']';
  7384. addNonemptyTrack(
  7385. THREE.VectorKeyframeTrack, boneName + '.position',
  7386. animationKeys, 'pos', tracks );
  7387. addNonemptyTrack(
  7388. THREE.QuaternionKeyframeTrack, boneName + '.quaternion',
  7389. animationKeys, 'rot', tracks );
  7390. addNonemptyTrack(
  7391. THREE.VectorKeyframeTrack, boneName + '.scale',
  7392. animationKeys, 'scl', tracks );
  7393. }
  7394. }
  7395. if ( tracks.length === 0 ) {
  7396. return null;
  7397. }
  7398. var clip = new THREE.AnimationClip( clipName, duration, tracks );
  7399. return clip;
  7400. }
  7401. } );
  7402. // File:src/animation/AnimationMixer.js
  7403. /**
  7404. *
  7405. * Player for AnimationClips.
  7406. *
  7407. *
  7408. * @author Ben Houston / http://clara.io/
  7409. * @author David Sarno / http://lighthaus.us/
  7410. * @author tschw
  7411. */
  7412. THREE.AnimationMixer = function( root ) {
  7413. this._root = root;
  7414. this._initMemoryManager();
  7415. this._accuIndex = 0;
  7416. this.time = 0;
  7417. this.timeScale = 1.0;
  7418. };
  7419. THREE.AnimationMixer.prototype = {
  7420. constructor: THREE.AnimationMixer,
  7421. // return an action for a clip optionally using a custom root target
  7422. // object (this method allocates a lot of dynamic memory in case a
  7423. // previously unknown clip/root combination is specified)
  7424. clipAction: function( clip, optionalRoot ) {
  7425. var root = optionalRoot || this._root,
  7426. rootUuid = root.uuid,
  7427. clipName = ( typeof clip === 'string' ) ? clip : clip.name,
  7428. clipObject = ( clip !== clipName ) ? clip : null,
  7429. actionsForClip = this._actionsByClip[ clipName ],
  7430. prototypeAction;
  7431. if ( actionsForClip !== undefined ) {
  7432. var existingAction =
  7433. actionsForClip.actionByRoot[ rootUuid ];
  7434. if ( existingAction !== undefined ) {
  7435. return existingAction;
  7436. }
  7437. // we know the clip, so we don't have to parse all
  7438. // the bindings again but can just copy
  7439. prototypeAction = actionsForClip.knownActions[ 0 ];
  7440. // also, take the clip from the prototype action
  7441. clipObject = prototypeAction._clip;
  7442. if ( clip !== clipName && clip !== clipObject ) {
  7443. throw new Error(
  7444. "Different clips with the same name detected!" );
  7445. }
  7446. }
  7447. // clip must be known when specified via string
  7448. if ( clipObject === null ) return null;
  7449. // allocate all resources required to run it
  7450. var newAction = new THREE.
  7451. AnimationMixer._Action( this, clipObject, optionalRoot );
  7452. this._bindAction( newAction, prototypeAction );
  7453. // and make the action known to the memory manager
  7454. this._addInactiveAction( newAction, clipName, rootUuid );
  7455. return newAction;
  7456. },
  7457. // get an existing action
  7458. existingAction: function( clip, optionalRoot ) {
  7459. var root = optionalRoot || this._root,
  7460. rootUuid = root.uuid,
  7461. clipName = ( typeof clip === 'string' ) ? clip : clip.name,
  7462. actionsForClip = this._actionsByClip[ clipName ];
  7463. if ( actionsForClip !== undefined ) {
  7464. return actionsForClip.actionByRoot[ rootUuid ] || null;
  7465. }
  7466. return null;
  7467. },
  7468. // deactivates all previously scheduled actions
  7469. stopAllAction: function() {
  7470. var actions = this._actions,
  7471. nActions = this._nActiveActions,
  7472. bindings = this._bindings,
  7473. nBindings = this._nActiveBindings;
  7474. this._nActiveActions = 0;
  7475. this._nActiveBindings = 0;
  7476. for ( var i = 0; i !== nActions; ++ i ) {
  7477. actions[ i ].reset();
  7478. }
  7479. for ( var i = 0; i !== nBindings; ++ i ) {
  7480. bindings[ i ].useCount = 0;
  7481. }
  7482. return this;
  7483. },
  7484. // advance the time and update apply the animation
  7485. update: function( deltaTime ) {
  7486. deltaTime *= this.timeScale;
  7487. var actions = this._actions,
  7488. nActions = this._nActiveActions,
  7489. time = this.time += deltaTime,
  7490. timeDirection = Math.sign( deltaTime ),
  7491. accuIndex = this._accuIndex ^= 1;
  7492. // run active actions
  7493. for ( var i = 0; i !== nActions; ++ i ) {
  7494. var action = actions[ i ];
  7495. if ( action.enabled ) {
  7496. action._update( time, deltaTime, timeDirection, accuIndex );
  7497. }
  7498. }
  7499. // update scene graph
  7500. var bindings = this._bindings,
  7501. nBindings = this._nActiveBindings;
  7502. for ( var i = 0; i !== nBindings; ++ i ) {
  7503. bindings[ i ].apply( accuIndex );
  7504. }
  7505. return this;
  7506. },
  7507. // return this mixer's root target object
  7508. getRoot: function() {
  7509. return this._root;
  7510. },
  7511. // free all resources specific to a particular clip
  7512. uncacheClip: function( clip ) {
  7513. var actions = this._actions,
  7514. clipName = clip.name,
  7515. actionsByClip = this._actionsByClip,
  7516. actionsForClip = actionsByClip[ clipName ];
  7517. if ( actionsForClip !== undefined ) {
  7518. // note: just calling _removeInactiveAction would mess up the
  7519. // iteration state and also require updating the state we can
  7520. // just throw away
  7521. var actionsToRemove = actionsForClip.knownActions;
  7522. for ( var i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  7523. var action = actionsToRemove[ i ];
  7524. this._deactivateAction( action );
  7525. var cacheIndex = action._cacheIndex,
  7526. lastInactiveAction = actions[ actions.length - 1 ];
  7527. action._cacheIndex = null;
  7528. action._byClipCacheIndex = null;
  7529. lastInactiveAction._cacheIndex = cacheIndex;
  7530. actions[ cacheIndex ] = lastInactiveAction;
  7531. actions.pop();
  7532. this._removeInactiveBindingsForAction( action );
  7533. }
  7534. delete actionsByClip[ clipName ];
  7535. }
  7536. },
  7537. // free all resources specific to a particular root target object
  7538. uncacheRoot: function( root ) {
  7539. var rootUuid = root.uuid,
  7540. actionsByClip = this._actionsByClip;
  7541. for ( var clipName in actionsByClip ) {
  7542. var actionByRoot = actionsByClip[ clipName ].actionByRoot,
  7543. action = actionByRoot[ rootUuid ];
  7544. if ( action !== undefined ) {
  7545. this._deactivateAction( action );
  7546. this._removeInactiveAction( action );
  7547. }
  7548. }
  7549. var bindingsByRoot = this._bindingsByRootAndName,
  7550. bindingByName = bindingsByRoot[ rootUuid ];
  7551. if ( bindingByName !== undefined ) {
  7552. for ( var trackName in bindingByName ) {
  7553. var binding = bindingByName[ trackName ];
  7554. binding.restoreOriginalState();
  7555. this._removeInactiveBinding( binding );
  7556. }
  7557. }
  7558. },
  7559. // remove a targeted clip from the cache
  7560. uncacheAction: function( clip, optionalRoot ) {
  7561. var action = this.existingAction( clip, optionalRoot );
  7562. if ( action !== null ) {
  7563. this._deactivateAction( action );
  7564. this._removeInactiveAction( action );
  7565. }
  7566. }
  7567. };
  7568. THREE.EventDispatcher.prototype.apply( THREE.AnimationMixer.prototype );
  7569. THREE.AnimationMixer._Action =
  7570. function( mixer, clip, localRoot ) {
  7571. this._mixer = mixer;
  7572. this._clip = clip;
  7573. this._localRoot = localRoot || null;
  7574. var tracks = clip.tracks,
  7575. nTracks = tracks.length,
  7576. interpolants = new Array( nTracks );
  7577. var interpolantSettings = {
  7578. endingStart: THREE.ZeroCurvatureEnding,
  7579. endingEnd: THREE.ZeroCurvatureEnding
  7580. };
  7581. for ( var i = 0; i !== nTracks; ++ i ) {
  7582. var interpolant = tracks[ i ].createInterpolant( null );
  7583. interpolants[ i ] = interpolant;
  7584. interpolant.settings = interpolantSettings
  7585. }
  7586. this._interpolantSettings = interpolantSettings;
  7587. this._interpolants = interpolants; // bound by the mixer
  7588. // inside: PropertyMixer (managed by the mixer)
  7589. this._propertyBindings = new Array( nTracks );
  7590. this._cacheIndex = null; // for the memory manager
  7591. this._byClipCacheIndex = null; // for the memory manager
  7592. this._timeScaleInterpolant = null;
  7593. this._weightInterpolant = null;
  7594. this.loop = THREE.LoopRepeat;
  7595. this._loopCount = -1;
  7596. // global mixer time when the action is to be started
  7597. // it's set back to 'null' upon start of the action
  7598. this._startTime = null;
  7599. // scaled local time of the action
  7600. // gets clamped or wrapped to 0..clip.duration according to loop
  7601. this.time = 0;
  7602. this.timeScale = 1;
  7603. this._effectiveTimeScale = 1;
  7604. this.weight = 1;
  7605. this._effectiveWeight = 1;
  7606. this.repetitions = Infinity; // no. of repetitions when looping
  7607. this.paused = false; // false -> zero effective time scale
  7608. this.enabled = true; // true -> zero effective weight
  7609. this.clampWhenFinished = false; // keep feeding the last frame?
  7610. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  7611. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  7612. };
  7613. THREE.AnimationMixer._Action.prototype = {
  7614. constructor: THREE.AnimationMixer._Action,
  7615. // State & Scheduling
  7616. play: function() {
  7617. this._mixer._activateAction( this );
  7618. return this;
  7619. },
  7620. stop: function() {
  7621. this._mixer._deactivateAction( this );
  7622. return this.reset();
  7623. },
  7624. reset: function() {
  7625. this.paused = false;
  7626. this.enabled = true;
  7627. this.time = 0; // restart clip
  7628. this._loopCount = -1; // forget previous loops
  7629. this._startTime = null; // forget scheduling
  7630. return this.stopFading().stopWarping();
  7631. },
  7632. isRunning: function() {
  7633. var start = this._startTime;
  7634. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  7635. this._startTime === null && this._mixer._isActiveAction( this )
  7636. },
  7637. // return true when play has been called
  7638. isScheduled: function() {
  7639. return this._mixer._isActiveAction( this );
  7640. },
  7641. startAt: function( time ) {
  7642. this._startTime = time;
  7643. return this;
  7644. },
  7645. setLoop: function( mode, repetitions ) {
  7646. this.loop = mode;
  7647. this.repetitions = repetitions;
  7648. return this;
  7649. },
  7650. // Weight
  7651. // set the weight stopping any scheduled fading
  7652. // although .enabled = false yields an effective weight of zero, this
  7653. // method does *not* change .enabled, because it would be confusing
  7654. setEffectiveWeight: function( weight ) {
  7655. this.weight = weight;
  7656. // note: same logic as when updated at runtime
  7657. this._effectiveWeight = this.enabled ? weight : 0;
  7658. return this.stopFading();
  7659. },
  7660. // return the weight considering fading and .enabled
  7661. getEffectiveWeight: function() {
  7662. return this._effectiveWeight;
  7663. },
  7664. fadeIn: function( duration ) {
  7665. return this._scheduleFading( duration, 0, 1 );
  7666. },
  7667. fadeOut: function( duration ) {
  7668. return this._scheduleFading( duration, 1, 0 );
  7669. },
  7670. crossFadeFrom: function( fadeOutAction, duration, warp ) {
  7671. var mixer = this._mixer;
  7672. fadeOutAction.fadeOut( duration );
  7673. this.fadeIn( duration );
  7674. if( warp ) {
  7675. var fadeInDuration = this._clip.duration,
  7676. fadeOutDuration = fadeOutAction._clip.duration,
  7677. startEndRatio = fadeOutDuration / fadeInDuration,
  7678. endStartRatio = fadeInDuration / fadeOutDuration;
  7679. fadeOutAction.warp( 1.0, startEndRatio, duration );
  7680. this.warp( endStartRatio, 1.0, duration );
  7681. }
  7682. return this;
  7683. },
  7684. crossFadeTo: function( fadeInAction, duration, warp ) {
  7685. return fadeInAction.crossFadeFrom( this, duration, warp );
  7686. },
  7687. stopFading: function() {
  7688. var weightInterpolant = this._weightInterpolant;
  7689. if ( weightInterpolant !== null ) {
  7690. this._weightInterpolant = null;
  7691. this._mixer._takeBackControlInterpolant( weightInterpolant );
  7692. }
  7693. return this;
  7694. },
  7695. // Time Scale Control
  7696. // set the weight stopping any scheduled warping
  7697. // although .paused = true yields an effective time scale of zero, this
  7698. // method does *not* change .paused, because it would be confusing
  7699. setEffectiveTimeScale: function( timeScale ) {
  7700. this.timeScale = timeScale;
  7701. this._effectiveTimeScale = this.paused ? 0 :timeScale;
  7702. return this.stopWarping();
  7703. },
  7704. // return the time scale considering warping and .paused
  7705. getEffectiveTimeScale: function() {
  7706. return this._effectiveTimeScale;
  7707. },
  7708. setDuration: function( duration ) {
  7709. this.timeScale = this._clip.duration / duration;
  7710. return this.stopWarping();
  7711. },
  7712. syncWith: function( action ) {
  7713. this.time = action.time;
  7714. this.timeScale = action.timeScale;
  7715. return this.stopWarping();
  7716. },
  7717. halt: function( duration ) {
  7718. return this.warp( this._currentTimeScale, 0, duration );
  7719. },
  7720. warp: function( startTimeScale, endTimeScale, duration ) {
  7721. var mixer = this._mixer, now = mixer.time,
  7722. interpolant = this._timeScaleInterpolant,
  7723. timeScale = this.timeScale;
  7724. if ( interpolant === null ) {
  7725. interpolant = mixer._lendControlInterpolant(),
  7726. this._timeScaleInterpolant = interpolant;
  7727. }
  7728. var times = interpolant.parameterPositions,
  7729. values = interpolant.sampleValues;
  7730. times[ 0 ] = now;
  7731. times[ 1 ] = now + duration;
  7732. values[ 0 ] = startTimeScale / timeScale;
  7733. values[ 1 ] = endTimeScale / timeScale;
  7734. return this;
  7735. },
  7736. stopWarping: function() {
  7737. var timeScaleInterpolant = this._timeScaleInterpolant;
  7738. if ( timeScaleInterpolant !== null ) {
  7739. this._timeScaleInterpolant = null;
  7740. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  7741. }
  7742. return this;
  7743. },
  7744. // Object Accessors
  7745. getMixer: function() {
  7746. return this._mixer;
  7747. },
  7748. getClip: function() {
  7749. return this._clip;
  7750. },
  7751. getRoot: function() {
  7752. return this._localRoot || this._mixer._root;
  7753. },
  7754. // Interna
  7755. _update: function( time, deltaTime, timeDirection, accuIndex ) {
  7756. // called by the mixer
  7757. var startTime = this._startTime;
  7758. if ( startTime !== null ) {
  7759. // check for scheduled start of action
  7760. var timeRunning = ( time - startTime ) * timeDirection;
  7761. if ( timeRunning < 0 || timeDirection === 0 ) {
  7762. return; // yet to come / don't decide when delta = 0
  7763. }
  7764. // start
  7765. this._startTime = null; // unschedule
  7766. deltaTime = timeDirection * timeRunning;
  7767. }
  7768. // apply time scale and advance time
  7769. deltaTime *= this._updateTimeScale( time );
  7770. var clipTime = this._updateTime( deltaTime );
  7771. // note: _updateTime may disable the action resulting in
  7772. // an effective weight of 0
  7773. var weight = this._updateWeight( time );
  7774. if ( weight > 0 ) {
  7775. var interpolants = this._interpolants;
  7776. var propertyMixers = this._propertyBindings;
  7777. for ( var j = 0, m = interpolants.length; j !== m; ++ j ) {
  7778. interpolants[ j ].evaluate( clipTime );
  7779. propertyMixers[ j ].accumulate( accuIndex, weight );
  7780. }
  7781. }
  7782. },
  7783. _updateWeight: function( time ) {
  7784. var weight = 0;
  7785. if ( this.enabled ) {
  7786. weight = this.weight;
  7787. var interpolant = this._weightInterpolant;
  7788. if ( interpolant !== null ) {
  7789. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  7790. weight *= interpolantValue;
  7791. if ( time > interpolant.parameterPositions[ 1 ] ) {
  7792. this.stopFading();
  7793. if ( interpolantValue === 0 ) {
  7794. // faded out, disable
  7795. this.enabled = false;
  7796. }
  7797. }
  7798. }
  7799. }
  7800. this._effectiveWeight = weight;
  7801. return weight;
  7802. },
  7803. _updateTimeScale: function( time ) {
  7804. var timeScale = 0;
  7805. if ( ! this.paused ) {
  7806. timeScale = this.timeScale;
  7807. var interpolant = this._timeScaleInterpolant;
  7808. if ( interpolant !== null ) {
  7809. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  7810. timeScale *= interpolantValue;
  7811. if ( time > interpolant.parameterPositions[ 1 ] ) {
  7812. this.stopWarping();
  7813. if ( timeScale === 0 ) {
  7814. // motion has halted, pause
  7815. this.pause = true;
  7816. } else {
  7817. // warp done - apply final time scale
  7818. this.timeScale = timeScale;
  7819. }
  7820. }
  7821. }
  7822. }
  7823. this._effectiveTimeScale = timeScale;
  7824. return timeScale;
  7825. },
  7826. _updateTime: function( deltaTime ) {
  7827. var time = this.time + deltaTime;
  7828. if ( deltaTime === 0 ) return time;
  7829. var duration = this._clip.duration,
  7830. loop = this.loop,
  7831. loopCount = this._loopCount,
  7832. pingPong = false;
  7833. switch ( loop ) {
  7834. case THREE.LoopOnce:
  7835. case THREE.LoopOnceClamp:
  7836. if ( loopCount === -1 ) {
  7837. // just started
  7838. this.loopCount = 0;
  7839. this._setEndings( true, true, false );
  7840. }
  7841. if ( time >= duration ) {
  7842. time = duration;
  7843. } else if ( time < 0 ) {
  7844. time = 0;
  7845. } else break;
  7846. // reached the end
  7847. if ( this.clampWhenFinished ) this.pause = true;
  7848. else this.enabled = false;
  7849. this._mixer.dispatchEvent( {
  7850. type: 'finished', action: this,
  7851. direction: deltaTime < 0 ? -1 : 1
  7852. } );
  7853. break;
  7854. case THREE.LoopPingPong:
  7855. pingPong = true;
  7856. case THREE.LoopRepeat:
  7857. if ( loopCount === -1 ) {
  7858. // just started
  7859. if ( deltaTime > 0 ) {
  7860. loopCount = 0;
  7861. this._setEndings(
  7862. true, this.repetitions === 0, pingPong );
  7863. } else {
  7864. // when looping in reverse direction, the initial
  7865. // transition through zero counts as a repetition,
  7866. // so leave loopCount at -1
  7867. this._setEndings(
  7868. this.repetitions === 0, true, pingPong );
  7869. }
  7870. }
  7871. if ( time >= duration || time < 0 ) {
  7872. // wrap around
  7873. var loopDelta = Math.floor( time / duration ); // signed
  7874. time -= duration * loopDelta;
  7875. loopCount += Math.abs( loopDelta );
  7876. var pending = this.repetitions - loopCount;
  7877. if ( pending < 0 ) {
  7878. // stop (switch state, clamp time, fire event)
  7879. if ( this.clampWhenFinished ) this.paused = true;
  7880. else this.enabled = false;
  7881. time = deltaTime > 0 ? duration : 0;
  7882. this._mixer.dispatchEvent( {
  7883. type: 'finished', action: this,
  7884. direction: deltaTime > 0 ? 1 : -1
  7885. } );
  7886. break;
  7887. } else if ( pending === 0 ) {
  7888. // transition to last round
  7889. var atStart = deltaTime < 0;
  7890. this._setEndings( atStart, ! atStart, pingPong );
  7891. } else {
  7892. this._setEndings( false, false, pingPong );
  7893. }
  7894. this._loopCount = loopCount;
  7895. this._mixer.dispatchEvent( {
  7896. type: 'loop', action: this, loopDelta: loopDelta
  7897. } );
  7898. }
  7899. if ( loop === THREE.LoopPingPong && ( loopCount & 1 ) === 1 ) {
  7900. // invert time for the "pong round"
  7901. this.time = time;
  7902. return duration - time;
  7903. }
  7904. break;
  7905. }
  7906. this.time = time;
  7907. return time;
  7908. },
  7909. _setEndings: function( atStart, atEnd, pingPong ) {
  7910. var settings = this._interpolantSettings;
  7911. if ( pingPong ) {
  7912. settings.endingStart = THREE.ZeroSlopeEnding;
  7913. settings.endingEnd = THREE.ZeroSlopeEnding;
  7914. } else {
  7915. // assuming for LoopOnce atStart == atEnd == true
  7916. if ( atStart ) {
  7917. settings.endingStart = this.zeroSlopeAtStart ?
  7918. THREE.ZeroSlopeEnding : THREE.ZeroCurvatureEnding;
  7919. } else {
  7920. settings.endingStart = THREE.WrapAroundEnding;
  7921. }
  7922. if ( atEnd ) {
  7923. settings.endingEnd = this.zeroSlopeAtEnd ?
  7924. THREE.ZeroSlopeEnding : THREE.ZeroCurvatureEnding;
  7925. } else {
  7926. settings.endingEnd = THREE.WrapAroundEnding;
  7927. }
  7928. }
  7929. },
  7930. _scheduleFading: function( duration, weightNow, weightThen ) {
  7931. var mixer = this._mixer, now = mixer.time,
  7932. interpolant = this._weightInterpolant;
  7933. if ( interpolant === null ) {
  7934. interpolant = mixer._lendControlInterpolant(),
  7935. this._weightInterpolant = interpolant;
  7936. }
  7937. var times = interpolant.parameterPositions,
  7938. values = interpolant.sampleValues;
  7939. times[ 0 ] = now; values[ 0 ] = weightNow;
  7940. times[ 1 ] = now + duration; values[ 1 ] = weightThen;
  7941. return this;
  7942. }
  7943. };
  7944. // Implementation details:
  7945. Object.assign( THREE.AnimationMixer.prototype, {
  7946. _bindAction: function( action, prototypeAction ) {
  7947. var root = action._localRoot || this._root,
  7948. tracks = action._clip.tracks,
  7949. nTracks = tracks.length,
  7950. bindings = action._propertyBindings,
  7951. interpolants = action._interpolants,
  7952. rootUuid = root.uuid,
  7953. bindingsByRoot = this._bindingsByRootAndName,
  7954. bindingsByName = bindingsByRoot[ rootUuid ];
  7955. if ( bindingsByName === undefined ) {
  7956. bindingsByName = {};
  7957. bindingsByRoot[ rootUuid ] = bindingsByName;
  7958. }
  7959. for ( var i = 0; i !== nTracks; ++ i ) {
  7960. var track = tracks[ i ],
  7961. trackName = track.name,
  7962. binding = bindingsByName[ trackName ];
  7963. if ( binding !== undefined ) {
  7964. bindings[ i ] = binding;
  7965. } else {
  7966. binding = bindings[ i ];
  7967. if ( binding !== undefined ) {
  7968. // existing binding, make sure the cache knows
  7969. if ( binding._cacheIndex === null ) {
  7970. ++ binding.referenceCount;
  7971. this._addInactiveBinding( binding, rootUuid, trackName );
  7972. }
  7973. continue;
  7974. }
  7975. var path = prototypeAction && prototypeAction.
  7976. _propertyBindings[ i ].binding.parsedPath;
  7977. binding = new THREE.PropertyMixer(
  7978. THREE.PropertyBinding.create( root, trackName, path ),
  7979. track.ValueTypeName, track.getValueSize() );
  7980. ++ binding.referenceCount;
  7981. this._addInactiveBinding( binding, rootUuid, trackName );
  7982. bindings[ i ] = binding;
  7983. }
  7984. interpolants[ i ].resultBuffer = binding.buffer;
  7985. }
  7986. },
  7987. _activateAction: function( action ) {
  7988. if ( ! this._isActiveAction( action ) ) {
  7989. if ( action._cacheIndex === null ) {
  7990. // this action has been forgotten by the cache, but the user
  7991. // appears to be still using it -> rebind
  7992. var rootUuid = ( action._localRoot || this._root ).uuid,
  7993. clipName = action._clip.name,
  7994. actionsForClip = this._actionsByClip[ clipName ];
  7995. this._bindAction( action,
  7996. actionsForClip && actionsForClip.knownActions[ 0 ] );
  7997. this._addInactiveAction( action, clipName, rootUuid );
  7998. }
  7999. var bindings = action._propertyBindings;
  8000. // increment reference counts / sort out state
  8001. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  8002. var binding = bindings[ i ];
  8003. if ( binding.useCount ++ === 0 ) {
  8004. this._lendBinding( binding );
  8005. binding.saveOriginalState();
  8006. }
  8007. }
  8008. this._lendAction( action );
  8009. }
  8010. },
  8011. _deactivateAction: function( action ) {
  8012. if ( this._isActiveAction( action ) ) {
  8013. var bindings = action._propertyBindings;
  8014. // decrement reference counts / sort out state
  8015. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  8016. var binding = bindings[ i ];
  8017. if ( -- binding.useCount === 0 ) {
  8018. binding.restoreOriginalState();
  8019. this._takeBackBinding( binding );
  8020. }
  8021. }
  8022. this._takeBackAction( action );
  8023. }
  8024. },
  8025. // Memory manager
  8026. _initMemoryManager: function() {
  8027. this._actions = []; // 'nActiveActions' followed by inactive ones
  8028. this._nActiveActions = 0;
  8029. this._actionsByClip = {};
  8030. // inside:
  8031. // {
  8032. // knownActions: Array< _Action > - used as prototypes
  8033. // actionByRoot: _Action - lookup
  8034. // }
  8035. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  8036. this._nActiveBindings = 0;
  8037. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  8038. this._controlInterpolants = []; // same game as above
  8039. this._nActiveControlInterpolants = 0;
  8040. var scope = this;
  8041. this.stats = {
  8042. actions: {
  8043. get total() { return scope._actions.length; },
  8044. get inUse() { return scope._nActiveActions; }
  8045. },
  8046. bindings: {
  8047. get total() { return scope._bindings.length; },
  8048. get inUse() { return scope._nActiveBindings; }
  8049. },
  8050. controlInterpolants: {
  8051. get total() { return scope._controlInterpolants.length; },
  8052. get inUse() { return scope._nActiveControlInterpolants; }
  8053. }
  8054. };
  8055. },
  8056. // Memory management for _Action objects
  8057. _isActiveAction: function( action ) {
  8058. var index = action._cacheIndex;
  8059. return index !== null && index < this._nActiveActions;
  8060. },
  8061. _addInactiveAction: function( action, clipName, rootUuid ) {
  8062. var actions = this._actions,
  8063. actionsByClip = this._actionsByClip,
  8064. actionsForClip = actionsByClip[ clipName ];
  8065. if ( actionsForClip === undefined ) {
  8066. actionsForClip = {
  8067. knownActions: [ action ],
  8068. actionByRoot: {}
  8069. };
  8070. action._byClipCacheIndex = 0;
  8071. actionsByClip[ clipName ] = actionsForClip;
  8072. } else {
  8073. var knownActions = actionsForClip.knownActions;
  8074. action._byClipCacheIndex = knownActions.length;
  8075. knownActions.push( action );
  8076. }
  8077. action._cacheIndex = actions.length;
  8078. actions.push( action );
  8079. actionsForClip.actionByRoot[ rootUuid ] = action;
  8080. },
  8081. _removeInactiveAction: function( action ) {
  8082. var actions = this._actions,
  8083. lastInactiveAction = actions[ actions.length - 1 ],
  8084. cacheIndex = action._cacheIndex;
  8085. lastInactiveAction._cacheIndex = cacheIndex;
  8086. actions[ cacheIndex ] = lastInactiveAction;
  8087. actions.pop();
  8088. action._cacheIndex = null;
  8089. var clipName = action._clip.name,
  8090. actionsByClip = this._actionsByClip,
  8091. actionsForClip = actionsByClip[ clipName ],
  8092. knownActionsForClip = actionsForClip.knownActions,
  8093. lastKnownAction =
  8094. knownActionsForClip[ knownActionsForClip.length - 1 ],
  8095. byClipCacheIndex = action._byClipCacheIndex;
  8096. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  8097. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  8098. knownActionsForClip.pop();
  8099. action._byClipCacheIndex = null;
  8100. var actionByRoot = actionsForClip.actionByRoot,
  8101. rootUuid = ( actions._localRoot || this._root ).uuid;
  8102. delete actionByRoot[ rootUuid ];
  8103. if ( knownActionsForClip.length === 0 ) {
  8104. delete actionsByClip[ clipName ];
  8105. }
  8106. this._removeInactiveBindingsForAction( action );
  8107. },
  8108. _removeInactiveBindingsForAction: function( action ) {
  8109. var bindings = action._propertyBindings;
  8110. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  8111. var binding = bindings[ i ];
  8112. if ( -- binding.referenceCount === 0 ) {
  8113. this._removeInactiveBinding( binding );
  8114. }
  8115. }
  8116. },
  8117. _lendAction: function( action ) {
  8118. // [ active actions | inactive actions ]
  8119. // [ active actions >| inactive actions ]
  8120. // s a
  8121. // <-swap->
  8122. // a s
  8123. var actions = this._actions,
  8124. prevIndex = action._cacheIndex,
  8125. lastActiveIndex = this._nActiveActions ++,
  8126. firstInactiveAction = actions[ lastActiveIndex ];
  8127. action._cacheIndex = lastActiveIndex;
  8128. actions[ lastActiveIndex ] = action;
  8129. firstInactiveAction._cacheIndex = prevIndex;
  8130. actions[ prevIndex ] = firstInactiveAction;
  8131. },
  8132. _takeBackAction: function( action ) {
  8133. // [ active actions | inactive actions ]
  8134. // [ active actions |< inactive actions ]
  8135. // a s
  8136. // <-swap->
  8137. // s a
  8138. var actions = this._actions,
  8139. prevIndex = action._cacheIndex,
  8140. firstInactiveIndex = -- this._nActiveActions,
  8141. lastActiveAction = actions[ firstInactiveIndex ];
  8142. action._cacheIndex = firstInactiveIndex;
  8143. actions[ firstInactiveIndex ] = action;
  8144. lastActiveAction._cacheIndex = prevIndex;
  8145. actions[ prevIndex ] = lastActiveAction;
  8146. },
  8147. // Memory management for PropertyMixer objects
  8148. _addInactiveBinding: function( binding, rootUuid, trackName ) {
  8149. var bindingsByRoot = this._bindingsByRootAndName,
  8150. bindingByName = bindingsByRoot[ rootUuid ],
  8151. bindings = this._bindings;
  8152. if ( bindingByName === undefined ) {
  8153. bindingByName = {};
  8154. bindingsByRoot[ rootUuid ] = bindingByName;
  8155. }
  8156. bindingByName[ trackName ] = binding;
  8157. binding._cacheIndex = bindings.length;
  8158. bindings.push( binding );
  8159. },
  8160. _removeInactiveBinding: function( binding ) {
  8161. var bindings = this._bindings,
  8162. propBinding = binding.binding,
  8163. rootUuid = propBinding.rootNode.uuid,
  8164. trackName = propBinding.path,
  8165. bindingsByRoot = this._bindingsByRootAndName,
  8166. bindingByName = bindingsByRoot[ rootUuid ],
  8167. lastInactiveBinding = bindings[ bindings.length - 1 ],
  8168. cacheIndex = binding._cacheIndex;
  8169. lastInactiveBinding._cacheIndex = cacheIndex;
  8170. bindings[ cacheIndex ] = lastInactiveBinding;
  8171. bindings.pop();
  8172. delete bindingByName[ trackName ];
  8173. remove_empty_map: {
  8174. for ( var _ in bindingByName ) break remove_empty_map;
  8175. delete bindingsByRoot[ rootUuid ];
  8176. }
  8177. },
  8178. _lendBinding: function( binding ) {
  8179. var bindings = this._bindings,
  8180. prevIndex = binding._cacheIndex,
  8181. lastActiveIndex = this._nActiveBindings ++,
  8182. firstInactiveBinding = bindings[ lastActiveIndex ];
  8183. binding._cacheIndex = lastActiveIndex;
  8184. bindings[ lastActiveIndex ] = binding;
  8185. firstInactiveBinding._cacheIndex = prevIndex;
  8186. bindings[ prevIndex ] = firstInactiveBinding;
  8187. },
  8188. _takeBackBinding: function( binding ) {
  8189. var bindings = this._bindings,
  8190. prevIndex = binding._cacheIndex,
  8191. firstInactiveIndex = -- this._nActiveBindings,
  8192. lastActiveBinding = bindings[ firstInactiveIndex ];
  8193. binding._cacheIndex = firstInactiveIndex;
  8194. bindings[ firstInactiveIndex ] = binding;
  8195. lastActiveBinding._cacheIndex = prevIndex;
  8196. bindings[ prevIndex ] = lastActiveBinding;
  8197. },
  8198. // Memory management of Interpolants for weight and time scale
  8199. _lendControlInterpolant: function() {
  8200. var interpolants = this._controlInterpolants,
  8201. lastActiveIndex = this._nActiveControlInterpolants ++,
  8202. interpolant = interpolants[ lastActiveIndex ];
  8203. if ( interpolant === undefined ) {
  8204. interpolant = new THREE.LinearInterpolant(
  8205. new Float32Array( 2 ), new Float32Array( 2 ),
  8206. 1, this._controlInterpolantsResultBuffer );
  8207. interpolant.__cacheIndex = lastActiveIndex;
  8208. interpolants[ lastActiveIndex ] = interpolant;
  8209. }
  8210. return interpolant;
  8211. },
  8212. _takeBackControlInterpolant: function( interpolant ) {
  8213. var interpolants = this._controlInterpolants,
  8214. prevIndex = interpolant.__cacheIndex,
  8215. firstInactiveIndex = -- this._nActiveControlInterpolants,
  8216. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  8217. interpolant.__cacheIndex = firstInactiveIndex;
  8218. interpolants[ firstInactiveIndex ] = interpolant;
  8219. lastActiveInterpolant.__cacheIndex = prevIndex;
  8220. interpolants[ prevIndex ] = lastActiveInterpolant;
  8221. },
  8222. _controlInterpolantsResultBuffer: new Float32Array( 1 )
  8223. } );
  8224. // File:src/animation/AnimationObjectGroup.js
  8225. /**
  8226. *
  8227. * A group of objects that receives a shared animation state.
  8228. *
  8229. * Usage:
  8230. *
  8231. * - Add objects you would otherwise pass as 'root' to the
  8232. * constructor or the .clipAction method of AnimationMixer.
  8233. *
  8234. * - Instead pass this object as 'root'.
  8235. *
  8236. * - You can also add and remove objects later when the mixer
  8237. * is running.
  8238. *
  8239. * Note:
  8240. *
  8241. * Objects of this class appear as one object to the mixer,
  8242. * so cache control of the individual objects must be done
  8243. * on the group.
  8244. *
  8245. * Limitation:
  8246. *
  8247. * - The animated properties must be compatible among the
  8248. * all objects in the group.
  8249. *
  8250. * - A single property can either be controlled through a
  8251. * target group or directly, but not both.
  8252. *
  8253. * @author tschw
  8254. */
  8255. THREE.AnimationObjectGroup = function( var_args ) {
  8256. this.uuid = THREE.Math.generateUUID();
  8257. // cached objects followed by the active ones
  8258. this._objects = Array.prototype.slice.call( arguments );
  8259. this.nCachedObjects_ = 0; // threshold
  8260. // note: read by PropertyBinding.Composite
  8261. var indices = {};
  8262. this._indicesByUUID = indices; // for bookkeeping
  8263. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  8264. indices[ arguments[ i ].uuid ] = i;
  8265. }
  8266. this._paths = []; // inside: string
  8267. this._parsedPaths = []; // inside: { we don't care, here }
  8268. this._bindings = []; // inside: Array< PropertyBinding >
  8269. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  8270. var scope = this;
  8271. this.stats = {
  8272. objects: {
  8273. get total() { return scope._objects.length; },
  8274. get inUse() { return this.total - scope.nCachedObjects_; }
  8275. },
  8276. get bindingsPerObject() { return scope._bindings.length; }
  8277. };
  8278. };
  8279. THREE.AnimationObjectGroup.prototype = {
  8280. constructor: THREE.AnimationObjectGroup,
  8281. add: function( var_args ) {
  8282. var objects = this._objects,
  8283. nObjects = objects.length,
  8284. nCachedObjects = this.nCachedObjects_,
  8285. indicesByUUID = this._indicesByUUID,
  8286. paths = this._paths,
  8287. parsedPaths = this._parsedPaths,
  8288. bindings = this._bindings,
  8289. nBindings = bindings.length;
  8290. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  8291. var object = arguments[ i ],
  8292. uuid = object.uuid,
  8293. index = indicesByUUID[ uuid ];
  8294. if ( index === undefined ) {
  8295. // unknown object -> add it to the ACTIVE region
  8296. index = nObjects ++;
  8297. indicesByUUID[ uuid ] = index;
  8298. objects.push( object );
  8299. // accounting is done, now do the same for all bindings
  8300. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  8301. bindings[ j ].push(
  8302. new THREE.PropertyBinding(
  8303. object, paths[ j ], parsedPaths[ j ] ) );
  8304. }
  8305. } else if ( index < nCachedObjects ) {
  8306. var knownObject = objects[ index ];
  8307. // move existing object to the ACTIVE region
  8308. var firstActiveIndex = -- nCachedObjects,
  8309. lastCachedObject = objects[ firstActiveIndex ];
  8310. indicesByUUID[ lastCachedObject.uuid ] = index;
  8311. objects[ index ] = lastCachedObject;
  8312. indicesByUUID[ uuid ] = firstActiveIndex;
  8313. objects[ firstActiveIndex ] = object;
  8314. // accounting is done, now do the same for all bindings
  8315. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  8316. var bindingsForPath = bindings[ j ],
  8317. lastCached = bindingsForPath[ firstActiveIndex ],
  8318. binding = bindingsForPath[ index ];
  8319. bindingsForPath[ index ] = lastCached;
  8320. if ( binding === undefined ) {
  8321. // since we do not bother to create new bindings
  8322. // for objects that are cached, the binding may
  8323. // or may not exist
  8324. binding = new THREE.PropertyBinding(
  8325. object, paths[ j ], parsedPaths[ j ] );
  8326. }
  8327. bindingsForPath[ firstActiveIndex ] = binding;
  8328. }
  8329. } else if ( objects[ index ] !== knownObject) {
  8330. console.error( "Different objects with the same UUID " +
  8331. "detected. Clean the caches or recreate your " +
  8332. "infrastructure when reloading scenes..." );
  8333. } // else the object is already where we want it to be
  8334. } // for arguments
  8335. this.nCachedObjects_ = nCachedObjects;
  8336. },
  8337. remove: function( var_args ) {
  8338. var objects = this._objects,
  8339. nObjects = objects.length,
  8340. nCachedObjects = this.nCachedObjects_,
  8341. indicesByUUID = this._indicesByUUID,
  8342. bindings = this._bindings,
  8343. nBindings = bindings.length;
  8344. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  8345. var object = arguments[ i ],
  8346. uuid = object.uuid,
  8347. index = indicesByUUID[ uuid ];
  8348. if ( index !== undefined && index >= nCachedObjects ) {
  8349. // move existing object into the CACHED region
  8350. var lastCachedIndex = nCachedObjects ++,
  8351. firstActiveObject = objects[ lastCachedIndex ];
  8352. indicesByUUID[ firstActiveObject.uuid ] = index;
  8353. objects[ index ] = firstActiveObject;
  8354. indicesByUUID[ uuid ] = lastCachedIndex;
  8355. objects[ lastCachedIndex ] = object;
  8356. // accounting is done, now do the same for all bindings
  8357. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  8358. var bindingsForPath = bindings[ j ],
  8359. firstActive = bindingsForPath[ lastCachedIndex ],
  8360. binding = bindingsForPath[ index ];
  8361. bindingsForPath[ index ] = firstActive;
  8362. bindingsForPath[ lastCachedIndex ] = binding;
  8363. }
  8364. }
  8365. } // for arguments
  8366. this.nCachedObjects_ = nCachedObjects;
  8367. },
  8368. // remove & forget
  8369. uncache: function( var_args ) {
  8370. var objects = this._objects,
  8371. nObjects = objects.length,
  8372. nCachedObjects = this.nCachedObjects_,
  8373. indicesByUUID = this._indicesByUUID,
  8374. bindings = this._bindings,
  8375. nBindings = bindings.length;
  8376. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  8377. var object = arguments[ i ],
  8378. uuid = object.uuid,
  8379. index = indicesByUUID[ uuid ];
  8380. if ( index !== undefined ) {
  8381. delete indicesByUUID[ uuid ];
  8382. if ( index < nCachedObjects ) {
  8383. // object is cached, shrink the CACHED region
  8384. var firstActiveIndex = -- nCachedObjects,
  8385. lastCachedObject = objects[ firstActiveIndex ],
  8386. lastIndex = -- nObjects,
  8387. lastObject = objects[ lastIndex ];
  8388. // last cached object takes this object's place
  8389. indicesByUUID[ lastCachedObject.uuid ] = index;
  8390. objects[ index ] = lastCachedObject;
  8391. // last object goes to the activated slot and pop
  8392. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  8393. objects[ firstActiveIndex ] = lastObject;
  8394. objects.pop();
  8395. // accounting is done, now do the same for all bindings
  8396. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  8397. var bindingsForPath = bindings[ j ],
  8398. lastCached = bindingsForPath[ firstActiveIndex ],
  8399. last = bindingsForPath[ lastIndex ];
  8400. bindingsForPath[ index ] = lastCached;
  8401. bindingsForPath[ firstActiveIndex ] = last;
  8402. bindingsForPath.pop();
  8403. }
  8404. } else {
  8405. // object is active, just swap with the last and pop
  8406. var lastIndex = -- nObjects,
  8407. lastObject = objects[ lastIndex ];
  8408. indicesByUUID[ lastObject.uuid ] = index;
  8409. objects[ index ] = lastObject;
  8410. objects.pop();
  8411. // accounting is done, now do the same for all bindings
  8412. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  8413. var bindingsForPath = bindings[ j ];
  8414. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  8415. bindingsForPath.pop();
  8416. }
  8417. } // cached or active
  8418. } // if object is known
  8419. } // for arguments
  8420. this.nCachedObjects_ = nCachedObjects;
  8421. },
  8422. // Internal interface used by befriended PropertyBinding.Composite:
  8423. subscribe_: function( path, parsedPath ) {
  8424. // returns an array of bindings for the given path that is changed
  8425. // according to the contained objects in the group
  8426. var indicesByPath = this._bindingsIndicesByPath,
  8427. index = indicesByPath[ path ],
  8428. bindings = this._bindings;
  8429. if ( index !== undefined ) return bindings[ index ];
  8430. var paths = this._paths,
  8431. parsedPaths = this._parsedPaths,
  8432. objects = this._objects,
  8433. nObjects = objects.length,
  8434. nCachedObjects = this.nCachedObjects_,
  8435. bindingsForPath = new Array( nObjects );
  8436. index = bindings.length;
  8437. indicesByPath[ path ] = index;
  8438. paths.push( path );
  8439. parsedPaths.push( parsedPath );
  8440. bindings.push( bindingsForPath );
  8441. for ( var i = nCachedObjects,
  8442. n = objects.length; i !== n; ++ i ) {
  8443. var object = objects[ i ];
  8444. bindingsForPath[ i ] =
  8445. new THREE.PropertyBinding( object, path, parsedPath );
  8446. }
  8447. return bindingsForPath;
  8448. },
  8449. unsubscribe_: function( path ) {
  8450. // tells the group to forget about a property path and no longer
  8451. // update the array previously obtained with 'subscribe_'
  8452. var indicesByPath = this._bindingsIndicesByPath,
  8453. index = indicesByPath[ path ];
  8454. if ( index !== undefined ) {
  8455. var paths = this._paths,
  8456. parsedPaths = this._parsedPaths,
  8457. bindings = this._bindings,
  8458. lastBindingsIndex = bindings.length - 1,
  8459. lastBindings = bindings[ lastBindingsIndex ],
  8460. lastBindingsPath = path[ lastBindingsIndex ];
  8461. indicesByPath[ lastBindingsPath ] = index;
  8462. bindings[ index ] = lastBindings;
  8463. bindings.pop();
  8464. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  8465. parsedPaths.pop();
  8466. paths[ index ] = paths[ lastBindingsIndex ];
  8467. paths.pop();
  8468. }
  8469. }
  8470. };
  8471. // File:src/animation/AnimationUtils.js
  8472. /**
  8473. * @author tschw
  8474. * @author Ben Houston / http://clara.io/
  8475. * @author David Sarno / http://lighthaus.us/
  8476. */
  8477. THREE.AnimationUtils = {
  8478. // same as Array.prototype.slice, but also works on typed arrays
  8479. arraySlice: function( array, from, to ) {
  8480. if ( THREE.AnimationUtils.isTypedArray( array ) ) {
  8481. return new array.constructor( array.subarray( from, to ) );
  8482. }
  8483. return array.slice( from, to );
  8484. },
  8485. // converts an array to a specific type
  8486. convertArray: function( array, type, forceClone ) {
  8487. if ( ! array || // let 'undefined' and 'null' pass
  8488. ! forceClone && array.constructor === type ) return array;
  8489. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  8490. return new type( array ); // create typed array
  8491. }
  8492. return Array.prototype.slice.call( array ); // create Array
  8493. },
  8494. isTypedArray: function( object ) {
  8495. return ArrayBuffer.isView( object ) &&
  8496. ! ( object instanceof DataView );
  8497. },
  8498. // returns an array by which times and values can be sorted
  8499. getKeyframeOrder: function( times ) {
  8500. function compareTime( i, j ) {
  8501. return times[ i ] - times[ j ];
  8502. }
  8503. var n = times.length;
  8504. var result = new Array( n );
  8505. for ( var i = 0; i !== n; ++ i ) result[ i ] = i;
  8506. result.sort( compareTime );
  8507. return result;
  8508. },
  8509. // uses the array previously returned by 'getKeyframeOrder' to sort data
  8510. sortedArray: function( values, stride, order ) {
  8511. var nValues = values.length;
  8512. var result = new values.constructor( nValues );
  8513. for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  8514. var srcOffset = order[ i ] * stride;
  8515. for ( var j = 0; j !== stride; ++ j ) {
  8516. result[ dstOffset ++ ] = values[ srcOffset + j ];
  8517. }
  8518. }
  8519. return result;
  8520. },
  8521. // function for parsing AOS keyframe formats
  8522. flattenJSON: function( jsonKeys, times, values, valuePropertyName ) {
  8523. var i = 1, key = jsonKeys[ 0 ];
  8524. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  8525. key = jsonKeys[ i ++ ];
  8526. }
  8527. if ( key === undefined ) return; // no data
  8528. var value = key[ valuePropertyName ];
  8529. if ( value === undefined ) return; // no data
  8530. if ( Array.isArray( value ) ) {
  8531. do {
  8532. value = key[ valuePropertyName ];
  8533. if ( value !== undefined ) {
  8534. times.push( key.time );
  8535. values.push.apply( values, value ); // push all elements
  8536. }
  8537. key = jsonKeys[ i ++ ];
  8538. } while ( key !== undefined );
  8539. } else if ( value.toArray !== undefined ) {
  8540. // ...assume THREE.Math-ish
  8541. do {
  8542. value = key[ valuePropertyName ];
  8543. if ( value !== undefined ) {
  8544. times.push( key.time );
  8545. value.toArray( values, values.length );
  8546. }
  8547. key = jsonKeys[ i ++ ];
  8548. } while ( key !== undefined );
  8549. } else {
  8550. // otherwise push as-is
  8551. do {
  8552. value = key[ valuePropertyName ];
  8553. if ( value !== undefined ) {
  8554. times.push( key.time );
  8555. values.push( value );
  8556. }
  8557. key = jsonKeys[ i ++ ];
  8558. } while ( key !== undefined );
  8559. }
  8560. }
  8561. };
  8562. // File:src/animation/KeyframeTrack.js
  8563. /**
  8564. *
  8565. * A timed sequence of keyframes for a specific property.
  8566. *
  8567. *
  8568. * @author Ben Houston / http://clara.io/
  8569. * @author David Sarno / http://lighthaus.us/
  8570. * @author tschw
  8571. */
  8572. THREE.KeyframeTrack = function ( name, times, values, interpolation ) {
  8573. if( name === undefined ) throw new Error( "track name is undefined" );
  8574. if( times === undefined || times.length === 0 ) {
  8575. throw new Error( "no keyframes in track named " + name );
  8576. }
  8577. this.name = name;
  8578. this.times = THREE.AnimationUtils.convertArray( times, this.TimeBufferType );
  8579. this.values = THREE.AnimationUtils.convertArray( values, this.ValueBufferType );
  8580. this.setInterpolation( interpolation || this.DefaultInterpolation );
  8581. this.validate();
  8582. this.optimize();
  8583. };
  8584. THREE.KeyframeTrack.prototype = {
  8585. constructor: THREE.KeyframeTrack,
  8586. TimeBufferType: Float32Array,
  8587. ValueBufferType: Float32Array,
  8588. DefaultInterpolation: THREE.InterpolateLinear,
  8589. InterpolantFactoryMethodDiscrete: function( result ) {
  8590. return new THREE.DiscreteInterpolant(
  8591. this.times, this.values, this.getValueSize(), result );
  8592. },
  8593. InterpolantFactoryMethodLinear: function( result ) {
  8594. return new THREE.LinearInterpolant(
  8595. this.times, this.values, this.getValueSize(), result );
  8596. },
  8597. InterpolantFactoryMethodSmooth: function( result ) {
  8598. return new THREE.CubicInterpolant(
  8599. this.times, this.values, this.getValueSize(), result );
  8600. },
  8601. setInterpolation: function( interpolation ) {
  8602. var factoryMethod = undefined;
  8603. switch ( interpolation ) {
  8604. case THREE.InterpolateDiscrete:
  8605. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  8606. break;
  8607. case THREE.InterpolateLinear:
  8608. factoryMethod = this.InterpolantFactoryMethodLinear;
  8609. break;
  8610. case THREE.InterpolateSmooth:
  8611. factoryMethod = this.InterpolantFactoryMethodSmooth;
  8612. break;
  8613. }
  8614. if ( factoryMethod === undefined ) {
  8615. var message = "unsupported interpolation for " +
  8616. this.ValueTypeName + " keyframe track named " + this.name;
  8617. if ( this.createInterpolant === undefined ) {
  8618. // fall back to default, unless the default itself is messed up
  8619. if ( interpolation !== this.DefaultInterpolation ) {
  8620. this.setInterpolation( this.DefaultInterpolation );
  8621. } else {
  8622. throw new Error( message ); // fatal, in this case
  8623. }
  8624. }
  8625. console.warn( message );
  8626. return;
  8627. }
  8628. this.createInterpolant = factoryMethod;
  8629. },
  8630. getInterpolation: function() {
  8631. switch ( this.createInterpolant ) {
  8632. case this.InterpolantFactoryMethodDiscrete:
  8633. return THREE.InterpolateDiscrete;
  8634. case this.InterpolantFactoryMethodLinear:
  8635. return THREE.InterpolateLinear;
  8636. case this.InterpolantFactoryMethodSmooth:
  8637. return THREE.InterpolateSmooth;
  8638. }
  8639. },
  8640. getValueSize: function() {
  8641. return this.values.length / this.times.length;
  8642. },
  8643. // move all keyframes either forwards or backwards in time
  8644. shift: function( timeOffset ) {
  8645. if( timeOffset !== 0.0 ) {
  8646. var times = this.times;
  8647. for( var i = 0, n = times.length; i !== n; ++ i ) {
  8648. times[ i ] += timeOffset;
  8649. }
  8650. }
  8651. return this;
  8652. },
  8653. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  8654. scale: function( timeScale ) {
  8655. if( timeScale !== 1.0 ) {
  8656. var times = this.times;
  8657. for( var i = 0, n = times.length; i !== n; ++ i ) {
  8658. times[ i ] *= timeScale;
  8659. }
  8660. }
  8661. return this;
  8662. },
  8663. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  8664. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  8665. trim: function( startTime, endTime ) {
  8666. var times = this.times;
  8667. var nKeys = times.length;
  8668. var firstKeysToRemove = 0;
  8669. for ( var i = 1; i !== nKeys; ++ i ) {
  8670. if ( times[i] <= startTime ) ++ firstKeysToRemove;
  8671. }
  8672. var lastKeysToRemove = 0;
  8673. for ( var i = nKeys - 2; i !== 0; -- i ) {
  8674. if ( times[i] >= endTime ) ++ lastKeysToRemove;
  8675. else break;
  8676. }
  8677. // remove last keys first because it doesn't affect the position of the first keys (the otherway around doesn't work as easily)
  8678. if( ( firstKeysToRemove + lastKeysToRemove ) !== 0 ) {
  8679. var from = firstKeysToRemove;
  8680. var to = nKeys - lastKeysToRemove - firstKeysToRemove;
  8681. this.times = THREE.AnimationUtils.arraySlice( times, from, to );
  8682. var values = this.values;
  8683. var stride = this.getValueSize();
  8684. this.values = THREE.AnimationUtils.arraySlice( values, from * stride, to * stride );
  8685. }
  8686. return this;
  8687. },
  8688. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  8689. validate: function() {
  8690. var valid = true;
  8691. var valueSize = this.getValueSize();
  8692. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  8693. console.error( "invalid value size in track", this );
  8694. valid = false;
  8695. }
  8696. var times = this.times,
  8697. values = this.values,
  8698. nKeys = times.length;
  8699. if( nKeys === 0 ) {
  8700. console.error( "track is empty", this );
  8701. valid = false;
  8702. }
  8703. var prevTime = null;
  8704. for( var i = 0; i !== nKeys; i ++ ) {
  8705. var currTime = times[ i ];
  8706. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  8707. console.error( "time is not a valid number", this, i, currTime );
  8708. valid = false;
  8709. break;
  8710. }
  8711. if( prevTime !== null && prevTime > currTime ) {
  8712. console.error( "out of order keys", this, i, currTime, prevTime );
  8713. valid = false;
  8714. break;
  8715. }
  8716. prevTime = currTime;
  8717. }
  8718. if ( values !== undefined ) {
  8719. if ( THREE.AnimationUtils.isTypedArray( values ) ) {
  8720. for ( var i = 0, n = values.length; i !== n; ++ i ) {
  8721. var value = values[ i ];
  8722. if ( isNaN( value ) ) {
  8723. console.error( "value is not a valid number", this, i, value );
  8724. valid = false;
  8725. break;
  8726. }
  8727. }
  8728. }
  8729. }
  8730. return valid;
  8731. },
  8732. // removes equivalent sequential keys as common in morph target sequences
  8733. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  8734. optimize: function() {
  8735. var times = this.times,
  8736. values = this.values,
  8737. stride = this.getValueSize(),
  8738. writeIndex = 1;
  8739. for( var i = 1, n = times.length - 1; i <= n; ++ i ) {
  8740. var keep = false;
  8741. var time = times[ i ];
  8742. var timeNext = times[ i + 1 ];
  8743. // remove adjacent keyframes scheduled at the same time
  8744. if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) {
  8745. // remove unnecessary keyframes same as their neighbors
  8746. var offset = i * stride,
  8747. offsetP = offset - stride,
  8748. offsetN = offset + stride;
  8749. for ( var j = 0; j !== stride; ++ j ) {
  8750. var value = values[ offset + j ];
  8751. if ( value !== values[ offsetP + j ] ||
  8752. value !== values[ offsetN + j ] ) {
  8753. keep = true;
  8754. break;
  8755. }
  8756. }
  8757. }
  8758. // in-place compaction
  8759. if ( keep ) {
  8760. if ( i !== writeIndex ) {
  8761. times[ writeIndex ] = times[ i ];
  8762. var readOffset = i * stride,
  8763. writeOffset = writeIndex * stride;
  8764. for ( var j = 0; j !== stride; ++ j ) {
  8765. values[ writeOffset + j ] = values[ readOffset + j ];
  8766. }
  8767. }
  8768. ++ writeIndex;
  8769. }
  8770. }
  8771. if ( writeIndex !== times.length ) {
  8772. this.times = THREE.AnimationUtils.arraySlice( times, 0, writeIndex );
  8773. this.values = THREE.AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  8774. }
  8775. return this;
  8776. }
  8777. };
  8778. // Static methods:
  8779. Object.assign( THREE.KeyframeTrack, {
  8780. // Serialization (in static context, because of constructor invocation
  8781. // and automatic invocation of .toJSON):
  8782. parse: function( json ) {
  8783. if( json.type === undefined ) {
  8784. throw new Error( "track type undefined, can not parse" );
  8785. }
  8786. var trackType = THREE.KeyframeTrack._getTrackTypeForValueTypeName( json.type );
  8787. if ( json.times === undefined ) {
  8788. console.warn( "legacy JSON format detected, converting" );
  8789. var times = [], values = [];
  8790. THREE.AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  8791. json.times = times;
  8792. json.values = values;
  8793. }
  8794. // derived classes can define a static parse method
  8795. if ( trackType.parse !== undefined ) {
  8796. return trackType.parse( json );
  8797. } else {
  8798. // by default, we asssume a constructor compatible with the base
  8799. return new trackType(
  8800. json.name, json.times, json.values, json.interpolation );
  8801. }
  8802. },
  8803. toJSON: function( track ) {
  8804. var trackType = track.constructor;
  8805. var json;
  8806. // derived classes can define a static toJSON method
  8807. if ( trackType.toJSON !== undefined ) {
  8808. json = trackType.toJSON( track );
  8809. } else {
  8810. // by default, we assume the data can be serialized as-is
  8811. json = {
  8812. 'name': track.name,
  8813. 'times': THREE.AnimationUtils.convertArray( track.times, Array ),
  8814. 'values': THREE.AnimationUtils.convertArray( track.values, Array )
  8815. };
  8816. var interpolation = track.getInterpolation();
  8817. if ( interpolation !== track.DefaultInterpolation ) {
  8818. json.interpolation = interpolation;
  8819. }
  8820. }
  8821. json.type = track.ValueTypeName; // mandatory
  8822. return json;
  8823. },
  8824. _getTrackTypeForValueTypeName: function( typeName ) {
  8825. switch( typeName.toLowerCase() ) {
  8826. case "scalar":
  8827. case "double":
  8828. case "float":
  8829. case "number":
  8830. case "integer":
  8831. return THREE.NumberKeyframeTrack;
  8832. case "vector":
  8833. case "vector2":
  8834. case "vector3":
  8835. case "vector4":
  8836. return THREE.VectorKeyframeTrack;
  8837. case "color":
  8838. return THREE.ColorKeyframeTrack;
  8839. case "quaternion":
  8840. return THREE.QuaternionKeyframeTrack;
  8841. case "bool":
  8842. case "boolean":
  8843. return THREE.BooleanKeyframeTrack;
  8844. case "string":
  8845. return THREE.StringKeyframeTrack;
  8846. };
  8847. throw new Error( "Unsupported typeName: " + typeName );
  8848. }
  8849. } );
  8850. // File:src/animation/PropertyBinding.js
  8851. /**
  8852. *
  8853. * A reference to a real property in the scene graph.
  8854. *
  8855. *
  8856. * @author Ben Houston / http://clara.io/
  8857. * @author David Sarno / http://lighthaus.us/
  8858. * @author tschw
  8859. */
  8860. THREE.PropertyBinding = function ( rootNode, path, parsedPath ) {
  8861. this.path = path;
  8862. this.parsedPath = parsedPath ||
  8863. THREE.PropertyBinding.parseTrackName( path );
  8864. this.node = THREE.PropertyBinding.findNode(
  8865. rootNode, this.parsedPath.nodeName ) || rootNode;
  8866. this.rootNode = rootNode;
  8867. };
  8868. THREE.PropertyBinding.prototype = {
  8869. constructor: THREE.PropertyBinding,
  8870. getValue: function getValue_unbound( targetArray, offset ) {
  8871. this.bind();
  8872. this.getValue( targetArray, offset );
  8873. // Note: This class uses a State pattern on a per-method basis:
  8874. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  8875. // prototype version of these methods with one that represents
  8876. // the bound state. When the property is not found, the methods
  8877. // become no-ops.
  8878. },
  8879. setValue: function getValue_unbound( sourceArray, offset ) {
  8880. this.bind();
  8881. this.setValue( sourceArray, offset );
  8882. },
  8883. // create getter / setter pair for a property in the scene graph
  8884. bind: function() {
  8885. var targetObject = this.node,
  8886. parsedPath = this.parsedPath,
  8887. objectName = parsedPath.objectName,
  8888. propertyName = parsedPath.propertyName,
  8889. propertyIndex = parsedPath.propertyIndex;
  8890. if ( ! targetObject ) {
  8891. targetObject = THREE.PropertyBinding.findNode(
  8892. this.rootNode, parsedPath.nodeName ) || this.rootNode;
  8893. this.node = targetObject;
  8894. }
  8895. // set fail state so we can just 'return' on error
  8896. this.getValue = this._getValue_unavailable;
  8897. this.setValue = this._setValue_unavailable;
  8898. // ensure there is a value node
  8899. if ( ! targetObject ) {
  8900. console.error( " trying to update node for track: " + this.path + " but it wasn't found." );
  8901. return;
  8902. }
  8903. if( objectName ) {
  8904. var objectIndex = parsedPath.objectIndex;
  8905. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  8906. switch ( objectName ) {
  8907. case 'materials':
  8908. if( ! targetObject.material ) {
  8909. console.error( ' can not bind to material as node does not have a material', this );
  8910. return;
  8911. }
  8912. if( ! targetObject.material.materials ) {
  8913. console.error( ' can not bind to material.materials as node.material does not have a materials array', this );
  8914. return;
  8915. }
  8916. targetObject = targetObject.material.materials;
  8917. break;
  8918. case 'bones':
  8919. if( ! targetObject.skeleton ) {
  8920. console.error( ' can not bind to bones as node does not have a skeleton', this );
  8921. return;
  8922. }
  8923. // potential future optimization: skip this if propertyIndex is already an integer
  8924. // and convert the integer string to a true integer.
  8925. targetObject = targetObject.skeleton.bones;
  8926. // support resolving morphTarget names into indices.
  8927. for ( var i = 0; i < targetObject.length; i ++ ) {
  8928. if ( targetObject[i].name === objectIndex ) {
  8929. objectIndex = i;
  8930. break;
  8931. }
  8932. }
  8933. break;
  8934. default:
  8935. if ( targetObject[ objectName ] === undefined ) {
  8936. console.error( ' can not bind to objectName of node, undefined', this );
  8937. return;
  8938. }
  8939. targetObject = targetObject[ objectName ];
  8940. }
  8941. if ( objectIndex !== undefined ) {
  8942. if( targetObject[ objectIndex ] === undefined ) {
  8943. console.error( " trying to bind to objectIndex of objectName, but is undefined:", this, targetObject );
  8944. return;
  8945. }
  8946. targetObject = targetObject[ objectIndex ];
  8947. }
  8948. }
  8949. // resolve property
  8950. var nodeProperty = targetObject[ propertyName ];
  8951. if ( ! nodeProperty ) {
  8952. var nodeName = parsedPath.nodeName;
  8953. console.error( " trying to update property for track: " + nodeName +
  8954. '.' + propertyName + " but it wasn't found.", targetObject );
  8955. return;
  8956. }
  8957. // determine versioning scheme
  8958. var versioning = this.Versioning.None;
  8959. if ( targetObject.needsUpdate !== undefined ) { // material
  8960. versioning = this.Versioning.NeedsUpdate;
  8961. this.targetObject = targetObject;
  8962. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  8963. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  8964. this.targetObject = targetObject;
  8965. }
  8966. // determine how the property gets bound
  8967. var bindingType = this.BindingType.Direct;
  8968. if ( propertyIndex !== undefined ) {
  8969. // access a sub element of the property array (only primitives are supported right now)
  8970. if ( propertyName === "morphTargetInfluences" ) {
  8971. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  8972. // support resolving morphTarget names into indices.
  8973. if ( ! targetObject.geometry ) {
  8974. console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry', this );
  8975. return;
  8976. }
  8977. if ( ! targetObject.geometry.morphTargets ) {
  8978. console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry.morphTargets', this );
  8979. return;
  8980. }
  8981. for ( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) {
  8982. if ( targetObject.geometry.morphTargets[i].name === propertyIndex ) {
  8983. propertyIndex = i;
  8984. break;
  8985. }
  8986. }
  8987. }
  8988. bindingType = this.BindingType.ArrayElement;
  8989. this.resolvedProperty = nodeProperty;
  8990. this.propertyIndex = propertyIndex;
  8991. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  8992. // must use copy for Object3D.Euler/Quaternion
  8993. bindingType = this.BindingType.HasFromToArray;
  8994. this.resolvedProperty = nodeProperty;
  8995. } else if ( nodeProperty.length !== undefined ) {
  8996. bindingType = this.BindingType.EntireArray;
  8997. this.resolvedProperty = nodeProperty;
  8998. } else {
  8999. this.propertyName = propertyName;
  9000. }
  9001. // select getter / setter
  9002. this.getValue = this.GetterByBindingType[ bindingType ];
  9003. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  9004. },
  9005. unbind: function() {
  9006. this.node = null;
  9007. // back to the prototype version of getValue / setValue
  9008. // note: avoiding to mutate the shape of 'this' via 'delete'
  9009. this.getValue = this._getValue_unbound;
  9010. this.setValue = this._setValue_unbound;
  9011. }
  9012. };
  9013. Object.assign( THREE.PropertyBinding.prototype, { // prototype, continued
  9014. // these are used to "bind" a nonexistent property
  9015. _getValue_unavailable: function() {},
  9016. _setValue_unavailable: function() {},
  9017. // initial state of these methods that calls 'bind'
  9018. _getValue_unbound: THREE.PropertyBinding.prototype.getValue,
  9019. _setValue_unbound: THREE.PropertyBinding.prototype.setValue,
  9020. BindingType: {
  9021. Direct: 0,
  9022. EntireArray: 1,
  9023. ArrayElement: 2,
  9024. HasFromToArray: 3
  9025. },
  9026. Versioning: {
  9027. None: 0,
  9028. NeedsUpdate: 1,
  9029. MatrixWorldNeedsUpdate: 2
  9030. },
  9031. GetterByBindingType: [
  9032. function getValue_direct( buffer, offset ) {
  9033. buffer[ offset ] = this.node[ this.propertyName ];
  9034. },
  9035. function getValue_array( buffer, offset ) {
  9036. var source = this.resolvedProperty;
  9037. for ( var i = 0, n = source.length; i !== n; ++ i ) {
  9038. buffer[ offset ++ ] = source[ i ];
  9039. }
  9040. },
  9041. function getValue_arrayElement( buffer, offset ) {
  9042. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  9043. },
  9044. function getValue_toArray( buffer, offset ) {
  9045. this.resolvedProperty.toArray( buffer, offset );
  9046. }
  9047. ],
  9048. SetterByBindingTypeAndVersioning: [
  9049. [
  9050. // Direct
  9051. function setValue_direct( buffer, offset ) {
  9052. this.node[ this.propertyName ] = buffer[ offset ];
  9053. },
  9054. function setValue_direct_setNeedsUpdate( buffer, offset ) {
  9055. this.node[ this.propertyName ] = buffer[ offset ];
  9056. this.targetObject.needsUpdate = true;
  9057. },
  9058. function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  9059. this.node[ this.propertyName ] = buffer[ offset ];
  9060. this.targetObject.matrixWorldNeedsUpdate = true;
  9061. }
  9062. ], [
  9063. // EntireArray
  9064. function setValue_array( buffer, offset ) {
  9065. var dest = this.resolvedProperty;
  9066. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  9067. dest[ i ] = buffer[ offset ++ ];
  9068. }
  9069. },
  9070. function setValue_array_setNeedsUpdate( buffer, offset ) {
  9071. var dest = this.resolvedProperty;
  9072. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  9073. dest[ i ] = buffer[ offset ++ ];
  9074. }
  9075. this.targetObject.needsUpdate = true;
  9076. },
  9077. function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  9078. var dest = this.resolvedProperty;
  9079. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  9080. dest[ i ] = buffer[ offset ++ ];
  9081. }
  9082. this.targetObject.matrixWorldNeedsUpdate = true;
  9083. }
  9084. ], [
  9085. // ArrayElement
  9086. function setValue_arrayElement( buffer, offset ) {
  9087. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  9088. },
  9089. function setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  9090. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  9091. this.targetObject.needsUpdate = true;
  9092. },
  9093. function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  9094. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  9095. this.targetObject.matrixWorldNeedsUpdate = true;
  9096. }
  9097. ], [
  9098. // HasToFromArray
  9099. function setValue_fromArray( buffer, offset ) {
  9100. this.resolvedProperty.fromArray( buffer, offset );
  9101. },
  9102. function setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  9103. this.resolvedProperty.fromArray( buffer, offset );
  9104. this.targetObject.needsUpdate = true;
  9105. },
  9106. function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  9107. this.resolvedProperty.fromArray( buffer, offset );
  9108. this.targetObject.matrixWorldNeedsUpdate = true;
  9109. }
  9110. ]
  9111. ]
  9112. } );
  9113. THREE.PropertyBinding.Composite =
  9114. function( targetGroup, path, optionalParsedPath ) {
  9115. var parsedPath = optionalParsedPath ||
  9116. THREE.PropertyBinding.parseTrackName( path );
  9117. this._targetGroup = targetGroup;
  9118. this._bindings = targetGroup.subscribe_( path, parsedPath );
  9119. };
  9120. THREE.PropertyBinding.Composite.prototype = {
  9121. constructor: THREE.PropertyBinding.Composite,
  9122. getValue: function( array, offset ) {
  9123. this.bind(); // bind all binding
  9124. var firstValidIndex = this._targetGroup.nCachedObjects_,
  9125. binding = this._bindings[ firstValidIndex ];
  9126. // and only call .getValue on the first
  9127. if ( binding !== undefined ) binding.getValue( array, offset );
  9128. },
  9129. setValue: function( array, offset ) {
  9130. var bindings = this._bindings;
  9131. for ( var i = this._targetGroup.nCachedObjects_,
  9132. n = bindings.length; i !== n; ++ i ) {
  9133. bindings[ i ].setValue( array, offset );
  9134. }
  9135. },
  9136. bind: function() {
  9137. var bindings = this._bindings;
  9138. for ( var i = this._targetGroup.nCachedObjects_,
  9139. n = bindings.length; i !== n; ++ i ) {
  9140. bindings[ i ].bind();
  9141. }
  9142. },
  9143. unbind: function() {
  9144. var bindings = this._bindings;
  9145. for ( var i = this._targetGroup.nCachedObjects_,
  9146. n = bindings.length; i !== n; ++ i ) {
  9147. bindings[ i ].unbind();
  9148. }
  9149. }
  9150. };
  9151. THREE.PropertyBinding.create = function( root, path, parsedPath ) {
  9152. if ( ! ( root instanceof THREE.AnimationObjectGroup ) ) {
  9153. return new THREE.PropertyBinding( root, path, parsedPath );
  9154. } else {
  9155. return new THREE.PropertyBinding.Composite( root, path, parsedPath );
  9156. }
  9157. };
  9158. THREE.PropertyBinding.parseTrackName = function( trackName ) {
  9159. // matches strings in the form of:
  9160. // nodeName.property
  9161. // nodeName.property[accessor]
  9162. // nodeName.material.property[accessor]
  9163. // uuid.property[accessor]
  9164. // uuid.objectName[objectIndex].propertyName[propertyIndex]
  9165. // parentName/nodeName.property
  9166. // parentName/parentName/nodeName.property[index]
  9167. // .bone[Armature.DEF_cog].position
  9168. // created and tested via https://regex101.com/#javascript
  9169. var re = /^(([\w]+\/)*)([\w-\d]+)?(\.([\w]+)(\[([\w\d\[\]\_. ]+)\])?)?(\.([\w.]+)(\[([\w\d\[\]\_. ]+)\])?)$/;
  9170. var matches = re.exec(trackName);
  9171. if( ! matches ) {
  9172. throw new Error( "cannot parse trackName at all: " + trackName );
  9173. }
  9174. if (matches.index === re.lastIndex) {
  9175. re.lastIndex++;
  9176. }
  9177. var results = {
  9178. // directoryName: matches[1], // (tschw) currently unused
  9179. nodeName: matches[3], // allowed to be null, specified root node.
  9180. objectName: matches[5],
  9181. objectIndex: matches[7],
  9182. propertyName: matches[9],
  9183. propertyIndex: matches[11] // allowed to be null, specifies that the whole property is set.
  9184. };
  9185. if( results.propertyName === null || results.propertyName.length === 0 ) {
  9186. throw new Error( "can not parse propertyName from trackName: " + trackName );
  9187. }
  9188. return results;
  9189. };
  9190. THREE.PropertyBinding.findNode = function( root, nodeName ) {
  9191. if( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  9192. return root;
  9193. }
  9194. // search into skeleton bones.
  9195. if( root.skeleton ) {
  9196. var searchSkeleton = function( skeleton ) {
  9197. for( var i = 0; i < skeleton.bones.length; i ++ ) {
  9198. var bone = skeleton.bones[i];
  9199. if( bone.name === nodeName ) {
  9200. return bone;
  9201. }
  9202. }
  9203. return null;
  9204. };
  9205. var bone = searchSkeleton( root.skeleton );
  9206. if( bone ) {
  9207. return bone;
  9208. }
  9209. }
  9210. // search into node subtree.
  9211. if( root.children ) {
  9212. var searchNodeSubtree = function( children ) {
  9213. for( var i = 0; i < children.length; i ++ ) {
  9214. var childNode = children[i];
  9215. if( childNode.name === nodeName || childNode.uuid === nodeName ) {
  9216. return childNode;
  9217. }
  9218. var result = searchNodeSubtree( childNode.children );
  9219. if( result ) return result;
  9220. }
  9221. return null;
  9222. };
  9223. var subTreeNode = searchNodeSubtree( root.children );
  9224. if( subTreeNode ) {
  9225. return subTreeNode;
  9226. }
  9227. }
  9228. return null;
  9229. }
  9230. // File:src/animation/PropertyMixer.js
  9231. /**
  9232. *
  9233. * Buffered scene graph property that allows weighted accumulation.
  9234. *
  9235. *
  9236. * @author Ben Houston / http://clara.io/
  9237. * @author David Sarno / http://lighthaus.us/
  9238. * @author tschw
  9239. */
  9240. THREE.PropertyMixer = function ( binding, typeName, valueSize ) {
  9241. this.binding = binding;
  9242. this.valueSize = valueSize;
  9243. var bufferType = Float64Array,
  9244. mixFunction;
  9245. switch ( typeName ) {
  9246. case 'quaternion': mixFunction = this._slerp; break;
  9247. case 'string':
  9248. case 'bool':
  9249. bufferType = Array, mixFunction = this._select; break;
  9250. default: mixFunction = this._lerp;
  9251. }
  9252. this.buffer = new bufferType( valueSize * 4 );
  9253. // layout: [ incoming | accu0 | accu1 | orig ]
  9254. //
  9255. // interpolators can use .buffer as their .result
  9256. // the data then goes to 'incoming'
  9257. //
  9258. // 'accu0' and 'accu1' are used frame-interleaved for
  9259. // the cumulative result and are compared to detect
  9260. // changes
  9261. //
  9262. // 'orig' stores the original state of the property
  9263. this._mixBufferRegion = mixFunction;
  9264. this.cumulativeWeight = 0;
  9265. this.useCount = 0;
  9266. this.referenceCount = 0;
  9267. };
  9268. THREE.PropertyMixer.prototype = {
  9269. constructor: THREE.PropertyMixer,
  9270. // accumulate data in the 'incoming' region into 'accu<i>'
  9271. accumulate: function( accuIndex, weight ) {
  9272. // note: happily accumulating nothing when weight = 0, the caller knows
  9273. // the weight and shouldn't have made the call in the first place
  9274. var buffer = this.buffer,
  9275. stride = this.valueSize,
  9276. offset = accuIndex * stride + stride,
  9277. currentWeight = this.cumulativeWeight;
  9278. if ( currentWeight === 0 ) {
  9279. // accuN := incoming * weight
  9280. for ( var i = 0; i !== stride; ++ i ) {
  9281. buffer[ offset + i ] = buffer[ i ];
  9282. }
  9283. currentWeight = weight;
  9284. } else {
  9285. // accuN := accuN + incoming * weight
  9286. currentWeight += weight;
  9287. var mix = weight / currentWeight;
  9288. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  9289. }
  9290. this.cumulativeWeight = currentWeight;
  9291. },
  9292. // apply the state of 'accu<i>' to the binding when accus differ
  9293. apply: function( accuIndex ) {
  9294. var stride = this.valueSize,
  9295. buffer = this.buffer,
  9296. offset = accuIndex * stride + stride,
  9297. weight = this.cumulativeWeight,
  9298. binding = this.binding;
  9299. this.cumulativeWeight = 0;
  9300. if ( weight < 1 ) {
  9301. // accuN := accuN + original * ( 1 - cumulativeWeight )
  9302. var originalValueOffset = stride * 3;
  9303. this._mixBufferRegion(
  9304. buffer, offset, originalValueOffset, 1 - weight, stride );
  9305. }
  9306. for ( var i = stride, e = stride + stride; i !== e; ++ i ) {
  9307. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  9308. // value has changed -> update scene graph
  9309. binding.setValue( buffer, offset );
  9310. break;
  9311. }
  9312. }
  9313. },
  9314. // remember the state of the bound property and copy it to both accus
  9315. saveOriginalState: function() {
  9316. var binding = this.binding;
  9317. var buffer = this.buffer,
  9318. stride = this.valueSize,
  9319. originalValueOffset = stride * 3;
  9320. binding.getValue( buffer, originalValueOffset );
  9321. // accu[0..1] := orig -- initially detect changes against the original
  9322. for ( var i = stride, e = originalValueOffset; i !== e; ++ i ) {
  9323. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  9324. }
  9325. this.cumulativeWeight = 0;
  9326. },
  9327. // apply the state previously taken via 'saveOriginalState' to the binding
  9328. restoreOriginalState: function() {
  9329. var originalValueOffset = this.valueSize * 3;
  9330. this.binding.setValue( this.buffer, originalValueOffset );
  9331. },
  9332. // mix functions
  9333. _select: function( buffer, dstOffset, srcOffset, t, stride ) {
  9334. if ( t >= 0.5 ) {
  9335. for ( var i = 0; i !== stride; ++ i ) {
  9336. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  9337. }
  9338. }
  9339. },
  9340. _slerp: function( buffer, dstOffset, srcOffset, t, stride ) {
  9341. THREE.Quaternion.slerpFlat( buffer, dstOffset,
  9342. buffer, dstOffset, buffer, srcOffset, t );
  9343. },
  9344. _lerp: function( buffer, dstOffset, srcOffset, t, stride ) {
  9345. var s = 1 - t;
  9346. for ( var i = 0; i !== stride; ++ i ) {
  9347. var j = dstOffset + i;
  9348. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  9349. }
  9350. }
  9351. };
  9352. // File:src/animation/tracks/BooleanKeyframeTrack.js
  9353. /**
  9354. *
  9355. * A Track of Boolean keyframe values.
  9356. *
  9357. *
  9358. * @author Ben Houston / http://clara.io/
  9359. * @author David Sarno / http://lighthaus.us/
  9360. * @author tschw
  9361. */
  9362. THREE.BooleanKeyframeTrack = function ( name, times, values ) {
  9363. THREE.KeyframeTrack.call( this, name, times, values );
  9364. };
  9365. THREE.BooleanKeyframeTrack.prototype =
  9366. Object.assign( Object.create( THREE.KeyframeTrack.prototype ), {
  9367. constructor: THREE.BooleanKeyframeTrack,
  9368. ValueTypeName: 'bool',
  9369. ValueBufferType: Array,
  9370. DefaultInterpolation: THREE.IntepolateDiscrete,
  9371. InterpolantFactoryMethodLinear: undefined,
  9372. InterpolantFactoryMethodSmooth: undefined
  9373. // Note: Actually this track could have a optimized / compressed
  9374. // representation of a single value and a custom interpolant that
  9375. // computes "firstValue ^ isOdd( index )".
  9376. } );
  9377. // File:src/animation/tracks/NumberKeyframeTrack.js
  9378. /**
  9379. *
  9380. * A Track of numeric keyframe values.
  9381. *
  9382. * @author Ben Houston / http://clara.io/
  9383. * @author David Sarno / http://lighthaus.us/
  9384. * @author tschw
  9385. */
  9386. THREE.NumberKeyframeTrack = function ( name, times, values, interpolation ) {
  9387. THREE.KeyframeTrack.call( this, name, times, values, interpolation );
  9388. };
  9389. THREE.NumberKeyframeTrack.prototype =
  9390. Object.assign( Object.create( THREE.KeyframeTrack.prototype ), {
  9391. constructor: THREE.NumberKeyframeTrack,
  9392. ValueTypeName: 'number',
  9393. // ValueBufferType is inherited
  9394. // DefaultInterpolation is inherited
  9395. } );
  9396. // File:src/animation/tracks/QuaternionKeyframeTrack.js
  9397. /**
  9398. *
  9399. * A Track of quaternion keyframe values.
  9400. *
  9401. * @author Ben Houston / http://clara.io/
  9402. * @author David Sarno / http://lighthaus.us/
  9403. * @author tschw
  9404. */
  9405. THREE.QuaternionKeyframeTrack = function ( name, times, values, interpolation ) {
  9406. THREE.KeyframeTrack.call( this, name, times, values, interpolation );
  9407. };
  9408. THREE.QuaternionKeyframeTrack.prototype =
  9409. Object.assign( Object.create( THREE.KeyframeTrack.prototype ), {
  9410. constructor: THREE.QuaternionKeyframeTrack,
  9411. ValueTypeName: 'quaternion',
  9412. // ValueBufferType is inherited
  9413. DefaultInterpolation: THREE.InterpolateLinear,
  9414. InterpolantFactoryMethodLinear: function( result ) {
  9415. return new THREE.QuaternionLinearInterpolant(
  9416. this.times, this.values, this.getValueSize(), result );
  9417. },
  9418. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  9419. } );
  9420. // File:src/animation/tracks/StringKeyframeTrack.js
  9421. /**
  9422. *
  9423. * A Track that interpolates Strings
  9424. *
  9425. *
  9426. * @author Ben Houston / http://clara.io/
  9427. * @author David Sarno / http://lighthaus.us/
  9428. * @author tschw
  9429. */
  9430. THREE.StringKeyframeTrack = function ( name, times, values, interpolation ) {
  9431. THREE.KeyframeTrack.call( this, name, times, values, interpolation );
  9432. };
  9433. THREE.StringKeyframeTrack.prototype =
  9434. Object.assign( Object.create( THREE.KeyframeTrack.prototype ), {
  9435. constructor: THREE.StringKeyframeTrack,
  9436. ValueTypeName: 'string',
  9437. ValueBufferType: Array,
  9438. DefaultInterpolation: THREE.IntepolateDiscrete,
  9439. InterpolantFactoryMethodLinear: undefined,
  9440. InterpolantFactoryMethodSmooth: undefined
  9441. } );
  9442. // File:src/animation/tracks/VectorKeyframeTrack.js
  9443. /**
  9444. *
  9445. * A Track of vectored keyframe values.
  9446. *
  9447. *
  9448. * @author Ben Houston / http://clara.io/
  9449. * @author David Sarno / http://lighthaus.us/
  9450. * @author tschw
  9451. */
  9452. THREE.VectorKeyframeTrack = function ( name, times, values, interpolation ) {
  9453. THREE.KeyframeTrack.call( this, name, times, values, interpolation );
  9454. };
  9455. THREE.VectorKeyframeTrack.prototype =
  9456. Object.assign( Object.create( THREE.KeyframeTrack.prototype ), {
  9457. constructor: THREE.VectorKeyframeTrack,
  9458. ValueTypeName: 'vector'
  9459. // ValueBufferType is inherited
  9460. // DefaultInterpolation is inherited
  9461. } );
  9462. // File:src/audio/Audio.js
  9463. /**
  9464. * @author mrdoob / http://mrdoob.com/
  9465. */
  9466. THREE.Audio = function ( listener ) {
  9467. THREE.Object3D.call( this );
  9468. this.type = 'Audio';
  9469. this.context = listener.context;
  9470. this.source = this.context.createBufferSource();
  9471. this.source.onended = this.onEnded.bind( this );
  9472. this.gain = this.context.createGain();
  9473. this.gain.connect( listener.getInput() );
  9474. this.autoplay = false;
  9475. this.startTime = 0;
  9476. this.playbackRate = 1;
  9477. this.isPlaying = false;
  9478. this.hasPlaybackControl = true;
  9479. this.sourceType = 'empty';
  9480. this.filter = null;
  9481. };
  9482. THREE.Audio.prototype = Object.create( THREE.Object3D.prototype );
  9483. THREE.Audio.prototype.constructor = THREE.Audio;
  9484. THREE.Audio.prototype.getOutput = function () {
  9485. return this.gain;
  9486. };
  9487. THREE.Audio.prototype.load = function ( file ) {
  9488. var buffer = new THREE.AudioBuffer( this.context );
  9489. buffer.load( file );
  9490. this.setBuffer( buffer );
  9491. return this;
  9492. };
  9493. THREE.Audio.prototype.setNodeSource = function ( audioNode ) {
  9494. this.hasPlaybackControl = false;
  9495. this.sourceType = 'audioNode';
  9496. this.source = audioNode;
  9497. this.connect();
  9498. return this;
  9499. };
  9500. THREE.Audio.prototype.setBuffer = function ( audioBuffer ) {
  9501. var scope = this;
  9502. audioBuffer.onReady( function( buffer ) {
  9503. scope.source.buffer = buffer;
  9504. scope.sourceType = 'buffer';
  9505. if ( scope.autoplay ) scope.play();
  9506. } );
  9507. return this;
  9508. };
  9509. THREE.Audio.prototype.play = function () {
  9510. if ( this.isPlaying === true ) {
  9511. console.warn( 'THREE.Audio: Audio is already playing.' );
  9512. return;
  9513. }
  9514. if ( this.hasPlaybackControl === false ) {
  9515. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  9516. return;
  9517. }
  9518. var source = this.context.createBufferSource();
  9519. source.buffer = this.source.buffer;
  9520. source.loop = this.source.loop;
  9521. source.onended = this.source.onended;
  9522. source.start( 0, this.startTime );
  9523. source.playbackRate.value = this.playbackRate;
  9524. this.isPlaying = true;
  9525. this.source = source;
  9526. this.connect();
  9527. };
  9528. THREE.Audio.prototype.pause = function () {
  9529. if ( this.hasPlaybackControl === false ) {
  9530. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  9531. return;
  9532. }
  9533. this.source.stop();
  9534. this.startTime = this.context.currentTime;
  9535. };
  9536. THREE.Audio.prototype.stop = function () {
  9537. if ( this.hasPlaybackControl === false ) {
  9538. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  9539. return;
  9540. }
  9541. this.source.stop();
  9542. this.startTime = 0;
  9543. };
  9544. THREE.Audio.prototype.connect = function () {
  9545. if ( this.filter !== null ) {
  9546. this.source.connect( this.filter );
  9547. this.filter.connect( this.getOutput() );
  9548. } else {
  9549. this.source.connect( this.getOutput() );
  9550. }
  9551. };
  9552. THREE.Audio.prototype.disconnect = function () {
  9553. if ( this.filter !== null ) {
  9554. this.source.disconnect( this.filter );
  9555. this.filter.disconnect( this.getOutput() );
  9556. } else {
  9557. this.source.disconnect( this.getOutput() );
  9558. }
  9559. };
  9560. THREE.Audio.prototype.getFilter = function () {
  9561. return this.filter;
  9562. };
  9563. THREE.Audio.prototype.setFilter = function ( value ) {
  9564. if ( value === undefined ) value = null;
  9565. if ( this.isPlaying === true ) {
  9566. this.disconnect();
  9567. this.filter = value;
  9568. this.connect();
  9569. } else {
  9570. this.filter = value;
  9571. }
  9572. };
  9573. THREE.Audio.prototype.setPlaybackRate = function ( value ) {
  9574. if ( this.hasPlaybackControl === false ) {
  9575. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  9576. return;
  9577. }
  9578. this.playbackRate = value;
  9579. if ( this.isPlaying === true ) {
  9580. this.source.playbackRate.value = this.playbackRate;
  9581. }
  9582. };
  9583. THREE.Audio.prototype.getPlaybackRate = function () {
  9584. return this.playbackRate;
  9585. };
  9586. THREE.Audio.prototype.onEnded = function() {
  9587. this.isPlaying = false;
  9588. };
  9589. THREE.Audio.prototype.setLoop = function ( value ) {
  9590. if ( this.hasPlaybackControl === false ) {
  9591. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  9592. return;
  9593. }
  9594. this.source.loop = value;
  9595. };
  9596. THREE.Audio.prototype.getLoop = function () {
  9597. if ( this.hasPlaybackControl === false ) {
  9598. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  9599. return false;
  9600. }
  9601. return this.source.loop;
  9602. };
  9603. THREE.Audio.prototype.setVolume = function ( value ) {
  9604. this.gain.gain.value = value;
  9605. };
  9606. THREE.Audio.prototype.getVolume = function () {
  9607. return this.gain.gain.value;
  9608. };
  9609. // File:src/audio/AudioAnalyser.js
  9610. /**
  9611. * @author mrdoob / http://mrdoob.com/
  9612. */
  9613. THREE.AudioAnalyser = function ( audio, fftSize ) {
  9614. this.analyser = audio.context.createAnalyser();
  9615. this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048;
  9616. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  9617. audio.getOutput().connect( this.analyser );
  9618. };
  9619. THREE.AudioAnalyser.prototype = {
  9620. constructor: THREE.AudioAnalyser,
  9621. getData: function () {
  9622. this.analyser.getByteFrequencyData( this.data );
  9623. return this.data;
  9624. }
  9625. };
  9626. // File:src/audio/AudioBuffer.js
  9627. /**
  9628. * @author mrdoob / http://mrdoob.com/
  9629. */
  9630. THREE.AudioBuffer = function ( context ) {
  9631. this.context = context;
  9632. this.ready = false;
  9633. this.readyCallbacks = [];
  9634. };
  9635. THREE.AudioBuffer.prototype.load = function ( file ) {
  9636. var scope = this;
  9637. var request = new XMLHttpRequest();
  9638. request.open( 'GET', file, true );
  9639. request.responseType = 'arraybuffer';
  9640. request.onload = function ( e ) {
  9641. scope.context.decodeAudioData( this.response, function ( buffer ) {
  9642. scope.buffer = buffer;
  9643. scope.ready = true;
  9644. for ( var i = 0; i < scope.readyCallbacks.length; i ++ ) {
  9645. scope.readyCallbacks[ i ]( scope.buffer );
  9646. }
  9647. scope.readyCallbacks = [];
  9648. } );
  9649. };
  9650. request.send();
  9651. return this;
  9652. };
  9653. THREE.AudioBuffer.prototype.onReady = function ( callback ) {
  9654. if ( this.ready ) {
  9655. callback( this.buffer );
  9656. } else {
  9657. this.readyCallbacks.push( callback );
  9658. }
  9659. };
  9660. // File:src/audio/PositionalAudio.js
  9661. /**
  9662. * @author mrdoob / http://mrdoob.com/
  9663. */
  9664. THREE.PositionalAudio = function ( listener ) {
  9665. THREE.Audio.call( this, listener );
  9666. this.panner = this.context.createPanner();
  9667. this.panner.connect( this.gain );
  9668. };
  9669. THREE.PositionalAudio.prototype = Object.create( THREE.Audio.prototype );
  9670. THREE.PositionalAudio.prototype.constructor = THREE.PositionalAudio;
  9671. THREE.PositionalAudio.prototype.getOutput = function () {
  9672. return this.panner;
  9673. };
  9674. THREE.PositionalAudio.prototype.setRefDistance = function ( value ) {
  9675. this.panner.refDistance = value;
  9676. };
  9677. THREE.PositionalAudio.prototype.getRefDistance = function () {
  9678. return this.panner.refDistance;
  9679. };
  9680. THREE.PositionalAudio.prototype.setRolloffFactor = function ( value ) {
  9681. this.panner.rolloffFactor = value;
  9682. };
  9683. THREE.PositionalAudio.prototype.getRolloffFactor = function () {
  9684. return this.panner.rolloffFactor;
  9685. };
  9686. THREE.PositionalAudio.prototype.setDistanceModel = function ( value ) {
  9687. this.panner.distanceModel = value;
  9688. };
  9689. THREE.PositionalAudio.prototype.getDistanceModel = function () {
  9690. return this.panner.distanceModel;
  9691. };
  9692. THREE.PositionalAudio.prototype.setMaxDistance = function ( value ) {
  9693. this.panner.maxDistance = value;
  9694. };
  9695. THREE.PositionalAudio.prototype.getMaxDistance = function () {
  9696. return this.panner.maxDistance;
  9697. };
  9698. THREE.PositionalAudio.prototype.updateMatrixWorld = ( function () {
  9699. var position = new THREE.Vector3();
  9700. return function updateMatrixWorld( force ) {
  9701. THREE.Object3D.prototype.updateMatrixWorld.call( this, force );
  9702. position.setFromMatrixPosition( this.matrixWorld );
  9703. this.panner.setPosition( position.x, position.y, position.z );
  9704. };
  9705. } )();
  9706. // File:src/audio/AudioListener.js
  9707. /**
  9708. * @author mrdoob / http://mrdoob.com/
  9709. */
  9710. THREE.AudioListener = function () {
  9711. THREE.Object3D.call( this );
  9712. this.type = 'AudioListener';
  9713. this.context = new ( window.AudioContext || window.webkitAudioContext )();
  9714. this.gain = this.context.createGain();
  9715. this.gain.connect( this.context.destination );
  9716. this.filter = null;
  9717. };
  9718. THREE.AudioListener.prototype = Object.create( THREE.Object3D.prototype );
  9719. THREE.AudioListener.prototype.constructor = THREE.AudioListener;
  9720. THREE.AudioListener.prototype.getInput = function () {
  9721. return this.gain;
  9722. };
  9723. THREE.AudioListener.prototype.removeFilter = function ( ) {
  9724. if ( this.filter !== null ) {
  9725. this.gain.disconnect( this.filter );
  9726. this.filter.disconnect( this.context.destination );
  9727. this.gain.connect( this.context.destination );
  9728. this.filter = null;
  9729. }
  9730. };
  9731. THREE.AudioListener.prototype.setFilter = function ( value ) {
  9732. if ( this.filter !== null ) {
  9733. this.gain.disconnect( this.filter );
  9734. this.filter.disconnect( this.context.destination );
  9735. } else {
  9736. this.gain.disconnect( this.context.destination );
  9737. }
  9738. this.filter = value;
  9739. this.gain.connect( this.filter );
  9740. this.filter.connect( this.context.destination );
  9741. };
  9742. THREE.AudioListener.prototype.getFilter = function () {
  9743. return this.filter;
  9744. };
  9745. THREE.AudioListener.prototype.setMasterVolume = function ( value ) {
  9746. this.gain.gain.value = value;
  9747. };
  9748. THREE.AudioListener.prototype.getMasterVolume = function () {
  9749. return this.gain.gain.value;
  9750. };
  9751. THREE.AudioListener.prototype.updateMatrixWorld = ( function () {
  9752. var position = new THREE.Vector3();
  9753. var quaternion = new THREE.Quaternion();
  9754. var scale = new THREE.Vector3();
  9755. var orientation = new THREE.Vector3();
  9756. return function updateMatrixWorld( force ) {
  9757. THREE.Object3D.prototype.updateMatrixWorld.call( this, force );
  9758. var listener = this.context.listener;
  9759. var up = this.up;
  9760. this.matrixWorld.decompose( position, quaternion, scale );
  9761. orientation.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  9762. listener.setPosition( position.x, position.y, position.z );
  9763. listener.setOrientation( orientation.x, orientation.y, orientation.z, up.x, up.y, up.z );
  9764. };
  9765. } )();
  9766. // File:src/cameras/Camera.js
  9767. /**
  9768. * @author mrdoob / http://mrdoob.com/
  9769. * @author mikael emtinger / http://gomo.se/
  9770. * @author WestLangley / http://github.com/WestLangley
  9771. */
  9772. THREE.Camera = function () {
  9773. THREE.Object3D.call( this );
  9774. this.type = 'Camera';
  9775. this.matrixWorldInverse = new THREE.Matrix4();
  9776. this.projectionMatrix = new THREE.Matrix4();
  9777. };
  9778. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  9779. THREE.Camera.prototype.constructor = THREE.Camera;
  9780. THREE.Camera.prototype.getWorldDirection = function () {
  9781. var quaternion = new THREE.Quaternion();
  9782. return function ( optionalTarget ) {
  9783. var result = optionalTarget || new THREE.Vector3();
  9784. this.getWorldQuaternion( quaternion );
  9785. return result.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  9786. };
  9787. }();
  9788. THREE.Camera.prototype.lookAt = function () {
  9789. // This routine does not support cameras with rotated and/or translated parent(s)
  9790. var m1 = new THREE.Matrix4();
  9791. return function ( vector ) {
  9792. m1.lookAt( this.position, vector, this.up );
  9793. this.quaternion.setFromRotationMatrix( m1 );
  9794. };
  9795. }();
  9796. THREE.Camera.prototype.clone = function () {
  9797. return new this.constructor().copy( this );
  9798. };
  9799. THREE.Camera.prototype.copy = function ( source ) {
  9800. THREE.Object3D.prototype.copy.call( this, source );
  9801. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  9802. this.projectionMatrix.copy( source.projectionMatrix );
  9803. return this;
  9804. };
  9805. // File:src/cameras/CubeCamera.js
  9806. /**
  9807. * Camera for rendering cube maps
  9808. * - renders scene into axis-aligned cube
  9809. *
  9810. * @author alteredq / http://alteredqualia.com/
  9811. */
  9812. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  9813. THREE.Object3D.call( this );
  9814. this.type = 'CubeCamera';
  9815. var fov = 90, aspect = 1;
  9816. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  9817. cameraPX.up.set( 0, - 1, 0 );
  9818. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  9819. this.add( cameraPX );
  9820. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  9821. cameraNX.up.set( 0, - 1, 0 );
  9822. cameraNX.lookAt( new THREE.Vector3( - 1, 0, 0 ) );
  9823. this.add( cameraNX );
  9824. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  9825. cameraPY.up.set( 0, 0, 1 );
  9826. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  9827. this.add( cameraPY );
  9828. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  9829. cameraNY.up.set( 0, 0, - 1 );
  9830. cameraNY.lookAt( new THREE.Vector3( 0, - 1, 0 ) );
  9831. this.add( cameraNY );
  9832. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  9833. cameraPZ.up.set( 0, - 1, 0 );
  9834. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  9835. this.add( cameraPZ );
  9836. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  9837. cameraNZ.up.set( 0, - 1, 0 );
  9838. cameraNZ.lookAt( new THREE.Vector3( 0, 0, - 1 ) );
  9839. this.add( cameraNZ );
  9840. var options = { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter };
  9841. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, options );
  9842. this.updateCubeMap = function ( renderer, scene ) {
  9843. if ( this.parent === null ) this.updateMatrixWorld();
  9844. var renderTarget = this.renderTarget;
  9845. var generateMipmaps = renderTarget.texture.generateMipmaps;
  9846. renderTarget.texture.generateMipmaps = false;
  9847. renderTarget.activeCubeFace = 0;
  9848. renderer.render( scene, cameraPX, renderTarget );
  9849. renderTarget.activeCubeFace = 1;
  9850. renderer.render( scene, cameraNX, renderTarget );
  9851. renderTarget.activeCubeFace = 2;
  9852. renderer.render( scene, cameraPY, renderTarget );
  9853. renderTarget.activeCubeFace = 3;
  9854. renderer.render( scene, cameraNY, renderTarget );
  9855. renderTarget.activeCubeFace = 4;
  9856. renderer.render( scene, cameraPZ, renderTarget );
  9857. renderTarget.texture.generateMipmaps = generateMipmaps;
  9858. renderTarget.activeCubeFace = 5;
  9859. renderer.render( scene, cameraNZ, renderTarget );
  9860. renderer.setRenderTarget( null );
  9861. };
  9862. };
  9863. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  9864. THREE.CubeCamera.prototype.constructor = THREE.CubeCamera;
  9865. // File:src/cameras/OrthographicCamera.js
  9866. /**
  9867. * @author alteredq / http://alteredqualia.com/
  9868. */
  9869. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  9870. THREE.Camera.call( this );
  9871. this.type = 'OrthographicCamera';
  9872. this.zoom = 1;
  9873. this.left = left;
  9874. this.right = right;
  9875. this.top = top;
  9876. this.bottom = bottom;
  9877. this.near = ( near !== undefined ) ? near : 0.1;
  9878. this.far = ( far !== undefined ) ? far : 2000;
  9879. this.updateProjectionMatrix();
  9880. };
  9881. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  9882. THREE.OrthographicCamera.prototype.constructor = THREE.OrthographicCamera;
  9883. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  9884. var dx = ( this.right - this.left ) / ( 2 * this.zoom );
  9885. var dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  9886. var cx = ( this.right + this.left ) / 2;
  9887. var cy = ( this.top + this.bottom ) / 2;
  9888. this.projectionMatrix.makeOrthographic( cx - dx, cx + dx, cy + dy, cy - dy, this.near, this.far );
  9889. };
  9890. THREE.OrthographicCamera.prototype.copy = function ( source ) {
  9891. THREE.Camera.prototype.copy.call( this, source );
  9892. this.left = source.left;
  9893. this.right = source.right;
  9894. this.top = source.top;
  9895. this.bottom = source.bottom;
  9896. this.near = source.near;
  9897. this.far = source.far;
  9898. this.zoom = source.zoom;
  9899. return this;
  9900. };
  9901. THREE.OrthographicCamera.prototype.toJSON = function ( meta ) {
  9902. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  9903. data.object.zoom = this.zoom;
  9904. data.object.left = this.left;
  9905. data.object.right = this.right;
  9906. data.object.top = this.top;
  9907. data.object.bottom = this.bottom;
  9908. data.object.near = this.near;
  9909. data.object.far = this.far;
  9910. return data;
  9911. };
  9912. // File:src/cameras/PerspectiveCamera.js
  9913. /**
  9914. * @author mrdoob / http://mrdoob.com/
  9915. * @author greggman / http://games.greggman.com/
  9916. * @author zz85 / http://www.lab4games.net/zz85/blog
  9917. */
  9918. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  9919. THREE.Camera.call( this );
  9920. this.type = 'PerspectiveCamera';
  9921. this.zoom = 1;
  9922. this.fov = fov !== undefined ? fov : 50;
  9923. this.aspect = aspect !== undefined ? aspect : 1;
  9924. this.near = near !== undefined ? near : 0.1;
  9925. this.far = far !== undefined ? far : 2000;
  9926. this.updateProjectionMatrix();
  9927. };
  9928. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  9929. THREE.PerspectiveCamera.prototype.constructor = THREE.PerspectiveCamera;
  9930. /**
  9931. * Uses Focal Length (in mm) to estimate and set FOV
  9932. * 35mm (full-frame) camera is used if frame size is not specified;
  9933. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  9934. */
  9935. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  9936. if ( frameHeight === undefined ) frameHeight = 24;
  9937. this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  9938. this.updateProjectionMatrix();
  9939. };
  9940. /**
  9941. * Sets an offset in a larger frustum. This is useful for multi-window or
  9942. * multi-monitor/multi-machine setups.
  9943. *
  9944. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  9945. * the monitors are in grid like this
  9946. *
  9947. * +---+---+---+
  9948. * | A | B | C |
  9949. * +---+---+---+
  9950. * | D | E | F |
  9951. * +---+---+---+
  9952. *
  9953. * then for each monitor you would call it like this
  9954. *
  9955. * var w = 1920;
  9956. * var h = 1080;
  9957. * var fullWidth = w * 3;
  9958. * var fullHeight = h * 2;
  9959. *
  9960. * --A--
  9961. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  9962. * --B--
  9963. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  9964. * --C--
  9965. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  9966. * --D--
  9967. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  9968. * --E--
  9969. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  9970. * --F--
  9971. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  9972. *
  9973. * Note there is no reason monitors have to be the same size or in a grid.
  9974. */
  9975. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  9976. this.fullWidth = fullWidth;
  9977. this.fullHeight = fullHeight;
  9978. this.x = x;
  9979. this.y = y;
  9980. this.width = width;
  9981. this.height = height;
  9982. this.updateProjectionMatrix();
  9983. };
  9984. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  9985. var fov = THREE.Math.radToDeg( 2 * Math.atan( Math.tan( THREE.Math.degToRad( this.fov ) * 0.5 ) / this.zoom ) );
  9986. if ( this.fullWidth ) {
  9987. var aspect = this.fullWidth / this.fullHeight;
  9988. var top = Math.tan( THREE.Math.degToRad( fov * 0.5 ) ) * this.near;
  9989. var bottom = - top;
  9990. var left = aspect * bottom;
  9991. var right = aspect * top;
  9992. var width = Math.abs( right - left );
  9993. var height = Math.abs( top - bottom );
  9994. this.projectionMatrix.makeFrustum(
  9995. left + this.x * width / this.fullWidth,
  9996. left + ( this.x + this.width ) * width / this.fullWidth,
  9997. top - ( this.y + this.height ) * height / this.fullHeight,
  9998. top - this.y * height / this.fullHeight,
  9999. this.near,
  10000. this.far
  10001. );
  10002. } else {
  10003. this.projectionMatrix.makePerspective( fov, this.aspect, this.near, this.far );
  10004. }
  10005. };
  10006. THREE.PerspectiveCamera.prototype.copy = function ( source ) {
  10007. THREE.Camera.prototype.copy.call( this, source );
  10008. this.fov = source.fov;
  10009. this.aspect = source.aspect;
  10010. this.near = source.near;
  10011. this.far = source.far;
  10012. this.zoom = source.zoom;
  10013. return this;
  10014. };
  10015. THREE.PerspectiveCamera.prototype.toJSON = function ( meta ) {
  10016. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  10017. data.object.zoom = this.zoom;
  10018. data.object.fov = this.fov;
  10019. data.object.aspect = this.aspect;
  10020. data.object.near = this.near;
  10021. data.object.far = this.far;
  10022. return data;
  10023. };
  10024. // File:src/cameras/StereoCamera.js
  10025. /**
  10026. * @author mrdoob / http://mrdoob.com/
  10027. */
  10028. THREE.StereoCamera = function ( fov, aspect, near, far ) {
  10029. THREE.PerspectiveCamera.call( this, fov, aspect, near, far );
  10030. this.type = 'StereoCamera';
  10031. this.focalLength = 125;
  10032. this.cameraL = new THREE.PerspectiveCamera();
  10033. this.cameraL.matrixAutoUpdate = false;
  10034. this.cameraR = new THREE.PerspectiveCamera();
  10035. this.cameraR.matrixAutoUpdate = false;
  10036. };
  10037. THREE.StereoCamera.prototype = Object.create( THREE.PerspectiveCamera.prototype );
  10038. THREE.StereoCamera.prototype.constructor = THREE.StereoCamera;
  10039. THREE.StereoCamera.prototype.updateMatrixWorld = ( function () {
  10040. var focalLength, fov, aspect, near, far;
  10041. var eyeRight = new THREE.Matrix4();
  10042. var eyeLeft = new THREE.Matrix4();
  10043. return function updateMatrixWorld ( force ) {
  10044. THREE.Object3D.prototype.updateMatrixWorld.call( this, force );
  10045. var needsUpdate = focalLength !== this.focalLength || fov !== this.fov ||
  10046. aspect !== this.aspect || near !== this.near ||
  10047. far !== this.far;
  10048. if ( needsUpdate ) {
  10049. focalLength = this.focalLength;
  10050. fov = this.fov;
  10051. aspect = this.aspect;
  10052. near = this.near;
  10053. far = this.far;
  10054. // Off-axis stereoscopic effect based on
  10055. // http://paulbourke.net/stereographics/stereorender/
  10056. var projectionMatrix = this.projectionMatrix.clone();
  10057. var eyeSep = focalLength / 30 * 0.5;
  10058. var eyeSepOnProjection = eyeSep * near / focalLength;
  10059. var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) );
  10060. var xmin, xmax;
  10061. // translate xOffset
  10062. eyeLeft.elements[ 12 ] = - eyeSep;
  10063. eyeRight.elements[ 12 ] = eyeSep;
  10064. // for left eye
  10065. xmin = - ymax * aspect + eyeSepOnProjection;
  10066. xmax = ymax * aspect + eyeSepOnProjection;
  10067. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  10068. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  10069. this.cameraL.projectionMatrix.copy( projectionMatrix );
  10070. // for right eye
  10071. xmin = - ymax * aspect - eyeSepOnProjection;
  10072. xmax = ymax * aspect - eyeSepOnProjection;
  10073. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  10074. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  10075. this.cameraR.projectionMatrix.copy( projectionMatrix );
  10076. }
  10077. this.cameraL.matrixWorld.copy( this.matrixWorld ).multiply( eyeLeft );
  10078. this.cameraR.matrixWorld.copy( this.matrixWorld ).multiply( eyeRight );
  10079. };
  10080. } )();
  10081. // File:src/lights/Light.js
  10082. /**
  10083. * @author mrdoob / http://mrdoob.com/
  10084. * @author alteredq / http://alteredqualia.com/
  10085. */
  10086. THREE.Light = function ( color, intensity ) {
  10087. THREE.Object3D.call( this );
  10088. this.type = 'Light';
  10089. this.color = new THREE.Color( color );
  10090. this.intensity = intensity !== undefined ? intensity : 1;
  10091. this.receiveShadow = undefined;
  10092. };
  10093. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  10094. THREE.Light.prototype.constructor = THREE.Light;
  10095. THREE.Light.prototype.copy = function ( source ) {
  10096. THREE.Object3D.prototype.copy.call( this, source );
  10097. this.color.copy( source.color );
  10098. this.intensity = source.intensity;
  10099. return this;
  10100. };
  10101. THREE.Light.prototype.toJSON = function ( meta ) {
  10102. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  10103. data.object.color = this.color.getHex();
  10104. data.object.intensity = this.intensity;
  10105. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  10106. if ( this.distance !== undefined ) data.object.distance = this.distance;
  10107. if ( this.angle !== undefined ) data.object.angle = this.angle;
  10108. if ( this.decay !== undefined ) data.object.decay = this.decay;
  10109. if ( this.exponent !== undefined ) data.object.exponent = this.exponent;
  10110. return data;
  10111. };
  10112. // File:src/lights/LightShadow.js
  10113. /**
  10114. * @author mrdoob / http://mrdoob.com/
  10115. */
  10116. THREE.LightShadow = function ( camera ) {
  10117. this.camera = camera;
  10118. this.bias = 0;
  10119. this.darkness = 1;
  10120. this.mapSize = new THREE.Vector2( 512, 512 );
  10121. this.map = null;
  10122. this.matrix = null;
  10123. };
  10124. THREE.LightShadow.prototype = {
  10125. constructor: THREE.LightShadow,
  10126. copy: function ( source ) {
  10127. this.camera = source.camera.clone();
  10128. this.bias = source.bias;
  10129. this.darkness = source.darkness;
  10130. this.mapSize.copy( source.mapSize );
  10131. return this;
  10132. },
  10133. clone: function () {
  10134. return new this.constructor().copy( this );
  10135. }
  10136. };
  10137. // File:src/lights/AmbientLight.js
  10138. /**
  10139. * @author mrdoob / http://mrdoob.com/
  10140. */
  10141. THREE.AmbientLight = function ( color, intensity ) {
  10142. THREE.Light.call( this, color, intensity );
  10143. this.type = 'AmbientLight';
  10144. this.castShadow = undefined;
  10145. };
  10146. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  10147. THREE.AmbientLight.prototype.constructor = THREE.AmbientLight;
  10148. // File:src/lights/DirectionalLight.js
  10149. /**
  10150. * @author mrdoob / http://mrdoob.com/
  10151. * @author alteredq / http://alteredqualia.com/
  10152. */
  10153. THREE.DirectionalLight = function ( color, intensity ) {
  10154. THREE.Light.call( this, color, intensity );
  10155. this.type = 'DirectionalLight';
  10156. this.position.set( 0, 1, 0 );
  10157. this.updateMatrix();
  10158. this.target = new THREE.Object3D();
  10159. this.shadow = new THREE.LightShadow( new THREE.OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  10160. };
  10161. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  10162. THREE.DirectionalLight.prototype.constructor = THREE.DirectionalLight;
  10163. THREE.DirectionalLight.prototype.copy = function ( source ) {
  10164. THREE.Light.prototype.copy.call( this, source );
  10165. this.target = source.target.clone();
  10166. this.shadow = source.shadow.clone();
  10167. return this;
  10168. };
  10169. // File:src/lights/HemisphereLight.js
  10170. /**
  10171. * @author alteredq / http://alteredqualia.com/
  10172. */
  10173. THREE.HemisphereLight = function ( skyColor, groundColor, intensity ) {
  10174. THREE.Light.call( this, skyColor, intensity );
  10175. this.type = 'HemisphereLight';
  10176. this.castShadow = undefined;
  10177. this.position.set( 0, 1, 0 );
  10178. this.updateMatrix();
  10179. this.groundColor = new THREE.Color( groundColor );
  10180. };
  10181. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  10182. THREE.HemisphereLight.prototype.constructor = THREE.HemisphereLight;
  10183. THREE.HemisphereLight.prototype.copy = function ( source ) {
  10184. THREE.Light.prototype.copy.call( this, source );
  10185. this.groundColor.copy( source.groundColor );
  10186. return this;
  10187. };
  10188. // File:src/lights/PointLight.js
  10189. /**
  10190. * @author mrdoob / http://mrdoob.com/
  10191. */
  10192. THREE.PointLight = function ( color, intensity, distance, decay ) {
  10193. THREE.Light.call( this, color, intensity );
  10194. this.type = 'PointLight';
  10195. this.distance = ( distance !== undefined ) ? distance : 0;
  10196. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  10197. this.shadow = new THREE.LightShadow( new THREE.PerspectiveCamera( 90, 1, 0.5, 500 ) );
  10198. };
  10199. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  10200. THREE.PointLight.prototype.constructor = THREE.PointLight;
  10201. THREE.PointLight.prototype.copy = function ( source ) {
  10202. THREE.Light.prototype.copy.call( this, source );
  10203. this.distance = source.distance;
  10204. this.decay = source.decay;
  10205. this.shadow = source.shadow.clone();
  10206. return this;
  10207. };
  10208. // File:src/lights/SpotLight.js
  10209. /**
  10210. * @author alteredq / http://alteredqualia.com/
  10211. */
  10212. THREE.SpotLight = function ( color, intensity, distance, angle, exponent, decay ) {
  10213. THREE.Light.call( this, color, intensity );
  10214. this.type = 'SpotLight';
  10215. this.position.set( 0, 1, 0 );
  10216. this.updateMatrix();
  10217. this.target = new THREE.Object3D();
  10218. this.distance = ( distance !== undefined ) ? distance : 0;
  10219. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  10220. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  10221. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  10222. this.shadow = new THREE.LightShadow( new THREE.PerspectiveCamera( 50, 1, 0.5, 500 ) );
  10223. };
  10224. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  10225. THREE.SpotLight.prototype.constructor = THREE.SpotLight;
  10226. THREE.SpotLight.prototype.copy = function ( source ) {
  10227. THREE.Light.prototype.copy.call( this, source );
  10228. this.distance = source.distance;
  10229. this.angle = source.angle;
  10230. this.exponent = source.exponent;
  10231. this.decay = source.decay;
  10232. this.target = source.target.clone();
  10233. this.shadow = source.shadow.clone();
  10234. return this;
  10235. };
  10236. // File:src/loaders/Cache.js
  10237. /**
  10238. * @author mrdoob / http://mrdoob.com/
  10239. */
  10240. THREE.Cache = {
  10241. enabled: false,
  10242. files: {},
  10243. add: function ( key, file ) {
  10244. if ( this.enabled === false ) return;
  10245. // console.log( 'THREE.Cache', 'Adding key:', key );
  10246. this.files[ key ] = file;
  10247. },
  10248. get: function ( key ) {
  10249. if ( this.enabled === false ) return;
  10250. // console.log( 'THREE.Cache', 'Checking key:', key );
  10251. return this.files[ key ];
  10252. },
  10253. remove: function ( key ) {
  10254. delete this.files[ key ];
  10255. },
  10256. clear: function () {
  10257. this.files = {};
  10258. }
  10259. };
  10260. // File:src/loaders/Loader.js
  10261. /**
  10262. * @author alteredq / http://alteredqualia.com/
  10263. */
  10264. THREE.Loader = function () {
  10265. this.onLoadStart = function () {};
  10266. this.onLoadProgress = function () {};
  10267. this.onLoadComplete = function () {};
  10268. };
  10269. THREE.Loader.prototype = {
  10270. constructor: THREE.Loader,
  10271. crossOrigin: undefined,
  10272. extractUrlBase: function ( url ) {
  10273. var parts = url.split( '/' );
  10274. if ( parts.length === 1 ) return './';
  10275. parts.pop();
  10276. return parts.join( '/' ) + '/';
  10277. },
  10278. initMaterials: function ( materials, texturePath, crossOrigin ) {
  10279. var array = [];
  10280. for ( var i = 0; i < materials.length; ++ i ) {
  10281. array[ i ] = this.createMaterial( materials[ i ], texturePath, crossOrigin );
  10282. }
  10283. return array;
  10284. },
  10285. createMaterial: ( function () {
  10286. var color, textureLoader, materialLoader;
  10287. return function ( m, texturePath, crossOrigin ) {
  10288. if ( color === undefined ) color = new THREE.Color();
  10289. if ( textureLoader === undefined ) textureLoader = new THREE.TextureLoader();
  10290. if ( materialLoader === undefined ) materialLoader = new THREE.MaterialLoader();
  10291. // convert from old material format
  10292. var textures = {};
  10293. function loadTexture( path, repeat, offset, wrap, anisotropy ) {
  10294. var fullPath = texturePath + path;
  10295. var loader = THREE.Loader.Handlers.get( fullPath );
  10296. var texture;
  10297. if ( loader !== null ) {
  10298. texture = loader.load( fullPath );
  10299. } else {
  10300. textureLoader.setCrossOrigin( crossOrigin );
  10301. texture = textureLoader.load( fullPath );
  10302. }
  10303. if ( repeat !== undefined ) {
  10304. texture.repeat.fromArray( repeat );
  10305. if ( repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  10306. if ( repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  10307. }
  10308. if ( offset !== undefined ) {
  10309. texture.offset.fromArray( offset );
  10310. }
  10311. if ( wrap !== undefined ) {
  10312. if ( wrap[ 0 ] === 'repeat' ) texture.wrapS = THREE.RepeatWrapping;
  10313. if ( wrap[ 0 ] === 'mirror' ) texture.wrapS = THREE.MirroredRepeatWrapping;
  10314. if ( wrap[ 1 ] === 'repeat' ) texture.wrapT = THREE.RepeatWrapping;
  10315. if ( wrap[ 1 ] === 'mirror' ) texture.wrapT = THREE.MirroredRepeatWrapping;
  10316. }
  10317. if ( anisotropy !== undefined ) {
  10318. texture.anisotropy = anisotropy;
  10319. }
  10320. var uuid = THREE.Math.generateUUID();
  10321. textures[ uuid ] = texture;
  10322. return uuid;
  10323. }
  10324. //
  10325. var json = {
  10326. uuid: THREE.Math.generateUUID(),
  10327. type: 'MeshLambertMaterial'
  10328. };
  10329. for ( var name in m ) {
  10330. var value = m[ name ];
  10331. switch ( name ) {
  10332. case 'DbgColor':
  10333. case 'DbgIndex':
  10334. case 'opticalDensity':
  10335. case 'illumination':
  10336. break;
  10337. case 'DbgName':
  10338. json.name = value;
  10339. break;
  10340. case 'blending':
  10341. json.blending = THREE[ value ];
  10342. break;
  10343. case 'colorAmbient':
  10344. console.warn( 'THREE.Loader.createMaterial: colorAmbient is no longer supported' );
  10345. break;
  10346. case 'colorDiffuse':
  10347. json.color = color.fromArray( value ).getHex();
  10348. break;
  10349. case 'colorSpecular':
  10350. json.specular = color.fromArray( value ).getHex();
  10351. break;
  10352. case 'colorEmissive':
  10353. json.emissive = color.fromArray( value ).getHex();
  10354. break;
  10355. case 'specularCoef':
  10356. json.shininess = value;
  10357. break;
  10358. case 'shading':
  10359. if ( value.toLowerCase() === 'basic' ) json.type = 'MeshBasicMaterial';
  10360. if ( value.toLowerCase() === 'phong' ) json.type = 'MeshPhongMaterial';
  10361. break;
  10362. case 'mapDiffuse':
  10363. json.map = loadTexture( value, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  10364. break;
  10365. case 'mapDiffuseRepeat':
  10366. case 'mapDiffuseOffset':
  10367. case 'mapDiffuseWrap':
  10368. case 'mapDiffuseAnisotropy':
  10369. break;
  10370. case 'mapLight':
  10371. json.lightMap = loadTexture( value, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  10372. break;
  10373. case 'mapLightRepeat':
  10374. case 'mapLightOffset':
  10375. case 'mapLightWrap':
  10376. case 'mapLightAnisotropy':
  10377. break;
  10378. case 'mapAO':
  10379. json.aoMap = loadTexture( value, m.mapAORepeat, m.mapAOOffset, m.mapAOWrap, m.mapAOAnisotropy );
  10380. break;
  10381. case 'mapAORepeat':
  10382. case 'mapAOOffset':
  10383. case 'mapAOWrap':
  10384. case 'mapAOAnisotropy':
  10385. break;
  10386. case 'mapBump':
  10387. json.bumpMap = loadTexture( value, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  10388. break;
  10389. case 'mapBumpScale':
  10390. json.bumpScale = value;
  10391. break;
  10392. case 'mapBumpRepeat':
  10393. case 'mapBumpOffset':
  10394. case 'mapBumpWrap':
  10395. case 'mapBumpAnisotropy':
  10396. break;
  10397. case 'mapNormal':
  10398. json.normalMap = loadTexture( value, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  10399. break;
  10400. case 'mapNormalFactor':
  10401. json.normalScale = [ value, value ];
  10402. break;
  10403. case 'mapNormalRepeat':
  10404. case 'mapNormalOffset':
  10405. case 'mapNormalWrap':
  10406. case 'mapNormalAnisotropy':
  10407. break;
  10408. case 'mapSpecular':
  10409. json.specularMap = loadTexture( value, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  10410. break;
  10411. case 'mapSpecularRepeat':
  10412. case 'mapSpecularOffset':
  10413. case 'mapSpecularWrap':
  10414. case 'mapSpecularAnisotropy':
  10415. break;
  10416. case 'mapAlpha':
  10417. json.alphaMap = loadTexture( value, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy );
  10418. break;
  10419. case 'mapAlphaRepeat':
  10420. case 'mapAlphaOffset':
  10421. case 'mapAlphaWrap':
  10422. case 'mapAlphaAnisotropy':
  10423. break;
  10424. case 'flipSided':
  10425. json.side = THREE.BackSide;
  10426. break;
  10427. case 'doubleSided':
  10428. json.side = THREE.DoubleSide;
  10429. break;
  10430. case 'transparency':
  10431. console.warn( 'THREE.Loader.createMaterial: transparency has been renamed to opacity' );
  10432. json.opacity = value;
  10433. break;
  10434. case 'depthTest':
  10435. case 'depthWrite':
  10436. case 'opacity':
  10437. case 'reflectivity':
  10438. case 'transparent':
  10439. case 'visible':
  10440. case 'wireframe':
  10441. json[ name ] = value;
  10442. break;
  10443. case 'vertexColors':
  10444. if ( value === true ) json.vertexColors = THREE.VertexColors;
  10445. if ( value === 'face' ) json.vertexColors = THREE.FaceColors;
  10446. break;
  10447. default:
  10448. console.error( 'THREE.Loader.createMaterial: Unsupported', name, value );
  10449. break;
  10450. }
  10451. }
  10452. if ( json.type === 'MeshBasicMaterial' ) delete json.emissive;
  10453. if ( json.type !== 'MeshPhongMaterial' ) delete json.specular;
  10454. if ( json.opacity < 1 ) json.transparent = true;
  10455. materialLoader.setTextures( textures );
  10456. return materialLoader.parse( json );
  10457. };
  10458. } )()
  10459. };
  10460. THREE.Loader.Handlers = {
  10461. handlers: [],
  10462. add: function ( regex, loader ) {
  10463. this.handlers.push( regex, loader );
  10464. },
  10465. get: function ( file ) {
  10466. var handlers = this.handlers;
  10467. for ( var i = 0, l = handlers.length; i < l; i += 2 ) {
  10468. var regex = handlers[ i ];
  10469. var loader = handlers[ i + 1 ];
  10470. if ( regex.test( file ) ) {
  10471. return loader;
  10472. }
  10473. }
  10474. return null;
  10475. }
  10476. };
  10477. // File:src/loaders/XHRLoader.js
  10478. /**
  10479. * @author mrdoob / http://mrdoob.com/
  10480. */
  10481. THREE.XHRLoader = function ( manager ) {
  10482. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  10483. };
  10484. THREE.XHRLoader.prototype = {
  10485. constructor: THREE.XHRLoader,
  10486. load: function ( url, onLoad, onProgress, onError ) {
  10487. if ( this.path !== undefined ) url = this.path + url;
  10488. var scope = this;
  10489. var cached = THREE.Cache.get( url );
  10490. if ( cached !== undefined ) {
  10491. if ( onLoad ) {
  10492. setTimeout( function () {
  10493. onLoad( cached );
  10494. }, 0 );
  10495. }
  10496. return cached;
  10497. }
  10498. var request = new XMLHttpRequest();
  10499. request.overrideMimeType( 'text/plain' );
  10500. request.open( 'GET', url, true );
  10501. request.addEventListener( 'load', function ( event ) {
  10502. var response = event.target.response;
  10503. THREE.Cache.add( url, response );
  10504. if ( this.status === 200 ) {
  10505. if ( onLoad ) onLoad( response );
  10506. scope.manager.itemEnd( url );
  10507. } else if ( this.status === 0 ) {
  10508. // Some browsers return HTTP Status 0 when using non-http protocol
  10509. // e.g. 'file://' or 'data://'. Handle as success.
  10510. console.warn( 'THREE.XHRLoader: HTTP Status 0 received.' );
  10511. if ( onLoad ) onLoad( response );
  10512. scope.manager.itemEnd( url );
  10513. } else {
  10514. if ( onError ) onError( event );
  10515. scope.manager.itemError( url );
  10516. }
  10517. }, false );
  10518. if ( onProgress !== undefined ) {
  10519. request.addEventListener( 'progress', function ( event ) {
  10520. onProgress( event );
  10521. }, false );
  10522. }
  10523. request.addEventListener( 'error', function ( event ) {
  10524. if ( onError ) onError( event );
  10525. scope.manager.itemError( url );
  10526. }, false );
  10527. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  10528. if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;
  10529. request.send( null );
  10530. scope.manager.itemStart( url );
  10531. return request;
  10532. },
  10533. setPath: function ( value ) {
  10534. this.path = value;
  10535. },
  10536. setResponseType: function ( value ) {
  10537. this.responseType = value;
  10538. },
  10539. setWithCredentials: function ( value ) {
  10540. this.withCredentials = value;
  10541. }
  10542. };
  10543. // File:src/loaders/ImageLoader.js
  10544. /**
  10545. * @author mrdoob / http://mrdoob.com/
  10546. */
  10547. THREE.ImageLoader = function ( manager ) {
  10548. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  10549. };
  10550. THREE.ImageLoader.prototype = {
  10551. constructor: THREE.ImageLoader,
  10552. load: function ( url, onLoad, onProgress, onError ) {
  10553. if ( this.path !== undefined ) url = this.path + url;
  10554. var scope = this;
  10555. var cached = THREE.Cache.get( url );
  10556. if ( cached !== undefined ) {
  10557. scope.manager.itemStart( url );
  10558. if ( onLoad ) {
  10559. setTimeout( function () {
  10560. onLoad( cached );
  10561. scope.manager.itemEnd( url );
  10562. }, 0 );
  10563. } else {
  10564. scope.manager.itemEnd( url );
  10565. }
  10566. return cached;
  10567. }
  10568. var image = document.createElement( 'img' );
  10569. image.addEventListener( 'load', function ( event ) {
  10570. THREE.Cache.add( url, this );
  10571. if ( onLoad ) onLoad( this );
  10572. scope.manager.itemEnd( url );
  10573. }, false );
  10574. if ( onProgress !== undefined ) {
  10575. image.addEventListener( 'progress', function ( event ) {
  10576. onProgress( event );
  10577. }, false );
  10578. }
  10579. image.addEventListener( 'error', function ( event ) {
  10580. if ( onError ) onError( event );
  10581. scope.manager.itemError( url );
  10582. }, false );
  10583. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  10584. scope.manager.itemStart( url );
  10585. image.src = url;
  10586. return image;
  10587. },
  10588. setCrossOrigin: function ( value ) {
  10589. this.crossOrigin = value;
  10590. },
  10591. setPath: function ( value ) {
  10592. this.path = value;
  10593. }
  10594. };
  10595. // File:src/loaders/JSONLoader.js
  10596. /**
  10597. * @author mrdoob / http://mrdoob.com/
  10598. * @author alteredq / http://alteredqualia.com/
  10599. */
  10600. THREE.JSONLoader = function ( manager ) {
  10601. if ( typeof manager === 'boolean' ) {
  10602. console.warn( 'THREE.JSONLoader: showStatus parameter has been removed from constructor.' );
  10603. manager = undefined;
  10604. }
  10605. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  10606. this.withCredentials = false;
  10607. };
  10608. THREE.JSONLoader.prototype = {
  10609. constructor: THREE.JSONLoader,
  10610. // Deprecated
  10611. get statusDomElement () {
  10612. if ( this._statusDomElement === undefined ) {
  10613. this._statusDomElement = document.createElement( 'div' );
  10614. }
  10615. console.warn( 'THREE.JSONLoader: .statusDomElement has been removed.' );
  10616. return this._statusDomElement;
  10617. },
  10618. load: function( url, onLoad, onProgress, onError ) {
  10619. var scope = this;
  10620. var texturePath = this.texturePath && ( typeof this.texturePath === "string" ) ? this.texturePath : THREE.Loader.prototype.extractUrlBase( url );
  10621. var loader = new THREE.XHRLoader( this.manager );
  10622. loader.setWithCredentials( this.withCredentials );
  10623. loader.load( url, function ( text ) {
  10624. var json = JSON.parse( text );
  10625. var metadata = json.metadata;
  10626. if ( metadata !== undefined ) {
  10627. var type = metadata.type;
  10628. if ( type !== undefined ) {
  10629. if ( type.toLowerCase() === 'object' ) {
  10630. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' );
  10631. return;
  10632. }
  10633. if ( type.toLowerCase() === 'scene' ) {
  10634. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.SceneLoader instead.' );
  10635. return;
  10636. }
  10637. }
  10638. }
  10639. var object = scope.parse( json, texturePath );
  10640. onLoad( object.geometry, object.materials );
  10641. }, onProgress, onError );
  10642. },
  10643. setTexturePath: function ( value ) {
  10644. this.texturePath = value;
  10645. },
  10646. parse: function ( json, texturePath ) {
  10647. var geometry = new THREE.Geometry(),
  10648. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  10649. parseModel( scale );
  10650. parseSkin();
  10651. parseMorphing( scale );
  10652. parseAnimations();
  10653. geometry.computeFaceNormals();
  10654. geometry.computeBoundingSphere();
  10655. function parseModel( scale ) {
  10656. function isBitSet( value, position ) {
  10657. return value & ( 1 << position );
  10658. }
  10659. var i, j, fi,
  10660. offset, zLength,
  10661. colorIndex, normalIndex, uvIndex, materialIndex,
  10662. type,
  10663. isQuad,
  10664. hasMaterial,
  10665. hasFaceVertexUv,
  10666. hasFaceNormal, hasFaceVertexNormal,
  10667. hasFaceColor, hasFaceVertexColor,
  10668. vertex, face, faceA, faceB, hex, normal,
  10669. uvLayer, uv, u, v,
  10670. faces = json.faces,
  10671. vertices = json.vertices,
  10672. normals = json.normals,
  10673. colors = json.colors,
  10674. nUvLayers = 0;
  10675. if ( json.uvs !== undefined ) {
  10676. // disregard empty arrays
  10677. for ( i = 0; i < json.uvs.length; i ++ ) {
  10678. if ( json.uvs[ i ].length ) nUvLayers ++;
  10679. }
  10680. for ( i = 0; i < nUvLayers; i ++ ) {
  10681. geometry.faceVertexUvs[ i ] = [];
  10682. }
  10683. }
  10684. offset = 0;
  10685. zLength = vertices.length;
  10686. while ( offset < zLength ) {
  10687. vertex = new THREE.Vector3();
  10688. vertex.x = vertices[ offset ++ ] * scale;
  10689. vertex.y = vertices[ offset ++ ] * scale;
  10690. vertex.z = vertices[ offset ++ ] * scale;
  10691. geometry.vertices.push( vertex );
  10692. }
  10693. offset = 0;
  10694. zLength = faces.length;
  10695. while ( offset < zLength ) {
  10696. type = faces[ offset ++ ];
  10697. isQuad = isBitSet( type, 0 );
  10698. hasMaterial = isBitSet( type, 1 );
  10699. hasFaceVertexUv = isBitSet( type, 3 );
  10700. hasFaceNormal = isBitSet( type, 4 );
  10701. hasFaceVertexNormal = isBitSet( type, 5 );
  10702. hasFaceColor = isBitSet( type, 6 );
  10703. hasFaceVertexColor = isBitSet( type, 7 );
  10704. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  10705. if ( isQuad ) {
  10706. faceA = new THREE.Face3();
  10707. faceA.a = faces[ offset ];
  10708. faceA.b = faces[ offset + 1 ];
  10709. faceA.c = faces[ offset + 3 ];
  10710. faceB = new THREE.Face3();
  10711. faceB.a = faces[ offset + 1 ];
  10712. faceB.b = faces[ offset + 2 ];
  10713. faceB.c = faces[ offset + 3 ];
  10714. offset += 4;
  10715. if ( hasMaterial ) {
  10716. materialIndex = faces[ offset ++ ];
  10717. faceA.materialIndex = materialIndex;
  10718. faceB.materialIndex = materialIndex;
  10719. }
  10720. // to get face <=> uv index correspondence
  10721. fi = geometry.faces.length;
  10722. if ( hasFaceVertexUv ) {
  10723. for ( i = 0; i < nUvLayers; i ++ ) {
  10724. uvLayer = json.uvs[ i ];
  10725. geometry.faceVertexUvs[ i ][ fi ] = [];
  10726. geometry.faceVertexUvs[ i ][ fi + 1 ] = [];
  10727. for ( j = 0; j < 4; j ++ ) {
  10728. uvIndex = faces[ offset ++ ];
  10729. u = uvLayer[ uvIndex * 2 ];
  10730. v = uvLayer[ uvIndex * 2 + 1 ];
  10731. uv = new THREE.Vector2( u, v );
  10732. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  10733. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  10734. }
  10735. }
  10736. }
  10737. if ( hasFaceNormal ) {
  10738. normalIndex = faces[ offset ++ ] * 3;
  10739. faceA.normal.set(
  10740. normals[ normalIndex ++ ],
  10741. normals[ normalIndex ++ ],
  10742. normals[ normalIndex ]
  10743. );
  10744. faceB.normal.copy( faceA.normal );
  10745. }
  10746. if ( hasFaceVertexNormal ) {
  10747. for ( i = 0; i < 4; i ++ ) {
  10748. normalIndex = faces[ offset ++ ] * 3;
  10749. normal = new THREE.Vector3(
  10750. normals[ normalIndex ++ ],
  10751. normals[ normalIndex ++ ],
  10752. normals[ normalIndex ]
  10753. );
  10754. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  10755. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  10756. }
  10757. }
  10758. if ( hasFaceColor ) {
  10759. colorIndex = faces[ offset ++ ];
  10760. hex = colors[ colorIndex ];
  10761. faceA.color.setHex( hex );
  10762. faceB.color.setHex( hex );
  10763. }
  10764. if ( hasFaceVertexColor ) {
  10765. for ( i = 0; i < 4; i ++ ) {
  10766. colorIndex = faces[ offset ++ ];
  10767. hex = colors[ colorIndex ];
  10768. if ( i !== 2 ) faceA.vertexColors.push( new THREE.Color( hex ) );
  10769. if ( i !== 0 ) faceB.vertexColors.push( new THREE.Color( hex ) );
  10770. }
  10771. }
  10772. geometry.faces.push( faceA );
  10773. geometry.faces.push( faceB );
  10774. } else {
  10775. face = new THREE.Face3();
  10776. face.a = faces[ offset ++ ];
  10777. face.b = faces[ offset ++ ];
  10778. face.c = faces[ offset ++ ];
  10779. if ( hasMaterial ) {
  10780. materialIndex = faces[ offset ++ ];
  10781. face.materialIndex = materialIndex;
  10782. }
  10783. // to get face <=> uv index correspondence
  10784. fi = geometry.faces.length;
  10785. if ( hasFaceVertexUv ) {
  10786. for ( i = 0; i < nUvLayers; i ++ ) {
  10787. uvLayer = json.uvs[ i ];
  10788. geometry.faceVertexUvs[ i ][ fi ] = [];
  10789. for ( j = 0; j < 3; j ++ ) {
  10790. uvIndex = faces[ offset ++ ];
  10791. u = uvLayer[ uvIndex * 2 ];
  10792. v = uvLayer[ uvIndex * 2 + 1 ];
  10793. uv = new THREE.Vector2( u, v );
  10794. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  10795. }
  10796. }
  10797. }
  10798. if ( hasFaceNormal ) {
  10799. normalIndex = faces[ offset ++ ] * 3;
  10800. face.normal.set(
  10801. normals[ normalIndex ++ ],
  10802. normals[ normalIndex ++ ],
  10803. normals[ normalIndex ]
  10804. );
  10805. }
  10806. if ( hasFaceVertexNormal ) {
  10807. for ( i = 0; i < 3; i ++ ) {
  10808. normalIndex = faces[ offset ++ ] * 3;
  10809. normal = new THREE.Vector3(
  10810. normals[ normalIndex ++ ],
  10811. normals[ normalIndex ++ ],
  10812. normals[ normalIndex ]
  10813. );
  10814. face.vertexNormals.push( normal );
  10815. }
  10816. }
  10817. if ( hasFaceColor ) {
  10818. colorIndex = faces[ offset ++ ];
  10819. face.color.setHex( colors[ colorIndex ] );
  10820. }
  10821. if ( hasFaceVertexColor ) {
  10822. for ( i = 0; i < 3; i ++ ) {
  10823. colorIndex = faces[ offset ++ ];
  10824. face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) );
  10825. }
  10826. }
  10827. geometry.faces.push( face );
  10828. }
  10829. }
  10830. };
  10831. function parseSkin() {
  10832. var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2;
  10833. if ( json.skinWeights ) {
  10834. for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {
  10835. var x = json.skinWeights[ i ];
  10836. var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
  10837. var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
  10838. var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;
  10839. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  10840. }
  10841. }
  10842. if ( json.skinIndices ) {
  10843. for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {
  10844. var a = json.skinIndices[ i ];
  10845. var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
  10846. var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
  10847. var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;
  10848. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  10849. }
  10850. }
  10851. geometry.bones = json.bones;
  10852. if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {
  10853. console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
  10854. geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );
  10855. }
  10856. };
  10857. function parseMorphing( scale ) {
  10858. if ( json.morphTargets !== undefined ) {
  10859. for ( var i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  10860. geometry.morphTargets[ i ] = {};
  10861. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  10862. geometry.morphTargets[ i ].vertices = [];
  10863. var dstVertices = geometry.morphTargets[ i ].vertices;
  10864. var srcVertices = json.morphTargets[ i ].vertices;
  10865. for ( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  10866. var vertex = new THREE.Vector3();
  10867. vertex.x = srcVertices[ v ] * scale;
  10868. vertex.y = srcVertices[ v + 1 ] * scale;
  10869. vertex.z = srcVertices[ v + 2 ] * scale;
  10870. dstVertices.push( vertex );
  10871. }
  10872. }
  10873. }
  10874. if ( json.morphColors !== undefined && json.morphColors.length > 0 ) {
  10875. console.warn( 'THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.' );
  10876. var faces = geometry.faces;
  10877. var morphColors = json.morphColors[ 0 ].colors;
  10878. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  10879. faces[ i ].color.fromArray( morphColors, i * 3 );
  10880. }
  10881. }
  10882. }
  10883. function parseAnimations() {
  10884. var outputAnimations = [];
  10885. // parse old style Bone/Hierarchy animations
  10886. var animations = [];
  10887. if ( json.animation !== undefined ) {
  10888. animations.push( json.animation );
  10889. }
  10890. if ( json.animations !== undefined ) {
  10891. if ( json.animations.length ) {
  10892. animations = animations.concat( json.animations );
  10893. } else {
  10894. animations.push( json.animations );
  10895. }
  10896. }
  10897. for ( var i = 0; i < animations.length; i ++ ) {
  10898. var clip = THREE.AnimationClip.parseAnimation( animations[ i ], geometry.bones );
  10899. if ( clip ) outputAnimations.push( clip );
  10900. }
  10901. // parse implicit morph animations
  10902. if ( geometry.morphTargets ) {
  10903. // TODO: Figure out what an appropraite FPS is for morph target animations -- defaulting to 10, but really it is completely arbitrary.
  10904. var morphAnimationClips = THREE.AnimationClip.CreateClipsFromMorphTargetSequences( geometry.morphTargets, 10 );
  10905. outputAnimations = outputAnimations.concat( morphAnimationClips );
  10906. }
  10907. if ( outputAnimations.length > 0 ) geometry.animations = outputAnimations;
  10908. };
  10909. if ( json.materials === undefined || json.materials.length === 0 ) {
  10910. return { geometry: geometry };
  10911. } else {
  10912. var materials = THREE.Loader.prototype.initMaterials( json.materials, texturePath, this.crossOrigin );
  10913. return { geometry: geometry, materials: materials };
  10914. }
  10915. }
  10916. };
  10917. // File:src/loaders/LoadingManager.js
  10918. /**
  10919. * @author mrdoob / http://mrdoob.com/
  10920. */
  10921. THREE.LoadingManager = function ( onLoad, onProgress, onError ) {
  10922. var scope = this;
  10923. var isLoading = false, itemsLoaded = 0, itemsTotal = 0;
  10924. this.onStart = undefined;
  10925. this.onLoad = onLoad;
  10926. this.onProgress = onProgress;
  10927. this.onError = onError;
  10928. this.itemStart = function ( url ) {
  10929. itemsTotal ++;
  10930. if ( isLoading === false ) {
  10931. if ( scope.onStart !== undefined ) {
  10932. scope.onStart( url, itemsLoaded, itemsTotal );
  10933. }
  10934. }
  10935. isLoading = true;
  10936. };
  10937. this.itemEnd = function ( url ) {
  10938. itemsLoaded ++;
  10939. if ( scope.onProgress !== undefined ) {
  10940. scope.onProgress( url, itemsLoaded, itemsTotal );
  10941. }
  10942. if ( itemsLoaded === itemsTotal ) {
  10943. isLoading = false;
  10944. if ( scope.onLoad !== undefined ) {
  10945. scope.onLoad();
  10946. }
  10947. }
  10948. };
  10949. this.itemError = function ( url ) {
  10950. if ( scope.onError !== undefined ) {
  10951. scope.onError( url );
  10952. }
  10953. };
  10954. };
  10955. THREE.DefaultLoadingManager = new THREE.LoadingManager();
  10956. // File:src/loaders/BufferGeometryLoader.js
  10957. /**
  10958. * @author mrdoob / http://mrdoob.com/
  10959. */
  10960. THREE.BufferGeometryLoader = function ( manager ) {
  10961. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  10962. };
  10963. THREE.BufferGeometryLoader.prototype = {
  10964. constructor: THREE.BufferGeometryLoader,
  10965. load: function ( url, onLoad, onProgress, onError ) {
  10966. var scope = this;
  10967. var loader = new THREE.XHRLoader( scope.manager );
  10968. loader.load( url, function ( text ) {
  10969. onLoad( scope.parse( JSON.parse( text ) ) );
  10970. }, onProgress, onError );
  10971. },
  10972. parse: function ( json ) {
  10973. var geometry = new THREE.BufferGeometry();
  10974. var index = json.data.index;
  10975. if ( index !== undefined ) {
  10976. var typedArray = new self[ index.type ]( index.array );
  10977. geometry.setIndex( new THREE.BufferAttribute( typedArray, 1 ) );
  10978. }
  10979. var attributes = json.data.attributes;
  10980. for ( var key in attributes ) {
  10981. var attribute = attributes[ key ];
  10982. var typedArray = new self[ attribute.type ]( attribute.array );
  10983. geometry.addAttribute( key, new THREE.BufferAttribute( typedArray, attribute.itemSize ) );
  10984. }
  10985. var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  10986. if ( groups !== undefined ) {
  10987. for ( var i = 0, n = groups.length; i !== n; ++ i ) {
  10988. var group = groups[ i ];
  10989. geometry.addGroup( group.start, group.count, group.materialIndex );
  10990. }
  10991. }
  10992. var boundingSphere = json.data.boundingSphere;
  10993. if ( boundingSphere !== undefined ) {
  10994. var center = new THREE.Vector3();
  10995. if ( boundingSphere.center !== undefined ) {
  10996. center.fromArray( boundingSphere.center );
  10997. }
  10998. geometry.boundingSphere = new THREE.Sphere( center, boundingSphere.radius );
  10999. }
  11000. return geometry;
  11001. }
  11002. };
  11003. // File:src/loaders/MaterialLoader.js
  11004. /**
  11005. * @author mrdoob / http://mrdoob.com/
  11006. */
  11007. THREE.MaterialLoader = function ( manager ) {
  11008. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  11009. this.textures = {};
  11010. };
  11011. THREE.MaterialLoader.prototype = {
  11012. constructor: THREE.MaterialLoader,
  11013. load: function ( url, onLoad, onProgress, onError ) {
  11014. var scope = this;
  11015. var loader = new THREE.XHRLoader( scope.manager );
  11016. loader.load( url, function ( text ) {
  11017. onLoad( scope.parse( JSON.parse( text ) ) );
  11018. }, onProgress, onError );
  11019. },
  11020. setTextures: function ( value ) {
  11021. this.textures = value;
  11022. },
  11023. getTexture: function ( name ) {
  11024. var textures = this.textures;
  11025. if ( textures[ name ] === undefined ) {
  11026. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  11027. }
  11028. return textures[ name ];
  11029. },
  11030. parse: function ( json ) {
  11031. var material = new THREE[ json.type ];
  11032. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  11033. if ( json.name !== undefined ) material.name = json.name;
  11034. if ( json.color !== undefined ) material.color.setHex( json.color );
  11035. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  11036. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  11037. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  11038. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  11039. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  11040. if ( json.uniforms !== undefined ) material.uniforms = json.uniforms;
  11041. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  11042. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  11043. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  11044. if ( json.shading !== undefined ) material.shading = json.shading;
  11045. if ( json.blending !== undefined ) material.blending = json.blending;
  11046. if ( json.side !== undefined ) material.side = json.side;
  11047. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  11048. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  11049. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  11050. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  11051. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  11052. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  11053. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  11054. // for PointsMaterial
  11055. if ( json.size !== undefined ) material.size = json.size;
  11056. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  11057. // maps
  11058. if ( json.map !== undefined ) material.map = this.getTexture( json.map );
  11059. if ( json.alphaMap !== undefined ) {
  11060. material.alphaMap = this.getTexture( json.alphaMap );
  11061. material.transparent = true;
  11062. }
  11063. if ( json.bumpMap !== undefined ) material.bumpMap = this.getTexture( json.bumpMap );
  11064. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  11065. if ( json.normalMap !== undefined ) material.normalMap = this.getTexture( json.normalMap );
  11066. if ( json.normalScale !== undefined ) {
  11067. var normalScale = json.normalScale;
  11068. if ( Array.isArray( normalScale ) === false ) {
  11069. // Blender exporter used to export a scalar. See #7459
  11070. normalScale = [ normalScale, normalScale ];
  11071. }
  11072. material.normalScale = new THREE.Vector2().fromArray( normalScale );
  11073. }
  11074. if ( json.displacementMap !== undefined ) material.displacementMap = this.getTexture( json.displacementMap );
  11075. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  11076. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  11077. if ( json.roughnessMap !== undefined ) material.roughnessMap = this.getTexture( json.roughnessMap );
  11078. if ( json.metalnessMap !== undefined ) material.metalnessMap = this.getTexture( json.metalnessMap );
  11079. if ( json.emissiveMap !== undefined ) material.emissiveMap = this.getTexture( json.emissiveMap );
  11080. if ( json.specularMap !== undefined ) material.specularMap = this.getTexture( json.specularMap );
  11081. if ( json.envMap !== undefined ) {
  11082. material.envMap = this.getTexture( json.envMap );
  11083. material.combine = THREE.MultiplyOperation;
  11084. }
  11085. if ( json.reflectivity ) material.reflectivity = json.reflectivity;
  11086. if ( json.lightMap !== undefined ) material.lightMap = this.getTexture( json.lightMap );
  11087. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  11088. if ( json.aoMap !== undefined ) material.aoMap = this.getTexture( json.aoMap );
  11089. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  11090. // MeshFaceMaterial
  11091. if ( json.materials !== undefined ) {
  11092. for ( var i = 0, l = json.materials.length; i < l; i ++ ) {
  11093. material.materials.push( this.parse( json.materials[ i ] ) );
  11094. }
  11095. }
  11096. return material;
  11097. }
  11098. };
  11099. // File:src/loaders/ObjectLoader.js
  11100. /**
  11101. * @author mrdoob / http://mrdoob.com/
  11102. */
  11103. THREE.ObjectLoader = function ( manager ) {
  11104. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  11105. this.texturePath = '';
  11106. };
  11107. THREE.ObjectLoader.prototype = {
  11108. constructor: THREE.ObjectLoader,
  11109. load: function ( url, onLoad, onProgress, onError ) {
  11110. if ( this.texturePath === '' ) {
  11111. this.texturePath = url.substring( 0, url.lastIndexOf( '/' ) + 1 );
  11112. }
  11113. var scope = this;
  11114. var loader = new THREE.XHRLoader( scope.manager );
  11115. loader.load( url, function ( text ) {
  11116. scope.parse( JSON.parse( text ), onLoad );
  11117. }, onProgress, onError );
  11118. },
  11119. setTexturePath: function ( value ) {
  11120. this.texturePath = value;
  11121. },
  11122. setCrossOrigin: function ( value ) {
  11123. this.crossOrigin = value;
  11124. },
  11125. parse: function ( json, onLoad ) {
  11126. var geometries = this.parseGeometries( json.geometries );
  11127. var images = this.parseImages( json.images, function () {
  11128. if ( onLoad !== undefined ) onLoad( object );
  11129. } );
  11130. var textures = this.parseTextures( json.textures, images );
  11131. var materials = this.parseMaterials( json.materials, textures );
  11132. var object = this.parseObject( json.object, geometries, materials );
  11133. if ( json.animations ) {
  11134. object.animations = this.parseAnimations( json.animations );
  11135. }
  11136. if ( json.images === undefined || json.images.length === 0 ) {
  11137. if ( onLoad !== undefined ) onLoad( object );
  11138. }
  11139. return object;
  11140. },
  11141. parseGeometries: function ( json ) {
  11142. var geometries = {};
  11143. if ( json !== undefined ) {
  11144. var geometryLoader = new THREE.JSONLoader();
  11145. var bufferGeometryLoader = new THREE.BufferGeometryLoader();
  11146. for ( var i = 0, l = json.length; i < l; i ++ ) {
  11147. var geometry;
  11148. var data = json[ i ];
  11149. switch ( data.type ) {
  11150. case 'PlaneGeometry':
  11151. case 'PlaneBufferGeometry':
  11152. geometry = new THREE[ data.type ](
  11153. data.width,
  11154. data.height,
  11155. data.widthSegments,
  11156. data.heightSegments
  11157. );
  11158. break;
  11159. case 'BoxGeometry':
  11160. case 'CubeGeometry': // backwards compatible
  11161. geometry = new THREE.BoxGeometry(
  11162. data.width,
  11163. data.height,
  11164. data.depth,
  11165. data.widthSegments,
  11166. data.heightSegments,
  11167. data.depthSegments
  11168. );
  11169. break;
  11170. case 'CircleBufferGeometry':
  11171. geometry = new THREE.CircleBufferGeometry(
  11172. data.radius,
  11173. data.segments,
  11174. data.thetaStart,
  11175. data.thetaLength
  11176. );
  11177. break;
  11178. case 'CircleGeometry':
  11179. geometry = new THREE.CircleGeometry(
  11180. data.radius,
  11181. data.segments,
  11182. data.thetaStart,
  11183. data.thetaLength
  11184. );
  11185. break;
  11186. case 'CylinderGeometry':
  11187. geometry = new THREE.CylinderGeometry(
  11188. data.radiusTop,
  11189. data.radiusBottom,
  11190. data.height,
  11191. data.radialSegments,
  11192. data.heightSegments,
  11193. data.openEnded,
  11194. data.thetaStart,
  11195. data.thetaLength
  11196. );
  11197. break;
  11198. case 'SphereGeometry':
  11199. geometry = new THREE.SphereGeometry(
  11200. data.radius,
  11201. data.widthSegments,
  11202. data.heightSegments,
  11203. data.phiStart,
  11204. data.phiLength,
  11205. data.thetaStart,
  11206. data.thetaLength
  11207. );
  11208. break;
  11209. case 'SphereBufferGeometry':
  11210. geometry = new THREE.SphereBufferGeometry(
  11211. data.radius,
  11212. data.widthSegments,
  11213. data.heightSegments,
  11214. data.phiStart,
  11215. data.phiLength,
  11216. data.thetaStart,
  11217. data.thetaLength
  11218. );
  11219. break;
  11220. case 'DodecahedronGeometry':
  11221. geometry = new THREE.DodecahedronGeometry(
  11222. data.radius,
  11223. data.detail
  11224. );
  11225. break;
  11226. case 'IcosahedronGeometry':
  11227. geometry = new THREE.IcosahedronGeometry(
  11228. data.radius,
  11229. data.detail
  11230. );
  11231. break;
  11232. case 'OctahedronGeometry':
  11233. geometry = new THREE.OctahedronGeometry(
  11234. data.radius,
  11235. data.detail
  11236. );
  11237. break;
  11238. case 'TetrahedronGeometry':
  11239. geometry = new THREE.TetrahedronGeometry(
  11240. data.radius,
  11241. data.detail
  11242. );
  11243. break;
  11244. case 'RingGeometry':
  11245. geometry = new THREE.RingGeometry(
  11246. data.innerRadius,
  11247. data.outerRadius,
  11248. data.thetaSegments,
  11249. data.phiSegments,
  11250. data.thetaStart,
  11251. data.thetaLength
  11252. );
  11253. break;
  11254. case 'TorusGeometry':
  11255. geometry = new THREE.TorusGeometry(
  11256. data.radius,
  11257. data.tube,
  11258. data.radialSegments,
  11259. data.tubularSegments,
  11260. data.arc
  11261. );
  11262. break;
  11263. case 'TorusKnotGeometry':
  11264. geometry = new THREE.TorusKnotGeometry(
  11265. data.radius,
  11266. data.tube,
  11267. data.radialSegments,
  11268. data.tubularSegments,
  11269. data.p,
  11270. data.q,
  11271. data.heightScale
  11272. );
  11273. break;
  11274. case 'BufferGeometry':
  11275. geometry = bufferGeometryLoader.parse( data );
  11276. break;
  11277. case 'Geometry':
  11278. geometry = geometryLoader.parse( data.data, this.texturePath ).geometry;
  11279. break;
  11280. default:
  11281. console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' );
  11282. continue;
  11283. }
  11284. geometry.uuid = data.uuid;
  11285. if ( data.name !== undefined ) geometry.name = data.name;
  11286. geometries[ data.uuid ] = geometry;
  11287. }
  11288. }
  11289. return geometries;
  11290. },
  11291. parseMaterials: function ( json, textures ) {
  11292. var materials = {};
  11293. if ( json !== undefined ) {
  11294. var loader = new THREE.MaterialLoader();
  11295. loader.setTextures( textures );
  11296. for ( var i = 0, l = json.length; i < l; i ++ ) {
  11297. var material = loader.parse( json[ i ] );
  11298. materials[ material.uuid ] = material;
  11299. }
  11300. }
  11301. return materials;
  11302. },
  11303. parseAnimations: function ( json ) {
  11304. var animations = [];
  11305. for ( var i = 0; i < json.length; i ++ ) {
  11306. var clip = THREE.AnimationClip.parse( json[ i ] );
  11307. animations.push( clip );
  11308. }
  11309. return animations;
  11310. },
  11311. parseImages: function ( json, onLoad ) {
  11312. var scope = this;
  11313. var images = {};
  11314. function loadImage( url ) {
  11315. scope.manager.itemStart( url );
  11316. return loader.load( url, function () {
  11317. scope.manager.itemEnd( url );
  11318. } );
  11319. }
  11320. if ( json !== undefined && json.length > 0 ) {
  11321. var manager = new THREE.LoadingManager( onLoad );
  11322. var loader = new THREE.ImageLoader( manager );
  11323. loader.setCrossOrigin( this.crossOrigin );
  11324. for ( var i = 0, l = json.length; i < l; i ++ ) {
  11325. var image = json[ i ];
  11326. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.texturePath + image.url;
  11327. images[ image.uuid ] = loadImage( path );
  11328. }
  11329. }
  11330. return images;
  11331. },
  11332. parseTextures: function ( json, images ) {
  11333. function parseConstant( value ) {
  11334. if ( typeof( value ) === 'number' ) return value;
  11335. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  11336. return THREE[ value ];
  11337. }
  11338. var textures = {};
  11339. if ( json !== undefined ) {
  11340. for ( var i = 0, l = json.length; i < l; i ++ ) {
  11341. var data = json[ i ];
  11342. if ( data.image === undefined ) {
  11343. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  11344. }
  11345. if ( images[ data.image ] === undefined ) {
  11346. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  11347. }
  11348. var texture = new THREE.Texture( images[ data.image ] );
  11349. texture.needsUpdate = true;
  11350. texture.uuid = data.uuid;
  11351. if ( data.name !== undefined ) texture.name = data.name;
  11352. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping );
  11353. if ( data.offset !== undefined ) texture.offset = new THREE.Vector2( data.offset[ 0 ], data.offset[ 1 ] );
  11354. if ( data.repeat !== undefined ) texture.repeat = new THREE.Vector2( data.repeat[ 0 ], data.repeat[ 1 ] );
  11355. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter );
  11356. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter );
  11357. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  11358. if ( Array.isArray( data.wrap ) ) {
  11359. texture.wrapS = parseConstant( data.wrap[ 0 ] );
  11360. texture.wrapT = parseConstant( data.wrap[ 1 ] );
  11361. }
  11362. textures[ data.uuid ] = texture;
  11363. }
  11364. }
  11365. return textures;
  11366. },
  11367. parseObject: function () {
  11368. var matrix = new THREE.Matrix4();
  11369. return function ( data, geometries, materials ) {
  11370. var object;
  11371. function getGeometry( name ) {
  11372. if ( geometries[ name ] === undefined ) {
  11373. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  11374. }
  11375. return geometries[ name ];
  11376. }
  11377. function getMaterial( name ) {
  11378. if ( name === undefined ) return undefined;
  11379. if ( materials[ name ] === undefined ) {
  11380. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  11381. }
  11382. return materials[ name ];
  11383. }
  11384. switch ( data.type ) {
  11385. case 'Scene':
  11386. object = new THREE.Scene();
  11387. break;
  11388. case 'PerspectiveCamera':
  11389. object = new THREE.PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  11390. break;
  11391. case 'OrthographicCamera':
  11392. object = new THREE.OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  11393. break;
  11394. case 'AmbientLight':
  11395. object = new THREE.AmbientLight( data.color, data.intensity );
  11396. break;
  11397. case 'DirectionalLight':
  11398. object = new THREE.DirectionalLight( data.color, data.intensity );
  11399. break;
  11400. case 'PointLight':
  11401. object = new THREE.PointLight( data.color, data.intensity, data.distance, data.decay );
  11402. break;
  11403. case 'SpotLight':
  11404. object = new THREE.SpotLight( data.color, data.intensity, data.distance, data.angle, data.exponent, data.decay );
  11405. break;
  11406. case 'HemisphereLight':
  11407. object = new THREE.HemisphereLight( data.color, data.groundColor, data.intensity );
  11408. break;
  11409. case 'Mesh':
  11410. var geometry = getGeometry( data.geometry );
  11411. var material = getMaterial( data.material );
  11412. if ( geometry.bones && geometry.bones.length > 0 ) {
  11413. object = new THREE.SkinnedMesh( geometry, material );
  11414. } else {
  11415. object = new THREE.Mesh( geometry, material );
  11416. }
  11417. break;
  11418. case 'LOD':
  11419. object = new THREE.LOD();
  11420. break;
  11421. case 'Line':
  11422. object = new THREE.Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode );
  11423. break;
  11424. case 'PointCloud':
  11425. case 'Points':
  11426. object = new THREE.Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  11427. break;
  11428. case 'Sprite':
  11429. object = new THREE.Sprite( getMaterial( data.material ) );
  11430. break;
  11431. case 'Group':
  11432. object = new THREE.Group();
  11433. break;
  11434. default:
  11435. object = new THREE.Object3D();
  11436. }
  11437. object.uuid = data.uuid;
  11438. if ( data.name !== undefined ) object.name = data.name;
  11439. if ( data.matrix !== undefined ) {
  11440. matrix.fromArray( data.matrix );
  11441. matrix.decompose( object.position, object.quaternion, object.scale );
  11442. } else {
  11443. if ( data.position !== undefined ) object.position.fromArray( data.position );
  11444. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  11445. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  11446. }
  11447. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  11448. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  11449. if ( data.visible !== undefined ) object.visible = data.visible;
  11450. if ( data.userData !== undefined ) object.userData = data.userData;
  11451. if ( data.children !== undefined ) {
  11452. for ( var child in data.children ) {
  11453. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  11454. }
  11455. }
  11456. if ( data.type === 'LOD' ) {
  11457. var levels = data.levels;
  11458. for ( var l = 0; l < levels.length; l ++ ) {
  11459. var level = levels[ l ];
  11460. var child = object.getObjectByProperty( 'uuid', level.object );
  11461. if ( child !== undefined ) {
  11462. object.addLevel( child, level.distance );
  11463. }
  11464. }
  11465. }
  11466. return object;
  11467. }
  11468. }()
  11469. };
  11470. // File:src/loaders/TextureLoader.js
  11471. /**
  11472. * @author mrdoob / http://mrdoob.com/
  11473. */
  11474. THREE.TextureLoader = function ( manager ) {
  11475. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  11476. };
  11477. THREE.TextureLoader.prototype = {
  11478. constructor: THREE.TextureLoader,
  11479. load: function ( url, onLoad, onProgress, onError ) {
  11480. var texture = new THREE.Texture();
  11481. var loader = new THREE.ImageLoader( this.manager );
  11482. loader.setCrossOrigin( this.crossOrigin );
  11483. loader.setPath( this.path );
  11484. loader.load( url, function ( image ) {
  11485. texture.image = image;
  11486. texture.needsUpdate = true;
  11487. if ( onLoad !== undefined ) {
  11488. onLoad( texture );
  11489. }
  11490. }, onProgress, onError );
  11491. return texture;
  11492. },
  11493. setCrossOrigin: function ( value ) {
  11494. this.crossOrigin = value;
  11495. },
  11496. setPath: function ( value ) {
  11497. this.path = value;
  11498. }
  11499. };
  11500. // File:src/loaders/CubeTextureLoader.js
  11501. /**
  11502. * @author mrdoob / http://mrdoob.com/
  11503. */
  11504. THREE.CubeTextureLoader = function ( manager ) {
  11505. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  11506. };
  11507. THREE.CubeTextureLoader.prototype = {
  11508. constructor: THREE.CubeTextureLoader,
  11509. load: function ( urls, onLoad, onProgress, onError ) {
  11510. var texture = new THREE.CubeTexture( [] );
  11511. var loader = new THREE.ImageLoader();
  11512. loader.setCrossOrigin( this.crossOrigin );
  11513. loader.setPath( this.path );
  11514. var loaded = 0;
  11515. function loadTexture( i ) {
  11516. loader.load( urls[ i ], function ( image ) {
  11517. texture.images[ i ] = image;
  11518. loaded ++;
  11519. if ( loaded === 6 ) {
  11520. texture.needsUpdate = true;
  11521. if ( onLoad ) onLoad( texture );
  11522. }
  11523. }, undefined, onError );
  11524. }
  11525. for ( var i = 0; i < urls.length; ++ i ) {
  11526. loadTexture( i );
  11527. }
  11528. return texture;
  11529. },
  11530. setCrossOrigin: function ( value ) {
  11531. this.crossOrigin = value;
  11532. },
  11533. setPath: function ( value ) {
  11534. this.path = value;
  11535. }
  11536. };
  11537. // File:src/loaders/BinaryTextureLoader.js
  11538. /**
  11539. * @author Nikos M. / https://github.com/foo123/
  11540. *
  11541. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  11542. */
  11543. THREE.DataTextureLoader = THREE.BinaryTextureLoader = function ( manager ) {
  11544. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  11545. // override in sub classes
  11546. this._parser = null;
  11547. };
  11548. THREE.BinaryTextureLoader.prototype = {
  11549. constructor: THREE.BinaryTextureLoader,
  11550. load: function ( url, onLoad, onProgress, onError ) {
  11551. var scope = this;
  11552. var texture = new THREE.DataTexture();
  11553. var loader = new THREE.XHRLoader( this.manager );
  11554. loader.setResponseType( 'arraybuffer' );
  11555. loader.load( url, function ( buffer ) {
  11556. var texData = scope._parser( buffer );
  11557. if ( ! texData ) return;
  11558. if ( undefined !== texData.image ) {
  11559. texture.image = texData.image;
  11560. } else if ( undefined !== texData.data ) {
  11561. texture.image.width = texData.width;
  11562. texture.image.height = texData.height;
  11563. texture.image.data = texData.data;
  11564. }
  11565. texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : THREE.ClampToEdgeWrapping;
  11566. texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : THREE.ClampToEdgeWrapping;
  11567. texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : THREE.LinearFilter;
  11568. texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : THREE.LinearMipMapLinearFilter;
  11569. texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1;
  11570. if ( undefined !== texData.format ) {
  11571. texture.format = texData.format;
  11572. }
  11573. if ( undefined !== texData.type ) {
  11574. texture.type = texData.type;
  11575. }
  11576. if ( undefined !== texData.mipmaps ) {
  11577. texture.mipmaps = texData.mipmaps;
  11578. }
  11579. if ( 1 === texData.mipmapCount ) {
  11580. texture.minFilter = THREE.LinearFilter;
  11581. }
  11582. texture.needsUpdate = true;
  11583. if ( onLoad ) onLoad( texture, texData );
  11584. }, onProgress, onError );
  11585. return texture;
  11586. }
  11587. };
  11588. // File:src/loaders/CompressedTextureLoader.js
  11589. /**
  11590. * @author mrdoob / http://mrdoob.com/
  11591. *
  11592. * Abstract Base class to block based textures loader (dds, pvr, ...)
  11593. */
  11594. THREE.CompressedTextureLoader = function ( manager ) {
  11595. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  11596. // override in sub classes
  11597. this._parser = null;
  11598. };
  11599. THREE.CompressedTextureLoader.prototype = {
  11600. constructor: THREE.CompressedTextureLoader,
  11601. load: function ( url, onLoad, onProgress, onError ) {
  11602. var scope = this;
  11603. var images = [];
  11604. var texture = new THREE.CompressedTexture();
  11605. texture.image = images;
  11606. var loader = new THREE.XHRLoader( this.manager );
  11607. loader.setPath( this.path );
  11608. loader.setResponseType( 'arraybuffer' );
  11609. function loadTexture( i ) {
  11610. loader.load( url[ i ], function ( buffer ) {
  11611. var texDatas = scope._parser( buffer, true );
  11612. images[ i ] = {
  11613. width: texDatas.width,
  11614. height: texDatas.height,
  11615. format: texDatas.format,
  11616. mipmaps: texDatas.mipmaps
  11617. };
  11618. loaded += 1;
  11619. if ( loaded === 6 ) {
  11620. if ( texDatas.mipmapCount === 1 )
  11621. texture.minFilter = THREE.LinearFilter;
  11622. texture.format = texDatas.format;
  11623. texture.needsUpdate = true;
  11624. if ( onLoad ) onLoad( texture );
  11625. }
  11626. }, onProgress, onError );
  11627. }
  11628. if ( Array.isArray( url ) ) {
  11629. var loaded = 0;
  11630. for ( var i = 0, il = url.length; i < il; ++ i ) {
  11631. loadTexture( i );
  11632. }
  11633. } else {
  11634. // compressed cubemap texture stored in a single DDS file
  11635. loader.load( url, function ( buffer ) {
  11636. var texDatas = scope._parser( buffer, true );
  11637. if ( texDatas.isCubemap ) {
  11638. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  11639. for ( var f = 0; f < faces; f ++ ) {
  11640. images[ f ] = { mipmaps : [] };
  11641. for ( var i = 0; i < texDatas.mipmapCount; i ++ ) {
  11642. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  11643. images[ f ].format = texDatas.format;
  11644. images[ f ].width = texDatas.width;
  11645. images[ f ].height = texDatas.height;
  11646. }
  11647. }
  11648. } else {
  11649. texture.image.width = texDatas.width;
  11650. texture.image.height = texDatas.height;
  11651. texture.mipmaps = texDatas.mipmaps;
  11652. }
  11653. if ( texDatas.mipmapCount === 1 ) {
  11654. texture.minFilter = THREE.LinearFilter;
  11655. }
  11656. texture.format = texDatas.format;
  11657. texture.needsUpdate = true;
  11658. if ( onLoad ) onLoad( texture );
  11659. }, onProgress, onError );
  11660. }
  11661. return texture;
  11662. },
  11663. setPath: function ( value ) {
  11664. this.path = value;
  11665. }
  11666. };
  11667. // File:src/materials/Material.js
  11668. /**
  11669. * @author mrdoob / http://mrdoob.com/
  11670. * @author alteredq / http://alteredqualia.com/
  11671. */
  11672. THREE.Material = function () {
  11673. Object.defineProperty( this, 'id', { value: THREE.MaterialIdCount ++ } );
  11674. this.uuid = THREE.Math.generateUUID();
  11675. this.name = '';
  11676. this.type = 'Material';
  11677. this.side = THREE.FrontSide;
  11678. this.opacity = 1;
  11679. this.transparent = false;
  11680. this.blending = THREE.NormalBlending;
  11681. this.blendSrc = THREE.SrcAlphaFactor;
  11682. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  11683. this.blendEquation = THREE.AddEquation;
  11684. this.blendSrcAlpha = null;
  11685. this.blendDstAlpha = null;
  11686. this.blendEquationAlpha = null;
  11687. this.depthFunc = THREE.LessEqualDepth;
  11688. this.depthTest = true;
  11689. this.depthWrite = true;
  11690. this.colorWrite = true;
  11691. this.precision = null; // override the renderer's default precision for this material
  11692. this.polygonOffset = false;
  11693. this.polygonOffsetFactor = 0;
  11694. this.polygonOffsetUnits = 0;
  11695. this.alphaTest = 0;
  11696. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  11697. this.visible = true;
  11698. this._needsUpdate = true;
  11699. };
  11700. THREE.Material.prototype = {
  11701. constructor: THREE.Material,
  11702. get needsUpdate () {
  11703. return this._needsUpdate;
  11704. },
  11705. set needsUpdate ( value ) {
  11706. if ( value === true ) this.update();
  11707. this._needsUpdate = value;
  11708. },
  11709. setValues: function ( values ) {
  11710. if ( values === undefined ) return;
  11711. for ( var key in values ) {
  11712. var newValue = values[ key ];
  11713. if ( newValue === undefined ) {
  11714. console.warn( "THREE.Material: '" + key + "' parameter is undefined." );
  11715. continue;
  11716. }
  11717. var currentValue = this[ key ];
  11718. if ( currentValue === undefined ) {
  11719. console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." );
  11720. continue;
  11721. }
  11722. if ( currentValue instanceof THREE.Color ) {
  11723. currentValue.set( newValue );
  11724. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  11725. currentValue.copy( newValue );
  11726. } else if ( key === 'overdraw' ) {
  11727. // ensure overdraw is backwards-compatible with legacy boolean type
  11728. this[ key ] = Number( newValue );
  11729. } else {
  11730. this[ key ] = newValue;
  11731. }
  11732. }
  11733. },
  11734. toJSON: function ( meta ) {
  11735. var isRoot = meta === undefined;
  11736. if ( isRoot ) {
  11737. meta = {
  11738. textures: {},
  11739. images: {}
  11740. };
  11741. }
  11742. var data = {
  11743. metadata: {
  11744. version: 4.4,
  11745. type: 'Material',
  11746. generator: 'Material.toJSON'
  11747. }
  11748. };
  11749. // standard Material serialization
  11750. data.uuid = this.uuid;
  11751. data.type = this.type;
  11752. if ( this.name !== '' ) data.name = this.name;
  11753. if ( this.color instanceof THREE.Color ) data.color = this.color.getHex();
  11754. if ( this.roughness !== 0.5 ) data.roughness = this.roughness;
  11755. if ( this.metalness > 0 ) data.metalness = this.metalness;
  11756. if ( this.emissive instanceof THREE.Color ) data.emissive = this.emissive.getHex();
  11757. if ( this.specular instanceof THREE.Color ) data.specular = this.specular.getHex();
  11758. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  11759. if ( this.map instanceof THREE.Texture ) data.map = this.map.toJSON( meta ).uuid;
  11760. if ( this.alphaMap instanceof THREE.Texture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  11761. if ( this.lightMap instanceof THREE.Texture ) data.lightMap = this.lightMap.toJSON( meta ).uuid;
  11762. if ( this.bumpMap instanceof THREE.Texture ) {
  11763. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  11764. data.bumpScale = this.bumpScale;
  11765. }
  11766. if ( this.normalMap instanceof THREE.Texture ) {
  11767. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  11768. data.normalScale = this.normalScale.toArray();
  11769. }
  11770. if ( this.displacementMap instanceof THREE.Texture ) {
  11771. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  11772. data.displacementScale = this.displacementScale;
  11773. data.displacementBias = this.displacementBias;
  11774. }
  11775. if ( this.roughnessMap instanceof THREE.Texture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  11776. if ( this.metalnessMap instanceof THREE.Texture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  11777. if ( this.emissiveMap instanceof THREE.Texture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  11778. if ( this.specularMap instanceof THREE.Texture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  11779. if ( this.envMap instanceof THREE.Texture ) {
  11780. data.envMap = this.envMap.toJSON( meta ).uuid;
  11781. data.reflectivity = this.reflectivity; // Scale behind envMap
  11782. }
  11783. if ( this.size !== undefined ) data.size = this.size;
  11784. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  11785. if ( this.vertexColors !== undefined && this.vertexColors !== THREE.NoColors ) data.vertexColors = this.vertexColors;
  11786. if ( this.shading !== undefined && this.shading !== THREE.SmoothShading ) data.shading = this.shading;
  11787. if ( this.blending !== undefined && this.blending !== THREE.NormalBlending ) data.blending = this.blending;
  11788. if ( this.side !== undefined && this.side !== THREE.FrontSide ) data.side = this.side;
  11789. if ( this.opacity < 1 ) data.opacity = this.opacity;
  11790. if ( this.transparent === true ) data.transparent = this.transparent;
  11791. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  11792. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  11793. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  11794. // TODO: Copied from Object3D.toJSON
  11795. function extractFromCache ( cache ) {
  11796. var values = [];
  11797. for ( var key in cache ) {
  11798. var data = cache[ key ];
  11799. delete data.metadata;
  11800. values.push( data );
  11801. }
  11802. return values;
  11803. }
  11804. if ( isRoot ) {
  11805. var textures = extractFromCache( meta.textures );
  11806. var images = extractFromCache( meta.images );
  11807. if ( textures.length > 0 ) data.textures = textures;
  11808. if ( images.length > 0 ) data.images = images;
  11809. }
  11810. return data;
  11811. },
  11812. clone: function () {
  11813. return new this.constructor().copy( this );
  11814. },
  11815. copy: function ( source ) {
  11816. this.name = source.name;
  11817. this.side = source.side;
  11818. this.opacity = source.opacity;
  11819. this.transparent = source.transparent;
  11820. this.blending = source.blending;
  11821. this.blendSrc = source.blendSrc;
  11822. this.blendDst = source.blendDst;
  11823. this.blendEquation = source.blendEquation;
  11824. this.blendSrcAlpha = source.blendSrcAlpha;
  11825. this.blendDstAlpha = source.blendDstAlpha;
  11826. this.blendEquationAlpha = source.blendEquationAlpha;
  11827. this.depthFunc = source.depthFunc;
  11828. this.depthTest = source.depthTest;
  11829. this.depthWrite = source.depthWrite;
  11830. this.precision = source.precision;
  11831. this.polygonOffset = source.polygonOffset;
  11832. this.polygonOffsetFactor = source.polygonOffsetFactor;
  11833. this.polygonOffsetUnits = source.polygonOffsetUnits;
  11834. this.alphaTest = source.alphaTest;
  11835. this.overdraw = source.overdraw;
  11836. this.visible = source.visible;
  11837. return this;
  11838. },
  11839. update: function () {
  11840. this.dispatchEvent( { type: 'update' } );
  11841. },
  11842. dispose: function () {
  11843. this.dispatchEvent( { type: 'dispose' } );
  11844. }
  11845. };
  11846. THREE.EventDispatcher.prototype.apply( THREE.Material.prototype );
  11847. THREE.MaterialIdCount = 0;
  11848. // File:src/materials/LineBasicMaterial.js
  11849. /**
  11850. * @author mrdoob / http://mrdoob.com/
  11851. * @author alteredq / http://alteredqualia.com/
  11852. *
  11853. * parameters = {
  11854. * color: <hex>,
  11855. * opacity: <float>,
  11856. *
  11857. * blending: THREE.NormalBlending,
  11858. * depthTest: <bool>,
  11859. * depthWrite: <bool>,
  11860. *
  11861. * linewidth: <float>,
  11862. * linecap: "round",
  11863. * linejoin: "round",
  11864. *
  11865. * vertexColors: <bool>
  11866. *
  11867. * fog: <bool>
  11868. * }
  11869. */
  11870. THREE.LineBasicMaterial = function ( parameters ) {
  11871. THREE.Material.call( this );
  11872. this.type = 'LineBasicMaterial';
  11873. this.color = new THREE.Color( 0xffffff );
  11874. this.linewidth = 1;
  11875. this.linecap = 'round';
  11876. this.linejoin = 'round';
  11877. this.vertexColors = THREE.NoColors;
  11878. this.fog = true;
  11879. this.setValues( parameters );
  11880. };
  11881. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  11882. THREE.LineBasicMaterial.prototype.constructor = THREE.LineBasicMaterial;
  11883. THREE.LineBasicMaterial.prototype.copy = function ( source ) {
  11884. THREE.Material.prototype.copy.call( this, source );
  11885. this.color.copy( source.color );
  11886. this.linewidth = source.linewidth;
  11887. this.linecap = source.linecap;
  11888. this.linejoin = source.linejoin;
  11889. this.vertexColors = source.vertexColors;
  11890. this.fog = source.fog;
  11891. return this;
  11892. };
  11893. // File:src/materials/LineDashedMaterial.js
  11894. /**
  11895. * @author alteredq / http://alteredqualia.com/
  11896. *
  11897. * parameters = {
  11898. * color: <hex>,
  11899. * opacity: <float>,
  11900. *
  11901. * blending: THREE.NormalBlending,
  11902. * depthTest: <bool>,
  11903. * depthWrite: <bool>,
  11904. *
  11905. * linewidth: <float>,
  11906. *
  11907. * scale: <float>,
  11908. * dashSize: <float>,
  11909. * gapSize: <float>,
  11910. *
  11911. * vertexColors: THREE.NoColors / THREE.FaceColors / THREE.VertexColors
  11912. *
  11913. * fog: <bool>
  11914. * }
  11915. */
  11916. THREE.LineDashedMaterial = function ( parameters ) {
  11917. THREE.Material.call( this );
  11918. this.type = 'LineDashedMaterial';
  11919. this.color = new THREE.Color( 0xffffff );
  11920. this.linewidth = 1;
  11921. this.scale = 1;
  11922. this.dashSize = 3;
  11923. this.gapSize = 1;
  11924. this.vertexColors = THREE.NoColors;
  11925. this.fog = true;
  11926. this.setValues( parameters );
  11927. };
  11928. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  11929. THREE.LineDashedMaterial.prototype.constructor = THREE.LineDashedMaterial;
  11930. THREE.LineDashedMaterial.prototype.copy = function ( source ) {
  11931. THREE.Material.prototype.copy.call( this, source );
  11932. this.color.copy( source.color );
  11933. this.linewidth = source.linewidth;
  11934. this.scale = source.scale;
  11935. this.dashSize = source.dashSize;
  11936. this.gapSize = source.gapSize;
  11937. this.vertexColors = source.vertexColors;
  11938. this.fog = source.fog;
  11939. return this;
  11940. };
  11941. // File:src/materials/MeshBasicMaterial.js
  11942. /**
  11943. * @author mrdoob / http://mrdoob.com/
  11944. * @author alteredq / http://alteredqualia.com/
  11945. *
  11946. * parameters = {
  11947. * color: <hex>,
  11948. * opacity: <float>,
  11949. * map: new THREE.Texture( <Image> ),
  11950. *
  11951. * aoMap: new THREE.Texture( <Image> ),
  11952. * aoMapIntensity: <float>
  11953. *
  11954. * specularMap: new THREE.Texture( <Image> ),
  11955. *
  11956. * alphaMap: new THREE.Texture( <Image> ),
  11957. *
  11958. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  11959. * combine: THREE.Multiply,
  11960. * reflectivity: <float>,
  11961. * refractionRatio: <float>,
  11962. *
  11963. * shading: THREE.SmoothShading,
  11964. * blending: THREE.NormalBlending,
  11965. * depthTest: <bool>,
  11966. * depthWrite: <bool>,
  11967. *
  11968. * wireframe: <boolean>,
  11969. * wireframeLinewidth: <float>,
  11970. *
  11971. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  11972. *
  11973. * skinning: <bool>,
  11974. * morphTargets: <bool>,
  11975. *
  11976. * fog: <bool>
  11977. * }
  11978. */
  11979. THREE.MeshBasicMaterial = function ( parameters ) {
  11980. THREE.Material.call( this );
  11981. this.type = 'MeshBasicMaterial';
  11982. this.color = new THREE.Color( 0xffffff ); // emissive
  11983. this.map = null;
  11984. this.aoMap = null;
  11985. this.aoMapIntensity = 1.0;
  11986. this.specularMap = null;
  11987. this.alphaMap = null;
  11988. this.envMap = null;
  11989. this.combine = THREE.MultiplyOperation;
  11990. this.reflectivity = 1;
  11991. this.refractionRatio = 0.98;
  11992. this.fog = true;
  11993. this.shading = THREE.SmoothShading;
  11994. this.wireframe = false;
  11995. this.wireframeLinewidth = 1;
  11996. this.wireframeLinecap = 'round';
  11997. this.wireframeLinejoin = 'round';
  11998. this.vertexColors = THREE.NoColors;
  11999. this.skinning = false;
  12000. this.morphTargets = false;
  12001. this.setValues( parameters );
  12002. };
  12003. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  12004. THREE.MeshBasicMaterial.prototype.constructor = THREE.MeshBasicMaterial;
  12005. THREE.MeshBasicMaterial.prototype.copy = function ( source ) {
  12006. THREE.Material.prototype.copy.call( this, source );
  12007. this.color.copy( source.color );
  12008. this.map = source.map;
  12009. this.aoMap = source.aoMap;
  12010. this.aoMapIntensity = source.aoMapIntensity;
  12011. this.specularMap = source.specularMap;
  12012. this.alphaMap = source.alphaMap;
  12013. this.envMap = source.envMap;
  12014. this.combine = source.combine;
  12015. this.reflectivity = source.reflectivity;
  12016. this.refractionRatio = source.refractionRatio;
  12017. this.fog = source.fog;
  12018. this.shading = source.shading;
  12019. this.wireframe = source.wireframe;
  12020. this.wireframeLinewidth = source.wireframeLinewidth;
  12021. this.wireframeLinecap = source.wireframeLinecap;
  12022. this.wireframeLinejoin = source.wireframeLinejoin;
  12023. this.vertexColors = source.vertexColors;
  12024. this.skinning = source.skinning;
  12025. this.morphTargets = source.morphTargets;
  12026. return this;
  12027. };
  12028. // File:src/materials/MeshLambertMaterial.js
  12029. /**
  12030. * @author mrdoob / http://mrdoob.com/
  12031. * @author alteredq / http://alteredqualia.com/
  12032. *
  12033. * parameters = {
  12034. * color: <hex>,
  12035. * emissive: <hex>,
  12036. * opacity: <float>,
  12037. *
  12038. * map: new THREE.Texture( <Image> ),
  12039. *
  12040. * specularMap: new THREE.Texture( <Image> ),
  12041. *
  12042. * alphaMap: new THREE.Texture( <Image> ),
  12043. *
  12044. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  12045. * combine: THREE.Multiply,
  12046. * reflectivity: <float>,
  12047. * refractionRatio: <float>,
  12048. *
  12049. * blending: THREE.NormalBlending,
  12050. * depthTest: <bool>,
  12051. * depthWrite: <bool>,
  12052. *
  12053. * wireframe: <boolean>,
  12054. * wireframeLinewidth: <float>,
  12055. *
  12056. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  12057. *
  12058. * skinning: <bool>,
  12059. * morphTargets: <bool>,
  12060. * morphNormals: <bool>,
  12061. *
  12062. * fog: <bool>
  12063. * }
  12064. */
  12065. THREE.MeshLambertMaterial = function ( parameters ) {
  12066. THREE.Material.call( this );
  12067. this.type = 'MeshLambertMaterial';
  12068. this.color = new THREE.Color( 0xffffff ); // diffuse
  12069. this.emissive = new THREE.Color( 0x000000 );
  12070. this.map = null;
  12071. this.specularMap = null;
  12072. this.alphaMap = null;
  12073. this.envMap = null;
  12074. this.combine = THREE.MultiplyOperation;
  12075. this.reflectivity = 1;
  12076. this.refractionRatio = 0.98;
  12077. this.fog = true;
  12078. this.wireframe = false;
  12079. this.wireframeLinewidth = 1;
  12080. this.wireframeLinecap = 'round';
  12081. this.wireframeLinejoin = 'round';
  12082. this.vertexColors = THREE.NoColors;
  12083. this.skinning = false;
  12084. this.morphTargets = false;
  12085. this.morphNormals = false;
  12086. this.setValues( parameters );
  12087. };
  12088. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  12089. THREE.MeshLambertMaterial.prototype.constructor = THREE.MeshLambertMaterial;
  12090. THREE.MeshLambertMaterial.prototype.copy = function ( source ) {
  12091. THREE.Material.prototype.copy.call( this, source );
  12092. this.color.copy( source.color );
  12093. this.emissive.copy( source.emissive );
  12094. this.map = source.map;
  12095. this.specularMap = source.specularMap;
  12096. this.alphaMap = source.alphaMap;
  12097. this.envMap = source.envMap;
  12098. this.combine = source.combine;
  12099. this.reflectivity = source.reflectivity;
  12100. this.refractionRatio = source.refractionRatio;
  12101. this.fog = source.fog;
  12102. this.wireframe = source.wireframe;
  12103. this.wireframeLinewidth = source.wireframeLinewidth;
  12104. this.wireframeLinecap = source.wireframeLinecap;
  12105. this.wireframeLinejoin = source.wireframeLinejoin;
  12106. this.vertexColors = source.vertexColors;
  12107. this.skinning = source.skinning;
  12108. this.morphTargets = source.morphTargets;
  12109. this.morphNormals = source.morphNormals;
  12110. return this;
  12111. };
  12112. // File:src/materials/MeshPhongMaterial.js
  12113. /**
  12114. * @author mrdoob / http://mrdoob.com/
  12115. * @author alteredq / http://alteredqualia.com/
  12116. *
  12117. * parameters = {
  12118. * color: <hex>,
  12119. * emissive: <hex>,
  12120. * specular: <hex>,
  12121. * shininess: <float>,
  12122. * opacity: <float>,
  12123. *
  12124. * map: new THREE.Texture( <Image> ),
  12125. *
  12126. * lightMap: new THREE.Texture( <Image> ),
  12127. * lightMapIntensity: <float>
  12128. *
  12129. * aoMap: new THREE.Texture( <Image> ),
  12130. * aoMapIntensity: <float>
  12131. *
  12132. * emissiveMap: new THREE.Texture( <Image> ),
  12133. *
  12134. * bumpMap: new THREE.Texture( <Image> ),
  12135. * bumpScale: <float>,
  12136. *
  12137. * normalMap: new THREE.Texture( <Image> ),
  12138. * normalScale: <Vector2>,
  12139. *
  12140. * displacementMap: new THREE.Texture( <Image> ),
  12141. * displacementScale: <float>,
  12142. * displacementBias: <float>,
  12143. *
  12144. * specularMap: new THREE.Texture( <Image> ),
  12145. *
  12146. * alphaMap: new THREE.Texture( <Image> ),
  12147. *
  12148. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  12149. * combine: THREE.Multiply,
  12150. * reflectivity: <float>,
  12151. * refractionRatio: <float>,
  12152. *
  12153. * shading: THREE.SmoothShading,
  12154. * blending: THREE.NormalBlending,
  12155. * depthTest: <bool>,
  12156. * depthWrite: <bool>,
  12157. *
  12158. * wireframe: <boolean>,
  12159. * wireframeLinewidth: <float>,
  12160. *
  12161. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  12162. *
  12163. * skinning: <bool>,
  12164. * morphTargets: <bool>,
  12165. * morphNormals: <bool>,
  12166. *
  12167. * fog: <bool>
  12168. * }
  12169. */
  12170. THREE.MeshPhongMaterial = function ( parameters ) {
  12171. THREE.Material.call( this );
  12172. this.type = 'MeshPhongMaterial';
  12173. this.color = new THREE.Color( 0xffffff ); // diffuse
  12174. this.emissive = new THREE.Color( 0x000000 );
  12175. this.specular = new THREE.Color( 0x111111 );
  12176. this.shininess = 30;
  12177. this.map = null;
  12178. this.lightMap = null;
  12179. this.lightMapIntensity = 1.0;
  12180. this.aoMap = null;
  12181. this.aoMapIntensity = 1.0;
  12182. this.emissiveMap = null;
  12183. this.bumpMap = null;
  12184. this.bumpScale = 1;
  12185. this.normalMap = null;
  12186. this.normalScale = new THREE.Vector2( 1, 1 );
  12187. this.displacementMap = null;
  12188. this.displacementScale = 1;
  12189. this.displacementBias = 0;
  12190. this.specularMap = null;
  12191. this.alphaMap = null;
  12192. this.envMap = null;
  12193. this.combine = THREE.MultiplyOperation;
  12194. this.reflectivity = 1;
  12195. this.refractionRatio = 0.98;
  12196. this.fog = true;
  12197. this.shading = THREE.SmoothShading;
  12198. this.wireframe = false;
  12199. this.wireframeLinewidth = 1;
  12200. this.wireframeLinecap = 'round';
  12201. this.wireframeLinejoin = 'round';
  12202. this.vertexColors = THREE.NoColors;
  12203. this.skinning = false;
  12204. this.morphTargets = false;
  12205. this.morphNormals = false;
  12206. this.setValues( parameters );
  12207. };
  12208. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  12209. THREE.MeshPhongMaterial.prototype.constructor = THREE.MeshPhongMaterial;
  12210. THREE.MeshPhongMaterial.prototype.copy = function ( source ) {
  12211. THREE.Material.prototype.copy.call( this, source );
  12212. this.color.copy( source.color );
  12213. this.emissive.copy( source.emissive );
  12214. this.specular.copy( source.specular );
  12215. this.shininess = source.shininess;
  12216. this.map = source.map;
  12217. this.lightMap = source.lightMap;
  12218. this.lightMapIntensity = source.lightMapIntensity;
  12219. this.aoMap = source.aoMap;
  12220. this.aoMapIntensity = source.aoMapIntensity;
  12221. this.emissiveMap = source.emissiveMap;
  12222. this.bumpMap = source.bumpMap;
  12223. this.bumpScale = source.bumpScale;
  12224. this.normalMap = source.normalMap;
  12225. this.normalScale.copy( source.normalScale );
  12226. this.displacementMap = source.displacementMap;
  12227. this.displacementScale = source.displacementScale;
  12228. this.displacementBias = source.displacementBias;
  12229. this.specularMap = source.specularMap;
  12230. this.alphaMap = source.alphaMap;
  12231. this.envMap = source.envMap;
  12232. this.combine = source.combine;
  12233. this.reflectivity = source.reflectivity;
  12234. this.refractionRatio = source.refractionRatio;
  12235. this.fog = source.fog;
  12236. this.shading = source.shading;
  12237. this.wireframe = source.wireframe;
  12238. this.wireframeLinewidth = source.wireframeLinewidth;
  12239. this.wireframeLinecap = source.wireframeLinecap;
  12240. this.wireframeLinejoin = source.wireframeLinejoin;
  12241. this.vertexColors = source.vertexColors;
  12242. this.skinning = source.skinning;
  12243. this.morphTargets = source.morphTargets;
  12244. this.morphNormals = source.morphNormals;
  12245. return this;
  12246. };
  12247. // File:src/materials/MeshStandardMaterial.js
  12248. /**
  12249. * @author WestLangley / http://github.com/WestLangley
  12250. *
  12251. * parameters = {
  12252. * color: <hex>,
  12253. * roughness: <float>,
  12254. * metalness: <float>,
  12255. * emissive: <hex>,
  12256. * opacity: <float>,
  12257. *
  12258. * map: new THREE.Texture( <Image> ),
  12259. *
  12260. * lightMap: new THREE.Texture( <Image> ),
  12261. * lightMapIntensity: <float>
  12262. *
  12263. * aoMap: new THREE.Texture( <Image> ),
  12264. * aoMapIntensity: <float>
  12265. *
  12266. * emissiveMap: new THREE.Texture( <Image> ),
  12267. *
  12268. * bumpMap: new THREE.Texture( <Image> ),
  12269. * bumpScale: <float>,
  12270. *
  12271. * normalMap: new THREE.Texture( <Image> ),
  12272. * normalScale: <Vector2>,
  12273. *
  12274. * displacementMap: new THREE.Texture( <Image> ),
  12275. * displacementScale: <float>,
  12276. * displacementBias: <float>,
  12277. *
  12278. * roughnessMap: new THREE.Texture( <Image> ),
  12279. *
  12280. * metalnessMap: new THREE.Texture( <Image> ),
  12281. *
  12282. * alphaMap: new THREE.Texture( <Image> ),
  12283. *
  12284. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  12285. * envMapIntensity: <float>
  12286. *
  12287. * refractionRatio: <float>,
  12288. *
  12289. * shading: THREE.SmoothShading,
  12290. * blending: THREE.NormalBlending,
  12291. * depthTest: <bool>,
  12292. * depthWrite: <bool>,
  12293. *
  12294. * wireframe: <boolean>,
  12295. * wireframeLinewidth: <float>,
  12296. *
  12297. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  12298. *
  12299. * skinning: <bool>,
  12300. * morphTargets: <bool>,
  12301. * morphNormals: <bool>,
  12302. *
  12303. * fog: <bool>
  12304. * }
  12305. */
  12306. THREE.MeshStandardMaterial = function ( parameters ) {
  12307. THREE.Material.call( this );
  12308. this.type = 'MeshStandardMaterial';
  12309. this.color = new THREE.Color( 0xffffff ); // diffuse
  12310. this.roughness = 0.5;
  12311. this.metalness = 0.5;
  12312. this.emissive = new THREE.Color( 0x000000 );
  12313. this.map = null;
  12314. this.lightMap = null;
  12315. this.lightMapIntensity = 1.0;
  12316. this.aoMap = null;
  12317. this.aoMapIntensity = 1.0;
  12318. this.emissiveMap = null;
  12319. this.bumpMap = null;
  12320. this.bumpScale = 1;
  12321. this.normalMap = null;
  12322. this.normalScale = new THREE.Vector2( 1, 1 );
  12323. this.displacementMap = null;
  12324. this.displacementScale = 1;
  12325. this.displacementBias = 0;
  12326. this.roughnessMap = null;
  12327. this.metalnessMap = null;
  12328. this.alphaMap = null;
  12329. this.envMap = null;
  12330. this.envMapIntensity = 1.0;
  12331. this.refractionRatio = 0.98;
  12332. this.fog = true;
  12333. this.shading = THREE.SmoothShading;
  12334. this.wireframe = false;
  12335. this.wireframeLinewidth = 1;
  12336. this.wireframeLinecap = 'round';
  12337. this.wireframeLinejoin = 'round';
  12338. this.vertexColors = THREE.NoColors;
  12339. this.skinning = false;
  12340. this.morphTargets = false;
  12341. this.morphNormals = false;
  12342. this.setValues( parameters );
  12343. };
  12344. THREE.MeshStandardMaterial.prototype = Object.create( THREE.Material.prototype );
  12345. THREE.MeshStandardMaterial.prototype.constructor = THREE.MeshStandardMaterial;
  12346. THREE.MeshStandardMaterial.prototype.copy = function ( source ) {
  12347. THREE.Material.prototype.copy.call( this, source );
  12348. this.color.copy( source.color );
  12349. this.roughness = source.roughness;
  12350. this.metalness = source.metalness;
  12351. this.emissive.copy( source.emissive );
  12352. this.map = source.map;
  12353. this.lightMap = source.lightMap;
  12354. this.lightMapIntensity = source.lightMapIntensity;
  12355. this.aoMap = source.aoMap;
  12356. this.aoMapIntensity = source.aoMapIntensity;
  12357. this.emissiveMap = source.emissiveMap;
  12358. this.bumpMap = source.bumpMap;
  12359. this.bumpScale = source.bumpScale;
  12360. this.normalMap = source.normalMap;
  12361. this.normalScale.copy( source.normalScale );
  12362. this.displacementMap = source.displacementMap;
  12363. this.displacementScale = source.displacementScale;
  12364. this.displacementBias = source.displacementBias;
  12365. this.roughnessMap = source.roughnessMap;
  12366. this.metalnessMap = source.metalnessMap;
  12367. this.alphaMap = source.alphaMap;
  12368. this.envMap = source.envMap;
  12369. this.envMapIntensity = source.envMapIntensity;
  12370. this.refractionRatio = source.refractionRatio;
  12371. this.fog = source.fog;
  12372. this.shading = source.shading;
  12373. this.wireframe = source.wireframe;
  12374. this.wireframeLinewidth = source.wireframeLinewidth;
  12375. this.wireframeLinecap = source.wireframeLinecap;
  12376. this.wireframeLinejoin = source.wireframeLinejoin;
  12377. this.vertexColors = source.vertexColors;
  12378. this.skinning = source.skinning;
  12379. this.morphTargets = source.morphTargets;
  12380. this.morphNormals = source.morphNormals;
  12381. return this;
  12382. };
  12383. // File:src/materials/MeshDepthMaterial.js
  12384. /**
  12385. * @author mrdoob / http://mrdoob.com/
  12386. * @author alteredq / http://alteredqualia.com/
  12387. *
  12388. * parameters = {
  12389. * opacity: <float>,
  12390. *
  12391. * blending: THREE.NormalBlending,
  12392. * depthTest: <bool>,
  12393. * depthWrite: <bool>,
  12394. *
  12395. * wireframe: <boolean>,
  12396. * wireframeLinewidth: <float>
  12397. * }
  12398. */
  12399. THREE.MeshDepthMaterial = function ( parameters ) {
  12400. THREE.Material.call( this );
  12401. this.type = 'MeshDepthMaterial';
  12402. this.morphTargets = false;
  12403. this.wireframe = false;
  12404. this.wireframeLinewidth = 1;
  12405. this.setValues( parameters );
  12406. };
  12407. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  12408. THREE.MeshDepthMaterial.prototype.constructor = THREE.MeshDepthMaterial;
  12409. THREE.MeshDepthMaterial.prototype.copy = function ( source ) {
  12410. THREE.Material.prototype.copy.call( this, source );
  12411. this.wireframe = source.wireframe;
  12412. this.wireframeLinewidth = source.wireframeLinewidth;
  12413. return this;
  12414. };
  12415. // File:src/materials/MeshNormalMaterial.js
  12416. /**
  12417. * @author mrdoob / http://mrdoob.com/
  12418. *
  12419. * parameters = {
  12420. * opacity: <float>,
  12421. *
  12422. * shading: THREE.FlatShading,
  12423. * blending: THREE.NormalBlending,
  12424. * depthTest: <bool>,
  12425. * depthWrite: <bool>,
  12426. *
  12427. * wireframe: <boolean>,
  12428. * wireframeLinewidth: <float>
  12429. * }
  12430. */
  12431. THREE.MeshNormalMaterial = function ( parameters ) {
  12432. THREE.Material.call( this, parameters );
  12433. this.type = 'MeshNormalMaterial';
  12434. this.wireframe = false;
  12435. this.wireframeLinewidth = 1;
  12436. this.morphTargets = false;
  12437. this.setValues( parameters );
  12438. };
  12439. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  12440. THREE.MeshNormalMaterial.prototype.constructor = THREE.MeshNormalMaterial;
  12441. THREE.MeshNormalMaterial.prototype.copy = function ( source ) {
  12442. THREE.Material.prototype.copy.call( this, source );
  12443. this.wireframe = source.wireframe;
  12444. this.wireframeLinewidth = source.wireframeLinewidth;
  12445. return this;
  12446. };
  12447. // File:src/materials/MultiMaterial.js
  12448. /**
  12449. * @author mrdoob / http://mrdoob.com/
  12450. */
  12451. THREE.MultiMaterial = function ( materials ) {
  12452. this.uuid = THREE.Math.generateUUID();
  12453. this.type = 'MultiMaterial';
  12454. this.materials = materials instanceof Array ? materials : [];
  12455. this.visible = true;
  12456. };
  12457. THREE.MultiMaterial.prototype = {
  12458. constructor: THREE.MultiMaterial,
  12459. toJSON: function ( meta ) {
  12460. var output = {
  12461. metadata: {
  12462. version: 4.2,
  12463. type: 'material',
  12464. generator: 'MaterialExporter'
  12465. },
  12466. uuid: this.uuid,
  12467. type: this.type,
  12468. materials: []
  12469. };
  12470. var materials = this.materials;
  12471. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  12472. var material = materials[ i ].toJSON( meta );
  12473. delete material.metadata;
  12474. output.materials.push( material );
  12475. }
  12476. output.visible = this.visible;
  12477. return output;
  12478. },
  12479. clone: function () {
  12480. var material = new this.constructor();
  12481. for ( var i = 0; i < this.materials.length; i ++ ) {
  12482. material.materials.push( this.materials[ i ].clone() );
  12483. }
  12484. material.visible = this.visible;
  12485. return material;
  12486. }
  12487. };
  12488. // File:src/materials/PointsMaterial.js
  12489. /**
  12490. * @author mrdoob / http://mrdoob.com/
  12491. * @author alteredq / http://alteredqualia.com/
  12492. *
  12493. * parameters = {
  12494. * color: <hex>,
  12495. * opacity: <float>,
  12496. * map: new THREE.Texture( <Image> ),
  12497. *
  12498. * size: <float>,
  12499. * sizeAttenuation: <bool>,
  12500. *
  12501. * blending: THREE.NormalBlending,
  12502. * depthTest: <bool>,
  12503. * depthWrite: <bool>,
  12504. *
  12505. * vertexColors: <bool>,
  12506. *
  12507. * fog: <bool>
  12508. * }
  12509. */
  12510. THREE.PointsMaterial = function ( parameters ) {
  12511. THREE.Material.call( this );
  12512. this.type = 'PointsMaterial';
  12513. this.color = new THREE.Color( 0xffffff );
  12514. this.map = null;
  12515. this.size = 1;
  12516. this.sizeAttenuation = true;
  12517. this.vertexColors = THREE.NoColors;
  12518. this.fog = true;
  12519. this.setValues( parameters );
  12520. };
  12521. THREE.PointsMaterial.prototype = Object.create( THREE.Material.prototype );
  12522. THREE.PointsMaterial.prototype.constructor = THREE.PointsMaterial;
  12523. THREE.PointsMaterial.prototype.copy = function ( source ) {
  12524. THREE.Material.prototype.copy.call( this, source );
  12525. this.color.copy( source.color );
  12526. this.map = source.map;
  12527. this.size = source.size;
  12528. this.sizeAttenuation = source.sizeAttenuation;
  12529. this.vertexColors = source.vertexColors;
  12530. this.fog = source.fog;
  12531. return this;
  12532. };
  12533. // File:src/materials/ShaderMaterial.js
  12534. /**
  12535. * @author alteredq / http://alteredqualia.com/
  12536. *
  12537. * parameters = {
  12538. * defines: { "label" : "value" },
  12539. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  12540. *
  12541. * fragmentShader: <string>,
  12542. * vertexShader: <string>,
  12543. *
  12544. * shading: THREE.SmoothShading,
  12545. * blending: THREE.NormalBlending,
  12546. * depthTest: <bool>,
  12547. * depthWrite: <bool>,
  12548. *
  12549. * wireframe: <boolean>,
  12550. * wireframeLinewidth: <float>,
  12551. *
  12552. * lights: <bool>,
  12553. *
  12554. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  12555. *
  12556. * skinning: <bool>,
  12557. * morphTargets: <bool>,
  12558. * morphNormals: <bool>,
  12559. *
  12560. * fog: <bool>
  12561. * }
  12562. */
  12563. THREE.ShaderMaterial = function ( parameters ) {
  12564. THREE.Material.call( this );
  12565. this.type = 'ShaderMaterial';
  12566. this.defines = {};
  12567. this.uniforms = {};
  12568. this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}';
  12569. this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}';
  12570. this.shading = THREE.SmoothShading;
  12571. this.linewidth = 1;
  12572. this.wireframe = false;
  12573. this.wireframeLinewidth = 1;
  12574. this.fog = false; // set to use scene fog
  12575. this.lights = false; // set to use scene lights
  12576. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  12577. this.skinning = false; // set to use skinning attribute streams
  12578. this.morphTargets = false; // set to use morph targets
  12579. this.morphNormals = false; // set to use morph normals
  12580. this.extensions = {
  12581. derivatives: false, // set to use derivatives
  12582. fragDepth: false, // set to use fragment depth values
  12583. drawBuffers: false, // set to use draw buffers
  12584. shaderTextureLOD: false // set to use shader texture LOD
  12585. };
  12586. // When rendered geometry doesn't include these attributes but the material does,
  12587. // use these default values in WebGL. This avoids errors when buffer data is missing.
  12588. this.defaultAttributeValues = {
  12589. 'color': [ 1, 1, 1 ],
  12590. 'uv': [ 0, 0 ],
  12591. 'uv2': [ 0, 0 ]
  12592. };
  12593. this.index0AttributeName = undefined;
  12594. if ( parameters !== undefined ) {
  12595. if ( parameters.attributes !== undefined ) {
  12596. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  12597. }
  12598. this.setValues( parameters );
  12599. }
  12600. };
  12601. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  12602. THREE.ShaderMaterial.prototype.constructor = THREE.ShaderMaterial;
  12603. THREE.ShaderMaterial.prototype.copy = function ( source ) {
  12604. THREE.Material.prototype.copy.call( this, source );
  12605. this.fragmentShader = source.fragmentShader;
  12606. this.vertexShader = source.vertexShader;
  12607. this.uniforms = THREE.UniformsUtils.clone( source.uniforms );
  12608. this.defines = source.defines;
  12609. this.shading = source.shading;
  12610. this.wireframe = source.wireframe;
  12611. this.wireframeLinewidth = source.wireframeLinewidth;
  12612. this.fog = source.fog;
  12613. this.lights = source.lights;
  12614. this.vertexColors = source.vertexColors;
  12615. this.skinning = source.skinning;
  12616. this.morphTargets = source.morphTargets;
  12617. this.morphNormals = source.morphNormals;
  12618. this.extensions = source.extensions;
  12619. return this;
  12620. };
  12621. THREE.ShaderMaterial.prototype.toJSON = function ( meta ) {
  12622. var data = THREE.Material.prototype.toJSON.call( this, meta );
  12623. data.uniforms = this.uniforms;
  12624. data.vertexShader = this.vertexShader;
  12625. data.fragmentShader = this.fragmentShader;
  12626. return data;
  12627. };
  12628. // File:src/materials/RawShaderMaterial.js
  12629. /**
  12630. * @author mrdoob / http://mrdoob.com/
  12631. */
  12632. THREE.RawShaderMaterial = function ( parameters ) {
  12633. THREE.ShaderMaterial.call( this, parameters );
  12634. this.type = 'RawShaderMaterial';
  12635. };
  12636. THREE.RawShaderMaterial.prototype = Object.create( THREE.ShaderMaterial.prototype );
  12637. THREE.RawShaderMaterial.prototype.constructor = THREE.RawShaderMaterial;
  12638. // File:src/materials/SpriteMaterial.js
  12639. /**
  12640. * @author alteredq / http://alteredqualia.com/
  12641. *
  12642. * parameters = {
  12643. * color: <hex>,
  12644. * opacity: <float>,
  12645. * map: new THREE.Texture( <Image> ),
  12646. *
  12647. * blending: THREE.NormalBlending,
  12648. * depthTest: <bool>,
  12649. * depthWrite: <bool>,
  12650. *
  12651. * uvOffset: new THREE.Vector2(),
  12652. * uvScale: new THREE.Vector2(),
  12653. *
  12654. * fog: <bool>
  12655. * }
  12656. */
  12657. THREE.SpriteMaterial = function ( parameters ) {
  12658. THREE.Material.call( this );
  12659. this.type = 'SpriteMaterial';
  12660. this.color = new THREE.Color( 0xffffff );
  12661. this.map = null;
  12662. this.rotation = 0;
  12663. this.fog = false;
  12664. // set parameters
  12665. this.setValues( parameters );
  12666. };
  12667. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  12668. THREE.SpriteMaterial.prototype.constructor = THREE.SpriteMaterial;
  12669. THREE.SpriteMaterial.prototype.copy = function ( source ) {
  12670. THREE.Material.prototype.copy.call( this, source );
  12671. this.color.copy( source.color );
  12672. this.map = source.map;
  12673. this.rotation = source.rotation;
  12674. this.fog = source.fog;
  12675. return this;
  12676. };
  12677. // File:src/textures/Texture.js
  12678. /**
  12679. * @author mrdoob / http://mrdoob.com/
  12680. * @author alteredq / http://alteredqualia.com/
  12681. * @author szimek / https://github.com/szimek/
  12682. */
  12683. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  12684. Object.defineProperty( this, 'id', { value: THREE.TextureIdCount ++ } );
  12685. this.uuid = THREE.Math.generateUUID();
  12686. this.name = '';
  12687. this.sourceFile = '';
  12688. this.image = image !== undefined ? image : THREE.Texture.DEFAULT_IMAGE;
  12689. this.mipmaps = [];
  12690. this.mapping = mapping !== undefined ? mapping : THREE.Texture.DEFAULT_MAPPING;
  12691. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  12692. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  12693. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  12694. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  12695. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  12696. this.format = format !== undefined ? format : THREE.RGBAFormat;
  12697. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  12698. this.offset = new THREE.Vector2( 0, 0 );
  12699. this.repeat = new THREE.Vector2( 1, 1 );
  12700. this.generateMipmaps = true;
  12701. this.premultiplyAlpha = false;
  12702. this.flipY = true;
  12703. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  12704. this.version = 0;
  12705. this.onUpdate = null;
  12706. };
  12707. THREE.Texture.DEFAULT_IMAGE = undefined;
  12708. THREE.Texture.DEFAULT_MAPPING = THREE.UVMapping;
  12709. THREE.Texture.prototype = {
  12710. constructor: THREE.Texture,
  12711. set needsUpdate ( value ) {
  12712. if ( value === true ) this.version ++;
  12713. },
  12714. clone: function () {
  12715. return new this.constructor().copy( this );
  12716. },
  12717. copy: function ( source ) {
  12718. this.image = source.image;
  12719. this.mipmaps = source.mipmaps.slice( 0 );
  12720. this.mapping = source.mapping;
  12721. this.wrapS = source.wrapS;
  12722. this.wrapT = source.wrapT;
  12723. this.magFilter = source.magFilter;
  12724. this.minFilter = source.minFilter;
  12725. this.anisotropy = source.anisotropy;
  12726. this.format = source.format;
  12727. this.type = source.type;
  12728. this.offset.copy( source.offset );
  12729. this.repeat.copy( source.repeat );
  12730. this.generateMipmaps = source.generateMipmaps;
  12731. this.premultiplyAlpha = source.premultiplyAlpha;
  12732. this.flipY = source.flipY;
  12733. this.unpackAlignment = source.unpackAlignment;
  12734. return this;
  12735. },
  12736. toJSON: function ( meta ) {
  12737. if ( meta.textures[ this.uuid ] !== undefined ) {
  12738. return meta.textures[ this.uuid ];
  12739. }
  12740. function getDataURL( image ) {
  12741. var canvas;
  12742. if ( image.toDataURL !== undefined ) {
  12743. canvas = image;
  12744. } else {
  12745. canvas = document.createElement( 'canvas' );
  12746. canvas.width = image.width;
  12747. canvas.height = image.height;
  12748. canvas.getContext( '2d' ).drawImage( image, 0, 0, image.width, image.height );
  12749. }
  12750. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  12751. return canvas.toDataURL( 'image/jpeg', 0.6 );
  12752. } else {
  12753. return canvas.toDataURL( 'image/png' );
  12754. }
  12755. }
  12756. var output = {
  12757. metadata: {
  12758. version: 4.4,
  12759. type: 'Texture',
  12760. generator: 'Texture.toJSON'
  12761. },
  12762. uuid: this.uuid,
  12763. name: this.name,
  12764. mapping: this.mapping,
  12765. repeat: [ this.repeat.x, this.repeat.y ],
  12766. offset: [ this.offset.x, this.offset.y ],
  12767. wrap: [ this.wrapS, this.wrapT ],
  12768. minFilter: this.minFilter,
  12769. magFilter: this.magFilter,
  12770. anisotropy: this.anisotropy
  12771. };
  12772. if ( this.image !== undefined ) {
  12773. // TODO: Move to THREE.Image
  12774. var image = this.image;
  12775. if ( image.uuid === undefined ) {
  12776. image.uuid = THREE.Math.generateUUID(); // UGH
  12777. }
  12778. if ( meta.images[ image.uuid ] === undefined ) {
  12779. meta.images[ image.uuid ] = {
  12780. uuid: image.uuid,
  12781. url: getDataURL( image )
  12782. };
  12783. }
  12784. output.image = image.uuid;
  12785. }
  12786. meta.textures[ this.uuid ] = output;
  12787. return output;
  12788. },
  12789. dispose: function () {
  12790. this.dispatchEvent( { type: 'dispose' } );
  12791. },
  12792. transformUv: function ( uv ) {
  12793. if ( this.mapping !== THREE.UVMapping ) return;
  12794. uv.multiply( this.repeat );
  12795. uv.add( this.offset );
  12796. if ( uv.x < 0 || uv.x > 1 ) {
  12797. switch ( this.wrapS ) {
  12798. case THREE.RepeatWrapping:
  12799. uv.x = uv.x - Math.floor( uv.x );
  12800. break;
  12801. case THREE.ClampToEdgeWrapping:
  12802. uv.x = uv.x < 0 ? 0 : 1;
  12803. break;
  12804. case THREE.MirroredRepeatWrapping:
  12805. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  12806. uv.x = Math.ceil( uv.x ) - uv.x;
  12807. } else {
  12808. uv.x = uv.x - Math.floor( uv.x );
  12809. }
  12810. break;
  12811. }
  12812. }
  12813. if ( uv.y < 0 || uv.y > 1 ) {
  12814. switch ( this.wrapT ) {
  12815. case THREE.RepeatWrapping:
  12816. uv.y = uv.y - Math.floor( uv.y );
  12817. break;
  12818. case THREE.ClampToEdgeWrapping:
  12819. uv.y = uv.y < 0 ? 0 : 1;
  12820. break;
  12821. case THREE.MirroredRepeatWrapping:
  12822. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  12823. uv.y = Math.ceil( uv.y ) - uv.y;
  12824. } else {
  12825. uv.y = uv.y - Math.floor( uv.y );
  12826. }
  12827. break;
  12828. }
  12829. }
  12830. if ( this.flipY ) {
  12831. uv.y = 1 - uv.y;
  12832. }
  12833. }
  12834. };
  12835. THREE.EventDispatcher.prototype.apply( THREE.Texture.prototype );
  12836. THREE.TextureIdCount = 0;
  12837. // File:src/textures/CanvasTexture.js
  12838. /**
  12839. * @author mrdoob / http://mrdoob.com/
  12840. */
  12841. THREE.CanvasTexture = function ( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  12842. THREE.Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  12843. this.needsUpdate = true;
  12844. };
  12845. THREE.CanvasTexture.prototype = Object.create( THREE.Texture.prototype );
  12846. THREE.CanvasTexture.prototype.constructor = THREE.CanvasTexture;
  12847. // File:src/textures/CubeTexture.js
  12848. /**
  12849. * @author mrdoob / http://mrdoob.com/
  12850. */
  12851. THREE.CubeTexture = function ( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  12852. mapping = mapping !== undefined ? mapping : THREE.CubeReflectionMapping;
  12853. THREE.Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  12854. this.images = images;
  12855. this.flipY = false;
  12856. };
  12857. THREE.CubeTexture.prototype = Object.create( THREE.Texture.prototype );
  12858. THREE.CubeTexture.prototype.constructor = THREE.CubeTexture;
  12859. THREE.CubeTexture.prototype.copy = function ( source ) {
  12860. THREE.Texture.prototype.copy.call( this, source );
  12861. this.images = source.images;
  12862. return this;
  12863. };
  12864. // File:src/textures/CompressedTexture.js
  12865. /**
  12866. * @author alteredq / http://alteredqualia.com/
  12867. */
  12868. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  12869. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  12870. this.image = { width: width, height: height };
  12871. this.mipmaps = mipmaps;
  12872. // no flipping for cube textures
  12873. // (also flipping doesn't work for compressed textures )
  12874. this.flipY = false;
  12875. // can't generate mipmaps for compressed textures
  12876. // mips must be embedded in DDS files
  12877. this.generateMipmaps = false;
  12878. };
  12879. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  12880. THREE.CompressedTexture.prototype.constructor = THREE.CompressedTexture;
  12881. // File:src/textures/DataTexture.js
  12882. /**
  12883. * @author alteredq / http://alteredqualia.com/
  12884. */
  12885. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  12886. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  12887. this.image = { data: data, width: width, height: height };
  12888. this.magFilter = magFilter !== undefined ? magFilter : THREE.NearestFilter;
  12889. this.minFilter = minFilter !== undefined ? minFilter : THREE.NearestFilter;
  12890. this.flipY = false;
  12891. this.generateMipmaps = false;
  12892. };
  12893. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  12894. THREE.DataTexture.prototype.constructor = THREE.DataTexture;
  12895. // File:src/textures/VideoTexture.js
  12896. /**
  12897. * @author mrdoob / http://mrdoob.com/
  12898. */
  12899. THREE.VideoTexture = function ( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  12900. THREE.Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  12901. this.generateMipmaps = false;
  12902. var scope = this;
  12903. function update() {
  12904. requestAnimationFrame( update );
  12905. if ( video.readyState === video.HAVE_ENOUGH_DATA ) {
  12906. scope.needsUpdate = true;
  12907. }
  12908. }
  12909. update();
  12910. };
  12911. THREE.VideoTexture.prototype = Object.create( THREE.Texture.prototype );
  12912. THREE.VideoTexture.prototype.constructor = THREE.VideoTexture;
  12913. // File:src/objects/Group.js
  12914. /**
  12915. * @author mrdoob / http://mrdoob.com/
  12916. */
  12917. THREE.Group = function () {
  12918. THREE.Object3D.call( this );
  12919. this.type = 'Group';
  12920. };
  12921. THREE.Group.prototype = Object.create( THREE.Object3D.prototype );
  12922. THREE.Group.prototype.constructor = THREE.Group;
  12923. // File:src/objects/Points.js
  12924. /**
  12925. * @author alteredq / http://alteredqualia.com/
  12926. */
  12927. THREE.Points = function ( geometry, material ) {
  12928. THREE.Object3D.call( this );
  12929. this.type = 'Points';
  12930. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  12931. this.material = material !== undefined ? material : new THREE.PointsMaterial( { color: Math.random() * 0xffffff } );
  12932. };
  12933. THREE.Points.prototype = Object.create( THREE.Object3D.prototype );
  12934. THREE.Points.prototype.constructor = THREE.Points;
  12935. THREE.Points.prototype.raycast = ( function () {
  12936. var inverseMatrix = new THREE.Matrix4();
  12937. var ray = new THREE.Ray();
  12938. var sphere = new THREE.Sphere();
  12939. return function raycast( raycaster, intersects ) {
  12940. var object = this;
  12941. var geometry = this.geometry;
  12942. var matrixWorld = this.matrixWorld;
  12943. var threshold = raycaster.params.Points.threshold;
  12944. // Checking boundingSphere distance to ray
  12945. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  12946. sphere.copy( geometry.boundingSphere );
  12947. sphere.applyMatrix4( matrixWorld );
  12948. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  12949. //
  12950. inverseMatrix.getInverse( matrixWorld );
  12951. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  12952. var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  12953. var localThresholdSq = localThreshold * localThreshold;
  12954. var position = new THREE.Vector3();
  12955. function testPoint( point, index ) {
  12956. var rayPointDistanceSq = ray.distanceSqToPoint( point );
  12957. if ( rayPointDistanceSq < localThresholdSq ) {
  12958. var intersectPoint = ray.closestPointToPoint( point );
  12959. intersectPoint.applyMatrix4( matrixWorld );
  12960. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  12961. if ( distance < raycaster.near || distance > raycaster.far ) return;
  12962. intersects.push( {
  12963. distance: distance,
  12964. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  12965. point: intersectPoint.clone(),
  12966. index: index,
  12967. face: null,
  12968. object: object
  12969. } );
  12970. }
  12971. }
  12972. if ( geometry instanceof THREE.BufferGeometry ) {
  12973. var index = geometry.index;
  12974. var attributes = geometry.attributes;
  12975. var positions = attributes.position.array;
  12976. if ( index !== null ) {
  12977. var indices = index.array;
  12978. for ( var i = 0, il = indices.length; i < il; i ++ ) {
  12979. var a = indices[ i ];
  12980. position.fromArray( positions, a * 3 );
  12981. testPoint( position, a );
  12982. }
  12983. } else {
  12984. for ( var i = 0, l = positions.length / 3; i < l; i ++ ) {
  12985. position.fromArray( positions, i * 3 );
  12986. testPoint( position, i );
  12987. }
  12988. }
  12989. } else {
  12990. var vertices = geometry.vertices;
  12991. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  12992. testPoint( vertices[ i ], i );
  12993. }
  12994. }
  12995. };
  12996. }() );
  12997. THREE.Points.prototype.clone = function () {
  12998. return new this.constructor( this.geometry, this.material ).copy( this );
  12999. };
  13000. // File:src/objects/Line.js
  13001. /**
  13002. * @author mrdoob / http://mrdoob.com/
  13003. */
  13004. THREE.Line = function ( geometry, material, mode ) {
  13005. if ( mode === 1 ) {
  13006. console.warn( 'THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead.' );
  13007. return new THREE.LineSegments( geometry, material );
  13008. }
  13009. THREE.Object3D.call( this );
  13010. this.type = 'Line';
  13011. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  13012. this.material = material !== undefined ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  13013. };
  13014. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  13015. THREE.Line.prototype.constructor = THREE.Line;
  13016. THREE.Line.prototype.raycast = ( function () {
  13017. var inverseMatrix = new THREE.Matrix4();
  13018. var ray = new THREE.Ray();
  13019. var sphere = new THREE.Sphere();
  13020. return function raycast( raycaster, intersects ) {
  13021. var precision = raycaster.linePrecision;
  13022. var precisionSq = precision * precision;
  13023. var geometry = this.geometry;
  13024. var matrixWorld = this.matrixWorld;
  13025. // Checking boundingSphere distance to ray
  13026. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  13027. sphere.copy( geometry.boundingSphere );
  13028. sphere.applyMatrix4( matrixWorld );
  13029. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  13030. //
  13031. inverseMatrix.getInverse( matrixWorld );
  13032. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  13033. var vStart = new THREE.Vector3();
  13034. var vEnd = new THREE.Vector3();
  13035. var interSegment = new THREE.Vector3();
  13036. var interRay = new THREE.Vector3();
  13037. var step = this instanceof THREE.LineSegments ? 2 : 1;
  13038. if ( geometry instanceof THREE.BufferGeometry ) {
  13039. var index = geometry.index;
  13040. var attributes = geometry.attributes;
  13041. var positions = attributes.position.array;
  13042. if ( index !== null ) {
  13043. var indices = index.array;
  13044. for ( var i = 0, l = indices.length - 1; i < l; i += step ) {
  13045. var a = indices[ i ];
  13046. var b = indices[ i + 1 ];
  13047. vStart.fromArray( positions, a * 3 );
  13048. vEnd.fromArray( positions, b * 3 );
  13049. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  13050. if ( distSq > precisionSq ) continue;
  13051. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  13052. var distance = raycaster.ray.origin.distanceTo( interRay );
  13053. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  13054. intersects.push( {
  13055. distance: distance,
  13056. // What do we want? intersection point on the ray or on the segment??
  13057. // point: raycaster.ray.at( distance ),
  13058. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  13059. index: i,
  13060. face: null,
  13061. faceIndex: null,
  13062. object: this
  13063. } );
  13064. }
  13065. } else {
  13066. for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) {
  13067. vStart.fromArray( positions, 3 * i );
  13068. vEnd.fromArray( positions, 3 * i + 3 );
  13069. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  13070. if ( distSq > precisionSq ) continue;
  13071. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  13072. var distance = raycaster.ray.origin.distanceTo( interRay );
  13073. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  13074. intersects.push( {
  13075. distance: distance,
  13076. // What do we want? intersection point on the ray or on the segment??
  13077. // point: raycaster.ray.at( distance ),
  13078. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  13079. index: i,
  13080. face: null,
  13081. faceIndex: null,
  13082. object: this
  13083. } );
  13084. }
  13085. }
  13086. } else if ( geometry instanceof THREE.Geometry ) {
  13087. var vertices = geometry.vertices;
  13088. var nbVertices = vertices.length;
  13089. for ( var i = 0; i < nbVertices - 1; i += step ) {
  13090. var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  13091. if ( distSq > precisionSq ) continue;
  13092. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  13093. var distance = raycaster.ray.origin.distanceTo( interRay );
  13094. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  13095. intersects.push( {
  13096. distance: distance,
  13097. // What do we want? intersection point on the ray or on the segment??
  13098. // point: raycaster.ray.at( distance ),
  13099. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  13100. index: i,
  13101. face: null,
  13102. faceIndex: null,
  13103. object: this
  13104. } );
  13105. }
  13106. }
  13107. };
  13108. }() );
  13109. THREE.Line.prototype.clone = function () {
  13110. return new this.constructor( this.geometry, this.material ).copy( this );
  13111. };
  13112. // DEPRECATED
  13113. THREE.LineStrip = 0;
  13114. THREE.LinePieces = 1;
  13115. // File:src/objects/LineSegments.js
  13116. /**
  13117. * @author mrdoob / http://mrdoob.com/
  13118. */
  13119. THREE.LineSegments = function ( geometry, material ) {
  13120. THREE.Line.call( this, geometry, material );
  13121. this.type = 'LineSegments';
  13122. };
  13123. THREE.LineSegments.prototype = Object.create( THREE.Line.prototype );
  13124. THREE.LineSegments.prototype.constructor = THREE.LineSegments;
  13125. // File:src/objects/Mesh.js
  13126. /**
  13127. * @author mrdoob / http://mrdoob.com/
  13128. * @author alteredq / http://alteredqualia.com/
  13129. * @author mikael emtinger / http://gomo.se/
  13130. * @author jonobr1 / http://jonobr1.com/
  13131. */
  13132. THREE.Mesh = function ( geometry, material ) {
  13133. THREE.Object3D.call( this );
  13134. this.type = 'Mesh';
  13135. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  13136. this.material = material !== undefined ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  13137. this.drawMode = THREE.TrianglesDrawMode;
  13138. this.updateMorphTargets();
  13139. };
  13140. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  13141. THREE.Mesh.prototype.constructor = THREE.Mesh;
  13142. THREE.Mesh.prototype.setDrawMode = function ( value ) {
  13143. this.drawMode = value;
  13144. };
  13145. THREE.Mesh.prototype.updateMorphTargets = function () {
  13146. if ( this.geometry.morphTargets !== undefined && this.geometry.morphTargets.length > 0 ) {
  13147. this.morphTargetBase = - 1;
  13148. this.morphTargetInfluences = [];
  13149. this.morphTargetDictionary = {};
  13150. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  13151. this.morphTargetInfluences.push( 0 );
  13152. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  13153. }
  13154. }
  13155. };
  13156. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  13157. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  13158. return this.morphTargetDictionary[ name ];
  13159. }
  13160. console.warn( 'THREE.Mesh.getMorphTargetIndexByName: morph target ' + name + ' does not exist. Returning 0.' );
  13161. return 0;
  13162. };
  13163. THREE.Mesh.prototype.raycast = ( function () {
  13164. var inverseMatrix = new THREE.Matrix4();
  13165. var ray = new THREE.Ray();
  13166. var sphere = new THREE.Sphere();
  13167. var vA = new THREE.Vector3();
  13168. var vB = new THREE.Vector3();
  13169. var vC = new THREE.Vector3();
  13170. var tempA = new THREE.Vector3();
  13171. var tempB = new THREE.Vector3();
  13172. var tempC = new THREE.Vector3();
  13173. var uvA = new THREE.Vector2();
  13174. var uvB = new THREE.Vector2();
  13175. var uvC = new THREE.Vector2();
  13176. var barycoord = new THREE.Vector3();
  13177. var intersectionPoint = new THREE.Vector3();
  13178. var intersectionPointWorld = new THREE.Vector3();
  13179. function uvIntersection( point, p1, p2, p3, uv1, uv2, uv3 ) {
  13180. THREE.Triangle.barycoordFromPoint( point, p1, p2, p3, barycoord );
  13181. uv1.multiplyScalar( barycoord.x );
  13182. uv2.multiplyScalar( barycoord.y );
  13183. uv3.multiplyScalar( barycoord.z );
  13184. uv1.add( uv2 ).add( uv3 );
  13185. return uv1.clone();
  13186. }
  13187. function checkIntersection( object, raycaster, ray, pA, pB, pC, point ) {
  13188. var intersect;
  13189. var material = object.material;
  13190. if ( material.side === THREE.BackSide ) {
  13191. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  13192. } else {
  13193. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== THREE.DoubleSide, point );
  13194. }
  13195. if ( intersect === null ) return null;
  13196. intersectionPointWorld.copy( point );
  13197. intersectionPointWorld.applyMatrix4( object.matrixWorld );
  13198. var distance = raycaster.ray.origin.distanceTo( intersectionPointWorld );
  13199. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  13200. return {
  13201. distance: distance,
  13202. point: intersectionPointWorld.clone(),
  13203. object: object
  13204. };
  13205. }
  13206. function checkBufferGeometryIntersection( object, raycaster, ray, positions, uvs, a, b, c ) {
  13207. vA.fromArray( positions, a * 3 );
  13208. vB.fromArray( positions, b * 3 );
  13209. vC.fromArray( positions, c * 3 );
  13210. var intersection = checkIntersection( object, raycaster, ray, vA, vB, vC, intersectionPoint );
  13211. if ( intersection ) {
  13212. if ( uvs ) {
  13213. uvA.fromArray( uvs, a * 2 );
  13214. uvB.fromArray( uvs, b * 2 );
  13215. uvC.fromArray( uvs, c * 2 );
  13216. intersection.uv = uvIntersection( intersectionPoint, vA, vB, vC, uvA, uvB, uvC );
  13217. }
  13218. intersection.face = new THREE.Face3( a, b, c, THREE.Triangle.normal( vA, vB, vC ) );
  13219. intersection.faceIndex = a;
  13220. }
  13221. return intersection;
  13222. }
  13223. return function raycast( raycaster, intersects ) {
  13224. var geometry = this.geometry;
  13225. var material = this.material;
  13226. var matrixWorld = this.matrixWorld;
  13227. if ( material === undefined ) return;
  13228. // Checking boundingSphere distance to ray
  13229. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  13230. sphere.copy( geometry.boundingSphere );
  13231. sphere.applyMatrix4( matrixWorld );
  13232. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  13233. //
  13234. inverseMatrix.getInverse( matrixWorld );
  13235. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  13236. // Check boundingBox before continuing
  13237. if ( geometry.boundingBox !== null ) {
  13238. if ( ray.intersectsBox( geometry.boundingBox ) === false ) return;
  13239. }
  13240. var uvs, intersection;
  13241. if ( geometry instanceof THREE.BufferGeometry ) {
  13242. var a, b, c;
  13243. var index = geometry.index;
  13244. var attributes = geometry.attributes;
  13245. var positions = attributes.position.array;
  13246. if ( attributes.uv !== undefined ) {
  13247. uvs = attributes.uv.array;
  13248. }
  13249. if ( index !== null ) {
  13250. var indices = index.array;
  13251. for ( var i = 0, l = indices.length; i < l; i += 3 ) {
  13252. a = indices[ i ];
  13253. b = indices[ i + 1 ];
  13254. c = indices[ i + 2 ];
  13255. intersection = checkBufferGeometryIntersection( this, raycaster, ray, positions, uvs, a, b, c );
  13256. if ( intersection ) {
  13257. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indices buffer semantics
  13258. intersects.push( intersection );
  13259. }
  13260. }
  13261. } else {
  13262. for ( var i = 0, l = positions.length; i < l; i += 9 ) {
  13263. a = i / 3;
  13264. b = a + 1;
  13265. c = a + 2;
  13266. intersection = checkBufferGeometryIntersection( this, raycaster, ray, positions, uvs, a, b, c );
  13267. if ( intersection ) {
  13268. intersection.index = a; // triangle number in positions buffer semantics
  13269. intersects.push( intersection );
  13270. }
  13271. }
  13272. }
  13273. } else if ( geometry instanceof THREE.Geometry ) {
  13274. var fvA, fvB, fvC;
  13275. var isFaceMaterial = material instanceof THREE.MeshFaceMaterial;
  13276. var materials = isFaceMaterial === true ? material.materials : null;
  13277. var vertices = geometry.vertices;
  13278. var faces = geometry.faces;
  13279. var faceVertexUvs = geometry.faceVertexUvs[ 0 ];
  13280. if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs;
  13281. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  13282. var face = faces[ f ];
  13283. var faceMaterial = isFaceMaterial === true ? materials[ face.materialIndex ] : material;
  13284. if ( faceMaterial === undefined ) continue;
  13285. fvA = vertices[ face.a ];
  13286. fvB = vertices[ face.b ];
  13287. fvC = vertices[ face.c ];
  13288. if ( faceMaterial.morphTargets === true ) {
  13289. var morphTargets = geometry.morphTargets;
  13290. var morphInfluences = this.morphTargetInfluences;
  13291. vA.set( 0, 0, 0 );
  13292. vB.set( 0, 0, 0 );
  13293. vC.set( 0, 0, 0 );
  13294. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  13295. var influence = morphInfluences[ t ];
  13296. if ( influence === 0 ) continue;
  13297. var targets = morphTargets[ t ].vertices;
  13298. vA.addScaledVector( tempA.subVectors( targets[ face.a ], fvA ), influence );
  13299. vB.addScaledVector( tempB.subVectors( targets[ face.b ], fvB ), influence );
  13300. vC.addScaledVector( tempC.subVectors( targets[ face.c ], fvC ), influence );
  13301. }
  13302. vA.add( fvA );
  13303. vB.add( fvB );
  13304. vC.add( fvC );
  13305. fvA = vA;
  13306. fvB = vB;
  13307. fvC = vC;
  13308. }
  13309. intersection = checkIntersection( this, raycaster, ray, fvA, fvB, fvC, intersectionPoint );
  13310. if ( intersection ) {
  13311. if ( uvs ) {
  13312. var uvs_f = uvs[ f ];
  13313. uvA.copy( uvs_f[ 0 ] );
  13314. uvB.copy( uvs_f[ 1 ] );
  13315. uvC.copy( uvs_f[ 2 ] );
  13316. intersection.uv = uvIntersection( intersectionPoint, fvA, fvB, fvC, uvA, uvB, uvC );
  13317. }
  13318. intersection.face = face;
  13319. intersection.faceIndex = f;
  13320. intersects.push( intersection );
  13321. }
  13322. }
  13323. }
  13324. };
  13325. }() );
  13326. THREE.Mesh.prototype.clone = function () {
  13327. return new this.constructor( this.geometry, this.material ).copy( this );
  13328. };
  13329. // File:src/objects/Bone.js
  13330. /**
  13331. * @author mikael emtinger / http://gomo.se/
  13332. * @author alteredq / http://alteredqualia.com/
  13333. * @author ikerr / http://verold.com
  13334. */
  13335. THREE.Bone = function ( skin ) {
  13336. THREE.Object3D.call( this );
  13337. this.type = 'Bone';
  13338. this.skin = skin;
  13339. };
  13340. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  13341. THREE.Bone.prototype.constructor = THREE.Bone;
  13342. THREE.Bone.prototype.copy = function ( source ) {
  13343. THREE.Object3D.prototype.copy.call( this, source );
  13344. this.skin = source.skin;
  13345. return this;
  13346. };
  13347. // File:src/objects/Skeleton.js
  13348. /**
  13349. * @author mikael emtinger / http://gomo.se/
  13350. * @author alteredq / http://alteredqualia.com/
  13351. * @author michael guerrero / http://realitymeltdown.com
  13352. * @author ikerr / http://verold.com
  13353. */
  13354. THREE.Skeleton = function ( bones, boneInverses, useVertexTexture ) {
  13355. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  13356. this.identityMatrix = new THREE.Matrix4();
  13357. // copy the bone array
  13358. bones = bones || [];
  13359. this.bones = bones.slice( 0 );
  13360. // create a bone texture or an array of floats
  13361. if ( this.useVertexTexture ) {
  13362. // layout (1 matrix = 4 pixels)
  13363. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  13364. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  13365. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  13366. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  13367. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  13368. var size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  13369. size = THREE.Math.nextPowerOfTwo( Math.ceil( size ) );
  13370. size = Math.max( size, 4 );
  13371. this.boneTextureWidth = size;
  13372. this.boneTextureHeight = size;
  13373. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  13374. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  13375. } else {
  13376. this.boneMatrices = new Float32Array( 16 * this.bones.length );
  13377. }
  13378. // use the supplied bone inverses or calculate the inverses
  13379. if ( boneInverses === undefined ) {
  13380. this.calculateInverses();
  13381. } else {
  13382. if ( this.bones.length === boneInverses.length ) {
  13383. this.boneInverses = boneInverses.slice( 0 );
  13384. } else {
  13385. console.warn( 'THREE.Skeleton bonInverses is the wrong length.' );
  13386. this.boneInverses = [];
  13387. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13388. this.boneInverses.push( new THREE.Matrix4() );
  13389. }
  13390. }
  13391. }
  13392. };
  13393. THREE.Skeleton.prototype.calculateInverses = function () {
  13394. this.boneInverses = [];
  13395. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13396. var inverse = new THREE.Matrix4();
  13397. if ( this.bones[ b ] ) {
  13398. inverse.getInverse( this.bones[ b ].matrixWorld );
  13399. }
  13400. this.boneInverses.push( inverse );
  13401. }
  13402. };
  13403. THREE.Skeleton.prototype.pose = function () {
  13404. var bone;
  13405. // recover the bind-time world matrices
  13406. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13407. bone = this.bones[ b ];
  13408. if ( bone ) {
  13409. bone.matrixWorld.getInverse( this.boneInverses[ b ] );
  13410. }
  13411. }
  13412. // compute the local matrices, positions, rotations and scales
  13413. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13414. bone = this.bones[ b ];
  13415. if ( bone ) {
  13416. if ( bone.parent ) {
  13417. bone.matrix.getInverse( bone.parent.matrixWorld );
  13418. bone.matrix.multiply( bone.matrixWorld );
  13419. } else {
  13420. bone.matrix.copy( bone.matrixWorld );
  13421. }
  13422. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  13423. }
  13424. }
  13425. };
  13426. THREE.Skeleton.prototype.update = ( function () {
  13427. var offsetMatrix = new THREE.Matrix4();
  13428. return function update() {
  13429. // flatten bone matrices to array
  13430. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13431. // compute the offset between the current and the original transform
  13432. var matrix = this.bones[ b ] ? this.bones[ b ].matrixWorld : this.identityMatrix;
  13433. offsetMatrix.multiplyMatrices( matrix, this.boneInverses[ b ] );
  13434. offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  13435. }
  13436. if ( this.useVertexTexture ) {
  13437. this.boneTexture.needsUpdate = true;
  13438. }
  13439. };
  13440. } )();
  13441. THREE.Skeleton.prototype.clone = function () {
  13442. return new THREE.Skeleton( this.bones, this.boneInverses, this.useVertexTexture );
  13443. };
  13444. // File:src/objects/SkinnedMesh.js
  13445. /**
  13446. * @author mikael emtinger / http://gomo.se/
  13447. * @author alteredq / http://alteredqualia.com/
  13448. * @author ikerr / http://verold.com
  13449. */
  13450. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  13451. THREE.Mesh.call( this, geometry, material );
  13452. this.type = 'SkinnedMesh';
  13453. this.bindMode = "attached";
  13454. this.bindMatrix = new THREE.Matrix4();
  13455. this.bindMatrixInverse = new THREE.Matrix4();
  13456. // init bones
  13457. // TODO: remove bone creation as there is no reason (other than
  13458. // convenience) for THREE.SkinnedMesh to do this.
  13459. var bones = [];
  13460. if ( this.geometry && this.geometry.bones !== undefined ) {
  13461. var bone, gbone;
  13462. for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {
  13463. gbone = this.geometry.bones[ b ];
  13464. bone = new THREE.Bone( this );
  13465. bones.push( bone );
  13466. bone.name = gbone.name;
  13467. bone.position.fromArray( gbone.pos );
  13468. bone.quaternion.fromArray( gbone.rotq );
  13469. if ( gbone.scl !== undefined ) bone.scale.fromArray( gbone.scl );
  13470. }
  13471. for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {
  13472. gbone = this.geometry.bones[ b ];
  13473. if ( gbone.parent !== - 1 && gbone.parent !== null ) {
  13474. bones[ gbone.parent ].add( bones[ b ] );
  13475. } else {
  13476. this.add( bones[ b ] );
  13477. }
  13478. }
  13479. }
  13480. this.normalizeSkinWeights();
  13481. this.updateMatrixWorld( true );
  13482. this.bind( new THREE.Skeleton( bones, undefined, useVertexTexture ), this.matrixWorld );
  13483. };
  13484. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  13485. THREE.SkinnedMesh.prototype.constructor = THREE.SkinnedMesh;
  13486. THREE.SkinnedMesh.prototype.bind = function( skeleton, bindMatrix ) {
  13487. this.skeleton = skeleton;
  13488. if ( bindMatrix === undefined ) {
  13489. this.updateMatrixWorld( true );
  13490. this.skeleton.calculateInverses();
  13491. bindMatrix = this.matrixWorld;
  13492. }
  13493. this.bindMatrix.copy( bindMatrix );
  13494. this.bindMatrixInverse.getInverse( bindMatrix );
  13495. };
  13496. THREE.SkinnedMesh.prototype.pose = function () {
  13497. this.skeleton.pose();
  13498. };
  13499. THREE.SkinnedMesh.prototype.normalizeSkinWeights = function () {
  13500. if ( this.geometry instanceof THREE.Geometry ) {
  13501. for ( var i = 0; i < this.geometry.skinWeights.length; i ++ ) {
  13502. var sw = this.geometry.skinWeights[ i ];
  13503. var scale = 1.0 / sw.lengthManhattan();
  13504. if ( scale !== Infinity ) {
  13505. sw.multiplyScalar( scale );
  13506. } else {
  13507. sw.set( 1, 0, 0, 0 ); // do something reasonable
  13508. }
  13509. }
  13510. } else if ( this.geometry instanceof THREE.BufferGeometry ) {
  13511. var vec = new THREE.Vector4();
  13512. var skinWeight = this.geometry.attributes.skinWeight;
  13513. for ( var i = 0; i < skinWeight.count; i ++ ) {
  13514. vec.x = skinWeight.getX( i );
  13515. vec.y = skinWeight.getY( i );
  13516. vec.z = skinWeight.getZ( i );
  13517. vec.w = skinWeight.getW( i );
  13518. var scale = 1.0 / vec.lengthManhattan();
  13519. if ( scale !== Infinity ) {
  13520. vec.multiplyScalar( scale );
  13521. } else {
  13522. vec.set( 1, 0, 0, 0 ); // do something reasonable
  13523. }
  13524. skinWeight.setXYZW( i, vec.x, vec.y, vec.z, vec.w );
  13525. }
  13526. }
  13527. };
  13528. THREE.SkinnedMesh.prototype.updateMatrixWorld = function( force ) {
  13529. THREE.Mesh.prototype.updateMatrixWorld.call( this, true );
  13530. if ( this.bindMode === "attached" ) {
  13531. this.bindMatrixInverse.getInverse( this.matrixWorld );
  13532. } else if ( this.bindMode === "detached" ) {
  13533. this.bindMatrixInverse.getInverse( this.bindMatrix );
  13534. } else {
  13535. console.warn( 'THREE.SkinnedMesh unrecognized bindMode: ' + this.bindMode );
  13536. }
  13537. };
  13538. THREE.SkinnedMesh.prototype.clone = function() {
  13539. return new this.constructor( this.geometry, this.material, this.useVertexTexture ).copy( this );
  13540. };
  13541. // File:src/objects/LOD.js
  13542. /**
  13543. * @author mikael emtinger / http://gomo.se/
  13544. * @author alteredq / http://alteredqualia.com/
  13545. * @author mrdoob / http://mrdoob.com/
  13546. */
  13547. THREE.LOD = function () {
  13548. THREE.Object3D.call( this );
  13549. this.type = 'LOD';
  13550. Object.defineProperties( this, {
  13551. levels: {
  13552. enumerable: true,
  13553. value: []
  13554. },
  13555. objects: {
  13556. get: function () {
  13557. console.warn( 'THREE.LOD: .objects has been renamed to .levels.' );
  13558. return this.levels;
  13559. }
  13560. }
  13561. } );
  13562. };
  13563. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  13564. THREE.LOD.prototype.constructor = THREE.LOD;
  13565. THREE.LOD.prototype.addLevel = function ( object, distance ) {
  13566. if ( distance === undefined ) distance = 0;
  13567. distance = Math.abs( distance );
  13568. var levels = this.levels;
  13569. for ( var l = 0; l < levels.length; l ++ ) {
  13570. if ( distance < levels[ l ].distance ) {
  13571. break;
  13572. }
  13573. }
  13574. levels.splice( l, 0, { distance: distance, object: object } );
  13575. this.add( object );
  13576. };
  13577. THREE.LOD.prototype.getObjectForDistance = function ( distance ) {
  13578. var levels = this.levels;
  13579. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  13580. if ( distance < levels[ i ].distance ) {
  13581. break;
  13582. }
  13583. }
  13584. return levels[ i - 1 ].object;
  13585. };
  13586. THREE.LOD.prototype.raycast = ( function () {
  13587. var matrixPosition = new THREE.Vector3();
  13588. return function raycast( raycaster, intersects ) {
  13589. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  13590. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  13591. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  13592. };
  13593. }() );
  13594. THREE.LOD.prototype.update = function () {
  13595. var v1 = new THREE.Vector3();
  13596. var v2 = new THREE.Vector3();
  13597. return function update( camera ) {
  13598. var levels = this.levels;
  13599. if ( levels.length > 1 ) {
  13600. v1.setFromMatrixPosition( camera.matrixWorld );
  13601. v2.setFromMatrixPosition( this.matrixWorld );
  13602. var distance = v1.distanceTo( v2 );
  13603. levels[ 0 ].object.visible = true;
  13604. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  13605. if ( distance >= levels[ i ].distance ) {
  13606. levels[ i - 1 ].object.visible = false;
  13607. levels[ i ].object.visible = true;
  13608. } else {
  13609. break;
  13610. }
  13611. }
  13612. for ( ; i < l; i ++ ) {
  13613. levels[ i ].object.visible = false;
  13614. }
  13615. }
  13616. };
  13617. }();
  13618. THREE.LOD.prototype.copy = function ( source ) {
  13619. THREE.Object3D.prototype.copy.call( this, source, false );
  13620. var levels = source.levels;
  13621. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  13622. var level = levels[ i ];
  13623. this.addLevel( level.object.clone(), level.distance );
  13624. }
  13625. return this;
  13626. };
  13627. THREE.LOD.prototype.toJSON = function ( meta ) {
  13628. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  13629. data.object.levels = [];
  13630. var levels = this.levels;
  13631. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  13632. var level = levels[ i ];
  13633. data.object.levels.push( {
  13634. object: level.object.uuid,
  13635. distance: level.distance
  13636. } );
  13637. }
  13638. return data;
  13639. };
  13640. // File:src/objects/Sprite.js
  13641. /**
  13642. * @author mikael emtinger / http://gomo.se/
  13643. * @author alteredq / http://alteredqualia.com/
  13644. */
  13645. THREE.Sprite = ( function () {
  13646. var indices = new Uint16Array( [ 0, 1, 2, 0, 2, 3 ] );
  13647. var vertices = new Float32Array( [ - 0.5, - 0.5, 0, 0.5, - 0.5, 0, 0.5, 0.5, 0, - 0.5, 0.5, 0 ] );
  13648. var uvs = new Float32Array( [ 0, 0, 1, 0, 1, 1, 0, 1 ] );
  13649. var geometry = new THREE.BufferGeometry();
  13650. geometry.setIndex( new THREE.BufferAttribute( indices, 1 ) );
  13651. geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  13652. geometry.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) );
  13653. return function Sprite( material ) {
  13654. THREE.Object3D.call( this );
  13655. this.type = 'Sprite';
  13656. this.geometry = geometry;
  13657. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  13658. };
  13659. } )();
  13660. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  13661. THREE.Sprite.prototype.constructor = THREE.Sprite;
  13662. THREE.Sprite.prototype.raycast = ( function () {
  13663. var matrixPosition = new THREE.Vector3();
  13664. return function raycast( raycaster, intersects ) {
  13665. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  13666. var distanceSq = raycaster.ray.distanceSqToPoint( matrixPosition );
  13667. var guessSizeSq = this.scale.x * this.scale.y;
  13668. if ( distanceSq > guessSizeSq ) {
  13669. return;
  13670. }
  13671. intersects.push( {
  13672. distance: Math.sqrt( distanceSq ),
  13673. point: this.position,
  13674. face: null,
  13675. object: this
  13676. } );
  13677. };
  13678. }() );
  13679. THREE.Sprite.prototype.clone = function () {
  13680. return new this.constructor( this.material ).copy( this );
  13681. };
  13682. // Backwards compatibility
  13683. THREE.Particle = THREE.Sprite;
  13684. // File:src/objects/LensFlare.js
  13685. /**
  13686. * @author mikael emtinger / http://gomo.se/
  13687. * @author alteredq / http://alteredqualia.com/
  13688. */
  13689. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  13690. THREE.Object3D.call( this );
  13691. this.lensFlares = [];
  13692. this.positionScreen = new THREE.Vector3();
  13693. this.customUpdateCallback = undefined;
  13694. if ( texture !== undefined ) {
  13695. this.add( texture, size, distance, blending, color );
  13696. }
  13697. };
  13698. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  13699. THREE.LensFlare.prototype.constructor = THREE.LensFlare;
  13700. /*
  13701. * Add: adds another flare
  13702. */
  13703. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  13704. if ( size === undefined ) size = - 1;
  13705. if ( distance === undefined ) distance = 0;
  13706. if ( opacity === undefined ) opacity = 1;
  13707. if ( color === undefined ) color = new THREE.Color( 0xffffff );
  13708. if ( blending === undefined ) blending = THREE.NormalBlending;
  13709. distance = Math.min( distance, Math.max( 0, distance ) );
  13710. this.lensFlares.push( {
  13711. texture: texture, // THREE.Texture
  13712. size: size, // size in pixels (-1 = use texture.width)
  13713. distance: distance, // distance (0-1) from light source (0=at light source)
  13714. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is in front z = 1 is back
  13715. scale: 1, // scale
  13716. rotation: 0, // rotation
  13717. opacity: opacity, // opacity
  13718. color: color, // color
  13719. blending: blending // blending
  13720. } );
  13721. };
  13722. /*
  13723. * Update lens flares update positions on all flares based on the screen position
  13724. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  13725. */
  13726. THREE.LensFlare.prototype.updateLensFlares = function () {
  13727. var f, fl = this.lensFlares.length;
  13728. var flare;
  13729. var vecX = - this.positionScreen.x * 2;
  13730. var vecY = - this.positionScreen.y * 2;
  13731. for ( f = 0; f < fl; f ++ ) {
  13732. flare = this.lensFlares[ f ];
  13733. flare.x = this.positionScreen.x + vecX * flare.distance;
  13734. flare.y = this.positionScreen.y + vecY * flare.distance;
  13735. flare.wantedRotation = flare.x * Math.PI * 0.25;
  13736. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  13737. }
  13738. };
  13739. THREE.LensFlare.prototype.copy = function ( source ) {
  13740. THREE.Object3D.prototype.copy.call( this, source );
  13741. this.positionScreen.copy( source.positionScreen );
  13742. this.customUpdateCallback = source.customUpdateCallback;
  13743. for ( var i = 0, l = source.lensFlares.length; i < l; i ++ ) {
  13744. this.lensFlares.push( source.lensFlares[ i ] );
  13745. }
  13746. return this;
  13747. };
  13748. // File:src/scenes/Scene.js
  13749. /**
  13750. * @author mrdoob / http://mrdoob.com/
  13751. */
  13752. THREE.Scene = function () {
  13753. THREE.Object3D.call( this );
  13754. this.type = 'Scene';
  13755. this.fog = null;
  13756. this.overrideMaterial = null;
  13757. this.autoUpdate = true; // checked by the renderer
  13758. };
  13759. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  13760. THREE.Scene.prototype.constructor = THREE.Scene;
  13761. THREE.Scene.prototype.copy = function ( source ) {
  13762. THREE.Object3D.prototype.copy.call( this, source );
  13763. if ( source.fog !== null ) this.fog = source.fog.clone();
  13764. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  13765. this.autoUpdate = source.autoUpdate;
  13766. this.matrixAutoUpdate = source.matrixAutoUpdate;
  13767. return this;
  13768. };
  13769. // File:src/scenes/Fog.js
  13770. /**
  13771. * @author mrdoob / http://mrdoob.com/
  13772. * @author alteredq / http://alteredqualia.com/
  13773. */
  13774. THREE.Fog = function ( color, near, far ) {
  13775. this.name = '';
  13776. this.color = new THREE.Color( color );
  13777. this.near = ( near !== undefined ) ? near : 1;
  13778. this.far = ( far !== undefined ) ? far : 1000;
  13779. };
  13780. THREE.Fog.prototype.clone = function () {
  13781. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  13782. };
  13783. // File:src/scenes/FogExp2.js
  13784. /**
  13785. * @author mrdoob / http://mrdoob.com/
  13786. * @author alteredq / http://alteredqualia.com/
  13787. */
  13788. THREE.FogExp2 = function ( color, density ) {
  13789. this.name = '';
  13790. this.color = new THREE.Color( color );
  13791. this.density = ( density !== undefined ) ? density : 0.00025;
  13792. };
  13793. THREE.FogExp2.prototype.clone = function () {
  13794. return new THREE.FogExp2( this.color.getHex(), this.density );
  13795. };
  13796. // File:src/renderers/shaders/ShaderChunk.js
  13797. THREE.ShaderChunk = {};
  13798. // File:src/renderers/shaders/ShaderChunk/alphamap_fragment.glsl
  13799. THREE.ShaderChunk[ 'alphamap_fragment' ] = "#ifdef USE_ALPHAMAP\n diffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif\n";
  13800. // File:src/renderers/shaders/ShaderChunk/alphamap_pars_fragment.glsl
  13801. THREE.ShaderChunk[ 'alphamap_pars_fragment' ] = "#ifdef USE_ALPHAMAP\n uniform sampler2D alphaMap;\n#endif\n";
  13802. // File:src/renderers/shaders/ShaderChunk/alphatest_fragment.glsl
  13803. THREE.ShaderChunk[ 'alphatest_fragment' ] = "#ifdef ALPHATEST\n if ( diffuseColor.a < ALPHATEST ) discard;\n#endif\n";
  13804. // File:src/renderers/shaders/ShaderChunk/ambient_pars.glsl
  13805. THREE.ShaderChunk[ 'ambient_pars' ] = "uniform vec3 ambientLightColor;\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n return PI * ambientLightColor;\n}\n";
  13806. // File:src/renderers/shaders/ShaderChunk/aomap_fragment.glsl
  13807. THREE.ShaderChunk[ 'aomap_fragment' ] = "#ifdef USE_AOMAP\n reflectedLight.indirectDiffuse *= ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n#endif\n";
  13808. // File:src/renderers/shaders/ShaderChunk/aomap_pars_fragment.glsl
  13809. THREE.ShaderChunk[ 'aomap_pars_fragment' ] = "#ifdef USE_AOMAP\n uniform sampler2D aoMap;\n uniform float aoMapIntensity;\n#endif";
  13810. // File:src/renderers/shaders/ShaderChunk/begin_vertex.glsl
  13811. THREE.ShaderChunk[ 'begin_vertex' ] = "\nvec3 transformed = vec3( position );\n";
  13812. // File:src/renderers/shaders/ShaderChunk/beginnormal_vertex.glsl
  13813. THREE.ShaderChunk[ 'beginnormal_vertex' ] = "\nvec3 objectNormal = vec3( normal );\n";
  13814. // File:src/renderers/shaders/ShaderChunk/bsdfs.glsl
  13815. THREE.ShaderChunk[ 'bsdfs' ] = "float calcLightAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n if ( decayExponent > 0.0 ) {\n return pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\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 = alpha * alpha;\n float gl = dotNL + pow( a2 + ( 1.0 - a2 ) * dotNL * dotNL, 0.5 );\n float gv = dotNV + pow( a2 + ( 1.0 - a2 ) * dotNV * dotNV, 0.5 );\n return 1.0 / ( gl * gv );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n float a2 = alpha * alpha;\n float denom = dotNH * dotNH * ( a2 - 1.0 ) + 1.0;\n return RECIPROCAL_PI * a2 / ( denom * 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 = roughness * 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_Smith( 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 / square( ggxRoughness + 0.0001 ) - 2.0 );\n}";
  13816. // File:src/renderers/shaders/ShaderChunk/bumpmap_pars_fragment.glsl
  13817. 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";
  13818. // File:src/renderers/shaders/ShaderChunk/color_fragment.glsl
  13819. THREE.ShaderChunk[ 'color_fragment' ] = "#ifdef USE_COLOR\n diffuseColor.rgb *= vColor;\n#endif";
  13820. // File:src/renderers/shaders/ShaderChunk/color_pars_fragment.glsl
  13821. THREE.ShaderChunk[ 'color_pars_fragment' ] = "#ifdef USE_COLOR\n varying vec3 vColor;\n#endif\n";
  13822. // File:src/renderers/shaders/ShaderChunk/color_pars_vertex.glsl
  13823. THREE.ShaderChunk[ 'color_pars_vertex' ] = "#ifdef USE_COLOR\n varying vec3 vColor;\n#endif";
  13824. // File:src/renderers/shaders/ShaderChunk/color_vertex.glsl
  13825. THREE.ShaderChunk[ 'color_vertex' ] = "#ifdef USE_COLOR\n vColor.xyz = color.xyz;\n#endif";
  13826. // File:src/renderers/shaders/ShaderChunk/common.glsl
  13827. 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 square( const in float x ) { return x*x; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nstruct IncidentLight {\n vec3 color;\n vec3 direction;\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}\nvec3 inputToLinear( in vec3 a ) {\n #ifdef GAMMA_INPUT\n return pow( a, vec3( float( GAMMA_FACTOR ) ) );\n #else\n return a;\n #endif\n}\nvec3 linearToOutput( in vec3 a ) {\n #ifdef GAMMA_OUTPUT\n return pow( a, vec3( 1.0 / float( GAMMA_FACTOR ) ) );\n #else\n return a;\n #endif\n}\n";
  13828. // File:src/renderers/shaders/ShaderChunk/defaultnormal_vertex.glsl
  13829. THREE.ShaderChunk[ 'defaultnormal_vertex' ] = "#ifdef FLIP_SIDED\n objectNormal = -objectNormal;\n#endif\nvec3 transformedNormal = normalMatrix * objectNormal;\n";
  13830. // File:src/renderers/shaders/ShaderChunk/displacementmap_vertex.glsl
  13831. THREE.ShaderChunk[ 'displacementmap_vertex' ] = "#ifdef USE_DISPLACEMENTMAP\n transformed += normal * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n#endif\n";
  13832. // File:src/renderers/shaders/ShaderChunk/displacementmap_pars_vertex.glsl
  13833. THREE.ShaderChunk[ 'displacementmap_pars_vertex' ] = "#ifdef USE_DISPLACEMENTMAP\n uniform sampler2D displacementMap;\n uniform float displacementScale;\n uniform float displacementBias;\n#endif\n";
  13834. // File:src/renderers/shaders/ShaderChunk/emissivemap_fragment.glsl
  13835. THREE.ShaderChunk[ 'emissivemap_fragment' ] = "#ifdef USE_EMISSIVEMAP\n vec4 emissiveColor = texture2D( emissiveMap, vUv );\n emissiveColor.rgb = inputToLinear( emissiveColor.rgb );\n totalEmissiveLight *= emissiveColor.rgb;\n#endif\n";
  13836. // File:src/renderers/shaders/ShaderChunk/emissivemap_pars_fragment.glsl
  13837. THREE.ShaderChunk[ 'emissivemap_pars_fragment' ] = "#ifdef USE_EMISSIVEMAP\n uniform sampler2D emissiveMap;\n#endif\n";
  13838. // File:src/renderers/shaders/ShaderChunk/envmap_fragment.glsl
  13839. 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.xyz = inputToLinear( envColor.xyz );\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";
  13840. // File:src/renderers/shaders/ShaderChunk/envmap_pars_fragment.glsl
  13841. 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 #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";
  13842. // File:src/renderers/shaders/ShaderChunk/envmap_pars_vertex.glsl
  13843. THREE.ShaderChunk[ 'envmap_pars_vertex' ] = "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP ) && ! defined( PHONG ) && ! defined( STANDARD )\n varying vec3 vReflect;\n uniform float refractionRatio;\n#endif\n";
  13844. // File:src/renderers/shaders/ShaderChunk/envmap_vertex.glsl
  13845. THREE.ShaderChunk[ 'envmap_vertex' ] = "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP ) && ! defined( PHONG ) && ! defined( STANDARD )\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";
  13846. // File:src/renderers/shaders/ShaderChunk/fog_fragment.glsl
  13847. 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 \n outgoingLight = mix( outgoingLight, fogColor, fogFactor );\n#endif";
  13848. // File:src/renderers/shaders/ShaderChunk/fog_pars_fragment.glsl
  13849. 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";
  13850. // File:src/renderers/shaders/ShaderChunk/lights_pars.glsl
  13851. THREE.ShaderChunk[ 'lights_pars' ] = "#if NUM_DIR_LIGHTS > 0\n struct DirectionalLight {\n vec3 direction;\n vec3 color;\n int shadow;\n };\n uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n IncidentLight getDirectionalDirectLight( const in DirectionalLight directionalLight, const in GeometricContext geometry ) {\n IncidentLight directLight;\n directLight.color = directionalLight.color;\n directLight.direction = directionalLight.direction;\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 };\n uniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n IncidentLight getPointDirectLight( const in PointLight pointLight, const in GeometricContext geometry ) {\n IncidentLight directLight;\n vec3 lVector = pointLight.position - geometry.position;\n directLight.direction = normalize( lVector );\n directLight.color = pointLight.color;\n directLight.color *= calcLightAttenuation( length( lVector ), pointLight.distance, pointLight.decay );\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 angleCos;\n float exponent;\n int shadow;\n };\n uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n IncidentLight getSpotDirectLight( 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 spotEffect = dot( directLight.direction, spotLight.direction );\n if ( spotEffect > spotLight.angleCos ) {\n float spotEffect = dot( spotLight.direction, directLight.direction );\n spotEffect = saturate( pow( saturate( spotEffect ), spotLight.exponent ) );\n directLight.color = spotLight.color;\n directLight.color *= ( spotEffect * calcLightAttenuation( length( lVector ), spotLight.distance, spotLight.decay ) );\n } else {\n directLight.color = vec3( 0.0 );\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 return PI * mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\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 #else\n vec3 envMapColor = vec3( 0.0 );\n #endif\n envMapColor.rgb = inputToLinear( envMapColor.rgb );\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( square( 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 #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 #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 #endif\n envMapColor.rgb = inputToLinear( envMapColor.rgb );\n return envMapColor.rgb * envMapIntensity;\n }\n#endif\n";
  13852. // File:src/renderers/shaders/ShaderChunk/lightmap_pars_fragment.glsl
  13853. THREE.ShaderChunk[ 'lightmap_pars_fragment' ] = "#ifdef USE_LIGHTMAP\n uniform sampler2D lightMap;\n uniform float lightMapIntensity;\n#endif";
  13854. // File:src/renderers/shaders/ShaderChunk/lights_lambert_vertex.glsl
  13855. 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\n#if NUM_POINT_LIGHTS > 0\n for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n IncidentLight directLight = getPointDirectLight( pointLights[ i ], geometry );\n float dotNL = dot( geometry.normal, directLight.direction );\n vec3 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 IncidentLight directLight = getSpotDirectLight( spotLights[ i ], geometry );\n float dotNL = dot( geometry.normal, directLight.direction );\n vec3 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 IncidentLight directLight = getDirectionalDirectLight( directionalLights[ i ], geometry );\n float dotNL = dot( geometry.normal, directLight.direction );\n vec3 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 {\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 }\n";
  13856. // File:src/renderers/shaders/ShaderChunk/lights_phong_fragment.glsl
  13857. THREE.ShaderChunk[ 'lights_phong_fragment' ] = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n";
  13858. // File:src/renderers/shaders/ShaderChunk/lights_phong_pars_fragment.glsl
  13859. THREE.ShaderChunk[ 'lights_phong_pars_fragment' ] = "#ifdef USE_ENVMAP\n varying vec3 vWorldPosition;\n#endif\nvarying 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 * PI * directLight.color;\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";
  13860. // File:src/renderers/shaders/ShaderChunk/lights_phong_pars_vertex.glsl
  13861. THREE.ShaderChunk[ 'lights_phong_pars_vertex' ] = "#ifdef USE_ENVMAP\n varying vec3 vWorldPosition;\n#endif\n";
  13862. // File:src/renderers/shaders/ShaderChunk/lights_phong_vertex.glsl
  13863. THREE.ShaderChunk[ 'lights_phong_vertex' ] = "#ifdef USE_ENVMAP\n vWorldPosition = worldPosition.xyz;\n#endif\n";
  13864. // File:src/renderers/shaders/ShaderChunk/lights_standard_fragment.glsl
  13865. 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";
  13866. // File:src/renderers/shaders/ShaderChunk/lights_standard_pars_fragment.glsl
  13867. 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 * PI * directLight.color;\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 )\n";
  13868. // File:src/renderers/shaders/ShaderChunk/lights_template.glsl
  13869. THREE.ShaderChunk[ 'lights_template' ] = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = normalize( vViewPosition );\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n PointLight pointLight = pointLights[ i ];\n IncidentLight directLight = getPointDirectLight( pointLight, geometry );\n #ifdef USE_SHADOWMAP\n if ( pointLight.shadow > - 1 ) {\n for ( int j = 0; j < NUM_SHADOWS; j ++ ) {\n if ( j == pointLight.shadow ) {\n directLight.color *= shadows[ j ];\n }\n }\n }\n #endif\n RE_Direct( directLight, geometry, material, reflectedLight );\n }\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n SpotLight spotLight = spotLights[ i ];\n IncidentLight directLight = getSpotDirectLight( spotLight, geometry );\n #ifdef USE_SHADOWMAP\n if ( spotLight.shadow > - 1 ) {\n for ( int j = 0; j < NUM_SHADOWS; j ++ ) {\n if ( j == spotLight.shadow ) {\n directLight.color *= shadows[ j ];\n }\n }\n }\n #endif\n RE_Direct( directLight, geometry, material, reflectedLight );\n }\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n DirectionalLight directionalLight = directionalLights[ i ];\n IncidentLight directLight = getDirectionalDirectLight( directionalLight, geometry );\n #ifdef USE_SHADOWMAP\n if ( directionalLight.shadow > - 1 ) {\n for ( int j = 0; j < NUM_SHADOWS; j ++ ) {\n if ( j == directionalLight.shadow ) {\n directLight.color *= shadows[ j ];\n }\n }\n }\n #endif\n RE_Direct( directLight, geometry, material, reflectedLight );\n }\n#endif\n#if defined( RE_IndirectDiffuse )\n {\n vec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n #ifdef USE_LIGHTMAP\n irradiance += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\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 RE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n }\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n {\n vec3 radiance = getLightProbeIndirectRadiance( geometry, Material_BlinnShininessExponent( material ), 8 );\n RE_IndirectSpecular( radiance, geometry, material, reflectedLight );\n }\n#endif\n";
  13870. // File:src/renderers/shaders/ShaderChunk/linear_to_gamma_fragment.glsl
  13871. THREE.ShaderChunk[ 'linear_to_gamma_fragment' ] = "\n outgoingLight = linearToOutput( outgoingLight );\n";
  13872. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_fragment.glsl
  13873. THREE.ShaderChunk[ 'logdepthbuf_fragment' ] = "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n gl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n#endif";
  13874. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_pars_fragment.glsl
  13875. 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";
  13876. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_pars_vertex.glsl
  13877. 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";
  13878. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_vertex.glsl
  13879. 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";
  13880. // File:src/renderers/shaders/ShaderChunk/map_fragment.glsl
  13881. THREE.ShaderChunk[ 'map_fragment' ] = "#ifdef USE_MAP\n vec4 texelColor = texture2D( map, vUv );\n texelColor.xyz = inputToLinear( texelColor.xyz );\n diffuseColor *= texelColor;\n#endif\n";
  13882. // File:src/renderers/shaders/ShaderChunk/map_pars_fragment.glsl
  13883. THREE.ShaderChunk[ 'map_pars_fragment' ] = "#ifdef USE_MAP\n uniform sampler2D map;\n#endif";
  13884. // File:src/renderers/shaders/ShaderChunk/map_particle_fragment.glsl
  13885. THREE.ShaderChunk[ 'map_particle_fragment' ] = "#ifdef USE_MAP\n diffuseColor *= texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) * offsetRepeat.zw + offsetRepeat.xy );\n#endif\n";
  13886. // File:src/renderers/shaders/ShaderChunk/map_particle_pars_fragment.glsl
  13887. THREE.ShaderChunk[ 'map_particle_pars_fragment' ] = "#ifdef USE_MAP\n uniform vec4 offsetRepeat;\n uniform sampler2D map;\n#endif\n";
  13888. // File:src/renderers/shaders/ShaderChunk/metalnessmap_fragment.glsl
  13889. THREE.ShaderChunk[ 'metalnessmap_fragment' ] = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n vec4 texelMetalness = texture2D( metalnessMap, vUv );\n metalnessFactor *= texelMetalness.r;\n#endif\n";
  13890. // File:src/renderers/shaders/ShaderChunk/metalnessmap_pars_fragment.glsl
  13891. THREE.ShaderChunk[ 'metalnessmap_pars_fragment' ] = "#ifdef USE_METALNESSMAP\n uniform sampler2D metalnessMap;\n#endif";
  13892. // File:src/renderers/shaders/ShaderChunk/morphnormal_vertex.glsl
  13893. 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";
  13894. // File:src/renderers/shaders/ShaderChunk/morphtarget_pars_vertex.glsl
  13895. 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";
  13896. // File:src/renderers/shaders/ShaderChunk/morphtarget_vertex.glsl
  13897. 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";
  13898. // File:src/renderers/shaders/ShaderChunk/normal_fragment.glsl
  13899. THREE.ShaderChunk[ 'normal_fragment' ] = "#ifdef FLAT_SHADED\n vec3 fdx = dFdx( vViewPosition );\n vec3 fdy = dFdy( vViewPosition );\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";
  13900. // File:src/renderers/shaders/ShaderChunk/normalmap_pars_fragment.glsl
  13901. 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";
  13902. // File:src/renderers/shaders/ShaderChunk/project_vertex.glsl
  13903. 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";
  13904. // File:src/renderers/shaders/ShaderChunk/roughnessmap_fragment.glsl
  13905. THREE.ShaderChunk[ 'roughnessmap_fragment' ] = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n vec4 texelRoughness = texture2D( roughnessMap, vUv );\n roughnessFactor *= texelRoughness.r;\n#endif\n";
  13906. // File:src/renderers/shaders/ShaderChunk/roughnessmap_pars_fragment.glsl
  13907. THREE.ShaderChunk[ 'roughnessmap_pars_fragment' ] = "#ifdef USE_ROUGHNESSMAP\n uniform sampler2D roughnessMap;\n#endif";
  13908. // File:src/renderers/shaders/ShaderChunk/shadowmap_fragment.glsl
  13909. THREE.ShaderChunk[ 'shadowmap_fragment' ] = "vec3 shadowMask = vec3( 1.0 );\n#ifdef USE_SHADOWMAP\n float shadows[ NUM_SHADOWS ];\n for ( int i = 0; i < NUM_SHADOWS; i ++ ) {\n float texelSizeY = 1.0 / shadowMapSize[ i ].y;\n float shadow = 0.0;\n#ifdef POINT_LIGHT_SHADOWS\n bool isPointLight = shadowDarkness[ i ] < 0.0;\n if ( isPointLight ) {\n float realShadowDarkness = abs( shadowDarkness[ i ] );\n vec3 lightToPosition = vShadowCoord[ i ].xyz;\n #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT )\n vec3 bd3D = normalize( lightToPosition );\n float dp = length( lightToPosition );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D, texelSizeY ) ), shadowBias[ i ], shadow );\n #if defined( SHADOWMAP_TYPE_PCF )\n const float Dr = 1.25;\n #elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n const float Dr = 2.25;\n #endif\n float os = Dr * 2.0 * texelSizeY;\n const vec3 Gsd = vec3( - 1, 0, 1 );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.zzz * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.zxz * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.xxz * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.xzz * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.zzx * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.zxx * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.xxx * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.xzx * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.zzy * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.zxy * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.xxy * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.xzy * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.zyz * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.xyz * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.zyx * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.xyx * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.yzz * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.yxz * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.yxx * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.yzx * os, texelSizeY ) ), shadowBias[ i ], shadow );\n shadow *= realShadowDarkness * ( 1.0 / 21.0 );\n #else\n vec3 bd3D = normalize( lightToPosition );\n float dp = length( lightToPosition );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D, texelSizeY ) ), shadowBias[ i ], shadow );\n shadow *= realShadowDarkness;\n #endif\n } else {\n#endif\n float texelSizeX = 1.0 / shadowMapSize[ i ].x;\n vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;\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 shadowCoord.z += shadowBias[ i ];\n const float ShadowDelta = 1.0 / 9.0;\n float xPixelOffset = texelSizeX;\n float yPixelOffset = texelSizeY;\n float dx0 = - 1.25 * xPixelOffset;\n float dy0 = - 1.25 * yPixelOffset;\n float dx1 = 1.25 * xPixelOffset;\n float dy1 = 1.25 * yPixelOffset;\n float fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += ShadowDelta;\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += ShadowDelta;\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += ShadowDelta;\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += ShadowDelta;\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );\n if ( fDepth < shadowCoord.z ) shadow += ShadowDelta;\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += ShadowDelta;\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += ShadowDelta;\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += ShadowDelta;\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += ShadowDelta;\n shadow *= shadowDarkness[ i ];\n #elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n shadowCoord.z += shadowBias[ i ];\n float xPixelOffset = texelSizeX;\n float yPixelOffset = texelSizeY;\n float dx0 = - 1.0 * xPixelOffset;\n float dy0 = - 1.0 * yPixelOffset;\n float dx1 = 1.0 * xPixelOffset;\n float dy1 = 1.0 * yPixelOffset;\n mat3 shadowKernel;\n mat3 depthKernel;\n depthKernel[ 0 ][ 0 ] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );\n depthKernel[ 0 ][ 1 ] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );\n depthKernel[ 0 ][ 2 ] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );\n depthKernel[ 1 ][ 0 ] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );\n depthKernel[ 1 ][ 1 ] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );\n depthKernel[ 1 ][ 2 ] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );\n depthKernel[ 2 ][ 0 ] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );\n depthKernel[ 2 ][ 1 ] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );\n depthKernel[ 2 ][ 2 ] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );\n vec3 shadowZ = vec3( shadowCoord.z );\n shadowKernel[ 0 ] = vec3( lessThan( depthKernel[ 0 ], shadowZ ) );\n shadowKernel[ 0 ] *= vec3( 0.25 );\n shadowKernel[ 1 ] = vec3( lessThan( depthKernel[ 1 ], shadowZ ) );\n shadowKernel[ 1 ] *= vec3( 0.25 );\n shadowKernel[ 2 ] = vec3( lessThan( depthKernel[ 2 ], shadowZ ) );\n shadowKernel[ 2 ] *= vec3( 0.25 );\n vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[ i ].xy );\n shadowKernel[ 0 ] = mix( shadowKernel[ 1 ], shadowKernel[ 0 ], fractionalCoord.x );\n shadowKernel[ 1 ] = mix( shadowKernel[ 2 ], shadowKernel[ 1 ], fractionalCoord.x );\n vec4 shadowValues;\n shadowValues.x = mix( shadowKernel[ 0 ][ 1 ], shadowKernel[ 0 ][ 0 ], fractionalCoord.y );\n shadowValues.y = mix( shadowKernel[ 0 ][ 2 ], shadowKernel[ 0 ][ 1 ], fractionalCoord.y );\n shadowValues.z = mix( shadowKernel[ 1 ][ 1 ], shadowKernel[ 1 ][ 0 ], fractionalCoord.y );\n shadowValues.w = mix( shadowKernel[ 1 ][ 2 ], shadowKernel[ 1 ][ 1 ], fractionalCoord.y );\n shadow = dot( shadowValues, vec4( 1.0 ) ) * shadowDarkness[ i ];\n #else\n shadowCoord.z += shadowBias[ i ];\n vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );\n float fDepth = unpackDepth( rgbaDepth );\n if ( fDepth < shadowCoord.z )\n shadow = shadowDarkness[ i ];\n #endif\n }\n#ifdef SHADOWMAP_DEBUG\n if ( inFrustum ) {\n if ( i == 0 ) {\n outgoingLight *= vec3( 1.0, 0.5, 0.0 );\n } else if ( i == 1 ) {\n outgoingLight *= vec3( 0.0, 1.0, 0.8 );\n } else {\n outgoingLight *= vec3( 0.0, 0.5, 1.0 );\n }\n }\n#endif\n#ifdef POINT_LIGHT_SHADOWS\n }\n#endif\n shadowMask = shadowMask * vec3( 1.0 - shadow );\n shadows[ i ] = 1.0 - shadow;\n }\n#endif\n";
  13910. // File:src/renderers/shaders/ShaderChunk/shadowmap_pars_fragment.glsl
  13911. THREE.ShaderChunk[ 'shadowmap_pars_fragment' ] = "#ifdef USE_SHADOWMAP\n uniform sampler2D shadowMap[ NUM_SHADOWS ];\n uniform vec2 shadowMapSize[ NUM_SHADOWS ];\n uniform float shadowDarkness[ NUM_SHADOWS ];\n uniform float shadowBias[ NUM_SHADOWS ];\n varying vec4 vShadowCoord[ NUM_SHADOWS ];\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 float depth = dot( rgba_depth, bit_shift );\n return depth;\n }\n #ifdef POINT_LIGHT_SHADOWS\n void adjustShadowValue1K( const float testDepth, const vec4 textureData, const float bias, inout float shadowValue ) {\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 if ( testDepth >= dot( textureData, bitSh ) * 1000.0 + bias )\n shadowValue += 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 #endif\n#endif\n";
  13912. // File:src/renderers/shaders/ShaderChunk/shadowmap_pars_vertex.glsl
  13913. THREE.ShaderChunk[ 'shadowmap_pars_vertex' ] = "#ifdef USE_SHADOWMAP\n uniform mat4 shadowMatrix[ NUM_SHADOWS ];\n varying vec4 vShadowCoord[ NUM_SHADOWS ];\n#endif\n";
  13914. // File:src/renderers/shaders/ShaderChunk/shadowmap_vertex.glsl
  13915. THREE.ShaderChunk[ 'shadowmap_vertex' ] = "#ifdef USE_SHADOWMAP\n for ( int i = 0; i < NUM_SHADOWS; i ++ ) {\n vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;\n }\n#endif";
  13916. // File:src/renderers/shaders/ShaderChunk/skinbase_vertex.glsl
  13917. 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";
  13918. // File:src/renderers/shaders/ShaderChunk/skinning_pars_vertex.glsl
  13919. 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";
  13920. // File:src/renderers/shaders/ShaderChunk/skinning_vertex.glsl
  13921. 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";
  13922. // File:src/renderers/shaders/ShaderChunk/skinnormal_vertex.glsl
  13923. 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";
  13924. // File:src/renderers/shaders/ShaderChunk/specularmap_fragment.glsl
  13925. 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";
  13926. // File:src/renderers/shaders/ShaderChunk/specularmap_pars_fragment.glsl
  13927. THREE.ShaderChunk[ 'specularmap_pars_fragment' ] = "#ifdef USE_SPECULARMAP\n uniform sampler2D specularMap;\n#endif";
  13928. // File:src/renderers/shaders/ShaderChunk/uv2_pars_fragment.glsl
  13929. THREE.ShaderChunk[ 'uv2_pars_fragment' ] = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n varying vec2 vUv2;\n#endif";
  13930. // File:src/renderers/shaders/ShaderChunk/uv2_pars_vertex.glsl
  13931. THREE.ShaderChunk[ 'uv2_pars_vertex' ] = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n attribute vec2 uv2;\n varying vec2 vUv2;\n#endif";
  13932. // File:src/renderers/shaders/ShaderChunk/uv2_vertex.glsl
  13933. THREE.ShaderChunk[ 'uv2_vertex' ] = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n vUv2 = uv2;\n#endif";
  13934. // File:src/renderers/shaders/ShaderChunk/uv_pars_fragment.glsl
  13935. 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";
  13936. // File:src/renderers/shaders/ShaderChunk/uv_pars_vertex.glsl
  13937. 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";
  13938. // File:src/renderers/shaders/ShaderChunk/uv_vertex.glsl
  13939. 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";
  13940. // File:src/renderers/shaders/ShaderChunk/worldpos_vertex.glsl
  13941. 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";
  13942. // File:src/renderers/shaders/UniformsUtils.js
  13943. /**
  13944. * Uniform Utilities
  13945. */
  13946. THREE.UniformsUtils = {
  13947. merge: function ( uniforms ) {
  13948. var merged = {};
  13949. for ( var u = 0; u < uniforms.length; u ++ ) {
  13950. var tmp = this.clone( uniforms[ u ] );
  13951. for ( var p in tmp ) {
  13952. merged[ p ] = tmp[ p ];
  13953. }
  13954. }
  13955. return merged;
  13956. },
  13957. clone: function ( uniforms_src ) {
  13958. var uniforms_dst = {};
  13959. for ( var u in uniforms_src ) {
  13960. uniforms_dst[ u ] = {};
  13961. for ( var p in uniforms_src[ u ] ) {
  13962. var parameter_src = uniforms_src[ u ][ p ];
  13963. if ( parameter_src instanceof THREE.Color ||
  13964. parameter_src instanceof THREE.Vector2 ||
  13965. parameter_src instanceof THREE.Vector3 ||
  13966. parameter_src instanceof THREE.Vector4 ||
  13967. parameter_src instanceof THREE.Matrix3 ||
  13968. parameter_src instanceof THREE.Matrix4 ||
  13969. parameter_src instanceof THREE.Texture ) {
  13970. uniforms_dst[ u ][ p ] = parameter_src.clone();
  13971. } else if ( Array.isArray( parameter_src ) ) {
  13972. uniforms_dst[ u ][ p ] = parameter_src.slice();
  13973. } else {
  13974. uniforms_dst[ u ][ p ] = parameter_src;
  13975. }
  13976. }
  13977. }
  13978. return uniforms_dst;
  13979. }
  13980. };
  13981. // File:src/renderers/shaders/UniformsLib.js
  13982. /**
  13983. * Uniforms library for shared webgl shaders
  13984. */
  13985. THREE.UniformsLib = {
  13986. common: {
  13987. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  13988. "opacity" : { type: "f", value: 1.0 },
  13989. "map" : { type: "t", value: null },
  13990. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  13991. "specularMap" : { type: "t", value: null },
  13992. "alphaMap" : { type: "t", value: null },
  13993. "envMap" : { type: "t", value: null },
  13994. "flipEnvMap" : { type: "f", value: - 1 },
  13995. "reflectivity" : { type: "f", value: 1.0 },
  13996. "refractionRatio" : { type: "f", value: 0.98 }
  13997. },
  13998. aomap: {
  13999. "aoMap" : { type: "t", value: null },
  14000. "aoMapIntensity" : { type: "f", value: 1 },
  14001. },
  14002. lightmap: {
  14003. "lightMap" : { type: "t", value: null },
  14004. "lightMapIntensity" : { type: "f", value: 1 },
  14005. },
  14006. emissivemap: {
  14007. "emissiveMap" : { type: "t", value: null },
  14008. },
  14009. bumpmap: {
  14010. "bumpMap" : { type: "t", value: null },
  14011. "bumpScale" : { type: "f", value: 1 }
  14012. },
  14013. normalmap: {
  14014. "normalMap" : { type: "t", value: null },
  14015. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  14016. },
  14017. displacementmap: {
  14018. "displacementMap" : { type: "t", value: null },
  14019. "displacementScale" : { type: "f", value: 1 },
  14020. "displacementBias" : { type: "f", value: 0 }
  14021. },
  14022. roughnessmap: {
  14023. "roughnessMap" : { type: "t", value: null }
  14024. },
  14025. metalnessmap: {
  14026. "metalnessMap" : { type: "t", value: null }
  14027. },
  14028. fog: {
  14029. "fogDensity" : { type: "f", value: 0.00025 },
  14030. "fogNear" : { type: "f", value: 1 },
  14031. "fogFar" : { type: "f", value: 2000 },
  14032. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  14033. },
  14034. ambient: {
  14035. "ambientLightColor" : { type: "fv", value: [] }
  14036. },
  14037. lights: {
  14038. "directionalLights" : { type: "sa", value: [], properties: {
  14039. "direction": { type: "v3" },
  14040. "color": { type: "c" },
  14041. "shadow": { type: "i" }
  14042. } },
  14043. "hemisphereLights" : { type: "sa", value: [], properties: {
  14044. "direction": { type: "v3" },
  14045. "skyColor": { type: "c" },
  14046. "groundColor": { type: "c" }
  14047. } },
  14048. "pointLights" : { type: "sa", value: [], properties: {
  14049. "color": { type: "c" },
  14050. "position": { type: "v3" },
  14051. "decay": { type: "f" },
  14052. "distance": { type: "f" },
  14053. "shadow": { type: "i" }
  14054. } },
  14055. "spotLights" : { type: "sa", value: [], properties: {
  14056. "color": { type: "c" },
  14057. "position": { type: "v3" },
  14058. "direction": { type: "v3" },
  14059. "distance": { type: "f" },
  14060. "angleCos": { type: "f" },
  14061. "exponent": { type: "f" },
  14062. "decay": { type: "f" },
  14063. "shadow": { type: "i" }
  14064. } }
  14065. },
  14066. points: {
  14067. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  14068. "opacity" : { type: "f", value: 1.0 },
  14069. "size" : { type: "f", value: 1.0 },
  14070. "scale" : { type: "f", value: 1.0 },
  14071. "map" : { type: "t", value: null },
  14072. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) }
  14073. },
  14074. shadowmap: {
  14075. "shadowMap": { type: "tv", value: [] },
  14076. "shadowMapSize": { type: "v2v", value: [] },
  14077. "shadowBias" : { type: "fv1", value: [] },
  14078. "shadowDarkness": { type: "fv1", value: [] },
  14079. "shadowMatrix" : { type: "m4v", value: [] }
  14080. }
  14081. };
  14082. // File:src/renderers/shaders/ShaderLib.js
  14083. /**
  14084. * Webgl Shader Library for three.js
  14085. *
  14086. * @author alteredq / http://alteredqualia.com/
  14087. * @author mrdoob / http://mrdoob.com/
  14088. * @author mikael emtinger / http://gomo.se/
  14089. */
  14090. THREE.ShaderLib = {
  14091. 'basic': {
  14092. uniforms: THREE.UniformsUtils.merge( [
  14093. THREE.UniformsLib[ "common" ],
  14094. THREE.UniformsLib[ "aomap" ],
  14095. THREE.UniformsLib[ "fog" ],
  14096. THREE.UniformsLib[ "shadowmap" ]
  14097. ] ),
  14098. vertexShader: [
  14099. THREE.ShaderChunk[ "common" ],
  14100. THREE.ShaderChunk[ "uv_pars_vertex" ],
  14101. THREE.ShaderChunk[ "uv2_pars_vertex" ],
  14102. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  14103. THREE.ShaderChunk[ "color_pars_vertex" ],
  14104. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  14105. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  14106. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  14107. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  14108. "void main() {",
  14109. THREE.ShaderChunk[ "uv_vertex" ],
  14110. THREE.ShaderChunk[ "uv2_vertex" ],
  14111. THREE.ShaderChunk[ "color_vertex" ],
  14112. THREE.ShaderChunk[ "skinbase_vertex" ],
  14113. " #ifdef USE_ENVMAP",
  14114. THREE.ShaderChunk[ "beginnormal_vertex" ],
  14115. THREE.ShaderChunk[ "morphnormal_vertex" ],
  14116. THREE.ShaderChunk[ "skinnormal_vertex" ],
  14117. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  14118. " #endif",
  14119. THREE.ShaderChunk[ "begin_vertex" ],
  14120. THREE.ShaderChunk[ "morphtarget_vertex" ],
  14121. THREE.ShaderChunk[ "skinning_vertex" ],
  14122. THREE.ShaderChunk[ "project_vertex" ],
  14123. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  14124. THREE.ShaderChunk[ "worldpos_vertex" ],
  14125. THREE.ShaderChunk[ "envmap_vertex" ],
  14126. THREE.ShaderChunk[ "shadowmap_vertex" ],
  14127. "}"
  14128. ].join( "\n" ),
  14129. fragmentShader: [
  14130. "uniform vec3 diffuse;",
  14131. "uniform float opacity;",
  14132. "#ifndef FLAT_SHADED",
  14133. " varying vec3 vNormal;",
  14134. "#endif",
  14135. THREE.ShaderChunk[ "common" ],
  14136. THREE.ShaderChunk[ "color_pars_fragment" ],
  14137. THREE.ShaderChunk[ "uv_pars_fragment" ],
  14138. THREE.ShaderChunk[ "uv2_pars_fragment" ],
  14139. THREE.ShaderChunk[ "map_pars_fragment" ],
  14140. THREE.ShaderChunk[ "alphamap_pars_fragment" ],
  14141. THREE.ShaderChunk[ "aomap_pars_fragment" ],
  14142. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  14143. THREE.ShaderChunk[ "fog_pars_fragment" ],
  14144. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  14145. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  14146. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  14147. "void main() {",
  14148. " vec4 diffuseColor = vec4( diffuse, opacity );",
  14149. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  14150. THREE.ShaderChunk[ "map_fragment" ],
  14151. THREE.ShaderChunk[ "color_fragment" ],
  14152. THREE.ShaderChunk[ "alphamap_fragment" ],
  14153. THREE.ShaderChunk[ "alphatest_fragment" ],
  14154. THREE.ShaderChunk[ "specularmap_fragment" ],
  14155. " ReflectedLight reflectedLight;",
  14156. " reflectedLight.directDiffuse = vec3( 0.0 );",
  14157. " reflectedLight.directSpecular = vec3( 0.0 );",
  14158. " reflectedLight.indirectDiffuse = diffuseColor.rgb;",
  14159. " reflectedLight.indirectSpecular = vec3( 0.0 );",
  14160. THREE.ShaderChunk[ "aomap_fragment" ],
  14161. THREE.ShaderChunk[ "shadowmap_fragment" ],
  14162. "reflectedLight.indirectDiffuse *= shadowMask;",
  14163. "vec3 outgoingLight = reflectedLight.indirectDiffuse;",
  14164. THREE.ShaderChunk[ "envmap_fragment" ],
  14165. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  14166. THREE.ShaderChunk[ "fog_fragment" ],
  14167. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );",
  14168. "}"
  14169. ].join( "\n" )
  14170. },
  14171. 'lambert': {
  14172. uniforms: THREE.UniformsUtils.merge( [
  14173. THREE.UniformsLib[ "common" ],
  14174. THREE.UniformsLib[ "fog" ],
  14175. THREE.UniformsLib[ "ambient" ],
  14176. THREE.UniformsLib[ "lights" ],
  14177. THREE.UniformsLib[ "shadowmap" ],
  14178. {
  14179. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) }
  14180. }
  14181. ] ),
  14182. vertexShader: [
  14183. "#define LAMBERT",
  14184. "varying vec3 vLightFront;",
  14185. "#ifdef DOUBLE_SIDED",
  14186. " varying vec3 vLightBack;",
  14187. "#endif",
  14188. THREE.ShaderChunk[ "common" ],
  14189. THREE.ShaderChunk[ "uv_pars_vertex" ],
  14190. THREE.ShaderChunk[ "uv2_pars_vertex" ],
  14191. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  14192. THREE.ShaderChunk[ "bsdfs" ],
  14193. THREE.ShaderChunk[ "lights_pars" ],
  14194. THREE.ShaderChunk[ "color_pars_vertex" ],
  14195. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  14196. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  14197. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  14198. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  14199. "void main() {",
  14200. THREE.ShaderChunk[ "uv_vertex" ],
  14201. THREE.ShaderChunk[ "uv2_vertex" ],
  14202. THREE.ShaderChunk[ "color_vertex" ],
  14203. THREE.ShaderChunk[ "beginnormal_vertex" ],
  14204. THREE.ShaderChunk[ "morphnormal_vertex" ],
  14205. THREE.ShaderChunk[ "skinbase_vertex" ],
  14206. THREE.ShaderChunk[ "skinnormal_vertex" ],
  14207. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  14208. THREE.ShaderChunk[ "begin_vertex" ],
  14209. THREE.ShaderChunk[ "morphtarget_vertex" ],
  14210. THREE.ShaderChunk[ "skinning_vertex" ],
  14211. THREE.ShaderChunk[ "project_vertex" ],
  14212. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  14213. THREE.ShaderChunk[ "worldpos_vertex" ],
  14214. THREE.ShaderChunk[ "envmap_vertex" ],
  14215. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  14216. THREE.ShaderChunk[ "shadowmap_vertex" ],
  14217. "}"
  14218. ].join( "\n" ),
  14219. fragmentShader: [
  14220. "uniform vec3 diffuse;",
  14221. "uniform vec3 emissive;",
  14222. "uniform float opacity;",
  14223. "varying vec3 vLightFront;",
  14224. "#ifdef DOUBLE_SIDED",
  14225. " varying vec3 vLightBack;",
  14226. "#endif",
  14227. THREE.ShaderChunk[ "common" ],
  14228. THREE.ShaderChunk[ "color_pars_fragment" ],
  14229. THREE.ShaderChunk[ "uv_pars_fragment" ],
  14230. THREE.ShaderChunk[ "uv2_pars_fragment" ],
  14231. THREE.ShaderChunk[ "map_pars_fragment" ],
  14232. THREE.ShaderChunk[ "alphamap_pars_fragment" ],
  14233. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  14234. THREE.ShaderChunk[ "ambient_pars" ],
  14235. THREE.ShaderChunk[ "fog_pars_fragment" ],
  14236. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  14237. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  14238. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  14239. "void main() {",
  14240. " vec3 outgoingLight = vec3( 0.0 );",
  14241. " vec4 diffuseColor = vec4( diffuse, opacity );",
  14242. " vec3 totalAmbientLight = getAmbientLightIrradiance( ambientLightColor );",
  14243. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  14244. THREE.ShaderChunk[ "map_fragment" ],
  14245. THREE.ShaderChunk[ "color_fragment" ],
  14246. THREE.ShaderChunk[ "alphamap_fragment" ],
  14247. THREE.ShaderChunk[ "alphatest_fragment" ],
  14248. THREE.ShaderChunk[ "specularmap_fragment" ],
  14249. THREE.ShaderChunk[ "shadowmap_fragment" ],
  14250. " #ifdef DOUBLE_SIDED",
  14251. " if ( gl_FrontFacing )",
  14252. " outgoingLight += RECIPROCAL_PI * diffuseColor.rgb * ( vLightFront * shadowMask + totalAmbientLight ) + emissive;",
  14253. " else",
  14254. " outgoingLight += RECIPROCAL_PI * diffuseColor.rgb * ( vLightBack * shadowMask + totalAmbientLight ) + emissive;",
  14255. " #else",
  14256. " outgoingLight += RECIPROCAL_PI * diffuseColor.rgb * ( vLightFront * shadowMask + totalAmbientLight ) + emissive;",
  14257. " #endif",
  14258. THREE.ShaderChunk[ "envmap_fragment" ],
  14259. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  14260. THREE.ShaderChunk[ "fog_fragment" ],
  14261. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );",
  14262. "}"
  14263. ].join( "\n" )
  14264. },
  14265. 'phong': {
  14266. uniforms: THREE.UniformsUtils.merge( [
  14267. THREE.UniformsLib[ "common" ],
  14268. THREE.UniformsLib[ "aomap" ],
  14269. THREE.UniformsLib[ "lightmap" ],
  14270. THREE.UniformsLib[ "emissivemap" ],
  14271. THREE.UniformsLib[ "bumpmap" ],
  14272. THREE.UniformsLib[ "normalmap" ],
  14273. THREE.UniformsLib[ "displacementmap" ],
  14274. THREE.UniformsLib[ "fog" ],
  14275. THREE.UniformsLib[ "ambient" ],
  14276. THREE.UniformsLib[ "lights" ],
  14277. THREE.UniformsLib[ "shadowmap" ],
  14278. {
  14279. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  14280. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  14281. "shininess": { type: "f", value: 30 }
  14282. }
  14283. ] ),
  14284. vertexShader: [
  14285. "#define PHONG",
  14286. "varying vec3 vViewPosition;",
  14287. "#ifndef FLAT_SHADED",
  14288. " varying vec3 vNormal;",
  14289. "#endif",
  14290. THREE.ShaderChunk[ "common" ],
  14291. THREE.ShaderChunk[ "uv_pars_vertex" ],
  14292. THREE.ShaderChunk[ "uv2_pars_vertex" ],
  14293. THREE.ShaderChunk[ "displacementmap_pars_vertex" ],
  14294. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  14295. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  14296. THREE.ShaderChunk[ "color_pars_vertex" ],
  14297. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  14298. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  14299. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  14300. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  14301. "void main() {",
  14302. THREE.ShaderChunk[ "uv_vertex" ],
  14303. THREE.ShaderChunk[ "uv2_vertex" ],
  14304. THREE.ShaderChunk[ "color_vertex" ],
  14305. THREE.ShaderChunk[ "beginnormal_vertex" ],
  14306. THREE.ShaderChunk[ "morphnormal_vertex" ],
  14307. THREE.ShaderChunk[ "skinbase_vertex" ],
  14308. THREE.ShaderChunk[ "skinnormal_vertex" ],
  14309. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  14310. "#ifndef FLAT_SHADED", // Normal computed with derivatives when FLAT_SHADED
  14311. " vNormal = normalize( transformedNormal );",
  14312. "#endif",
  14313. THREE.ShaderChunk[ "begin_vertex" ],
  14314. THREE.ShaderChunk[ "displacementmap_vertex" ],
  14315. THREE.ShaderChunk[ "morphtarget_vertex" ],
  14316. THREE.ShaderChunk[ "skinning_vertex" ],
  14317. THREE.ShaderChunk[ "project_vertex" ],
  14318. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  14319. " vViewPosition = - mvPosition.xyz;",
  14320. THREE.ShaderChunk[ "worldpos_vertex" ],
  14321. THREE.ShaderChunk[ "envmap_vertex" ],
  14322. THREE.ShaderChunk[ "lights_phong_vertex" ],
  14323. THREE.ShaderChunk[ "shadowmap_vertex" ],
  14324. "}"
  14325. ].join( "\n" ),
  14326. fragmentShader: [
  14327. "#define PHONG",
  14328. "uniform vec3 diffuse;",
  14329. "uniform vec3 emissive;",
  14330. "uniform vec3 specular;",
  14331. "uniform float shininess;",
  14332. "uniform float opacity;",
  14333. THREE.ShaderChunk[ "common" ],
  14334. THREE.ShaderChunk[ "color_pars_fragment" ],
  14335. THREE.ShaderChunk[ "uv_pars_fragment" ],
  14336. THREE.ShaderChunk[ "uv2_pars_fragment" ],
  14337. THREE.ShaderChunk[ "map_pars_fragment" ],
  14338. THREE.ShaderChunk[ "alphamap_pars_fragment" ],
  14339. THREE.ShaderChunk[ "aomap_pars_fragment" ],
  14340. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  14341. THREE.ShaderChunk[ "emissivemap_pars_fragment" ],
  14342. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  14343. THREE.ShaderChunk[ "fog_pars_fragment" ],
  14344. THREE.ShaderChunk[ "bsdfs" ],
  14345. THREE.ShaderChunk[ "ambient_pars" ],
  14346. THREE.ShaderChunk[ "lights_pars" ],
  14347. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  14348. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  14349. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  14350. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  14351. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  14352. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  14353. "void main() {",
  14354. " vec4 diffuseColor = vec4( diffuse, opacity );",
  14355. " ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );",
  14356. " vec3 totalEmissiveLight = emissive;",
  14357. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  14358. THREE.ShaderChunk[ "map_fragment" ],
  14359. THREE.ShaderChunk[ "color_fragment" ],
  14360. THREE.ShaderChunk[ "alphamap_fragment" ],
  14361. THREE.ShaderChunk[ "alphatest_fragment" ],
  14362. THREE.ShaderChunk[ "specularmap_fragment" ],
  14363. THREE.ShaderChunk[ "normal_fragment" ],
  14364. THREE.ShaderChunk[ "emissivemap_fragment" ],
  14365. THREE.ShaderChunk[ "shadowmap_fragment" ],
  14366. // accumulation
  14367. THREE.ShaderChunk[ "lights_phong_fragment" ],
  14368. THREE.ShaderChunk[ "lights_template" ],
  14369. THREE.ShaderChunk[ "lightmap_fragment" ],
  14370. // modulation
  14371. THREE.ShaderChunk[ "aomap_fragment" ],
  14372. "vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveLight;",
  14373. THREE.ShaderChunk[ "envmap_fragment" ],
  14374. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  14375. THREE.ShaderChunk[ "fog_fragment" ],
  14376. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );",
  14377. "}"
  14378. ].join( "\n" )
  14379. },
  14380. 'standard': {
  14381. uniforms: THREE.UniformsUtils.merge( [
  14382. THREE.UniformsLib[ "common" ],
  14383. THREE.UniformsLib[ "aomap" ],
  14384. THREE.UniformsLib[ "lightmap" ],
  14385. THREE.UniformsLib[ "emissivemap" ],
  14386. THREE.UniformsLib[ "bumpmap" ],
  14387. THREE.UniformsLib[ "normalmap" ],
  14388. THREE.UniformsLib[ "displacementmap" ],
  14389. THREE.UniformsLib[ "roughnessmap" ],
  14390. THREE.UniformsLib[ "metalnessmap" ],
  14391. THREE.UniformsLib[ "fog" ],
  14392. THREE.UniformsLib[ "ambient" ],
  14393. THREE.UniformsLib[ "lights" ],
  14394. THREE.UniformsLib[ "shadowmap" ],
  14395. {
  14396. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  14397. "roughness": { type: "f", value: 0.5 },
  14398. "metalness": { type: "f", value: 0 },
  14399. "envMapIntensity" : { type: "f", value: 1 } // temporary
  14400. }
  14401. ] ),
  14402. vertexShader: [
  14403. "#define STANDARD",
  14404. "varying vec3 vViewPosition;",
  14405. "#ifndef FLAT_SHADED",
  14406. " varying vec3 vNormal;",
  14407. "#endif",
  14408. THREE.ShaderChunk[ "common" ],
  14409. THREE.ShaderChunk[ "uv_pars_vertex" ],
  14410. THREE.ShaderChunk[ "uv2_pars_vertex" ],
  14411. THREE.ShaderChunk[ "displacementmap_pars_vertex" ],
  14412. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  14413. THREE.ShaderChunk[ "color_pars_vertex" ],
  14414. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  14415. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  14416. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  14417. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  14418. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  14419. "void main() {", // STANDARD
  14420. THREE.ShaderChunk[ "uv_vertex" ],
  14421. THREE.ShaderChunk[ "uv2_vertex" ],
  14422. THREE.ShaderChunk[ "color_vertex" ],
  14423. THREE.ShaderChunk[ "beginnormal_vertex" ],
  14424. THREE.ShaderChunk[ "morphnormal_vertex" ],
  14425. THREE.ShaderChunk[ "skinbase_vertex" ],
  14426. THREE.ShaderChunk[ "skinnormal_vertex" ],
  14427. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  14428. "#ifndef FLAT_SHADED", // Normal computed with derivatives when FLAT_SHADED
  14429. " vNormal = normalize( transformedNormal );",
  14430. "#endif",
  14431. THREE.ShaderChunk[ "begin_vertex" ],
  14432. THREE.ShaderChunk[ "displacementmap_vertex" ],
  14433. THREE.ShaderChunk[ "morphtarget_vertex" ],
  14434. THREE.ShaderChunk[ "skinning_vertex" ],
  14435. THREE.ShaderChunk[ "project_vertex" ],
  14436. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  14437. " vViewPosition = - mvPosition.xyz;",
  14438. THREE.ShaderChunk[ "worldpos_vertex" ],
  14439. THREE.ShaderChunk[ "envmap_vertex" ],
  14440. THREE.ShaderChunk[ "shadowmap_vertex" ],
  14441. "}"
  14442. ].join( "\n" ),
  14443. fragmentShader: [
  14444. "#define STANDARD",
  14445. "uniform vec3 diffuse;",
  14446. "uniform vec3 emissive;",
  14447. "uniform float roughness;",
  14448. "uniform float metalness;",
  14449. "uniform float opacity;",
  14450. "uniform float envMapIntensity;", // temporary
  14451. "varying vec3 vViewPosition;",
  14452. "#ifndef FLAT_SHADED",
  14453. " varying vec3 vNormal;",
  14454. "#endif",
  14455. THREE.ShaderChunk[ "common" ],
  14456. THREE.ShaderChunk[ "color_pars_fragment" ],
  14457. THREE.ShaderChunk[ "uv_pars_fragment" ],
  14458. THREE.ShaderChunk[ "uv2_pars_fragment" ],
  14459. THREE.ShaderChunk[ "map_pars_fragment" ],
  14460. THREE.ShaderChunk[ "alphamap_pars_fragment" ],
  14461. THREE.ShaderChunk[ "aomap_pars_fragment" ],
  14462. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  14463. THREE.ShaderChunk[ "emissivemap_pars_fragment" ],
  14464. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  14465. THREE.ShaderChunk[ "fog_pars_fragment" ],
  14466. THREE.ShaderChunk[ "bsdfs" ],
  14467. THREE.ShaderChunk[ "ambient_pars" ],
  14468. THREE.ShaderChunk[ "lights_pars" ],
  14469. THREE.ShaderChunk[ "lights_standard_pars_fragment" ],
  14470. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  14471. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  14472. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  14473. THREE.ShaderChunk[ "roughnessmap_pars_fragment" ],
  14474. THREE.ShaderChunk[ "metalnessmap_pars_fragment" ],
  14475. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  14476. "void main() {",
  14477. " vec4 diffuseColor = vec4( diffuse, opacity );",
  14478. " ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );",
  14479. " vec3 totalEmissiveLight = emissive;",
  14480. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  14481. THREE.ShaderChunk[ "map_fragment" ],
  14482. THREE.ShaderChunk[ "color_fragment" ],
  14483. THREE.ShaderChunk[ "alphamap_fragment" ],
  14484. THREE.ShaderChunk[ "alphatest_fragment" ],
  14485. THREE.ShaderChunk[ "specularmap_fragment" ],
  14486. THREE.ShaderChunk[ "roughnessmap_fragment" ],
  14487. THREE.ShaderChunk[ "metalnessmap_fragment" ],
  14488. THREE.ShaderChunk[ "normal_fragment" ],
  14489. THREE.ShaderChunk[ "emissivemap_fragment" ],
  14490. THREE.ShaderChunk[ "shadowmap_fragment" ],
  14491. // accumulation
  14492. THREE.ShaderChunk[ "lights_standard_fragment" ],
  14493. THREE.ShaderChunk[ "lights_template" ],
  14494. THREE.ShaderChunk[ "lightmap_fragment" ],
  14495. // modulation
  14496. THREE.ShaderChunk[ "aomap_fragment" ],
  14497. "vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveLight;",
  14498. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  14499. THREE.ShaderChunk[ "fog_fragment" ],
  14500. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );",
  14501. "}"
  14502. ].join( "\n" )
  14503. },
  14504. 'points': {
  14505. uniforms: THREE.UniformsUtils.merge( [
  14506. THREE.UniformsLib[ "points" ],
  14507. THREE.UniformsLib[ "fog" ],
  14508. THREE.UniformsLib[ "shadowmap" ]
  14509. ] ),
  14510. vertexShader: [
  14511. "uniform float size;",
  14512. "uniform float scale;",
  14513. THREE.ShaderChunk[ "common" ],
  14514. THREE.ShaderChunk[ "color_pars_vertex" ],
  14515. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  14516. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  14517. "void main() {",
  14518. THREE.ShaderChunk[ "color_vertex" ],
  14519. THREE.ShaderChunk[ "begin_vertex" ],
  14520. THREE.ShaderChunk[ "project_vertex" ],
  14521. " #ifdef USE_SIZEATTENUATION",
  14522. " gl_PointSize = size * ( scale / - mvPosition.z );",
  14523. " #else",
  14524. " gl_PointSize = size;",
  14525. " #endif",
  14526. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  14527. THREE.ShaderChunk[ "worldpos_vertex" ],
  14528. THREE.ShaderChunk[ "shadowmap_vertex" ],
  14529. "}"
  14530. ].join( "\n" ),
  14531. fragmentShader: [
  14532. "uniform vec3 diffuse;",
  14533. "uniform float opacity;",
  14534. THREE.ShaderChunk[ "common" ],
  14535. THREE.ShaderChunk[ "color_pars_fragment" ],
  14536. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  14537. THREE.ShaderChunk[ "fog_pars_fragment" ],
  14538. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  14539. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  14540. "void main() {",
  14541. " vec3 outgoingLight = vec3( 0.0 );",
  14542. " vec4 diffuseColor = vec4( diffuse, opacity );",
  14543. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  14544. THREE.ShaderChunk[ "map_particle_fragment" ],
  14545. THREE.ShaderChunk[ "color_fragment" ],
  14546. THREE.ShaderChunk[ "alphatest_fragment" ],
  14547. THREE.ShaderChunk[ "shadowmap_fragment" ],
  14548. " outgoingLight = diffuseColor.rgb * shadowMask;",
  14549. THREE.ShaderChunk[ "fog_fragment" ],
  14550. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );",
  14551. "}"
  14552. ].join( "\n" )
  14553. },
  14554. 'dashed': {
  14555. uniforms: THREE.UniformsUtils.merge( [
  14556. THREE.UniformsLib[ "common" ],
  14557. THREE.UniformsLib[ "fog" ],
  14558. {
  14559. "scale" : { type: "f", value: 1 },
  14560. "dashSize" : { type: "f", value: 1 },
  14561. "totalSize": { type: "f", value: 2 }
  14562. }
  14563. ] ),
  14564. vertexShader: [
  14565. "uniform float scale;",
  14566. "attribute float lineDistance;",
  14567. "varying float vLineDistance;",
  14568. THREE.ShaderChunk[ "common" ],
  14569. THREE.ShaderChunk[ "color_pars_vertex" ],
  14570. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  14571. "void main() {",
  14572. THREE.ShaderChunk[ "color_vertex" ],
  14573. " vLineDistance = scale * lineDistance;",
  14574. " vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  14575. " gl_Position = projectionMatrix * mvPosition;",
  14576. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  14577. "}"
  14578. ].join( "\n" ),
  14579. fragmentShader: [
  14580. "uniform vec3 diffuse;",
  14581. "uniform float opacity;",
  14582. "uniform float dashSize;",
  14583. "uniform float totalSize;",
  14584. "varying float vLineDistance;",
  14585. THREE.ShaderChunk[ "common" ],
  14586. THREE.ShaderChunk[ "color_pars_fragment" ],
  14587. THREE.ShaderChunk[ "fog_pars_fragment" ],
  14588. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  14589. "void main() {",
  14590. " if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  14591. " discard;",
  14592. " }",
  14593. " vec3 outgoingLight = vec3( 0.0 );",
  14594. " vec4 diffuseColor = vec4( diffuse, opacity );",
  14595. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  14596. THREE.ShaderChunk[ "color_fragment" ],
  14597. " outgoingLight = diffuseColor.rgb;", // simple shader
  14598. THREE.ShaderChunk[ "fog_fragment" ],
  14599. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );",
  14600. "}"
  14601. ].join( "\n" )
  14602. },
  14603. 'depth': {
  14604. uniforms: {
  14605. "mNear": { type: "f", value: 1.0 },
  14606. "mFar" : { type: "f", value: 2000.0 },
  14607. "opacity" : { type: "f", value: 1.0 }
  14608. },
  14609. vertexShader: [
  14610. THREE.ShaderChunk[ "common" ],
  14611. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  14612. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  14613. "void main() {",
  14614. THREE.ShaderChunk[ "begin_vertex" ],
  14615. THREE.ShaderChunk[ "morphtarget_vertex" ],
  14616. THREE.ShaderChunk[ "project_vertex" ],
  14617. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  14618. "}"
  14619. ].join( "\n" ),
  14620. fragmentShader: [
  14621. "uniform float mNear;",
  14622. "uniform float mFar;",
  14623. "uniform float opacity;",
  14624. THREE.ShaderChunk[ "common" ],
  14625. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  14626. "void main() {",
  14627. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  14628. " #ifdef USE_LOGDEPTHBUF_EXT",
  14629. " float depth = gl_FragDepthEXT / gl_FragCoord.w;",
  14630. " #else",
  14631. " float depth = gl_FragCoord.z / gl_FragCoord.w;",
  14632. " #endif",
  14633. " float color = 1.0 - smoothstep( mNear, mFar, depth );",
  14634. " gl_FragColor = vec4( vec3( color ), opacity );",
  14635. "}"
  14636. ].join( "\n" )
  14637. },
  14638. 'normal': {
  14639. uniforms: {
  14640. "opacity" : { type: "f", value: 1.0 }
  14641. },
  14642. vertexShader: [
  14643. "varying vec3 vNormal;",
  14644. THREE.ShaderChunk[ "common" ],
  14645. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  14646. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  14647. "void main() {",
  14648. " vNormal = normalize( normalMatrix * normal );",
  14649. THREE.ShaderChunk[ "begin_vertex" ],
  14650. THREE.ShaderChunk[ "morphtarget_vertex" ],
  14651. THREE.ShaderChunk[ "project_vertex" ],
  14652. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  14653. "}"
  14654. ].join( "\n" ),
  14655. fragmentShader: [
  14656. "uniform float opacity;",
  14657. "varying vec3 vNormal;",
  14658. THREE.ShaderChunk[ "common" ],
  14659. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  14660. "void main() {",
  14661. " gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  14662. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  14663. "}"
  14664. ].join( "\n" )
  14665. },
  14666. /* -------------------------------------------------------------------------
  14667. // Cube map shader
  14668. ------------------------------------------------------------------------- */
  14669. 'cube': {
  14670. uniforms: {
  14671. "tCube": { type: "t", value: null },
  14672. "tFlip": { type: "f", value: - 1 }
  14673. },
  14674. vertexShader: [
  14675. "varying vec3 vWorldPosition;",
  14676. THREE.ShaderChunk[ "common" ],
  14677. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  14678. "void main() {",
  14679. " vWorldPosition = transformDirection( position, modelMatrix );",
  14680. " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  14681. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  14682. "}"
  14683. ].join( "\n" ),
  14684. fragmentShader: [
  14685. "uniform samplerCube tCube;",
  14686. "uniform float tFlip;",
  14687. "varying vec3 vWorldPosition;",
  14688. THREE.ShaderChunk[ "common" ],
  14689. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  14690. "void main() {",
  14691. " gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  14692. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  14693. "}"
  14694. ].join( "\n" )
  14695. },
  14696. /* -------------------------------------------------------------------------
  14697. // Cube map shader
  14698. ------------------------------------------------------------------------- */
  14699. 'equirect': {
  14700. uniforms: {
  14701. "tEquirect": { type: "t", value: null },
  14702. "tFlip": { type: "f", value: - 1 }
  14703. },
  14704. vertexShader: [
  14705. "varying vec3 vWorldPosition;",
  14706. THREE.ShaderChunk[ "common" ],
  14707. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  14708. "void main() {",
  14709. " vWorldPosition = transformDirection( position, modelMatrix );",
  14710. " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  14711. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  14712. "}"
  14713. ].join( "\n" ),
  14714. fragmentShader: [
  14715. "uniform sampler2D tEquirect;",
  14716. "uniform float tFlip;",
  14717. "varying vec3 vWorldPosition;",
  14718. THREE.ShaderChunk[ "common" ],
  14719. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  14720. "void main() {",
  14721. // " gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  14722. "vec3 direction = normalize( vWorldPosition );",
  14723. "vec2 sampleUV;",
  14724. "sampleUV.y = saturate( tFlip * direction.y * -0.5 + 0.5 );",
  14725. "sampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;",
  14726. "gl_FragColor = texture2D( tEquirect, sampleUV );",
  14727. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  14728. "}"
  14729. ].join( "\n" )
  14730. },
  14731. /* Depth encoding into RGBA texture
  14732. *
  14733. * based on SpiderGL shadow map example
  14734. * http://spidergl.org/example.php?id=6
  14735. *
  14736. * originally from
  14737. * http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  14738. *
  14739. * see also
  14740. * http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  14741. */
  14742. 'depthRGBA': {
  14743. uniforms: {},
  14744. vertexShader: [
  14745. THREE.ShaderChunk[ "common" ],
  14746. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  14747. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  14748. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  14749. "void main() {",
  14750. THREE.ShaderChunk[ "skinbase_vertex" ],
  14751. THREE.ShaderChunk[ "begin_vertex" ],
  14752. THREE.ShaderChunk[ "morphtarget_vertex" ],
  14753. THREE.ShaderChunk[ "skinning_vertex" ],
  14754. THREE.ShaderChunk[ "project_vertex" ],
  14755. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  14756. "}"
  14757. ].join( "\n" ),
  14758. fragmentShader: [
  14759. THREE.ShaderChunk[ "common" ],
  14760. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  14761. "vec4 pack_depth( const in float depth ) {",
  14762. " const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  14763. " const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  14764. " vec4 res = mod( depth * bit_shift * vec4( 255 ), vec4( 256 ) ) / vec4( 255 );", // " vec4 res = fract( depth * bit_shift );",
  14765. " res -= res.xxyz * bit_mask;",
  14766. " return res;",
  14767. "}",
  14768. "void main() {",
  14769. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  14770. " #ifdef USE_LOGDEPTHBUF_EXT",
  14771. " gl_FragData[ 0 ] = pack_depth( gl_FragDepthEXT );",
  14772. " #else",
  14773. " gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  14774. " #endif",
  14775. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  14776. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  14777. //"gl_FragData[ 0 ] = pack_depth( z );",
  14778. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  14779. "}"
  14780. ].join( "\n" )
  14781. },
  14782. 'distanceRGBA': {
  14783. uniforms: {
  14784. "lightPos": { type: "v3", value: new THREE.Vector3( 0, 0, 0 ) }
  14785. },
  14786. vertexShader: [
  14787. "varying vec4 vWorldPosition;",
  14788. THREE.ShaderChunk[ "common" ],
  14789. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  14790. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  14791. "void main() {",
  14792. THREE.ShaderChunk[ "skinbase_vertex" ],
  14793. THREE.ShaderChunk[ "begin_vertex" ],
  14794. THREE.ShaderChunk[ "morphtarget_vertex" ],
  14795. THREE.ShaderChunk[ "skinning_vertex" ],
  14796. THREE.ShaderChunk[ "project_vertex" ],
  14797. THREE.ShaderChunk[ "worldpos_vertex" ],
  14798. "vWorldPosition = worldPosition;",
  14799. "}"
  14800. ].join( "\n" ),
  14801. fragmentShader: [
  14802. "uniform vec3 lightPos;",
  14803. "varying vec4 vWorldPosition;",
  14804. THREE.ShaderChunk[ "common" ],
  14805. "vec4 pack1K ( float depth ) {",
  14806. " depth /= 1000.0;",
  14807. " const vec4 bitSh = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  14808. " const vec4 bitMsk = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  14809. " vec4 res = fract( depth * bitSh );",
  14810. " res -= res.xxyz * bitMsk;",
  14811. " return res; ",
  14812. "}",
  14813. "float unpack1K ( vec4 color ) {",
  14814. " const vec4 bitSh = vec4( 1.0 / ( 256.0 * 256.0 * 256.0 ), 1.0 / ( 256.0 * 256.0 ), 1.0 / 256.0, 1.0 );",
  14815. " return dot( color, bitSh ) * 1000.0;",
  14816. "}",
  14817. "void main () {",
  14818. " gl_FragColor = pack1K( length( vWorldPosition.xyz - lightPos.xyz ) );",
  14819. "}"
  14820. ].join( "\n" )
  14821. }
  14822. };
  14823. // File:src/renderers/WebGLRenderer.js
  14824. /**
  14825. * @author supereggbert / http://www.paulbrunt.co.uk/
  14826. * @author mrdoob / http://mrdoob.com/
  14827. * @author alteredq / http://alteredqualia.com/
  14828. * @author szimek / https://github.com/szimek/
  14829. */
  14830. THREE.WebGLRenderer = function ( parameters ) {
  14831. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  14832. parameters = parameters || {};
  14833. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  14834. _context = parameters.context !== undefined ? parameters.context : null,
  14835. _width = _canvas.width,
  14836. _height = _canvas.height,
  14837. pixelRatio = 1,
  14838. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  14839. _depth = parameters.depth !== undefined ? parameters.depth : true,
  14840. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  14841. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  14842. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  14843. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  14844. _clearColor = new THREE.Color( 0x000000 ),
  14845. _clearAlpha = 0;
  14846. var lights = [];
  14847. var opaqueObjects = [];
  14848. var opaqueObjectsLastIndex = - 1;
  14849. var transparentObjects = [];
  14850. var transparentObjectsLastIndex = - 1;
  14851. var morphInfluences = new Float32Array( 8 );
  14852. var sprites = [];
  14853. var lensFlares = [];
  14854. // public properties
  14855. this.domElement = _canvas;
  14856. this.context = null;
  14857. // clearing
  14858. this.autoClear = true;
  14859. this.autoClearColor = true;
  14860. this.autoClearDepth = true;
  14861. this.autoClearStencil = true;
  14862. // scene graph
  14863. this.sortObjects = true;
  14864. // physically based shading
  14865. this.gammaFactor = 2.0; // for backwards compatibility
  14866. this.gammaInput = false;
  14867. this.gammaOutput = false;
  14868. // morphs
  14869. this.maxMorphTargets = 8;
  14870. this.maxMorphNormals = 4;
  14871. // flags
  14872. this.autoScaleCubemaps = true;
  14873. // internal properties
  14874. var _this = this,
  14875. // internal state cache
  14876. _currentProgram = null,
  14877. _currentRenderTarget = null,
  14878. _currentFramebuffer = null,
  14879. _currentMaterialId = - 1,
  14880. _currentGeometryProgram = '',
  14881. _currentCamera = null,
  14882. _usedTextureUnits = 0,
  14883. _viewport = new THREE.Rectangle( 0, 0, _canvas.width, _canvas.height ),
  14884. _currentWidth = 0,
  14885. _currentHeight = 0,
  14886. // frustum
  14887. _frustum = new THREE.Frustum(),
  14888. // camera matrices cache
  14889. _projScreenMatrix = new THREE.Matrix4(),
  14890. _vector3 = new THREE.Vector3(),
  14891. // light arrays cache
  14892. _lights = {
  14893. hash: '',
  14894. ambient: [ 0, 0, 0 ],
  14895. directional: [],
  14896. point: [],
  14897. spot: [],
  14898. hemi: [],
  14899. shadows: [],
  14900. shadowsPointLight: 0
  14901. },
  14902. // info
  14903. _infoMemory = {
  14904. geometries: 0,
  14905. textures: 0
  14906. },
  14907. _infoRender = {
  14908. calls: 0,
  14909. vertices: 0,
  14910. faces: 0,
  14911. points: 0
  14912. };
  14913. this.info = {
  14914. render: _infoRender,
  14915. memory: _infoMemory,
  14916. programs: null
  14917. };
  14918. // initialize
  14919. var _gl;
  14920. try {
  14921. var attributes = {
  14922. alpha: _alpha,
  14923. depth: _depth,
  14924. stencil: _stencil,
  14925. antialias: _antialias,
  14926. premultipliedAlpha: _premultipliedAlpha,
  14927. preserveDrawingBuffer: _preserveDrawingBuffer
  14928. };
  14929. _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  14930. if ( _gl === null ) {
  14931. if ( _canvas.getContext( 'webgl' ) !== null ) {
  14932. throw 'Error creating WebGL context with your selected attributes.';
  14933. } else {
  14934. throw 'Error creating WebGL context.';
  14935. }
  14936. }
  14937. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  14938. } catch ( error ) {
  14939. console.error( 'THREE.WebGLRenderer: ' + error );
  14940. }
  14941. var extensions = new THREE.WebGLExtensions( _gl );
  14942. extensions.get( 'OES_texture_float' );
  14943. extensions.get( 'OES_texture_float_linear' );
  14944. extensions.get( 'OES_texture_half_float' );
  14945. extensions.get( 'OES_texture_half_float_linear' );
  14946. extensions.get( 'OES_standard_derivatives' );
  14947. extensions.get( 'ANGLE_instanced_arrays' );
  14948. if ( extensions.get( 'OES_element_index_uint' ) ) {
  14949. THREE.BufferGeometry.MaxIndex = 4294967296;
  14950. }
  14951. var capabilities = new THREE.WebGLCapabilities( _gl, extensions, parameters );
  14952. var state = new THREE.WebGLState( _gl, extensions, paramThreeToGL );
  14953. var properties = new THREE.WebGLProperties();
  14954. var objects = new THREE.WebGLObjects( _gl, properties, this.info );
  14955. var programCache = new THREE.WebGLPrograms( this, capabilities );
  14956. var lightCache = new THREE.WebGLLights();
  14957. this.info.programs = programCache.programs;
  14958. var bufferRenderer = new THREE.WebGLBufferRenderer( _gl, extensions, _infoRender );
  14959. var indexedBufferRenderer = new THREE.WebGLIndexedBufferRenderer( _gl, extensions, _infoRender );
  14960. //
  14961. function getTargetPixelRatio() {
  14962. return _currentRenderTarget === null ? pixelRatio : 1;
  14963. }
  14964. function glClearColor( r, g, b, a ) {
  14965. if ( _premultipliedAlpha === true ) {
  14966. r *= a; g *= a; b *= a;
  14967. }
  14968. _gl.clearColor( r, g, b, a );
  14969. }
  14970. function setDefaultGLState() {
  14971. state.init();
  14972. _gl.viewport( _viewport.x, _viewport.y, _viewport.width, _viewport.height );
  14973. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  14974. }
  14975. function resetGLState() {
  14976. _currentProgram = null;
  14977. _currentCamera = null;
  14978. _currentGeometryProgram = '';
  14979. _currentMaterialId = - 1;
  14980. state.reset();
  14981. }
  14982. setDefaultGLState();
  14983. this.context = _gl;
  14984. this.capabilities = capabilities;
  14985. this.extensions = extensions;
  14986. this.properties = properties;
  14987. this.state = state;
  14988. // shadow map
  14989. var shadowMap = new THREE.WebGLShadowMap( this, _lights, objects );
  14990. this.shadowMap = shadowMap;
  14991. // Plugins
  14992. var spritePlugin = new THREE.SpritePlugin( this, sprites );
  14993. var lensFlarePlugin = new THREE.LensFlarePlugin( this, lensFlares );
  14994. // API
  14995. this.getContext = function () {
  14996. return _gl;
  14997. };
  14998. this.getContextAttributes = function () {
  14999. return _gl.getContextAttributes();
  15000. };
  15001. this.forceContextLoss = function () {
  15002. extensions.get( 'WEBGL_lose_context' ).loseContext();
  15003. };
  15004. this.getMaxAnisotropy = ( function () {
  15005. var value;
  15006. return function getMaxAnisotropy() {
  15007. if ( value !== undefined ) return value;
  15008. var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  15009. if ( extension !== null ) {
  15010. value = _gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  15011. } else {
  15012. value = 0;
  15013. }
  15014. return value;
  15015. };
  15016. } )();
  15017. this.getPrecision = function () {
  15018. return capabilities.precision;
  15019. };
  15020. this.getPixelRatio = function () {
  15021. return pixelRatio;
  15022. };
  15023. this.setPixelRatio = function ( value ) {
  15024. if ( value !== undefined ) pixelRatio = value;
  15025. };
  15026. this.getSize = function () {
  15027. return {
  15028. width: _width,
  15029. height: _height
  15030. };
  15031. };
  15032. this.setSize = function ( width, height, updateStyle ) {
  15033. _width = width;
  15034. _height = height;
  15035. _canvas.width = width * pixelRatio;
  15036. _canvas.height = height * pixelRatio;
  15037. if ( updateStyle !== false ) {
  15038. _canvas.style.width = width + 'px';
  15039. _canvas.style.height = height + 'px';
  15040. }
  15041. this.setViewport( 0, 0, width, height );
  15042. };
  15043. this.setViewport = function ( x, y, width, height ) {
  15044. if ( _currentRenderTarget === null ) {
  15045. x *= pixelRatio;
  15046. y *= pixelRatio;
  15047. width *= pixelRatio;
  15048. height *= pixelRatio;
  15049. _viewport.set( x, y, width, height );
  15050. }
  15051. _gl.viewport( x, y, width, height );
  15052. };
  15053. this.setScissor = function ( x, y, width, height ) {
  15054. if ( _currentRenderTarget === null ) {
  15055. x *= pixelRatio;
  15056. y *= pixelRatio;
  15057. width *= pixelRatio;
  15058. height *= pixelRatio;
  15059. }
  15060. _gl.scissor( x, y, width, height );
  15061. };
  15062. this.enableScissorTest = function ( boolean ) {
  15063. state.setScissorTest( boolean );
  15064. };
  15065. // Clearing
  15066. this.getClearColor = function () {
  15067. return _clearColor;
  15068. };
  15069. this.setClearColor = function ( color, alpha ) {
  15070. _clearColor.set( color );
  15071. _clearAlpha = alpha !== undefined ? alpha : 1;
  15072. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  15073. };
  15074. this.getClearAlpha = function () {
  15075. return _clearAlpha;
  15076. };
  15077. this.setClearAlpha = function ( alpha ) {
  15078. _clearAlpha = alpha;
  15079. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  15080. };
  15081. this.clear = function ( color, depth, stencil ) {
  15082. var bits = 0;
  15083. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  15084. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  15085. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  15086. _gl.clear( bits );
  15087. };
  15088. this.clearColor = function () {
  15089. _gl.clear( _gl.COLOR_BUFFER_BIT );
  15090. };
  15091. this.clearDepth = function () {
  15092. _gl.clear( _gl.DEPTH_BUFFER_BIT );
  15093. };
  15094. this.clearStencil = function () {
  15095. _gl.clear( _gl.STENCIL_BUFFER_BIT );
  15096. };
  15097. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  15098. this.setRenderTarget( renderTarget );
  15099. this.clear( color, depth, stencil );
  15100. };
  15101. // Reset
  15102. this.resetGLState = resetGLState;
  15103. this.dispose = function() {
  15104. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  15105. };
  15106. // Events
  15107. function onContextLost( event ) {
  15108. event.preventDefault();
  15109. resetGLState();
  15110. setDefaultGLState();
  15111. properties.clear();
  15112. }
  15113. function onTextureDispose( event ) {
  15114. var texture = event.target;
  15115. texture.removeEventListener( 'dispose', onTextureDispose );
  15116. deallocateTexture( texture );
  15117. _infoMemory.textures --;
  15118. }
  15119. function onRenderTargetDispose( event ) {
  15120. var renderTarget = event.target;
  15121. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  15122. deallocateRenderTarget( renderTarget );
  15123. _infoMemory.textures --;
  15124. }
  15125. function onMaterialDispose( event ) {
  15126. var material = event.target;
  15127. material.removeEventListener( 'dispose', onMaterialDispose );
  15128. deallocateMaterial( material );
  15129. }
  15130. // Buffer deallocation
  15131. function deallocateTexture( texture ) {
  15132. var textureProperties = properties.get( texture );
  15133. if ( texture.image && textureProperties.__image__webglTextureCube ) {
  15134. // cube texture
  15135. _gl.deleteTexture( textureProperties.__image__webglTextureCube );
  15136. } else {
  15137. // 2D texture
  15138. if ( textureProperties.__webglInit === undefined ) return;
  15139. _gl.deleteTexture( textureProperties.__webglTexture );
  15140. }
  15141. // remove all webgl properties
  15142. properties.delete( texture );
  15143. }
  15144. function deallocateRenderTarget( renderTarget ) {
  15145. var renderTargetProperties = properties.get( renderTarget );
  15146. var textureProperties = properties.get( renderTarget.texture );
  15147. if ( ! renderTarget || textureProperties.__webglTexture === undefined ) return;
  15148. _gl.deleteTexture( textureProperties.__webglTexture );
  15149. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  15150. for ( var i = 0; i < 6; i ++ ) {
  15151. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  15152. _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  15153. }
  15154. } else {
  15155. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  15156. _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  15157. }
  15158. properties.delete( renderTarget.texture );
  15159. properties.delete( renderTarget );
  15160. }
  15161. function deallocateMaterial( material ) {
  15162. releaseMaterialProgramReference( material );
  15163. properties.delete( material );
  15164. }
  15165. function releaseMaterialProgramReference( material ) {
  15166. var programInfo = properties.get( material ).program;
  15167. material.program = undefined;
  15168. if ( programInfo !== undefined ) {
  15169. programCache.releaseProgram( programInfo );
  15170. }
  15171. }
  15172. // Buffer rendering
  15173. this.renderBufferImmediate = function ( object, program, material ) {
  15174. state.initAttributes();
  15175. var buffers = properties.get( object );
  15176. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  15177. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  15178. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  15179. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  15180. var attributes = program.getAttributes();
  15181. if ( object.hasPositions ) {
  15182. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position );
  15183. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  15184. state.enableAttribute( attributes.position );
  15185. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  15186. }
  15187. if ( object.hasNormals ) {
  15188. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal );
  15189. if ( material.type !== 'MeshPhongMaterial' && material.type !== 'MeshStandardMaterial' && material.shading === THREE.FlatShading ) {
  15190. for ( var i = 0, l = object.count * 3; i < l; i += 9 ) {
  15191. var array = object.normalArray;
  15192. var nx = ( array[ i + 0 ] + array[ i + 3 ] + array[ i + 6 ] ) / 3;
  15193. var ny = ( array[ i + 1 ] + array[ i + 4 ] + array[ i + 7 ] ) / 3;
  15194. var nz = ( array[ i + 2 ] + array[ i + 5 ] + array[ i + 8 ] ) / 3;
  15195. array[ i + 0 ] = nx;
  15196. array[ i + 1 ] = ny;
  15197. array[ i + 2 ] = nz;
  15198. array[ i + 3 ] = nx;
  15199. array[ i + 4 ] = ny;
  15200. array[ i + 5 ] = nz;
  15201. array[ i + 6 ] = nx;
  15202. array[ i + 7 ] = ny;
  15203. array[ i + 8 ] = nz;
  15204. }
  15205. }
  15206. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  15207. state.enableAttribute( attributes.normal );
  15208. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  15209. }
  15210. if ( object.hasUvs && material.map ) {
  15211. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv );
  15212. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  15213. state.enableAttribute( attributes.uv );
  15214. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  15215. }
  15216. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  15217. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color );
  15218. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  15219. state.enableAttribute( attributes.color );
  15220. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  15221. }
  15222. state.disableUnusedAttributes();
  15223. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  15224. object.count = 0;
  15225. };
  15226. this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) {
  15227. setMaterial( material );
  15228. var program = setProgram( camera, fog, material, object );
  15229. var updateBuffers = false;
  15230. var geometryProgram = geometry.id + '_' + program.id + '_' + material.wireframe;
  15231. if ( geometryProgram !== _currentGeometryProgram ) {
  15232. _currentGeometryProgram = geometryProgram;
  15233. updateBuffers = true;
  15234. }
  15235. // morph targets
  15236. var morphTargetInfluences = object.morphTargetInfluences;
  15237. if ( morphTargetInfluences !== undefined ) {
  15238. var activeInfluences = [];
  15239. for ( var i = 0, l = morphTargetInfluences.length; i < l; i ++ ) {
  15240. var influence = morphTargetInfluences[ i ];
  15241. activeInfluences.push( [ influence, i ] );
  15242. }
  15243. activeInfluences.sort( absNumericalSort );
  15244. if ( activeInfluences.length > 8 ) {
  15245. activeInfluences.length = 8;
  15246. }
  15247. var morphAttributes = geometry.morphAttributes;
  15248. for ( var i = 0, l = activeInfluences.length; i < l; i ++ ) {
  15249. var influence = activeInfluences[ i ];
  15250. morphInfluences[ i ] = influence[ 0 ];
  15251. if ( influence[ 0 ] !== 0 ) {
  15252. var index = influence[ 1 ];
  15253. if ( material.morphTargets === true && morphAttributes.position ) geometry.addAttribute( 'morphTarget' + i, morphAttributes.position[ index ] );
  15254. if ( material.morphNormals === true && morphAttributes.normal ) geometry.addAttribute( 'morphNormal' + i, morphAttributes.normal[ index ] );
  15255. } else {
  15256. if ( material.morphTargets === true ) geometry.removeAttribute( 'morphTarget' + i );
  15257. if ( material.morphNormals === true ) geometry.removeAttribute( 'morphNormal' + i );
  15258. }
  15259. }
  15260. var uniforms = program.getUniforms();
  15261. if ( uniforms.morphTargetInfluences !== null ) {
  15262. _gl.uniform1fv( uniforms.morphTargetInfluences, morphInfluences );
  15263. }
  15264. updateBuffers = true;
  15265. }
  15266. //
  15267. var index = geometry.index;
  15268. var position = geometry.attributes.position;
  15269. if ( material.wireframe === true ) {
  15270. index = objects.getWireframeAttribute( geometry );
  15271. }
  15272. var renderer;
  15273. if ( index !== null ) {
  15274. renderer = indexedBufferRenderer;
  15275. renderer.setIndex( index );
  15276. } else {
  15277. renderer = bufferRenderer;
  15278. }
  15279. if ( updateBuffers ) {
  15280. setupVertexAttributes( material, program, geometry );
  15281. if ( index !== null ) {
  15282. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, objects.getAttributeBuffer( index ) );
  15283. }
  15284. }
  15285. //
  15286. var dataStart = 0;
  15287. var dataCount = Infinity;
  15288. if ( index !== null ) {
  15289. dataCount = index.count;
  15290. } else if ( position !== undefined ) {
  15291. dataCount = position.count;
  15292. }
  15293. var rangeStart = geometry.drawRange.start;
  15294. var rangeCount = geometry.drawRange.count;
  15295. var groupStart = group !== null ? group.start : 0;
  15296. var groupCount = group !== null ? group.count : Infinity;
  15297. var drawStart = Math.max( dataStart, rangeStart, groupStart );
  15298. var drawEnd = Math.min( dataStart + dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  15299. var drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  15300. //
  15301. if ( object instanceof THREE.Mesh ) {
  15302. if ( material.wireframe === true ) {
  15303. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  15304. renderer.setMode( _gl.LINES );
  15305. } else {
  15306. switch ( object.drawMode ) {
  15307. case THREE.TrianglesDrawMode:
  15308. renderer.setMode( _gl.TRIANGLES );
  15309. break;
  15310. case THREE.TriangleStripDrawMode:
  15311. renderer.setMode( _gl.TRIANGLE_STRIP );
  15312. break;
  15313. case THREE.TriangleFanDrawMode:
  15314. renderer.setMode( _gl.TRIANGLE_FAN );
  15315. break;
  15316. }
  15317. }
  15318. } else if ( object instanceof THREE.Line ) {
  15319. var lineWidth = material.linewidth;
  15320. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  15321. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  15322. if ( object instanceof THREE.LineSegments ) {
  15323. renderer.setMode( _gl.LINES );
  15324. } else {
  15325. renderer.setMode( _gl.LINE_STRIP );
  15326. }
  15327. } else if ( object instanceof THREE.Points ) {
  15328. renderer.setMode( _gl.POINTS );
  15329. }
  15330. if ( geometry instanceof THREE.InstancedBufferGeometry && geometry.maxInstancedCount > 0 ) {
  15331. renderer.renderInstances( geometry, drawStart, drawCount );
  15332. } else {
  15333. renderer.render( drawStart, drawCount );
  15334. }
  15335. };
  15336. function setupVertexAttributes( material, program, geometry, startIndex ) {
  15337. var extension;
  15338. if ( geometry instanceof THREE.InstancedBufferGeometry ) {
  15339. extension = extensions.get( 'ANGLE_instanced_arrays' );
  15340. if ( extension === null ) {
  15341. console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  15342. return;
  15343. }
  15344. }
  15345. if ( startIndex === undefined ) startIndex = 0;
  15346. state.initAttributes();
  15347. var geometryAttributes = geometry.attributes;
  15348. var programAttributes = program.getAttributes();
  15349. var materialDefaultAttributeValues = material.defaultAttributeValues;
  15350. for ( var name in programAttributes ) {
  15351. var programAttribute = programAttributes[ name ];
  15352. if ( programAttribute >= 0 ) {
  15353. var geometryAttribute = geometryAttributes[ name ];
  15354. if ( geometryAttribute !== undefined ) {
  15355. var size = geometryAttribute.itemSize;
  15356. var buffer = objects.getAttributeBuffer( geometryAttribute );
  15357. if ( geometryAttribute instanceof THREE.InterleavedBufferAttribute ) {
  15358. var data = geometryAttribute.data;
  15359. var stride = data.stride;
  15360. var offset = geometryAttribute.offset;
  15361. if ( data instanceof THREE.InstancedInterleavedBuffer ) {
  15362. state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute, extension );
  15363. if ( geometry.maxInstancedCount === undefined ) {
  15364. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  15365. }
  15366. } else {
  15367. state.enableAttribute( programAttribute );
  15368. }
  15369. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  15370. _gl.vertexAttribPointer( programAttribute, size, _gl.FLOAT, false, stride * data.array.BYTES_PER_ELEMENT, ( startIndex * stride + offset ) * data.array.BYTES_PER_ELEMENT );
  15371. } else {
  15372. if ( geometryAttribute instanceof THREE.InstancedBufferAttribute ) {
  15373. state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute, extension );
  15374. if ( geometry.maxInstancedCount === undefined ) {
  15375. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  15376. }
  15377. } else {
  15378. state.enableAttribute( programAttribute );
  15379. }
  15380. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  15381. _gl.vertexAttribPointer( programAttribute, size, _gl.FLOAT, false, 0, startIndex * size * 4 ); // 4 bytes per Float32
  15382. }
  15383. } else if ( materialDefaultAttributeValues !== undefined ) {
  15384. var value = materialDefaultAttributeValues[ name ];
  15385. if ( value !== undefined ) {
  15386. switch ( value.length ) {
  15387. case 2:
  15388. _gl.vertexAttrib2fv( programAttribute, value );
  15389. break;
  15390. case 3:
  15391. _gl.vertexAttrib3fv( programAttribute, value );
  15392. break;
  15393. case 4:
  15394. _gl.vertexAttrib4fv( programAttribute, value );
  15395. break;
  15396. default:
  15397. _gl.vertexAttrib1fv( programAttribute, value );
  15398. }
  15399. }
  15400. }
  15401. }
  15402. }
  15403. state.disableUnusedAttributes();
  15404. }
  15405. // Sorting
  15406. function absNumericalSort( a, b ) {
  15407. return Math.abs( b[ 0 ] ) - Math.abs( a[ 0 ] );
  15408. }
  15409. function painterSortStable ( a, b ) {
  15410. if ( a.object.renderOrder !== b.object.renderOrder ) {
  15411. return a.object.renderOrder - b.object.renderOrder;
  15412. } else if ( a.material.id !== b.material.id ) {
  15413. return a.material.id - b.material.id;
  15414. } else if ( a.z !== b.z ) {
  15415. return a.z - b.z;
  15416. } else {
  15417. return a.id - b.id;
  15418. }
  15419. }
  15420. function reversePainterSortStable ( a, b ) {
  15421. if ( a.object.renderOrder !== b.object.renderOrder ) {
  15422. return a.object.renderOrder - b.object.renderOrder;
  15423. } if ( a.z !== b.z ) {
  15424. return b.z - a.z;
  15425. } else {
  15426. return a.id - b.id;
  15427. }
  15428. }
  15429. // Rendering
  15430. this.render = function ( scene, camera, renderTarget, forceClear ) {
  15431. if ( camera instanceof THREE.Camera === false ) {
  15432. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  15433. return;
  15434. }
  15435. var fog = scene.fog;
  15436. // reset caching for this frame
  15437. _currentGeometryProgram = '';
  15438. _currentMaterialId = - 1;
  15439. _currentCamera = null;
  15440. // update scene graph
  15441. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  15442. // update camera matrices and frustum
  15443. if ( camera.parent === null ) camera.updateMatrixWorld();
  15444. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  15445. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  15446. _frustum.setFromMatrix( _projScreenMatrix );
  15447. lights.length = 0;
  15448. opaqueObjectsLastIndex = - 1;
  15449. transparentObjectsLastIndex = - 1;
  15450. sprites.length = 0;
  15451. lensFlares.length = 0;
  15452. projectObject( scene, camera );
  15453. opaqueObjects.length = opaqueObjectsLastIndex + 1;
  15454. transparentObjects.length = transparentObjectsLastIndex + 1;
  15455. if ( _this.sortObjects === true ) {
  15456. opaqueObjects.sort( painterSortStable );
  15457. transparentObjects.sort( reversePainterSortStable );
  15458. }
  15459. setupLights( lights, camera );
  15460. //
  15461. shadowMap.render( scene, camera );
  15462. //
  15463. _infoRender.calls = 0;
  15464. _infoRender.vertices = 0;
  15465. _infoRender.faces = 0;
  15466. _infoRender.points = 0;
  15467. if ( renderTarget === undefined ) {
  15468. renderTarget = null;
  15469. }
  15470. this.setRenderTarget( renderTarget );
  15471. if ( this.autoClear || forceClear ) {
  15472. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  15473. }
  15474. //
  15475. if ( scene.overrideMaterial ) {
  15476. var overrideMaterial = scene.overrideMaterial;
  15477. renderObjects( opaqueObjects, camera, fog, overrideMaterial );
  15478. renderObjects( transparentObjects, camera, fog, overrideMaterial );
  15479. } else {
  15480. // opaque pass (front-to-back order)
  15481. state.setBlending( THREE.NoBlending );
  15482. renderObjects( opaqueObjects, camera, fog );
  15483. // transparent pass (back-to-front order)
  15484. renderObjects( transparentObjects, camera, fog );
  15485. }
  15486. // custom render plugins (post pass)
  15487. spritePlugin.render( scene, camera );
  15488. lensFlarePlugin.render( scene, camera, _currentWidth, _currentHeight );
  15489. // Generate mipmap if we're using any kind of mipmap filtering
  15490. if ( renderTarget ) {
  15491. var texture = renderTarget.texture;
  15492. if ( texture.generateMipmaps && isPowerOfTwo( renderTarget ) &&
  15493. texture.minFilter !== THREE.NearestFilter &&
  15494. texture.minFilter !== THREE.LinearFilter ) {
  15495. updateRenderTargetMipmap( renderTarget );
  15496. }
  15497. }
  15498. // Ensure depth buffer writing is enabled so it can be cleared on next render
  15499. state.setDepthTest( true );
  15500. state.setDepthWrite( true );
  15501. state.setColorWrite( true );
  15502. // _gl.finish();
  15503. };
  15504. function pushRenderItem( object, geometry, material, z, group ) {
  15505. var array, index;
  15506. // allocate the next position in the appropriate array
  15507. if ( material.transparent ) {
  15508. array = transparentObjects;
  15509. index = ++ transparentObjectsLastIndex;
  15510. } else {
  15511. array = opaqueObjects;
  15512. index = ++ opaqueObjectsLastIndex;
  15513. }
  15514. // recycle existing render item or grow the array
  15515. var renderItem = array[ index ];
  15516. if ( renderItem !== undefined ) {
  15517. renderItem.id = object.id;
  15518. renderItem.object = object;
  15519. renderItem.geometry = geometry;
  15520. renderItem.material = material;
  15521. renderItem.z = _vector3.z;
  15522. renderItem.group = group;
  15523. } else {
  15524. renderItem = {
  15525. id: object.id,
  15526. object: object,
  15527. geometry: geometry,
  15528. material: material,
  15529. z: _vector3.z,
  15530. group: group
  15531. };
  15532. // assert( index === array.length );
  15533. array.push( renderItem );
  15534. }
  15535. }
  15536. function projectObject( object, camera ) {
  15537. if ( object.visible === false ) return;
  15538. if ( object.layers.test( camera.layers ) ) {
  15539. if ( object instanceof THREE.Light ) {
  15540. lights.push( object );
  15541. } else if ( object instanceof THREE.Sprite ) {
  15542. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  15543. sprites.push( object );
  15544. }
  15545. } else if ( object instanceof THREE.LensFlare ) {
  15546. lensFlares.push( object );
  15547. } else if ( object instanceof THREE.ImmediateRenderObject ) {
  15548. if ( _this.sortObjects === true ) {
  15549. _vector3.setFromMatrixPosition( object.matrixWorld );
  15550. _vector3.applyProjection( _projScreenMatrix );
  15551. }
  15552. pushRenderItem( object, null, object.material, _vector3.z, null );
  15553. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.Points ) {
  15554. if ( object instanceof THREE.SkinnedMesh ) {
  15555. object.skeleton.update();
  15556. }
  15557. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  15558. var material = object.material;
  15559. if ( material.visible === true ) {
  15560. if ( _this.sortObjects === true ) {
  15561. _vector3.setFromMatrixPosition( object.matrixWorld );
  15562. _vector3.applyProjection( _projScreenMatrix );
  15563. }
  15564. var geometry = objects.update( object );
  15565. if ( material instanceof THREE.MultiMaterial ) {
  15566. var groups = geometry.groups;
  15567. var materials = material.materials;
  15568. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  15569. var group = groups[ i ];
  15570. var groupMaterial = materials[ group.materialIndex ];
  15571. if ( groupMaterial.visible === true ) {
  15572. pushRenderItem( object, geometry, groupMaterial, _vector3.z, group );
  15573. }
  15574. }
  15575. } else {
  15576. pushRenderItem( object, geometry, material, _vector3.z, null );
  15577. }
  15578. }
  15579. }
  15580. }
  15581. }
  15582. var children = object.children;
  15583. for ( var i = 0, l = children.length; i < l; i ++ ) {
  15584. projectObject( children[ i ], camera );
  15585. }
  15586. }
  15587. function renderObjects( renderList, camera, fog, overrideMaterial ) {
  15588. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  15589. var renderItem = renderList[ i ];
  15590. var object = renderItem.object;
  15591. var geometry = renderItem.geometry;
  15592. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  15593. var group = renderItem.group;
  15594. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  15595. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  15596. if ( object instanceof THREE.ImmediateRenderObject ) {
  15597. setMaterial( material );
  15598. var program = setProgram( camera, fog, material, object );
  15599. _currentGeometryProgram = '';
  15600. object.render( function ( object ) {
  15601. _this.renderBufferImmediate( object, program, material );
  15602. } );
  15603. } else {
  15604. _this.renderBufferDirect( camera, fog, geometry, material, object, group );
  15605. }
  15606. }
  15607. }
  15608. function initMaterial( material, fog, object ) {
  15609. var materialProperties = properties.get( material );
  15610. var parameters = programCache.getParameters( material, _lights, fog, object );
  15611. var code = programCache.getProgramCode( material, parameters );
  15612. var program = materialProperties.program;
  15613. var programChange = true;
  15614. if ( program === undefined ) {
  15615. // new material
  15616. material.addEventListener( 'dispose', onMaterialDispose );
  15617. } else if ( program.code !== code ) {
  15618. // changed glsl or parameters
  15619. releaseMaterialProgramReference( material );
  15620. } else if ( parameters.shaderID !== undefined ) {
  15621. // same glsl and uniform list
  15622. return;
  15623. } else {
  15624. // only rebuild uniform list
  15625. programChange = false;
  15626. }
  15627. if ( programChange ) {
  15628. if ( parameters.shaderID ) {
  15629. var shader = THREE.ShaderLib[ parameters.shaderID ];
  15630. materialProperties.__webglShader = {
  15631. name: material.type,
  15632. uniforms: THREE.UniformsUtils.clone( shader.uniforms ),
  15633. vertexShader: shader.vertexShader,
  15634. fragmentShader: shader.fragmentShader
  15635. };
  15636. } else {
  15637. materialProperties.__webglShader = {
  15638. name: material.type,
  15639. uniforms: material.uniforms,
  15640. vertexShader: material.vertexShader,
  15641. fragmentShader: material.fragmentShader
  15642. };
  15643. }
  15644. material.__webglShader = materialProperties.__webglShader;
  15645. program = programCache.acquireProgram( material, parameters, code );
  15646. materialProperties.program = program;
  15647. material.program = program;
  15648. }
  15649. var attributes = program.getAttributes();
  15650. if ( material.morphTargets ) {
  15651. material.numSupportedMorphTargets = 0;
  15652. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  15653. if ( attributes[ 'morphTarget' + i ] >= 0 ) {
  15654. material.numSupportedMorphTargets ++;
  15655. }
  15656. }
  15657. }
  15658. if ( material.morphNormals ) {
  15659. material.numSupportedMorphNormals = 0;
  15660. for ( var i = 0; i < _this.maxMorphNormals; i ++ ) {
  15661. if ( attributes[ 'morphNormal' + i ] >= 0 ) {
  15662. material.numSupportedMorphNormals ++;
  15663. }
  15664. }
  15665. }
  15666. materialProperties.uniformsList = [];
  15667. var uniforms = materialProperties.__webglShader.uniforms,
  15668. uniformLocations = materialProperties.program.getUniforms();
  15669. for ( var u in uniforms ) {
  15670. var location = uniformLocations[ u ];
  15671. if ( location ) {
  15672. materialProperties.uniformsList.push( [ materialProperties.__webglShader.uniforms[ u ], location ] );
  15673. }
  15674. }
  15675. if ( material instanceof THREE.MeshPhongMaterial ||
  15676. material instanceof THREE.MeshLambertMaterial ||
  15677. material instanceof THREE.MeshStandardMaterial ||
  15678. material.lights ) {
  15679. // store the light setup it was created for
  15680. materialProperties.lightsHash = _lights.hash;
  15681. // wire up the material to this renderer's lighting state
  15682. uniforms.ambientLightColor.value = _lights.ambient;
  15683. uniforms.directionalLights.value = _lights.directional;
  15684. uniforms.pointLights.value = _lights.point;
  15685. uniforms.spotLights.value = _lights.spot;
  15686. uniforms.hemisphereLights.value = _lights.hemi;
  15687. }
  15688. // detect dynamic uniforms
  15689. materialProperties.hasDynamicUniforms = false;
  15690. for ( var j = 0, jl = materialProperties.uniformsList.length; j < jl; j ++ ) {
  15691. var uniform = materialProperties.uniformsList[ j ][ 0 ];
  15692. if ( uniform.dynamic === true ) {
  15693. materialProperties.hasDynamicUniforms = true;
  15694. break;
  15695. }
  15696. }
  15697. }
  15698. function setMaterial( material ) {
  15699. setMaterialFaces( material );
  15700. if ( material.transparent === true ) {
  15701. state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha );
  15702. } else {
  15703. state.setBlending( THREE.NoBlending );
  15704. }
  15705. state.setDepthFunc( material.depthFunc );
  15706. state.setDepthTest( material.depthTest );
  15707. state.setDepthWrite( material.depthWrite );
  15708. state.setColorWrite( material.colorWrite );
  15709. state.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  15710. }
  15711. function setMaterialFaces( material ) {
  15712. material.side !== THREE.DoubleSide ? state.enable( _gl.CULL_FACE ) : state.disable( _gl.CULL_FACE );
  15713. state.setFlipSided( material.side === THREE.BackSide );
  15714. }
  15715. function setProgram( camera, fog, material, object ) {
  15716. _usedTextureUnits = 0;
  15717. var materialProperties = properties.get( material );
  15718. if ( materialProperties.program === undefined ) {
  15719. material.needsUpdate = true;
  15720. }
  15721. if ( materialProperties.lightsHash !== undefined &&
  15722. materialProperties.lightsHash !== _lights.hash ) {
  15723. material.needsUpdate = true;
  15724. }
  15725. if ( material.needsUpdate ) {
  15726. initMaterial( material, fog, object );
  15727. material.needsUpdate = false;
  15728. }
  15729. var refreshProgram = false;
  15730. var refreshMaterial = false;
  15731. var refreshLights = false;
  15732. var program = materialProperties.program,
  15733. p_uniforms = program.getUniforms(),
  15734. m_uniforms = materialProperties.__webglShader.uniforms;
  15735. if ( program.id !== _currentProgram ) {
  15736. _gl.useProgram( program.program );
  15737. _currentProgram = program.id;
  15738. refreshProgram = true;
  15739. refreshMaterial = true;
  15740. refreshLights = true;
  15741. }
  15742. if ( material.id !== _currentMaterialId ) {
  15743. _currentMaterialId = material.id;
  15744. refreshMaterial = true;
  15745. }
  15746. if ( refreshProgram || camera !== _currentCamera ) {
  15747. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  15748. if ( capabilities.logarithmicDepthBuffer ) {
  15749. _gl.uniform1f( p_uniforms.logDepthBufFC, 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  15750. }
  15751. if ( camera !== _currentCamera ) {
  15752. _currentCamera = camera;
  15753. // lighting uniforms depend on the camera so enforce an update
  15754. // now, in case this material supports lights - or later, when
  15755. // the next material that does gets activated:
  15756. refreshMaterial = true; // set to true on material change
  15757. refreshLights = true; // remains set until update done
  15758. }
  15759. // load material specific uniforms
  15760. // (shader material also gets them for the sake of genericity)
  15761. if ( material instanceof THREE.ShaderMaterial ||
  15762. material instanceof THREE.MeshPhongMaterial ||
  15763. material instanceof THREE.MeshStandardMaterial ||
  15764. material.envMap ) {
  15765. if ( p_uniforms.cameraPosition !== undefined ) {
  15766. _vector3.setFromMatrixPosition( camera.matrixWorld );
  15767. _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  15768. }
  15769. }
  15770. if ( material instanceof THREE.MeshPhongMaterial ||
  15771. material instanceof THREE.MeshLambertMaterial ||
  15772. material instanceof THREE.MeshBasicMaterial ||
  15773. material instanceof THREE.MeshStandardMaterial ||
  15774. material instanceof THREE.ShaderMaterial ||
  15775. material.skinning ) {
  15776. if ( p_uniforms.viewMatrix !== undefined ) {
  15777. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  15778. }
  15779. }
  15780. }
  15781. // skinning uniforms must be set even if material didn't change
  15782. // auto-setting of texture unit for bone texture must go before other textures
  15783. // not sure why, but otherwise weird things happen
  15784. if ( material.skinning ) {
  15785. if ( object.bindMatrix && p_uniforms.bindMatrix !== undefined ) {
  15786. _gl.uniformMatrix4fv( p_uniforms.bindMatrix, false, object.bindMatrix.elements );
  15787. }
  15788. if ( object.bindMatrixInverse && p_uniforms.bindMatrixInverse !== undefined ) {
  15789. _gl.uniformMatrix4fv( p_uniforms.bindMatrixInverse, false, object.bindMatrixInverse.elements );
  15790. }
  15791. if ( capabilities.floatVertexTextures && object.skeleton && object.skeleton.useVertexTexture ) {
  15792. if ( p_uniforms.boneTexture !== undefined ) {
  15793. var textureUnit = getTextureUnit();
  15794. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  15795. _this.setTexture( object.skeleton.boneTexture, textureUnit );
  15796. }
  15797. if ( p_uniforms.boneTextureWidth !== undefined ) {
  15798. _gl.uniform1i( p_uniforms.boneTextureWidth, object.skeleton.boneTextureWidth );
  15799. }
  15800. if ( p_uniforms.boneTextureHeight !== undefined ) {
  15801. _gl.uniform1i( p_uniforms.boneTextureHeight, object.skeleton.boneTextureHeight );
  15802. }
  15803. } else if ( object.skeleton && object.skeleton.boneMatrices ) {
  15804. if ( p_uniforms.boneGlobalMatrices !== undefined ) {
  15805. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.skeleton.boneMatrices );
  15806. }
  15807. }
  15808. }
  15809. if ( refreshMaterial ) {
  15810. if ( material instanceof THREE.MeshPhongMaterial ||
  15811. material instanceof THREE.MeshLambertMaterial ||
  15812. material instanceof THREE.MeshStandardMaterial ||
  15813. material.lights ) {
  15814. // the current material requires lighting info
  15815. // note: all lighting uniforms are always set correctly
  15816. // they simply reference the renderer's state for their
  15817. // values
  15818. //
  15819. // use the current material's .needsUpdate flags to set
  15820. // the GL state when required
  15821. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  15822. }
  15823. // refresh uniforms common to several materials
  15824. if ( fog && material.fog ) {
  15825. refreshUniformsFog( m_uniforms, fog );
  15826. }
  15827. if ( material instanceof THREE.MeshBasicMaterial ||
  15828. material instanceof THREE.MeshLambertMaterial ||
  15829. material instanceof THREE.MeshPhongMaterial ||
  15830. material instanceof THREE.MeshStandardMaterial ) {
  15831. refreshUniformsCommon( m_uniforms, material );
  15832. }
  15833. // refresh single material specific uniforms
  15834. if ( material instanceof THREE.LineBasicMaterial ) {
  15835. refreshUniformsLine( m_uniforms, material );
  15836. } else if ( material instanceof THREE.LineDashedMaterial ) {
  15837. refreshUniformsLine( m_uniforms, material );
  15838. refreshUniformsDash( m_uniforms, material );
  15839. } else if ( material instanceof THREE.PointsMaterial ) {
  15840. refreshUniformsPoints( m_uniforms, material );
  15841. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  15842. refreshUniformsPhong( m_uniforms, material );
  15843. } else if ( material instanceof THREE.MeshStandardMaterial ) {
  15844. refreshUniformsStandard( m_uniforms, material );
  15845. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  15846. m_uniforms.mNear.value = camera.near;
  15847. m_uniforms.mFar.value = camera.far;
  15848. m_uniforms.opacity.value = material.opacity;
  15849. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  15850. m_uniforms.opacity.value = material.opacity;
  15851. }
  15852. if ( shadowMap.enabled ) {
  15853. if ( object.receiveShadow && ! material._shadowPass ) {
  15854. refreshUniformsShadow( m_uniforms, camera );
  15855. }
  15856. }
  15857. // load common uniforms
  15858. loadUniformsGeneric( materialProperties.uniformsList );
  15859. }
  15860. loadUniformsMatrices( p_uniforms, object );
  15861. if ( p_uniforms.modelMatrix !== undefined ) {
  15862. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  15863. }
  15864. if ( materialProperties.hasDynamicUniforms === true ) {
  15865. updateDynamicUniforms( materialProperties.uniformsList, object, camera );
  15866. }
  15867. return program;
  15868. }
  15869. function updateDynamicUniforms ( uniforms, object, camera ) {
  15870. var dynamicUniforms = [];
  15871. for ( var j = 0, jl = uniforms.length; j < jl; j ++ ) {
  15872. var uniform = uniforms[ j ][ 0 ];
  15873. var onUpdateCallback = uniform.onUpdateCallback;
  15874. if ( onUpdateCallback !== undefined ) {
  15875. onUpdateCallback.bind( uniform )( object, camera );
  15876. dynamicUniforms.push( uniforms[ j ] );
  15877. }
  15878. }
  15879. loadUniformsGeneric( dynamicUniforms );
  15880. }
  15881. // Uniforms (refresh uniforms objects)
  15882. function refreshUniformsCommon ( uniforms, material ) {
  15883. uniforms.opacity.value = material.opacity;
  15884. uniforms.diffuse.value = material.color;
  15885. if ( material.emissive ) {
  15886. uniforms.emissive.value = material.emissive;
  15887. }
  15888. uniforms.map.value = material.map;
  15889. uniforms.specularMap.value = material.specularMap;
  15890. uniforms.alphaMap.value = material.alphaMap;
  15891. if ( material.aoMap ) {
  15892. uniforms.aoMap.value = material.aoMap;
  15893. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  15894. }
  15895. // uv repeat and offset setting priorities
  15896. // 1. color map
  15897. // 2. specular map
  15898. // 3. normal map
  15899. // 4. bump map
  15900. // 5. alpha map
  15901. // 6. emissive map
  15902. var uvScaleMap;
  15903. if ( material.map ) {
  15904. uvScaleMap = material.map;
  15905. } else if ( material.specularMap ) {
  15906. uvScaleMap = material.specularMap;
  15907. } else if ( material.displacementMap ) {
  15908. uvScaleMap = material.displacementMap;
  15909. } else if ( material.normalMap ) {
  15910. uvScaleMap = material.normalMap;
  15911. } else if ( material.bumpMap ) {
  15912. uvScaleMap = material.bumpMap;
  15913. } else if ( material.roughnessMap ) {
  15914. uvScaleMap = material.roughnessMap;
  15915. } else if ( material.metalnessMap ) {
  15916. uvScaleMap = material.metalnessMap;
  15917. } else if ( material.alphaMap ) {
  15918. uvScaleMap = material.alphaMap;
  15919. } else if ( material.emissiveMap ) {
  15920. uvScaleMap = material.emissiveMap;
  15921. }
  15922. if ( uvScaleMap !== undefined ) {
  15923. if ( uvScaleMap instanceof THREE.WebGLRenderTarget ) {
  15924. uvScaleMap = uvScaleMap.texture;
  15925. }
  15926. var offset = uvScaleMap.offset;
  15927. var repeat = uvScaleMap.repeat;
  15928. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  15929. }
  15930. uniforms.envMap.value = material.envMap;
  15931. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : - 1;
  15932. uniforms.reflectivity.value = material.reflectivity;
  15933. uniforms.refractionRatio.value = material.refractionRatio;
  15934. }
  15935. function refreshUniformsLine ( uniforms, material ) {
  15936. uniforms.diffuse.value = material.color;
  15937. uniforms.opacity.value = material.opacity;
  15938. }
  15939. function refreshUniformsDash ( uniforms, material ) {
  15940. uniforms.dashSize.value = material.dashSize;
  15941. uniforms.totalSize.value = material.dashSize + material.gapSize;
  15942. uniforms.scale.value = material.scale;
  15943. }
  15944. function refreshUniformsPoints ( uniforms, material ) {
  15945. uniforms.diffuse.value = material.color;
  15946. uniforms.opacity.value = material.opacity;
  15947. uniforms.size.value = material.size;
  15948. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  15949. uniforms.map.value = material.map;
  15950. if ( material.map !== null ) {
  15951. var offset = material.map.offset;
  15952. var repeat = material.map.repeat;
  15953. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  15954. }
  15955. }
  15956. function refreshUniformsFog ( uniforms, fog ) {
  15957. uniforms.fogColor.value = fog.color;
  15958. if ( fog instanceof THREE.Fog ) {
  15959. uniforms.fogNear.value = fog.near;
  15960. uniforms.fogFar.value = fog.far;
  15961. } else if ( fog instanceof THREE.FogExp2 ) {
  15962. uniforms.fogDensity.value = fog.density;
  15963. }
  15964. }
  15965. function refreshUniformsPhong ( uniforms, material ) {
  15966. uniforms.specular.value = material.specular;
  15967. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  15968. if ( material.lightMap ) {
  15969. uniforms.lightMap.value = material.lightMap;
  15970. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  15971. }
  15972. if ( material.emissiveMap ) {
  15973. uniforms.emissiveMap.value = material.emissiveMap;
  15974. }
  15975. if ( material.bumpMap ) {
  15976. uniforms.bumpMap.value = material.bumpMap;
  15977. uniforms.bumpScale.value = material.bumpScale;
  15978. }
  15979. if ( material.normalMap ) {
  15980. uniforms.normalMap.value = material.normalMap;
  15981. uniforms.normalScale.value.copy( material.normalScale );
  15982. }
  15983. if ( material.displacementMap ) {
  15984. uniforms.displacementMap.value = material.displacementMap;
  15985. uniforms.displacementScale.value = material.displacementScale;
  15986. uniforms.displacementBias.value = material.displacementBias;
  15987. }
  15988. }
  15989. function refreshUniformsStandard ( uniforms, material ) {
  15990. uniforms.roughness.value = material.roughness;
  15991. uniforms.metalness.value = material.metalness;
  15992. if ( material.roughnessMap ) {
  15993. uniforms.roughnessMap.value = material.roughnessMap;
  15994. }
  15995. if ( material.metalnessMap ) {
  15996. uniforms.metalnessMap.value = material.metalnessMap;
  15997. }
  15998. if ( material.lightMap ) {
  15999. uniforms.lightMap.value = material.lightMap;
  16000. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  16001. }
  16002. if ( material.emissiveMap ) {
  16003. uniforms.emissiveMap.value = material.emissiveMap;
  16004. }
  16005. if ( material.bumpMap ) {
  16006. uniforms.bumpMap.value = material.bumpMap;
  16007. uniforms.bumpScale.value = material.bumpScale;
  16008. }
  16009. if ( material.normalMap ) {
  16010. uniforms.normalMap.value = material.normalMap;
  16011. uniforms.normalScale.value.copy( material.normalScale );
  16012. }
  16013. if ( material.displacementMap ) {
  16014. uniforms.displacementMap.value = material.displacementMap;
  16015. uniforms.displacementScale.value = material.displacementScale;
  16016. uniforms.displacementBias.value = material.displacementBias;
  16017. }
  16018. if ( material.envMap ) {
  16019. //uniforms.envMap.value = material.envMap; // part of uniforms common
  16020. uniforms.envMapIntensity.value = material.envMapIntensity;
  16021. }
  16022. }
  16023. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  16024. function markUniformsLightsNeedsUpdate ( uniforms, value ) {
  16025. uniforms.ambientLightColor.needsUpdate = value;
  16026. uniforms.directionalLights.needsUpdate = value;
  16027. uniforms.pointLights.needsUpdate = value;
  16028. uniforms.spotLights.needsUpdate = value;
  16029. uniforms.hemisphereLights.needsUpdate = value;
  16030. }
  16031. function refreshUniformsShadow ( uniforms, camera ) {
  16032. if ( uniforms.shadowMatrix ) {
  16033. var shadows = _lights.shadows;
  16034. for ( var i = 0, l = shadows.length; i < l; i ++ ) {
  16035. var light = shadows[ i ];
  16036. var shadow = light.shadow;
  16037. if ( light instanceof THREE.PointLight ) {
  16038. // for point lights we set the shadow matrix to be a translation-only matrix
  16039. // equal to inverse of the light's position
  16040. _vector3.setFromMatrixPosition( light.matrixWorld ).negate();
  16041. shadow.matrix.identity().setPosition( _vector3 );
  16042. // for point lights we set the sign of the shadowDarkness uniform to be negative
  16043. uniforms.shadowDarkness.value[ i ] = - shadow.darkness;
  16044. } else {
  16045. uniforms.shadowDarkness.value[ i ] = shadow.darkness;
  16046. }
  16047. uniforms.shadowBias.value[ i ] = shadow.bias;
  16048. uniforms.shadowMap.value[ i ] = shadow.map;
  16049. uniforms.shadowMapSize.value[ i ] = shadow.mapSize;
  16050. uniforms.shadowMatrix.value[ i ] = shadow.matrix;
  16051. }
  16052. }
  16053. }
  16054. // Uniforms (load to GPU)
  16055. function loadUniformsMatrices ( uniforms, object ) {
  16056. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object.modelViewMatrix.elements );
  16057. if ( uniforms.normalMatrix ) {
  16058. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object.normalMatrix.elements );
  16059. }
  16060. }
  16061. function getTextureUnit() {
  16062. var textureUnit = _usedTextureUnits;
  16063. if ( textureUnit >= capabilities.maxTextures ) {
  16064. console.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  16065. }
  16066. _usedTextureUnits += 1;
  16067. return textureUnit;
  16068. }
  16069. function loadUniformsGeneric ( uniforms ) {
  16070. var texture, textureUnit;
  16071. for ( var j = 0, jl = uniforms.length; j < jl; j ++ ) {
  16072. var uniform = uniforms[ j ][ 0 ];
  16073. // needsUpdate property is not added to all uniforms.
  16074. if ( uniform.needsUpdate === false ) continue;
  16075. var type = uniform.type;
  16076. var value = uniform.value;
  16077. var location = uniforms[ j ][ 1 ];
  16078. switch ( type ) {
  16079. case '1i':
  16080. _gl.uniform1i( location, value );
  16081. break;
  16082. case '1f':
  16083. _gl.uniform1f( location, value );
  16084. break;
  16085. case '2f':
  16086. _gl.uniform2f( location, value[ 0 ], value[ 1 ] );
  16087. break;
  16088. case '3f':
  16089. _gl.uniform3f( location, value[ 0 ], value[ 1 ], value[ 2 ] );
  16090. break;
  16091. case '4f':
  16092. _gl.uniform4f( location, value[ 0 ], value[ 1 ], value[ 2 ], value[ 3 ] );
  16093. break;
  16094. case '1iv':
  16095. _gl.uniform1iv( location, value );
  16096. break;
  16097. case '3iv':
  16098. _gl.uniform3iv( location, value );
  16099. break;
  16100. case '1fv':
  16101. _gl.uniform1fv( location, value );
  16102. break;
  16103. case '2fv':
  16104. _gl.uniform2fv( location, value );
  16105. break;
  16106. case '3fv':
  16107. _gl.uniform3fv( location, value );
  16108. break;
  16109. case '4fv':
  16110. _gl.uniform4fv( location, value );
  16111. break;
  16112. case 'Matrix2fv':
  16113. _gl.uniformMatrix2fv( location, false, value );
  16114. break;
  16115. case 'Matrix3fv':
  16116. _gl.uniformMatrix3fv( location, false, value );
  16117. break;
  16118. case 'Matrix4fv':
  16119. _gl.uniformMatrix4fv( location, false, value );
  16120. break;
  16121. //
  16122. case 'i':
  16123. // single integer
  16124. _gl.uniform1i( location, value );
  16125. break;
  16126. case 'f':
  16127. // single float
  16128. _gl.uniform1f( location, value );
  16129. break;
  16130. case 'v2':
  16131. // single THREE.Vector2
  16132. _gl.uniform2f( location, value.x, value.y );
  16133. break;
  16134. case 'v3':
  16135. // single THREE.Vector3
  16136. _gl.uniform3f( location, value.x, value.y, value.z );
  16137. break;
  16138. case 'v4':
  16139. // single THREE.Vector4
  16140. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  16141. break;
  16142. case 'c':
  16143. // single THREE.Color
  16144. _gl.uniform3f( location, value.r, value.g, value.b );
  16145. break;
  16146. /*
  16147. case 's':
  16148. // TODO: Optimize this.
  16149. for( var propertyName in uniform.properties ) {
  16150. var property = uniform.properties[ propertyName ];
  16151. var locationProperty = location[ propertyName ];
  16152. var valueProperty = value[ propertyName ];
  16153. switch( property.type ) {
  16154. case 'i':
  16155. _gl.uniform1i( locationProperty, valueProperty );
  16156. break;
  16157. case 'f':
  16158. _gl.uniform1f( locationProperty, valueProperty );
  16159. break;
  16160. case 'v2':
  16161. _gl.uniform2f( locationProperty, valueProperty.x, valueProperty.y );
  16162. break;
  16163. case 'v3':
  16164. _gl.uniform3f( locationProperty, valueProperty.x, valueProperty.y, valueProperty.z );
  16165. break;
  16166. case 'v4':
  16167. _gl.uniform4f( locationProperty, valueProperty.x, valueProperty.y, valueProperty.z, valueProperty.w );
  16168. break;
  16169. case 'c':
  16170. _gl.uniform3f( locationProperty, valueProperty.r, valueProperty.g, valueProperty.b );
  16171. break;
  16172. };
  16173. }
  16174. break;
  16175. */
  16176. case 'sa':
  16177. // TODO: Optimize this.
  16178. for ( var i = 0; i < value.length; i ++ ) {
  16179. for ( var propertyName in uniform.properties ) {
  16180. var property = uniform.properties[ propertyName ];
  16181. var locationProperty = location[ i ][ propertyName ];
  16182. var valueProperty = value[ i ][ propertyName ];
  16183. switch ( property.type ) {
  16184. case 'i':
  16185. _gl.uniform1i( locationProperty, valueProperty );
  16186. break;
  16187. case 'f':
  16188. _gl.uniform1f( locationProperty, valueProperty );
  16189. break;
  16190. case 'v2':
  16191. _gl.uniform2f( locationProperty, valueProperty.x, valueProperty.y );
  16192. break;
  16193. case 'v3':
  16194. _gl.uniform3f( locationProperty, valueProperty.x, valueProperty.y, valueProperty.z );
  16195. break;
  16196. case 'v4':
  16197. _gl.uniform4f( locationProperty, valueProperty.x, valueProperty.y, valueProperty.z, valueProperty.w );
  16198. break;
  16199. case 'c':
  16200. _gl.uniform3f( locationProperty, valueProperty.r, valueProperty.g, valueProperty.b );
  16201. break;
  16202. }
  16203. }
  16204. }
  16205. break;
  16206. case 'iv1':
  16207. // flat array of integers (JS or typed array)
  16208. _gl.uniform1iv( location, value );
  16209. break;
  16210. case 'iv':
  16211. // flat array of integers with 3 x N size (JS or typed array)
  16212. _gl.uniform3iv( location, value );
  16213. break;
  16214. case 'fv1':
  16215. // flat array of floats (JS or typed array)
  16216. _gl.uniform1fv( location, value );
  16217. break;
  16218. case 'fv':
  16219. // flat array of floats with 3 x N size (JS or typed array)
  16220. _gl.uniform3fv( location, value );
  16221. break;
  16222. case 'v2v':
  16223. // array of THREE.Vector2
  16224. if ( uniform._array === undefined ) {
  16225. uniform._array = new Float32Array( 2 * value.length );
  16226. }
  16227. for ( var i = 0, i2 = 0, il = value.length; i < il; i ++, i2 += 2 ) {
  16228. uniform._array[ i2 + 0 ] = value[ i ].x;
  16229. uniform._array[ i2 + 1 ] = value[ i ].y;
  16230. }
  16231. _gl.uniform2fv( location, uniform._array );
  16232. break;
  16233. case 'v3v':
  16234. // array of THREE.Vector3
  16235. if ( uniform._array === undefined ) {
  16236. uniform._array = new Float32Array( 3 * value.length );
  16237. }
  16238. for ( var i = 0, i3 = 0, il = value.length; i < il; i ++, i3 += 3 ) {
  16239. uniform._array[ i3 + 0 ] = value[ i ].x;
  16240. uniform._array[ i3 + 1 ] = value[ i ].y;
  16241. uniform._array[ i3 + 2 ] = value[ i ].z;
  16242. }
  16243. _gl.uniform3fv( location, uniform._array );
  16244. break;
  16245. case 'v4v':
  16246. // array of THREE.Vector4
  16247. if ( uniform._array === undefined ) {
  16248. uniform._array = new Float32Array( 4 * value.length );
  16249. }
  16250. for ( var i = 0, i4 = 0, il = value.length; i < il; i ++, i4 += 4 ) {
  16251. uniform._array[ i4 + 0 ] = value[ i ].x;
  16252. uniform._array[ i4 + 1 ] = value[ i ].y;
  16253. uniform._array[ i4 + 2 ] = value[ i ].z;
  16254. uniform._array[ i4 + 3 ] = value[ i ].w;
  16255. }
  16256. _gl.uniform4fv( location, uniform._array );
  16257. break;
  16258. case 'm2':
  16259. // single THREE.Matrix2
  16260. _gl.uniformMatrix2fv( location, false, value.elements );
  16261. break;
  16262. case 'm3':
  16263. // single THREE.Matrix3
  16264. _gl.uniformMatrix3fv( location, false, value.elements );
  16265. break;
  16266. case 'm3v':
  16267. // array of THREE.Matrix3
  16268. if ( uniform._array === undefined ) {
  16269. uniform._array = new Float32Array( 9 * value.length );
  16270. }
  16271. for ( var i = 0, il = value.length; i < il; i ++ ) {
  16272. value[ i ].flattenToArrayOffset( uniform._array, i * 9 );
  16273. }
  16274. _gl.uniformMatrix3fv( location, false, uniform._array );
  16275. break;
  16276. case 'm4':
  16277. // single THREE.Matrix4
  16278. _gl.uniformMatrix4fv( location, false, value.elements );
  16279. break;
  16280. case 'm4v':
  16281. // array of THREE.Matrix4
  16282. if ( uniform._array === undefined ) {
  16283. uniform._array = new Float32Array( 16 * value.length );
  16284. }
  16285. for ( var i = 0, il = value.length; i < il; i ++ ) {
  16286. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  16287. }
  16288. _gl.uniformMatrix4fv( location, false, uniform._array );
  16289. break;
  16290. case 't':
  16291. // single THREE.Texture (2d or cube)
  16292. texture = value;
  16293. textureUnit = getTextureUnit();
  16294. _gl.uniform1i( location, textureUnit );
  16295. if ( ! texture ) continue;
  16296. if ( texture instanceof THREE.CubeTexture ||
  16297. ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {
  16298. // CompressedTexture can have Array in image :/
  16299. setCubeTexture( texture, textureUnit );
  16300. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  16301. setCubeTextureDynamic( texture.texture, textureUnit );
  16302. } else if ( texture instanceof THREE.WebGLRenderTarget ) {
  16303. _this.setTexture( texture.texture, textureUnit );
  16304. } else {
  16305. _this.setTexture( texture, textureUnit );
  16306. }
  16307. break;
  16308. case 'tv':
  16309. // array of THREE.Texture (2d or cube)
  16310. if ( uniform._array === undefined ) {
  16311. uniform._array = [];
  16312. }
  16313. for ( var i = 0, il = uniform.value.length; i < il; i ++ ) {
  16314. uniform._array[ i ] = getTextureUnit();
  16315. }
  16316. _gl.uniform1iv( location, uniform._array );
  16317. for ( var i = 0, il = uniform.value.length; i < il; i ++ ) {
  16318. texture = uniform.value[ i ];
  16319. textureUnit = uniform._array[ i ];
  16320. if ( ! texture ) continue;
  16321. if ( texture instanceof THREE.CubeTexture ||
  16322. ( texture.image instanceof Array && texture.image.length === 6 ) ) {
  16323. // CompressedTexture can have Array in image :/
  16324. setCubeTexture( texture, textureUnit );
  16325. } else if ( texture instanceof THREE.WebGLRenderTarget ) {
  16326. _this.setTexture( texture.texture, textureUnit );
  16327. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  16328. setCubeTextureDynamic( texture.texture, textureUnit );
  16329. } else {
  16330. _this.setTexture( texture, textureUnit );
  16331. }
  16332. }
  16333. break;
  16334. default:
  16335. console.warn( 'THREE.WebGLRenderer: Unknown uniform type: ' + type );
  16336. }
  16337. }
  16338. }
  16339. function setupLights ( lights, camera ) {
  16340. var l, ll, light,
  16341. r = 0, g = 0, b = 0,
  16342. color,
  16343. intensity,
  16344. distance,
  16345. viewMatrix = camera.matrixWorldInverse,
  16346. directionalLength = 0,
  16347. pointLength = 0,
  16348. spotLength = 0,
  16349. hemiLength = 0,
  16350. shadowsLength = 0;
  16351. _lights.shadowsPointLight = 0;
  16352. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  16353. light = lights[ l ];
  16354. color = light.color;
  16355. intensity = light.intensity;
  16356. distance = light.distance;
  16357. if ( light instanceof THREE.AmbientLight ) {
  16358. r += color.r * intensity;
  16359. g += color.g * intensity;
  16360. b += color.b * intensity;
  16361. } else if ( light instanceof THREE.DirectionalLight ) {
  16362. var uniforms = lightCache.get( light );
  16363. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  16364. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  16365. uniforms.direction.sub( _vector3 );
  16366. uniforms.direction.transformDirection( viewMatrix );
  16367. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  16368. if ( light.castShadow ) {
  16369. uniforms.shadow = shadowsLength;
  16370. _lights.shadows[ shadowsLength ++ ] = light;
  16371. } else {
  16372. uniforms.shadow = - 1;
  16373. }
  16374. _lights.directional[ directionalLength ++ ] = uniforms;
  16375. } else if ( light instanceof THREE.PointLight ) {
  16376. var uniforms = lightCache.get( light );
  16377. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  16378. uniforms.position.applyMatrix4( viewMatrix );
  16379. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  16380. uniforms.distance = light.distance;
  16381. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  16382. if ( light.castShadow ) {
  16383. uniforms.shadow = shadowsLength;
  16384. _lights.shadows[ shadowsLength ++ ] = light;
  16385. _lights.shadowsPointLight ++;
  16386. } else {
  16387. uniforms.shadow = - 1;
  16388. }
  16389. _lights.point[ pointLength ++ ] = uniforms;
  16390. } else if ( light instanceof THREE.SpotLight ) {
  16391. var uniforms = lightCache.get( light );
  16392. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  16393. uniforms.position.applyMatrix4( viewMatrix );
  16394. uniforms.color.copy( color ).multiplyScalar( intensity );
  16395. uniforms.distance = distance;
  16396. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  16397. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  16398. uniforms.direction.sub( _vector3 );
  16399. uniforms.direction.transformDirection( viewMatrix );
  16400. uniforms.angleCos = Math.cos( light.angle );
  16401. uniforms.exponent = light.exponent;
  16402. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  16403. if ( light.castShadow ) {
  16404. uniforms.shadow = shadowsLength;
  16405. _lights.shadows[ shadowsLength ++ ] = light;
  16406. } else {
  16407. uniforms.shadow = - 1;
  16408. }
  16409. _lights.spot[ spotLength ++ ] = uniforms;
  16410. } else if ( light instanceof THREE.HemisphereLight ) {
  16411. var uniforms = lightCache.get( light );
  16412. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  16413. uniforms.direction.transformDirection( viewMatrix );
  16414. uniforms.direction.normalize();
  16415. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  16416. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  16417. _lights.hemi[ hemiLength ++ ] = uniforms;
  16418. }
  16419. }
  16420. _lights.ambient[ 0 ] = r;
  16421. _lights.ambient[ 1 ] = g;
  16422. _lights.ambient[ 2 ] = b;
  16423. _lights.directional.length = directionalLength;
  16424. _lights.point.length = pointLength;
  16425. _lights.spot.length = spotLength;
  16426. _lights.hemi.length = hemiLength;
  16427. _lights.shadows.length = shadowsLength;
  16428. _lights.hash = directionalLength + ',' + pointLength + ',' + spotLength + ',' + hemiLength + ',' + shadowsLength;
  16429. }
  16430. // GL state setting
  16431. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  16432. if ( cullFace === THREE.CullFaceNone ) {
  16433. state.disable( _gl.CULL_FACE );
  16434. } else {
  16435. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  16436. _gl.frontFace( _gl.CW );
  16437. } else {
  16438. _gl.frontFace( _gl.CCW );
  16439. }
  16440. if ( cullFace === THREE.CullFaceBack ) {
  16441. _gl.cullFace( _gl.BACK );
  16442. } else if ( cullFace === THREE.CullFaceFront ) {
  16443. _gl.cullFace( _gl.FRONT );
  16444. } else {
  16445. _gl.cullFace( _gl.FRONT_AND_BACK );
  16446. }
  16447. state.enable( _gl.CULL_FACE );
  16448. }
  16449. };
  16450. // Textures
  16451. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  16452. var extension;
  16453. if ( isImagePowerOfTwo ) {
  16454. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  16455. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  16456. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  16457. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  16458. } else {
  16459. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  16460. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  16461. if ( texture.wrapS !== THREE.ClampToEdgeWrapping || texture.wrapT !== THREE.ClampToEdgeWrapping ) {
  16462. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.', texture );
  16463. }
  16464. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  16465. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  16466. if ( texture.minFilter !== THREE.NearestFilter && texture.minFilter !== THREE.LinearFilter ) {
  16467. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.', texture );
  16468. }
  16469. }
  16470. extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  16471. if ( extension ) {
  16472. if ( texture.type === THREE.FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return;
  16473. if ( texture.type === THREE.HalfFloatType && extensions.get( 'OES_texture_half_float_linear' ) === null ) return;
  16474. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  16475. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _this.getMaxAnisotropy() ) );
  16476. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  16477. }
  16478. }
  16479. }
  16480. function uploadTexture( textureProperties, texture, slot ) {
  16481. if ( textureProperties.__webglInit === undefined ) {
  16482. textureProperties.__webglInit = true;
  16483. texture.addEventListener( 'dispose', onTextureDispose );
  16484. textureProperties.__webglTexture = _gl.createTexture();
  16485. _infoMemory.textures ++;
  16486. }
  16487. state.activeTexture( _gl.TEXTURE0 + slot );
  16488. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  16489. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  16490. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  16491. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  16492. texture.image = clampToMaxSize( texture.image, capabilities.maxTextureSize );
  16493. if ( textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( texture.image ) === false ) {
  16494. texture.image = makePowerOfTwo( texture.image );
  16495. }
  16496. var image = texture.image,
  16497. isImagePowerOfTwo = isPowerOfTwo( image ),
  16498. glFormat = paramThreeToGL( texture.format ),
  16499. glType = paramThreeToGL( texture.type );
  16500. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  16501. var mipmap, mipmaps = texture.mipmaps;
  16502. if ( texture instanceof THREE.DataTexture ) {
  16503. // use manually created mipmaps if available
  16504. // if there are no manual mipmaps
  16505. // set 0 level mipmap and then use GL to generate other mipmap levels
  16506. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  16507. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  16508. mipmap = mipmaps[ i ];
  16509. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  16510. }
  16511. texture.generateMipmaps = false;
  16512. } else {
  16513. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  16514. }
  16515. } else if ( texture instanceof THREE.CompressedTexture ) {
  16516. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  16517. mipmap = mipmaps[ i ];
  16518. if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) {
  16519. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  16520. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  16521. } else {
  16522. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()" );
  16523. }
  16524. } else {
  16525. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  16526. }
  16527. }
  16528. } else {
  16529. // regular Texture (image, video, canvas)
  16530. // use manually created mipmaps if available
  16531. // if there are no manual mipmaps
  16532. // set 0 level mipmap and then use GL to generate other mipmap levels
  16533. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  16534. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  16535. mipmap = mipmaps[ i ];
  16536. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  16537. }
  16538. texture.generateMipmaps = false;
  16539. } else {
  16540. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  16541. }
  16542. }
  16543. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  16544. textureProperties.__version = texture.version;
  16545. if ( texture.onUpdate ) texture.onUpdate( texture );
  16546. }
  16547. this.setTexture = function ( texture, slot ) {
  16548. var textureProperties = properties.get( texture );
  16549. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  16550. var image = texture.image;
  16551. if ( image === undefined ) {
  16552. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined', texture );
  16553. return;
  16554. }
  16555. if ( image.complete === false ) {
  16556. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture );
  16557. return;
  16558. }
  16559. uploadTexture( textureProperties, texture, slot );
  16560. return;
  16561. }
  16562. state.activeTexture( _gl.TEXTURE0 + slot );
  16563. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  16564. };
  16565. function clampToMaxSize ( image, maxSize ) {
  16566. if ( image.width > maxSize || image.height > maxSize ) {
  16567. // Warning: Scaling through the canvas will only work with images that use
  16568. // premultiplied alpha.
  16569. var scale = maxSize / Math.max( image.width, image.height );
  16570. var canvas = document.createElement( 'canvas' );
  16571. canvas.width = Math.floor( image.width * scale );
  16572. canvas.height = Math.floor( image.height * scale );
  16573. var context = canvas.getContext( '2d' );
  16574. context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
  16575. console.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  16576. return canvas;
  16577. }
  16578. return image;
  16579. }
  16580. function isPowerOfTwo( image ) {
  16581. return THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height );
  16582. }
  16583. function textureNeedsPowerOfTwo( texture ) {
  16584. if ( texture.wrapS !== THREE.ClampToEdgeWrapping || texture.wrapT !== THREE.ClampToEdgeWrapping ) return true;
  16585. if ( texture.minFilter !== THREE.NearestFilter && texture.minFilter !== THREE.LinearFilter ) return true;
  16586. return false;
  16587. }
  16588. function makePowerOfTwo( image ) {
  16589. if ( image instanceof HTMLImageElement || image instanceof HTMLCanvasElement ) {
  16590. var canvas = document.createElement( 'canvas' );
  16591. canvas.width = THREE.Math.nearestPowerOfTwo( image.width );
  16592. canvas.height = THREE.Math.nearestPowerOfTwo( image.height );
  16593. var context = canvas.getContext( '2d' );
  16594. context.drawImage( image, 0, 0, canvas.width, canvas.height );
  16595. console.warn( 'THREE.WebGLRenderer: image is not power of two (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  16596. return canvas;
  16597. }
  16598. return image;
  16599. }
  16600. function setCubeTexture ( texture, slot ) {
  16601. var textureProperties = properties.get( texture );
  16602. if ( texture.image.length === 6 ) {
  16603. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  16604. if ( ! textureProperties.__image__webglTextureCube ) {
  16605. texture.addEventListener( 'dispose', onTextureDispose );
  16606. textureProperties.__image__webglTextureCube = _gl.createTexture();
  16607. _infoMemory.textures ++;
  16608. }
  16609. state.activeTexture( _gl.TEXTURE0 + slot );
  16610. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  16611. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  16612. var isCompressed = texture instanceof THREE.CompressedTexture;
  16613. var isDataTexture = texture.image[ 0 ] instanceof THREE.DataTexture;
  16614. var cubeImage = [];
  16615. for ( var i = 0; i < 6; i ++ ) {
  16616. if ( _this.autoScaleCubemaps && ! isCompressed && ! isDataTexture ) {
  16617. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], capabilities.maxCubemapSize );
  16618. } else {
  16619. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  16620. }
  16621. }
  16622. var image = cubeImage[ 0 ],
  16623. isImagePowerOfTwo = isPowerOfTwo( image ),
  16624. glFormat = paramThreeToGL( texture.format ),
  16625. glType = paramThreeToGL( texture.type );
  16626. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  16627. for ( var i = 0; i < 6; i ++ ) {
  16628. if ( ! isCompressed ) {
  16629. if ( isDataTexture ) {
  16630. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  16631. } else {
  16632. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  16633. }
  16634. } else {
  16635. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  16636. for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  16637. mipmap = mipmaps[ j ];
  16638. if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) {
  16639. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  16640. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  16641. } else {
  16642. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setCubeTexture()" );
  16643. }
  16644. } else {
  16645. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  16646. }
  16647. }
  16648. }
  16649. }
  16650. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  16651. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  16652. }
  16653. textureProperties.__version = texture.version;
  16654. if ( texture.onUpdate ) texture.onUpdate( texture );
  16655. } else {
  16656. state.activeTexture( _gl.TEXTURE0 + slot );
  16657. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  16658. }
  16659. }
  16660. }
  16661. function setCubeTextureDynamic ( texture, slot ) {
  16662. state.activeTexture( _gl.TEXTURE0 + slot );
  16663. state.bindTexture( _gl.TEXTURE_CUBE_MAP, properties.get( texture ).__webglTexture );
  16664. }
  16665. // Render targets
  16666. // Setup storage for target texture and bind it to correct framebuffer
  16667. function setupFrameBufferTexture ( framebuffer, renderTarget, attachment, textureTarget ) {
  16668. var glFormat = paramThreeToGL( renderTarget.texture.format );
  16669. var glType = paramThreeToGL( renderTarget.texture.type );
  16670. state.texImage2D( textureTarget, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  16671. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  16672. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
  16673. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  16674. }
  16675. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  16676. function setupRenderBufferStorage ( renderbuffer, renderTarget ) {
  16677. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  16678. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  16679. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  16680. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  16681. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  16682. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  16683. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  16684. } else {
  16685. // FIXME: We don't support !depth !stencil
  16686. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  16687. }
  16688. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  16689. }
  16690. // Setup GL resources for a non-texture depth buffer
  16691. function setupDepthRenderbuffer( renderTarget ) {
  16692. var renderTargetProperties = properties.get( renderTarget );
  16693. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  16694. if ( isCube ) {
  16695. renderTargetProperties.__webglDepthbuffer = [];
  16696. for ( var i = 0; i < 6; i ++ ) {
  16697. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  16698. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  16699. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget );
  16700. }
  16701. } else {
  16702. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  16703. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  16704. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget );
  16705. }
  16706. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  16707. }
  16708. // Set up GL resources for the render target
  16709. function setupRenderTarget( renderTarget ) {
  16710. var renderTargetProperties = properties.get( renderTarget );
  16711. var textureProperties = properties.get( renderTarget.texture );
  16712. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  16713. textureProperties.__webglTexture = _gl.createTexture();
  16714. _infoMemory.textures ++;
  16715. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  16716. var isTargetPowerOfTwo = THREE.Math.isPowerOfTwo( renderTarget.width ) && THREE.Math.isPowerOfTwo( renderTarget.height );
  16717. // Setup framebuffer
  16718. if ( isCube ) {
  16719. renderTargetProperties.__webglFramebuffer = [];
  16720. for ( var i = 0; i < 6; i ++ ) {
  16721. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  16722. }
  16723. } else {
  16724. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  16725. }
  16726. // Setup color buffer
  16727. if ( isCube ) {
  16728. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  16729. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, isTargetPowerOfTwo );
  16730. for ( var i = 0; i < 6; i ++ ) {
  16731. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  16732. }
  16733. if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  16734. state.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  16735. } else {
  16736. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  16737. setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, isTargetPowerOfTwo );
  16738. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D );
  16739. if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  16740. state.bindTexture( _gl.TEXTURE_2D, null );
  16741. }
  16742. // Setup depth and stencil buffers
  16743. if ( renderTarget.depthBuffer ) {
  16744. setupDepthRenderbuffer( renderTarget );
  16745. }
  16746. }
  16747. this.setRenderTarget = function ( renderTarget ) {
  16748. _currentRenderTarget = renderTarget;
  16749. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  16750. setupRenderTarget( renderTarget );
  16751. }
  16752. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  16753. var framebuffer, viewport;
  16754. if ( renderTarget ) {
  16755. var renderTargetProperties = properties.get( renderTarget );
  16756. if ( isCube ) {
  16757. framebuffer = renderTargetProperties.__webglFramebuffer[ renderTarget.activeCubeFace ];
  16758. } else {
  16759. framebuffer = renderTargetProperties.__webglFramebuffer;
  16760. }
  16761. viewport = renderTarget.viewport;
  16762. } else {
  16763. framebuffer = null;
  16764. viewport = _viewport;
  16765. }
  16766. if ( framebuffer !== _currentFramebuffer ) {
  16767. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  16768. _gl.viewport( viewport.x, viewport.y, viewport.width, viewport.height );
  16769. _currentFramebuffer = framebuffer;
  16770. }
  16771. if ( isCube ) {
  16772. var textureProperties = properties.get( renderTarget.texture );
  16773. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, 0 );
  16774. }
  16775. _currentWidth = viewport.width;
  16776. _currentHeight = viewport.height;
  16777. };
  16778. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) {
  16779. if ( renderTarget instanceof THREE.WebGLRenderTarget === false ) {
  16780. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  16781. return;
  16782. }
  16783. var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  16784. if ( framebuffer ) {
  16785. var restore = false;
  16786. if ( framebuffer !== _currentFramebuffer ) {
  16787. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  16788. restore = true;
  16789. }
  16790. try {
  16791. var texture = renderTarget.texture;
  16792. if ( texture.format !== THREE.RGBAFormat
  16793. && paramThreeToGL( texture.format ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  16794. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  16795. return;
  16796. }
  16797. if ( texture.type !== THREE.UnsignedByteType
  16798. && paramThreeToGL( texture.type ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE )
  16799. && ! ( texture.type === THREE.FloatType && extensions.get( 'WEBGL_color_buffer_float' ) )
  16800. && ! ( texture.type === THREE.HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) {
  16801. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  16802. return;
  16803. }
  16804. if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
  16805. _gl.readPixels( x, y, width, height, paramThreeToGL( texture.format ), paramThreeToGL( texture.type ), buffer );
  16806. } else {
  16807. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  16808. }
  16809. } finally {
  16810. if ( restore ) {
  16811. _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
  16812. }
  16813. }
  16814. }
  16815. };
  16816. function updateRenderTargetMipmap( renderTarget ) {
  16817. var target = renderTarget instanceof THREE.WebGLRenderTargetCube ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  16818. var texture = properties.get( renderTarget.texture ).__webglTexture;
  16819. state.bindTexture( target, texture );
  16820. _gl.generateMipmap( target );
  16821. state.bindTexture( target, null );
  16822. }
  16823. // Fallback filters for non-power-of-2 textures
  16824. function filterFallback ( f ) {
  16825. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  16826. return _gl.NEAREST;
  16827. }
  16828. return _gl.LINEAR;
  16829. }
  16830. // Map three.js constants to WebGL constants
  16831. function paramThreeToGL ( p ) {
  16832. var extension;
  16833. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  16834. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  16835. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  16836. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  16837. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  16838. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  16839. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  16840. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  16841. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  16842. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  16843. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  16844. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  16845. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  16846. if ( p === THREE.ByteType ) return _gl.BYTE;
  16847. if ( p === THREE.ShortType ) return _gl.SHORT;
  16848. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  16849. if ( p === THREE.IntType ) return _gl.INT;
  16850. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  16851. if ( p === THREE.FloatType ) return _gl.FLOAT;
  16852. extension = extensions.get( 'OES_texture_half_float' );
  16853. if ( extension !== null ) {
  16854. if ( p === THREE.HalfFloatType ) return extension.HALF_FLOAT_OES;
  16855. }
  16856. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  16857. if ( p === THREE.RGBFormat ) return _gl.RGB;
  16858. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  16859. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  16860. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  16861. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  16862. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  16863. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  16864. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  16865. if ( p === THREE.OneFactor ) return _gl.ONE;
  16866. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  16867. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  16868. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  16869. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  16870. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  16871. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  16872. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  16873. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  16874. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  16875. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  16876. if ( extension !== null ) {
  16877. if ( p === THREE.RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  16878. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  16879. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  16880. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  16881. }
  16882. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  16883. if ( extension !== null ) {
  16884. if ( p === THREE.RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  16885. if ( p === THREE.RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  16886. if ( p === THREE.RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  16887. if ( p === THREE.RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  16888. }
  16889. extension = extensions.get( 'EXT_blend_minmax' );
  16890. if ( extension !== null ) {
  16891. if ( p === THREE.MinEquation ) return extension.MIN_EXT;
  16892. if ( p === THREE.MaxEquation ) return extension.MAX_EXT;
  16893. }
  16894. return 0;
  16895. }
  16896. };
  16897. // File:src/renderers/WebGLRenderTarget.js
  16898. /**
  16899. * @author szimek / https://github.com/szimek/
  16900. * @author alteredq / http://alteredqualia.com/
  16901. * @author Marius Kintel / https://github.com/kintel
  16902. */
  16903. /*
  16904. In options, we can specify:
  16905. * Texture parameters for an auto-generated target texture
  16906. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  16907. */
  16908. THREE.WebGLRenderTarget = function ( width, height, options ) {
  16909. this.uuid = THREE.Math.generateUUID();
  16910. this.width = width;
  16911. this.height = height;
  16912. this.viewport = new THREE.Rectangle( 0, 0, width, height );
  16913. options = options || {};
  16914. if ( options.minFilter === undefined ) options.minFilter = THREE.LinearFilter;
  16915. this.texture = new THREE.Texture( undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy );
  16916. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  16917. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  16918. };
  16919. THREE.WebGLRenderTarget.prototype = {
  16920. constructor: THREE.WebGLRenderTarget,
  16921. setSize: function ( width, height ) {
  16922. if ( this.width !== width || this.height !== height ) {
  16923. this.width = width;
  16924. this.height = height;
  16925. this.dispose();
  16926. }
  16927. this.viewport.set( 0, 0, width, height );
  16928. },
  16929. setViewport: function ( x, y, width, height ) {
  16930. this.viewport.set( x, y, width, height );
  16931. },
  16932. clone: function () {
  16933. return new this.constructor().copy( this );
  16934. },
  16935. copy: function ( source ) {
  16936. this.width = source.width;
  16937. this.height = source.height;
  16938. this.viewport.copy( source.viewport );
  16939. this.texture = source.texture.clone();
  16940. this.depthBuffer = source.depthBuffer;
  16941. this.stencilBuffer = source.stencilBuffer;
  16942. this.shareDepthFrom = source.shareDepthFrom;
  16943. return this;
  16944. },
  16945. dispose: function () {
  16946. this.dispatchEvent( { type: 'dispose' } );
  16947. }
  16948. };
  16949. THREE.EventDispatcher.prototype.apply( THREE.WebGLRenderTarget.prototype );
  16950. // File:src/renderers/WebGLRenderTargetCube.js
  16951. /**
  16952. * @author alteredq / http://alteredqualia.com
  16953. */
  16954. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  16955. THREE.WebGLRenderTarget.call( this, width, height, options );
  16956. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  16957. };
  16958. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  16959. THREE.WebGLRenderTargetCube.prototype.constructor = THREE.WebGLRenderTargetCube;
  16960. // File:src/renderers/webgl/WebGLBufferRenderer.js
  16961. /**
  16962. * @author mrdoob / http://mrdoob.com/
  16963. */
  16964. THREE.WebGLBufferRenderer = function ( _gl, extensions, _infoRender ) {
  16965. var mode;
  16966. function setMode( value ) {
  16967. mode = value;
  16968. }
  16969. function render( start, count ) {
  16970. _gl.drawArrays( mode, start, count );
  16971. _infoRender.calls ++;
  16972. _infoRender.vertices += count;
  16973. if ( mode === _gl.TRIANGLES ) _infoRender.faces += count / 3;
  16974. }
  16975. function renderInstances( geometry ) {
  16976. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  16977. if ( extension === null ) {
  16978. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  16979. return;
  16980. }
  16981. var position = geometry.attributes.position;
  16982. if ( position instanceof THREE.InterleavedBufferAttribute ) {
  16983. extension.drawArraysInstancedANGLE( mode, 0, position.data.count, geometry.maxInstancedCount );
  16984. } else {
  16985. extension.drawArraysInstancedANGLE( mode, 0, position.count, geometry.maxInstancedCount );
  16986. }
  16987. }
  16988. this.setMode = setMode;
  16989. this.render = render;
  16990. this.renderInstances = renderInstances;
  16991. };
  16992. // File:src/renderers/webgl/WebGLIndexedBufferRenderer.js
  16993. /**
  16994. * @author mrdoob / http://mrdoob.com/
  16995. */
  16996. THREE.WebGLIndexedBufferRenderer = function ( _gl, extensions, _infoRender ) {
  16997. var mode;
  16998. function setMode( value ) {
  16999. mode = value;
  17000. }
  17001. var type, size;
  17002. function setIndex( index ) {
  17003. if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) {
  17004. type = _gl.UNSIGNED_INT;
  17005. size = 4;
  17006. } else {
  17007. type = _gl.UNSIGNED_SHORT;
  17008. size = 2;
  17009. }
  17010. }
  17011. function render( start, count ) {
  17012. _gl.drawElements( mode, count, type, start * size );
  17013. _infoRender.calls ++;
  17014. _infoRender.vertices += count;
  17015. if ( mode === _gl.TRIANGLES ) _infoRender.faces += count / 3;
  17016. }
  17017. function renderInstances( geometry, start, count ) {
  17018. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  17019. if ( extension === null ) {
  17020. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  17021. return;
  17022. }
  17023. extension.drawElementsInstancedANGLE( mode, count, type, start * size, geometry.maxInstancedCount );
  17024. }
  17025. this.setMode = setMode;
  17026. this.setIndex = setIndex;
  17027. this.render = render;
  17028. this.renderInstances = renderInstances;
  17029. };
  17030. // File:src/renderers/webgl/WebGLExtensions.js
  17031. /**
  17032. * @author mrdoob / http://mrdoob.com/
  17033. */
  17034. THREE.WebGLExtensions = function ( gl ) {
  17035. var extensions = {};
  17036. this.get = function ( name ) {
  17037. if ( extensions[ name ] !== undefined ) {
  17038. return extensions[ name ];
  17039. }
  17040. var extension;
  17041. switch ( name ) {
  17042. case 'EXT_texture_filter_anisotropic':
  17043. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  17044. break;
  17045. case 'WEBGL_compressed_texture_s3tc':
  17046. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  17047. break;
  17048. case 'WEBGL_compressed_texture_pvrtc':
  17049. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  17050. break;
  17051. default:
  17052. extension = gl.getExtension( name );
  17053. }
  17054. if ( extension === null ) {
  17055. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  17056. }
  17057. extensions[ name ] = extension;
  17058. return extension;
  17059. };
  17060. };
  17061. // File:src/renderers/webgl/WebGLCapabilities.js
  17062. THREE.WebGLCapabilities = function ( gl, extensions, parameters ) {
  17063. function getMaxPrecision( precision ) {
  17064. if ( precision === 'highp' ) {
  17065. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  17066. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  17067. return 'highp';
  17068. }
  17069. precision = 'mediump';
  17070. }
  17071. if ( precision === 'mediump' ) {
  17072. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  17073. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  17074. return 'mediump';
  17075. }
  17076. }
  17077. return 'lowp';
  17078. }
  17079. this.getMaxPrecision = getMaxPrecision;
  17080. this.precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  17081. this.logarithmicDepthBuffer = parameters.logarithmicDepthBuffer !== undefined ? parameters.logarithmicDepthBuffer : false;
  17082. this.maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  17083. this.maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  17084. this.maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  17085. this.maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  17086. this.maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  17087. this.maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  17088. this.maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  17089. this.maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  17090. this.vertexTextures = this.maxVertexTextures > 0;
  17091. this.floatFragmentTextures = !! extensions.get( 'OES_texture_float' );
  17092. this.floatVertexTextures = this.vertexTextures && this.floatFragmentTextures;
  17093. var _maxPrecision = getMaxPrecision( this.precision );
  17094. if ( _maxPrecision !== this.precision ) {
  17095. console.warn( 'THREE.WebGLRenderer:', this.precision, 'not supported, using', _maxPrecision, 'instead.' );
  17096. this.precision = _maxPrecision;
  17097. }
  17098. if ( this.logarithmicDepthBuffer ) {
  17099. this.logarithmicDepthBuffer = !! extensions.get( 'EXT_frag_depth' );
  17100. }
  17101. };
  17102. // File:src/renderers/webgl/WebGLGeometries.js
  17103. /**
  17104. * @author mrdoob / http://mrdoob.com/
  17105. */
  17106. THREE.WebGLGeometries = function ( gl, properties, info ) {
  17107. var geometries = {};
  17108. function get( object ) {
  17109. var geometry = object.geometry;
  17110. if ( geometries[ geometry.id ] !== undefined ) {
  17111. return geometries[ geometry.id ];
  17112. }
  17113. geometry.addEventListener( 'dispose', onGeometryDispose );
  17114. var buffergeometry;
  17115. if ( geometry instanceof THREE.BufferGeometry ) {
  17116. buffergeometry = geometry;
  17117. } else if ( geometry instanceof THREE.Geometry ) {
  17118. if ( geometry._bufferGeometry === undefined ) {
  17119. geometry._bufferGeometry = new THREE.BufferGeometry().setFromObject( object );
  17120. }
  17121. buffergeometry = geometry._bufferGeometry;
  17122. }
  17123. geometries[ geometry.id ] = buffergeometry;
  17124. info.memory.geometries ++;
  17125. return buffergeometry;
  17126. }
  17127. function onGeometryDispose( event ) {
  17128. var geometry = event.target;
  17129. var buffergeometry = geometries[ geometry.id ];
  17130. if ( buffergeometry.index !== null ) {
  17131. deleteAttribute( buffergeometry.index );
  17132. }
  17133. deleteAttributes( buffergeometry.attributes );
  17134. geometry.removeEventListener( 'dispose', onGeometryDispose );
  17135. delete geometries[ geometry.id ];
  17136. // TODO
  17137. var property = properties.get( geometry );
  17138. if ( property.wireframe ) {
  17139. deleteAttribute( property.wireframe );
  17140. }
  17141. properties.delete( geometry );
  17142. var bufferproperty = properties.get( buffergeometry );
  17143. if ( bufferproperty.wireframe ) {
  17144. deleteAttribute( bufferproperty.wireframe );
  17145. }
  17146. properties.delete( buffergeometry );
  17147. //
  17148. info.memory.geometries --;
  17149. }
  17150. function getAttributeBuffer( attribute ) {
  17151. if ( attribute instanceof THREE.InterleavedBufferAttribute ) {
  17152. return properties.get( attribute.data ).__webglBuffer;
  17153. }
  17154. return properties.get( attribute ).__webglBuffer;
  17155. }
  17156. function deleteAttribute( attribute ) {
  17157. var buffer = getAttributeBuffer( attribute );
  17158. if ( buffer !== undefined ) {
  17159. gl.deleteBuffer( buffer );
  17160. removeAttributeBuffer( attribute );
  17161. }
  17162. }
  17163. function deleteAttributes( attributes ) {
  17164. for ( var name in attributes ) {
  17165. deleteAttribute( attributes[ name ] );
  17166. }
  17167. }
  17168. function removeAttributeBuffer( attribute ) {
  17169. if ( attribute instanceof THREE.InterleavedBufferAttribute ) {
  17170. properties.delete( attribute.data );
  17171. } else {
  17172. properties.delete( attribute );
  17173. }
  17174. }
  17175. this.get = get;
  17176. };
  17177. // File:src/renderers/webgl/WebGLLights.js
  17178. /**
  17179. * @author mrdoob / http://mrdoob.com/
  17180. */
  17181. THREE.WebGLLights = function () {
  17182. var lights = {};
  17183. this.get = function ( light ) {
  17184. if ( lights[ light.id ] !== undefined ) {
  17185. return lights[ light.id ];
  17186. }
  17187. var uniforms;
  17188. switch ( light.type ) {
  17189. case 'HemisphereLight':
  17190. uniforms = {
  17191. direction: new THREE.Vector3(),
  17192. skyColor: new THREE.Color(),
  17193. groundColor: new THREE.Color()
  17194. };
  17195. break;
  17196. case 'DirectionalLight':
  17197. uniforms = {
  17198. direction: new THREE.Vector3(),
  17199. color: new THREE.Color(),
  17200. shadow: -1
  17201. };
  17202. break;
  17203. case 'PointLight':
  17204. uniforms = {
  17205. position: new THREE.Vector3(),
  17206. color: new THREE.Color(),
  17207. distance: 0,
  17208. decay: 0,
  17209. shadow: -1
  17210. };
  17211. break;
  17212. case 'SpotLight':
  17213. uniforms = {
  17214. position: new THREE.Vector3(),
  17215. direction: new THREE.Vector3(),
  17216. color: new THREE.Color(),
  17217. distance: 0,
  17218. angleCos: 0,
  17219. exponent: 0,
  17220. decay: 0,
  17221. shadow: -1
  17222. };
  17223. break;
  17224. }
  17225. lights[ light.id ] = uniforms;
  17226. return uniforms;
  17227. };
  17228. };
  17229. // File:src/renderers/webgl/WebGLObjects.js
  17230. /**
  17231. * @author mrdoob / http://mrdoob.com/
  17232. */
  17233. THREE.WebGLObjects = function ( gl, properties, info ) {
  17234. var geometries = new THREE.WebGLGeometries( gl, properties, info );
  17235. //
  17236. function update( object ) {
  17237. // TODO: Avoid updating twice (when using shadowMap). Maybe add frame counter.
  17238. var geometry = geometries.get( object );
  17239. if ( object.geometry instanceof THREE.Geometry ) {
  17240. geometry.updateFromObject( object );
  17241. }
  17242. var index = geometry.index;
  17243. var attributes = geometry.attributes;
  17244. if ( index !== null ) {
  17245. updateAttribute( index, gl.ELEMENT_ARRAY_BUFFER );
  17246. }
  17247. for ( var name in attributes ) {
  17248. updateAttribute( attributes[ name ], gl.ARRAY_BUFFER );
  17249. }
  17250. // morph targets
  17251. var morphAttributes = geometry.morphAttributes;
  17252. for ( var name in morphAttributes ) {
  17253. var array = morphAttributes[ name ];
  17254. for ( var i = 0, l = array.length; i < l; i ++ ) {
  17255. updateAttribute( array[ i ], gl.ARRAY_BUFFER );
  17256. }
  17257. }
  17258. return geometry;
  17259. }
  17260. function updateAttribute( attribute, bufferType ) {
  17261. var data = ( attribute instanceof THREE.InterleavedBufferAttribute ) ? attribute.data : attribute;
  17262. var attributeProperties = properties.get( data );
  17263. if ( attributeProperties.__webglBuffer === undefined ) {
  17264. createBuffer( attributeProperties, data, bufferType );
  17265. } else if ( attributeProperties.version !== data.version ) {
  17266. updateBuffer( attributeProperties, data, bufferType );
  17267. }
  17268. }
  17269. function createBuffer( attributeProperties, data, bufferType ) {
  17270. attributeProperties.__webglBuffer = gl.createBuffer();
  17271. gl.bindBuffer( bufferType, attributeProperties.__webglBuffer );
  17272. var usage = data.dynamic ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW;
  17273. gl.bufferData( bufferType, data.array, usage );
  17274. attributeProperties.version = data.version;
  17275. }
  17276. function updateBuffer( attributeProperties, data, bufferType ) {
  17277. gl.bindBuffer( bufferType, attributeProperties.__webglBuffer );
  17278. if ( data.dynamic === false || data.updateRange.count === - 1 ) {
  17279. // Not using update ranges
  17280. gl.bufferSubData( bufferType, 0, data.array );
  17281. } else if ( data.updateRange.count === 0 ) {
  17282. 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.' );
  17283. } else {
  17284. gl.bufferSubData( bufferType, data.updateRange.offset * data.array.BYTES_PER_ELEMENT,
  17285. data.array.subarray( data.updateRange.offset, data.updateRange.offset + data.updateRange.count ) );
  17286. data.updateRange.count = 0; // reset range
  17287. }
  17288. attributeProperties.version = data.version;
  17289. }
  17290. function getAttributeBuffer( attribute ) {
  17291. if ( attribute instanceof THREE.InterleavedBufferAttribute ) {
  17292. return properties.get( attribute.data ).__webglBuffer;
  17293. }
  17294. return properties.get( attribute ).__webglBuffer;
  17295. }
  17296. function getWireframeAttribute( geometry ) {
  17297. var property = properties.get( geometry );
  17298. if ( property.wireframe !== undefined ) {
  17299. return property.wireframe;
  17300. }
  17301. var indices = [];
  17302. var index = geometry.index;
  17303. var attributes = geometry.attributes;
  17304. var position = attributes.position;
  17305. // console.time( 'wireframe' );
  17306. if ( index !== null ) {
  17307. var edges = {};
  17308. var array = index.array;
  17309. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  17310. var a = array[ i + 0 ];
  17311. var b = array[ i + 1 ];
  17312. var c = array[ i + 2 ];
  17313. if ( checkEdge( edges, a, b ) ) indices.push( a, b );
  17314. if ( checkEdge( edges, b, c ) ) indices.push( b, c );
  17315. if ( checkEdge( edges, c, a ) ) indices.push( c, a );
  17316. }
  17317. } else {
  17318. var array = attributes.position.array;
  17319. for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  17320. var a = i + 0;
  17321. var b = i + 1;
  17322. var c = i + 2;
  17323. indices.push( a, b, b, c, c, a );
  17324. }
  17325. }
  17326. // console.timeEnd( 'wireframe' );
  17327. var TypeArray = position.count > 65535 ? Uint32Array : Uint16Array;
  17328. var attribute = new THREE.BufferAttribute( new TypeArray( indices ), 1 );
  17329. updateAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  17330. property.wireframe = attribute;
  17331. return attribute;
  17332. }
  17333. function checkEdge( edges, a, b ) {
  17334. if ( a > b ) {
  17335. var tmp = a;
  17336. a = b;
  17337. b = tmp;
  17338. }
  17339. var list = edges[ a ];
  17340. if ( list === undefined ) {
  17341. edges[ a ] = [ b ];
  17342. return true;
  17343. } else if ( list.indexOf( b ) === -1 ) {
  17344. list.push( b );
  17345. return true;
  17346. }
  17347. return false;
  17348. }
  17349. this.getAttributeBuffer = getAttributeBuffer;
  17350. this.getWireframeAttribute = getWireframeAttribute;
  17351. this.update = update;
  17352. };
  17353. // File:src/renderers/webgl/WebGLProgram.js
  17354. THREE.WebGLProgram = ( function () {
  17355. var programIdCount = 0;
  17356. // TODO: Combine the regex
  17357. var structRe = /^([\w\d_]+)\.([\w\d_]+)$/;
  17358. var arrayStructRe = /^([\w\d_]+)\[(\d+)\]\.([\w\d_]+)$/;
  17359. var arrayRe = /^([\w\d_]+)\[0\]$/;
  17360. function generateExtensions( extensions, parameters, rendererExtensions ) {
  17361. extensions = extensions || {};
  17362. var chunks = [
  17363. ( extensions.derivatives || parameters.bumpMap || parameters.normalMap || parameters.flatShading ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  17364. ( extensions.fragDepth || parameters.logarithmicDepthBuffer ) && rendererExtensions.get( 'EXT_frag_depth' ) ? '#extension GL_EXT_frag_depth : enable' : '',
  17365. ( extensions.drawBuffers ) && rendererExtensions.get( 'WEBGL_draw_buffers' ) ? '#extension GL_EXT_draw_buffers : require' : '',
  17366. ( extensions.shaderTextureLOD || parameters.envMap ) && rendererExtensions.get( 'EXT_shader_texture_lod' ) ? '#extension GL_EXT_shader_texture_lod : enable' : '',
  17367. ];
  17368. return chunks.filter( filterEmptyLine ).join( '\n' );
  17369. }
  17370. function generateDefines( defines ) {
  17371. var chunks = [];
  17372. for ( var name in defines ) {
  17373. var value = defines[ name ];
  17374. if ( value === false ) continue;
  17375. chunks.push( '#define ' + name + ' ' + value );
  17376. }
  17377. return chunks.join( '\n' );
  17378. }
  17379. function fetchUniformLocations( gl, program, identifiers ) {
  17380. var uniforms = {};
  17381. var n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  17382. for ( var i = 0; i < n; i ++ ) {
  17383. var info = gl.getActiveUniform( program, i );
  17384. var name = info.name;
  17385. var location = gl.getUniformLocation( program, name );
  17386. //console.log("THREE.WebGLProgram: ACTIVE UNIFORM:", name);
  17387. var matches = structRe.exec( name );
  17388. if ( matches ) {
  17389. var structName = matches[ 1 ];
  17390. var structProperty = matches[ 2 ];
  17391. var uniformsStruct = uniforms[ structName ];
  17392. if ( ! uniformsStruct ) {
  17393. uniformsStruct = uniforms[ structName ] = {};
  17394. }
  17395. uniformsStruct[ structProperty ] = location;
  17396. continue;
  17397. }
  17398. matches = arrayStructRe.exec( name );
  17399. if ( matches ) {
  17400. var arrayName = matches[ 1 ];
  17401. var arrayIndex = matches[ 2 ];
  17402. var arrayProperty = matches[ 3 ];
  17403. var uniformsArray = uniforms[ arrayName ];
  17404. if ( ! uniformsArray ) {
  17405. uniformsArray = uniforms[ arrayName ] = [];
  17406. }
  17407. var uniformsArrayIndex = uniformsArray[ arrayIndex ];
  17408. if ( ! uniformsArrayIndex ) {
  17409. uniformsArrayIndex = uniformsArray[ arrayIndex ] = {};
  17410. }
  17411. uniformsArrayIndex[ arrayProperty ] = location;
  17412. continue;
  17413. }
  17414. matches = arrayRe.exec( name );
  17415. if ( matches ) {
  17416. var arrayName = matches[ 1 ];
  17417. uniforms[ arrayName ] = location;
  17418. continue;
  17419. }
  17420. uniforms[ name ] = location;
  17421. }
  17422. return uniforms;
  17423. }
  17424. function fetchAttributeLocations( gl, program, identifiers ) {
  17425. var attributes = {};
  17426. var n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  17427. for ( var i = 0; i < n; i ++ ) {
  17428. var info = gl.getActiveAttrib( program, i );
  17429. var name = info.name;
  17430. // console.log("THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:", name, i );
  17431. attributes[ name ] = gl.getAttribLocation( program, name );
  17432. }
  17433. return attributes;
  17434. }
  17435. function filterEmptyLine( string ) {
  17436. return string !== '';
  17437. }
  17438. return function WebGLProgram( renderer, code, material, parameters ) {
  17439. var gl = renderer.context;
  17440. var extensions = material.extensions;
  17441. var defines = material.defines;
  17442. var vertexShader = material.__webglShader.vertexShader;
  17443. var fragmentShader = material.__webglShader.fragmentShader;
  17444. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  17445. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  17446. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  17447. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  17448. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  17449. }
  17450. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  17451. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  17452. var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  17453. if ( parameters.envMap ) {
  17454. switch ( material.envMap.mapping ) {
  17455. case THREE.CubeReflectionMapping:
  17456. case THREE.CubeRefractionMapping:
  17457. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  17458. break;
  17459. case THREE.EquirectangularReflectionMapping:
  17460. case THREE.EquirectangularRefractionMapping:
  17461. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  17462. break;
  17463. case THREE.SphericalReflectionMapping:
  17464. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  17465. break;
  17466. }
  17467. switch ( material.envMap.mapping ) {
  17468. case THREE.CubeRefractionMapping:
  17469. case THREE.EquirectangularRefractionMapping:
  17470. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  17471. break;
  17472. }
  17473. switch ( material.combine ) {
  17474. case THREE.MultiplyOperation:
  17475. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  17476. break;
  17477. case THREE.MixOperation:
  17478. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  17479. break;
  17480. case THREE.AddOperation:
  17481. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  17482. break;
  17483. }
  17484. }
  17485. var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  17486. // console.log( 'building new program ' );
  17487. //
  17488. var customExtensions = generateExtensions( extensions, parameters, renderer.extensions );
  17489. var customDefines = generateDefines( defines );
  17490. //
  17491. var program = gl.createProgram();
  17492. var prefixVertex, prefixFragment;
  17493. if ( material instanceof THREE.RawShaderMaterial ) {
  17494. prefixVertex = '';
  17495. prefixFragment = '';
  17496. } else {
  17497. prefixVertex = [
  17498. 'precision ' + parameters.precision + ' float;',
  17499. 'precision ' + parameters.precision + ' int;',
  17500. '#define SHADER_NAME ' + material.__webglShader.name,
  17501. customDefines,
  17502. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  17503. renderer.gammaInput ? '#define GAMMA_INPUT' : '',
  17504. renderer.gammaOutput ? '#define GAMMA_OUTPUT' : '',
  17505. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  17506. '#define NUM_DIR_LIGHTS ' + parameters.numDirLights,
  17507. '#define NUM_POINT_LIGHTS ' + parameters.numPointLights,
  17508. '#define NUM_SPOT_LIGHTS ' + parameters.numSpotLights,
  17509. '#define NUM_HEMI_LIGHTS ' + parameters.numHemiLights,
  17510. '#define NUM_SHADOWS ' + parameters.numShadows,
  17511. '#define MAX_BONES ' + parameters.maxBones,
  17512. parameters.map ? '#define USE_MAP' : '',
  17513. parameters.envMap ? '#define USE_ENVMAP' : '',
  17514. parameters.envMap ? '#define ' + envMapModeDefine : '',
  17515. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  17516. parameters.aoMap ? '#define USE_AOMAP' : '',
  17517. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  17518. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  17519. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  17520. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  17521. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  17522. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  17523. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  17524. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  17525. parameters.vertexColors ? '#define USE_COLOR' : '',
  17526. parameters.flatShading ? '#define FLAT_SHADED' : '',
  17527. parameters.skinning ? '#define USE_SKINNING' : '',
  17528. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  17529. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  17530. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  17531. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  17532. parameters.flipSided ? '#define FLIP_SIDED' : '',
  17533. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  17534. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  17535. parameters.shadowMapDebug ? '#define SHADOWMAP_DEBUG' : '',
  17536. parameters.pointLightShadows > 0 ? '#define POINT_LIGHT_SHADOWS' : '',
  17537. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  17538. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  17539. parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  17540. 'uniform mat4 modelMatrix;',
  17541. 'uniform mat4 modelViewMatrix;',
  17542. 'uniform mat4 projectionMatrix;',
  17543. 'uniform mat4 viewMatrix;',
  17544. 'uniform mat3 normalMatrix;',
  17545. 'uniform vec3 cameraPosition;',
  17546. 'attribute vec3 position;',
  17547. 'attribute vec3 normal;',
  17548. 'attribute vec2 uv;',
  17549. '#ifdef USE_COLOR',
  17550. ' attribute vec3 color;',
  17551. '#endif',
  17552. '#ifdef USE_MORPHTARGETS',
  17553. ' attribute vec3 morphTarget0;',
  17554. ' attribute vec3 morphTarget1;',
  17555. ' attribute vec3 morphTarget2;',
  17556. ' attribute vec3 morphTarget3;',
  17557. ' #ifdef USE_MORPHNORMALS',
  17558. ' attribute vec3 morphNormal0;',
  17559. ' attribute vec3 morphNormal1;',
  17560. ' attribute vec3 morphNormal2;',
  17561. ' attribute vec3 morphNormal3;',
  17562. ' #else',
  17563. ' attribute vec3 morphTarget4;',
  17564. ' attribute vec3 morphTarget5;',
  17565. ' attribute vec3 morphTarget6;',
  17566. ' attribute vec3 morphTarget7;',
  17567. ' #endif',
  17568. '#endif',
  17569. '#ifdef USE_SKINNING',
  17570. ' attribute vec4 skinIndex;',
  17571. ' attribute vec4 skinWeight;',
  17572. '#endif',
  17573. '\n'
  17574. ].filter( filterEmptyLine ).join( '\n' );
  17575. prefixFragment = [
  17576. customExtensions,
  17577. 'precision ' + parameters.precision + ' float;',
  17578. 'precision ' + parameters.precision + ' int;',
  17579. '#define SHADER_NAME ' + material.__webglShader.name,
  17580. customDefines,
  17581. '#define NUM_DIR_LIGHTS ' + parameters.numDirLights,
  17582. '#define NUM_POINT_LIGHTS ' + parameters.numPointLights,
  17583. '#define NUM_SPOT_LIGHTS ' + parameters.numSpotLights,
  17584. '#define NUM_HEMI_LIGHTS ' + parameters.numHemiLights,
  17585. '#define NUM_SHADOWS ' + parameters.numShadows,
  17586. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest : '',
  17587. renderer.gammaInput ? '#define GAMMA_INPUT' : '',
  17588. renderer.gammaOutput ? '#define GAMMA_OUTPUT' : '',
  17589. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  17590. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  17591. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  17592. parameters.map ? '#define USE_MAP' : '',
  17593. parameters.envMap ? '#define USE_ENVMAP' : '',
  17594. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  17595. parameters.envMap ? '#define ' + envMapModeDefine : '',
  17596. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  17597. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  17598. parameters.aoMap ? '#define USE_AOMAP' : '',
  17599. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  17600. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  17601. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  17602. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  17603. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  17604. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  17605. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  17606. parameters.vertexColors ? '#define USE_COLOR' : '',
  17607. parameters.flatShading ? '#define FLAT_SHADED' : '',
  17608. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  17609. parameters.flipSided ? '#define FLIP_SIDED' : '',
  17610. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  17611. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  17612. parameters.shadowMapDebug ? '#define SHADOWMAP_DEBUG' : '',
  17613. parameters.pointLightShadows > 0 ? '#define POINT_LIGHT_SHADOWS' : '',
  17614. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  17615. parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  17616. parameters.envMap && renderer.extensions.get( 'EXT_shader_texture_lod' ) ? '#define TEXTURE_LOD_EXT' : '',
  17617. 'uniform mat4 viewMatrix;',
  17618. 'uniform vec3 cameraPosition;',
  17619. '\n'
  17620. ].filter( filterEmptyLine ).join( '\n' );
  17621. }
  17622. var vertexGlsl = prefixVertex + vertexShader;
  17623. var fragmentGlsl = prefixFragment + fragmentShader;
  17624. var glVertexShader = THREE.WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  17625. var glFragmentShader = THREE.WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  17626. gl.attachShader( program, glVertexShader );
  17627. gl.attachShader( program, glFragmentShader );
  17628. // Force a particular attribute to index 0.
  17629. if ( material.index0AttributeName !== undefined ) {
  17630. gl.bindAttribLocation( program, 0, material.index0AttributeName );
  17631. } else if ( parameters.morphTargets === true ) {
  17632. // programs with morphTargets displace position out of attribute 0
  17633. gl.bindAttribLocation( program, 0, 'position' );
  17634. }
  17635. gl.linkProgram( program );
  17636. var programLog = gl.getProgramInfoLog( program );
  17637. var vertexLog = gl.getShaderInfoLog( glVertexShader );
  17638. var fragmentLog = gl.getShaderInfoLog( glFragmentShader );
  17639. var runnable = true;
  17640. var haveDiagnostics = true;
  17641. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  17642. runnable = false;
  17643. console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), 'gl.VALIDATE_STATUS', gl.getProgramParameter( program, gl.VALIDATE_STATUS ), 'gl.getProgramInfoLog', programLog, vertexLog, fragmentLog );
  17644. } else if ( programLog !== '' ) {
  17645. console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog );
  17646. } else if ( vertexLog === '' || fragmentLog === '' ) {
  17647. haveDiagnostics = false;
  17648. }
  17649. if ( haveDiagnostics ) {
  17650. this.diagnostics = {
  17651. runnable: runnable,
  17652. material: material,
  17653. programLog: programLog,
  17654. vertexShader: {
  17655. log: vertexLog,
  17656. prefix: prefixVertex
  17657. },
  17658. fragmentShader: {
  17659. log: fragmentLog,
  17660. prefix: prefixFragment
  17661. }
  17662. };
  17663. }
  17664. // clean up
  17665. gl.deleteShader( glVertexShader );
  17666. gl.deleteShader( glFragmentShader );
  17667. // set up caching for uniform locations
  17668. var cachedUniforms;
  17669. this.getUniforms = function() {
  17670. if ( cachedUniforms === undefined ) {
  17671. cachedUniforms = fetchUniformLocations( gl, program );
  17672. }
  17673. return cachedUniforms;
  17674. };
  17675. // set up caching for attribute locations
  17676. var cachedAttributes;
  17677. this.getAttributes = function() {
  17678. if ( cachedAttributes === undefined ) {
  17679. cachedAttributes = fetchAttributeLocations( gl, program );
  17680. }
  17681. return cachedAttributes;
  17682. };
  17683. // free resource
  17684. this.destroy = function() {
  17685. gl.deleteProgram( program );
  17686. this.program = undefined;
  17687. };
  17688. // DEPRECATED
  17689. Object.defineProperties( this, {
  17690. uniforms: {
  17691. get: function() {
  17692. console.warn( 'THREE.WebGLProgram: .uniforms is now .getUniforms().' );
  17693. return this.getUniforms();
  17694. }
  17695. },
  17696. attributes: {
  17697. get: function() {
  17698. console.warn( 'THREE.WebGLProgram: .attributes is now .getAttributes().' );
  17699. return this.getAttributes();
  17700. }
  17701. }
  17702. } );
  17703. //
  17704. this.id = programIdCount ++;
  17705. this.code = code;
  17706. this.usedTimes = 1;
  17707. this.program = program;
  17708. this.vertexShader = glVertexShader;
  17709. this.fragmentShader = glFragmentShader;
  17710. return this;
  17711. };
  17712. } )();
  17713. // File:src/renderers/webgl/WebGLPrograms.js
  17714. THREE.WebGLPrograms = function ( renderer, capabilities ) {
  17715. var programs = [];
  17716. var shaderIDs = {
  17717. MeshDepthMaterial: 'depth',
  17718. MeshNormalMaterial: 'normal',
  17719. MeshBasicMaterial: 'basic',
  17720. MeshLambertMaterial: 'lambert',
  17721. MeshPhongMaterial: 'phong',
  17722. MeshStandardMaterial: 'standard',
  17723. LineBasicMaterial: 'basic',
  17724. LineDashedMaterial: 'dashed',
  17725. PointsMaterial: 'points'
  17726. };
  17727. var parameterNames = [
  17728. "precision", "supportsVertexTextures", "map", "envMap", "envMapMode",
  17729. "lightMap", "aoMap", "emissiveMap", "bumpMap", "normalMap", "displacementMap", "specularMap",
  17730. "roughnessMap", "metalnessMap",
  17731. "alphaMap", "combine", "vertexColors", "fog", "useFog", "fogExp",
  17732. "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning",
  17733. "maxBones", "useVertexTexture", "morphTargets", "morphNormals",
  17734. "maxMorphTargets", "maxMorphNormals",
  17735. "numDirLights", "numPointLights", "numSpotLights", "numHemiLights",
  17736. "numShadows", "shadowMapEnabled", "pointLightShadows",
  17737. "shadowMapType", "shadowMapDebug",
  17738. "alphaTest", "doubleSided", "flipSided"
  17739. ];
  17740. function allocateBones ( object ) {
  17741. if ( capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture ) {
  17742. return 1024;
  17743. } else {
  17744. // default for when object is not specified
  17745. // ( for example when prebuilding shader to be used with multiple objects )
  17746. //
  17747. // - leave some extra space for other uniforms
  17748. // - limit here is ANGLE's 254 max uniform vectors
  17749. // (up to 54 should be safe)
  17750. var nVertexUniforms = capabilities.maxVertexUniforms;
  17751. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  17752. var maxBones = nVertexMatrices;
  17753. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  17754. maxBones = Math.min( object.skeleton.bones.length, maxBones );
  17755. if ( maxBones < object.skeleton.bones.length ) {
  17756. console.warn( 'WebGLRenderer: too many bones - ' + object.skeleton.bones.length + ', this GPU supports just ' + maxBones + ' (try OpenGL instead of ANGLE)' );
  17757. }
  17758. }
  17759. return maxBones;
  17760. }
  17761. }
  17762. this.getParameters = function ( material, lights, fog, object ) {
  17763. var shaderID = shaderIDs[ material.type ];
  17764. // heuristics to create shader parameters according to lights in the scene
  17765. // (not to blow over maxLights budget)
  17766. var maxBones = allocateBones( object );
  17767. var precision = renderer.getPrecision();
  17768. if ( material.precision !== null ) {
  17769. precision = capabilities.getMaxPrecision( material.precision );
  17770. if ( precision !== material.precision ) {
  17771. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  17772. }
  17773. }
  17774. var parameters = {
  17775. shaderID: shaderID,
  17776. precision: precision,
  17777. supportsVertexTextures: capabilities.vertexTextures,
  17778. map: !! material.map,
  17779. envMap: !! material.envMap,
  17780. envMapMode: material.envMap && material.envMap.mapping,
  17781. lightMap: !! material.lightMap,
  17782. aoMap: !! material.aoMap,
  17783. emissiveMap: !! material.emissiveMap,
  17784. bumpMap: !! material.bumpMap,
  17785. normalMap: !! material.normalMap,
  17786. displacementMap: !! material.displacementMap,
  17787. roughnessMap: !! material.roughnessMap,
  17788. metalnessMap: !! material.metalnessMap,
  17789. specularMap: !! material.specularMap,
  17790. alphaMap: !! material.alphaMap,
  17791. combine: material.combine,
  17792. vertexColors: material.vertexColors,
  17793. fog: fog,
  17794. useFog: material.fog,
  17795. fogExp: fog instanceof THREE.FogExp2,
  17796. flatShading: material.shading === THREE.FlatShading,
  17797. sizeAttenuation: material.sizeAttenuation,
  17798. logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer,
  17799. skinning: material.skinning,
  17800. maxBones: maxBones,
  17801. useVertexTexture: capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture,
  17802. morphTargets: material.morphTargets,
  17803. morphNormals: material.morphNormals,
  17804. maxMorphTargets: renderer.maxMorphTargets,
  17805. maxMorphNormals: renderer.maxMorphNormals,
  17806. numDirLights: lights.directional.length,
  17807. numPointLights: lights.point.length,
  17808. numSpotLights: lights.spot.length,
  17809. numHemiLights: lights.hemi.length,
  17810. numShadows: lights.shadows.length,
  17811. pointLightShadows: lights.shadowsPointLight,
  17812. shadowMapEnabled: renderer.shadowMap.enabled && object.receiveShadow && lights.shadows.length > 0,
  17813. shadowMapType: renderer.shadowMap.type,
  17814. shadowMapDebug: renderer.shadowMap.debug,
  17815. alphaTest: material.alphaTest,
  17816. doubleSided: material.side === THREE.DoubleSide,
  17817. flipSided: material.side === THREE.BackSide
  17818. };
  17819. return parameters;
  17820. };
  17821. this.getProgramCode = function ( material, parameters ) {
  17822. var chunks = [];
  17823. if ( parameters.shaderID ) {
  17824. chunks.push( parameters.shaderID );
  17825. } else {
  17826. chunks.push( material.fragmentShader );
  17827. chunks.push( material.vertexShader );
  17828. }
  17829. if ( material.defines !== undefined ) {
  17830. for ( var name in material.defines ) {
  17831. chunks.push( name );
  17832. chunks.push( material.defines[ name ] );
  17833. }
  17834. }
  17835. for ( var i = 0; i < parameterNames.length; i ++ ) {
  17836. var parameterName = parameterNames[ i ];
  17837. chunks.push( parameterName );
  17838. chunks.push( parameters[ parameterName ] );
  17839. }
  17840. return chunks.join();
  17841. };
  17842. this.acquireProgram = function ( material, parameters, code ) {
  17843. var program;
  17844. // Check if code has been already compiled
  17845. for ( var p = 0, pl = programs.length; p < pl; p ++ ) {
  17846. var programInfo = programs[ p ];
  17847. if ( programInfo.code === code ) {
  17848. program = programInfo;
  17849. ++ program.usedTimes;
  17850. break;
  17851. }
  17852. }
  17853. if ( program === undefined ) {
  17854. program = new THREE.WebGLProgram( renderer, code, material, parameters );
  17855. programs.push( program );
  17856. }
  17857. return program;
  17858. };
  17859. this.releaseProgram = function( program ) {
  17860. if ( -- program.usedTimes === 0 ) {
  17861. // Remove from unordered set
  17862. var i = programs.indexOf( program );
  17863. programs[ i ] = programs[ programs.length - 1 ];
  17864. programs.pop();
  17865. // Free WebGL resources
  17866. program.destroy();
  17867. }
  17868. };
  17869. // Exposed for resource monitoring & error feedback via renderer.info:
  17870. this.programs = programs;
  17871. };
  17872. // File:src/renderers/webgl/WebGLProperties.js
  17873. /**
  17874. * @author fordacious / fordacious.github.io
  17875. */
  17876. THREE.WebGLProperties = function () {
  17877. var properties = {};
  17878. this.get = function ( object ) {
  17879. var uuid = object.uuid;
  17880. var map = properties[ uuid ];
  17881. if ( map === undefined ) {
  17882. map = {};
  17883. properties[ uuid ] = map;
  17884. }
  17885. return map;
  17886. };
  17887. this.delete = function ( object ) {
  17888. delete properties[ object.uuid ];
  17889. };
  17890. this.clear = function () {
  17891. properties = {};
  17892. };
  17893. };
  17894. // File:src/renderers/webgl/WebGLShader.js
  17895. THREE.WebGLShader = ( function () {
  17896. function addLineNumbers( string ) {
  17897. var lines = string.split( '\n' );
  17898. for ( var i = 0; i < lines.length; i ++ ) {
  17899. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  17900. }
  17901. return lines.join( '\n' );
  17902. }
  17903. return function WebGLShader( gl, type, string ) {
  17904. var shader = gl.createShader( type );
  17905. gl.shaderSource( shader, string );
  17906. gl.compileShader( shader );
  17907. if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) {
  17908. console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' );
  17909. }
  17910. if ( gl.getShaderInfoLog( shader ) !== '' ) {
  17911. console.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', type === gl.VERTEX_SHADER ? 'vertex' : 'fragment', gl.getShaderInfoLog( shader ), addLineNumbers( string ) );
  17912. }
  17913. // --enable-privileged-webgl-extension
  17914. // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  17915. return shader;
  17916. };
  17917. } )();
  17918. // File:src/renderers/webgl/WebGLShadowMap.js
  17919. /**
  17920. * @author alteredq / http://alteredqualia.com/
  17921. * @author mrdoob / http://mrdoob.com/
  17922. */
  17923. THREE.WebGLShadowMap = function ( _renderer, _lights, _objects ) {
  17924. var _gl = _renderer.context,
  17925. _state = _renderer.state,
  17926. _frustum = new THREE.Frustum(),
  17927. _projScreenMatrix = new THREE.Matrix4(),
  17928. _lookTarget = new THREE.Vector3(),
  17929. _lightPositionWorld = new THREE.Vector3(),
  17930. _renderList = [],
  17931. _MorphingFlag = 1,
  17932. _SkinningFlag = 2,
  17933. _NumberOfMaterialVariants = ( _MorphingFlag | _SkinningFlag ) + 1,
  17934. _depthMaterials = new Array( _NumberOfMaterialVariants ),
  17935. _distanceMaterials = new Array( _NumberOfMaterialVariants );
  17936. var cubeDirections = [
  17937. new THREE.Vector3( 1, 0, 0 ), new THREE.Vector3( - 1, 0, 0 ), new THREE.Vector3( 0, 0, 1 ),
  17938. new THREE.Vector3( 0, 0, - 1 ), new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, - 1, 0 )
  17939. ];
  17940. var cubeUps = [
  17941. new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 1, 0 ),
  17942. new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 0, 1 ), new THREE.Vector3( 0, 0, - 1 )
  17943. ];
  17944. var cube2DViewPorts = [
  17945. new THREE.Vector4(), new THREE.Vector4(), new THREE.Vector4(),
  17946. new THREE.Vector4(), new THREE.Vector4(), new THREE.Vector4()
  17947. ];
  17948. // init
  17949. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  17950. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  17951. var distanceShader = THREE.ShaderLib[ "distanceRGBA" ];
  17952. var distanceUniforms = THREE.UniformsUtils.clone( distanceShader.uniforms );
  17953. for ( var i = 0; i !== _NumberOfMaterialVariants; ++ i ) {
  17954. var useMorphing = ( i & _MorphingFlag ) !== 0;
  17955. var useSkinning = ( i & _SkinningFlag ) !== 0;
  17956. var depthMaterial = new THREE.ShaderMaterial( {
  17957. uniforms: depthUniforms,
  17958. vertexShader: depthShader.vertexShader,
  17959. fragmentShader: depthShader.fragmentShader,
  17960. morphTargets: useMorphing,
  17961. skinning: useSkinning
  17962. } );
  17963. depthMaterial._shadowPass = true;
  17964. _depthMaterials[ i ] = depthMaterial;
  17965. var distanceMaterial = new THREE.ShaderMaterial( {
  17966. uniforms: distanceUniforms,
  17967. vertexShader: distanceShader.vertexShader,
  17968. fragmentShader: distanceShader.fragmentShader,
  17969. morphTargets: useMorphing,
  17970. skinning: useSkinning
  17971. } );
  17972. distanceMaterial._shadowPass = true;
  17973. _distanceMaterials[ i ] = distanceMaterial;
  17974. }
  17975. //
  17976. var scope = this;
  17977. this.enabled = false;
  17978. this.autoUpdate = true;
  17979. this.needsUpdate = false;
  17980. this.type = THREE.PCFShadowMap;
  17981. this.cullFace = THREE.CullFaceFront;
  17982. this.render = function ( scene, camera ) {
  17983. var faceCount, isPointLight;
  17984. if ( scope.enabled === false ) return;
  17985. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  17986. // Save GL state
  17987. var currentScissorTest = _state.getScissorTest();
  17988. // Set GL state for depth map.
  17989. _gl.clearColor( 1, 1, 1, 1 );
  17990. _state.disable( _gl.BLEND );
  17991. _state.enable( _gl.CULL_FACE );
  17992. _gl.frontFace( _gl.CCW );
  17993. _gl.cullFace( scope.cullFace === THREE.CullFaceFront ? _gl.FRONT : _gl.BACK );
  17994. _state.setDepthTest( true );
  17995. _state.setScissorTest( false );
  17996. // render depth map
  17997. var shadows = _lights.shadows;
  17998. for ( var i = 0, il = shadows.length; i < il; i ++ ) {
  17999. var light = shadows[ i ];
  18000. var shadow = light.shadow;
  18001. var shadowCamera = shadow.camera;
  18002. var shadowMapSize = shadow.mapSize;
  18003. if ( light instanceof THREE.PointLight ) {
  18004. faceCount = 6;
  18005. isPointLight = true;
  18006. var vpWidth = shadowMapSize.x / 4.0;
  18007. var vpHeight = shadowMapSize.y / 2.0;
  18008. // These viewports map a cube-map onto a 2D texture with the
  18009. // following orientation:
  18010. //
  18011. // xzXZ
  18012. // y Y
  18013. //
  18014. // X - Positive x direction
  18015. // x - Negative x direction
  18016. // Y - Positive y direction
  18017. // y - Negative y direction
  18018. // Z - Positive z direction
  18019. // z - Negative z direction
  18020. // positive X
  18021. cube2DViewPorts[ 0 ].set( vpWidth * 2, vpHeight, vpWidth, vpHeight );
  18022. // negative X
  18023. cube2DViewPorts[ 1 ].set( 0, vpHeight, vpWidth, vpHeight );
  18024. // positive Z
  18025. cube2DViewPorts[ 2 ].set( vpWidth * 3, vpHeight, vpWidth, vpHeight );
  18026. // negative Z
  18027. cube2DViewPorts[ 3 ].set( vpWidth, vpHeight, vpWidth, vpHeight );
  18028. // positive Y
  18029. cube2DViewPorts[ 4 ].set( vpWidth * 3, 0, vpWidth, vpHeight );
  18030. // negative Y
  18031. cube2DViewPorts[ 5 ].set( vpWidth, 0, vpWidth, vpHeight );
  18032. } else {
  18033. faceCount = 1;
  18034. isPointLight = false;
  18035. }
  18036. if ( shadow.map === null ) {
  18037. var shadowFilter = THREE.LinearFilter;
  18038. if ( scope.type === THREE.PCFSoftShadowMap ) {
  18039. shadowFilter = THREE.NearestFilter;
  18040. }
  18041. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  18042. shadow.map = new THREE.WebGLRenderTarget( shadowMapSize.x, shadowMapSize.y, pars );
  18043. shadow.matrix = new THREE.Matrix4();
  18044. //
  18045. if ( light instanceof THREE.SpotLight ) {
  18046. shadowCamera.aspect = shadowMapSize.x / shadowMapSize.y;
  18047. }
  18048. shadowCamera.updateProjectionMatrix();
  18049. }
  18050. var shadowMap = shadow.map;
  18051. var shadowMatrix = shadow.matrix;
  18052. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  18053. shadowCamera.position.copy( _lightPositionWorld );
  18054. _renderer.setRenderTarget( shadowMap );
  18055. _renderer.clear();
  18056. // render shadow map for each cube face (if omni-directional) or
  18057. // run a single pass if not
  18058. for ( var face = 0; face < faceCount; face ++ ) {
  18059. if ( isPointLight ) {
  18060. _lookTarget.copy( shadowCamera.position );
  18061. _lookTarget.add( cubeDirections[ face ] );
  18062. shadowCamera.up.copy( cubeUps[ face ] );
  18063. shadowCamera.lookAt( _lookTarget );
  18064. var vpDimensions = cube2DViewPorts[ face ];
  18065. _renderer.setViewport( vpDimensions.x, vpDimensions.y, vpDimensions.z, vpDimensions.w );
  18066. } else {
  18067. _lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  18068. shadowCamera.lookAt( _lookTarget );
  18069. }
  18070. shadowCamera.updateMatrixWorld();
  18071. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  18072. // compute shadow matrix
  18073. shadowMatrix.set(
  18074. 0.5, 0.0, 0.0, 0.5,
  18075. 0.0, 0.5, 0.0, 0.5,
  18076. 0.0, 0.0, 0.5, 0.5,
  18077. 0.0, 0.0, 0.0, 1.0
  18078. );
  18079. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  18080. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  18081. // update camera matrices and frustum
  18082. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  18083. _frustum.setFromMatrix( _projScreenMatrix );
  18084. // set object matrices & frustum culling
  18085. _renderList.length = 0;
  18086. projectObject( scene, camera, shadowCamera );
  18087. // render shadow map
  18088. // render regular objects
  18089. for ( var j = 0, jl = _renderList.length; j < jl; j ++ ) {
  18090. var object = _renderList[ j ];
  18091. var geometry = _objects.update( object );
  18092. var material = object.material;
  18093. if ( material instanceof THREE.MeshFaceMaterial ) {
  18094. var groups = geometry.groups;
  18095. var materials = material.materials;
  18096. for ( var k = 0, kl = groups.length; k < kl; k ++ ) {
  18097. var group = groups[ k ];
  18098. var groupMaterial = materials[ group.materialIndex ];
  18099. if ( groupMaterial.visible === true ) {
  18100. var depthMaterial = getDepthMaterial( object, groupMaterial, isPointLight, _lightPositionWorld );
  18101. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  18102. }
  18103. }
  18104. } else {
  18105. var depthMaterial = getDepthMaterial( object, material, isPointLight, _lightPositionWorld );
  18106. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  18107. }
  18108. }
  18109. }
  18110. // We must call _renderer.resetGLState() at the end of each iteration of
  18111. // the light loop in order to force material updates for each light.
  18112. _renderer.resetGLState();
  18113. }
  18114. // Restore GL state.
  18115. var clearColor = _renderer.getClearColor(),
  18116. clearAlpha = _renderer.getClearAlpha();
  18117. _renderer.setClearColor( clearColor, clearAlpha );
  18118. _state.enable( _gl.BLEND );
  18119. if ( currentScissorTest === true ) {
  18120. _state.setScissorTest( true );
  18121. }
  18122. if ( scope.cullFace === THREE.CullFaceFront ) {
  18123. _gl.cullFace( _gl.BACK );
  18124. }
  18125. _renderer.resetGLState();
  18126. scope.needsUpdate = false;
  18127. };
  18128. function getDepthMaterial( object, material, isPointLight, lightPositionWorld ) {
  18129. var geometry = object.geometry;
  18130. var newMaterial = null;
  18131. var materialVariants = _depthMaterials;
  18132. var customMaterial = object.customDepthMaterial;
  18133. if ( isPointLight ) {
  18134. materialVariants = _distanceMaterials;
  18135. customMaterial = object.customDistanceMaterial;
  18136. }
  18137. if ( ! customMaterial ) {
  18138. var useMorphing = geometry.morphTargets !== undefined &&
  18139. geometry.morphTargets.length > 0 && material.morphTargets;
  18140. var useSkinning = object instanceof THREE.SkinnedMesh && material.skinning;
  18141. var variantIndex = 0;
  18142. if ( useMorphing ) variantIndex |= _MorphingFlag;
  18143. if ( useSkinning ) variantIndex |= _SkinningFlag;
  18144. newMaterial = materialVariants[ variantIndex ];
  18145. } else {
  18146. newMaterial = customMaterial;
  18147. }
  18148. newMaterial.visible = material.visible;
  18149. newMaterial.wireframe = material.wireframe;
  18150. newMaterial.wireframeLinewidth = material.wireframeLinewidth;
  18151. if ( isPointLight && newMaterial.uniforms.lightPos !== undefined ) {
  18152. newMaterial.uniforms.lightPos.value.copy( lightPositionWorld );
  18153. }
  18154. return newMaterial;
  18155. }
  18156. function projectObject( object, camera, shadowCamera ) {
  18157. if ( object.visible === false ) return;
  18158. if ( object.layers.test( camera.layers ) && ( object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.Points ) ) {
  18159. if ( object.castShadow && ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) ) {
  18160. var material = object.material;
  18161. if ( material.visible === true ) {
  18162. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  18163. _renderList.push( object );
  18164. }
  18165. }
  18166. }
  18167. var children = object.children;
  18168. for ( var i = 0, l = children.length; i < l; i ++ ) {
  18169. projectObject( children[ i ], camera, shadowCamera );
  18170. }
  18171. }
  18172. };
  18173. // File:src/renderers/webgl/WebGLState.js
  18174. /**
  18175. * @author mrdoob / http://mrdoob.com/
  18176. */
  18177. THREE.WebGLState = function ( gl, extensions, paramThreeToGL ) {
  18178. var _this = this;
  18179. var newAttributes = new Uint8Array( 16 );
  18180. var enabledAttributes = new Uint8Array( 16 );
  18181. var attributeDivisors = new Uint8Array( 16 );
  18182. var capabilities = {};
  18183. var compressedTextureFormats = null;
  18184. var currentBlending = null;
  18185. var currentBlendEquation = null;
  18186. var currentBlendSrc = null;
  18187. var currentBlendDst = null;
  18188. var currentBlendEquationAlpha = null;
  18189. var currentBlendSrcAlpha = null;
  18190. var currentBlendDstAlpha = null;
  18191. var currentDepthFunc = null;
  18192. var currentDepthWrite = null;
  18193. var currentColorWrite = null;
  18194. var currentFlipSided = null;
  18195. var currentLineWidth = null;
  18196. var currentPolygonOffsetFactor = null;
  18197. var currentPolygonOffsetUnits = null;
  18198. var currentScissorTest = null;
  18199. var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  18200. var currentTextureSlot = undefined;
  18201. var currentBoundTextures = {};
  18202. this.init = function () {
  18203. gl.clearColor( 0, 0, 0, 1 );
  18204. gl.clearDepth( 1 );
  18205. gl.clearStencil( 0 );
  18206. this.enable( gl.DEPTH_TEST );
  18207. gl.depthFunc( gl.LEQUAL );
  18208. gl.frontFace( gl.CCW );
  18209. gl.cullFace( gl.BACK );
  18210. this.enable( gl.CULL_FACE );
  18211. this.enable( gl.BLEND );
  18212. gl.blendEquation( gl.FUNC_ADD );
  18213. gl.blendFunc( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA );
  18214. };
  18215. this.initAttributes = function () {
  18216. for ( var i = 0, l = newAttributes.length; i < l; i ++ ) {
  18217. newAttributes[ i ] = 0;
  18218. }
  18219. };
  18220. this.enableAttribute = function ( attribute ) {
  18221. newAttributes[ attribute ] = 1;
  18222. if ( enabledAttributes[ attribute ] === 0 ) {
  18223. gl.enableVertexAttribArray( attribute );
  18224. enabledAttributes[ attribute ] = 1;
  18225. }
  18226. if ( attributeDivisors[ attribute ] !== 0 ) {
  18227. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  18228. extension.vertexAttribDivisorANGLE( attribute, 0 );
  18229. attributeDivisors[ attribute ] = 0;
  18230. }
  18231. };
  18232. this.enableAttributeAndDivisor = function ( attribute, meshPerAttribute, extension ) {
  18233. newAttributes[ attribute ] = 1;
  18234. if ( enabledAttributes[ attribute ] === 0 ) {
  18235. gl.enableVertexAttribArray( attribute );
  18236. enabledAttributes[ attribute ] = 1;
  18237. }
  18238. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  18239. extension.vertexAttribDivisorANGLE( attribute, meshPerAttribute );
  18240. attributeDivisors[ attribute ] = meshPerAttribute;
  18241. }
  18242. };
  18243. this.disableUnusedAttributes = function () {
  18244. for ( var i = 0, l = enabledAttributes.length; i < l; i ++ ) {
  18245. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  18246. gl.disableVertexAttribArray( i );
  18247. enabledAttributes[ i ] = 0;
  18248. }
  18249. }
  18250. };
  18251. this.enable = function ( id ) {
  18252. if ( capabilities[ id ] !== true ) {
  18253. gl.enable( id );
  18254. capabilities[ id ] = true;
  18255. }
  18256. };
  18257. this.disable = function ( id ) {
  18258. if ( capabilities[ id ] !== false ) {
  18259. gl.disable( id );
  18260. capabilities[ id ] = false;
  18261. }
  18262. };
  18263. this.getCompressedTextureFormats = function () {
  18264. if ( compressedTextureFormats === null ) {
  18265. compressedTextureFormats = [];
  18266. if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) ||
  18267. extensions.get( 'WEBGL_compressed_texture_s3tc' ) ) {
  18268. var formats = gl.getParameter( gl.COMPRESSED_TEXTURE_FORMATS );
  18269. for ( var i = 0; i < formats.length; i ++ ) {
  18270. compressedTextureFormats.push( formats[ i ] );
  18271. }
  18272. }
  18273. }
  18274. return compressedTextureFormats;
  18275. };
  18276. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha ) {
  18277. if ( blending !== currentBlending ) {
  18278. if ( blending === THREE.NoBlending ) {
  18279. this.disable( gl.BLEND );
  18280. } else if ( blending === THREE.AdditiveBlending ) {
  18281. this.enable( gl.BLEND );
  18282. gl.blendEquation( gl.FUNC_ADD );
  18283. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  18284. } else if ( blending === THREE.SubtractiveBlending ) {
  18285. // TODO: Find blendFuncSeparate() combination
  18286. this.enable( gl.BLEND );
  18287. gl.blendEquation( gl.FUNC_ADD );
  18288. gl.blendFunc( gl.ZERO, gl.ONE_MINUS_SRC_COLOR );
  18289. } else if ( blending === THREE.MultiplyBlending ) {
  18290. // TODO: Find blendFuncSeparate() combination
  18291. this.enable( gl.BLEND );
  18292. gl.blendEquation( gl.FUNC_ADD );
  18293. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  18294. } else if ( blending === THREE.CustomBlending ) {
  18295. this.enable( gl.BLEND );
  18296. } else {
  18297. this.enable( gl.BLEND );
  18298. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  18299. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  18300. }
  18301. currentBlending = blending;
  18302. }
  18303. if ( blending === THREE.CustomBlending ) {
  18304. blendEquationAlpha = blendEquationAlpha || blendEquation;
  18305. blendSrcAlpha = blendSrcAlpha || blendSrc;
  18306. blendDstAlpha = blendDstAlpha || blendDst;
  18307. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  18308. gl.blendEquationSeparate( paramThreeToGL( blendEquation ), paramThreeToGL( blendEquationAlpha ) );
  18309. currentBlendEquation = blendEquation;
  18310. currentBlendEquationAlpha = blendEquationAlpha;
  18311. }
  18312. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  18313. gl.blendFuncSeparate( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ), paramThreeToGL( blendSrcAlpha ), paramThreeToGL( blendDstAlpha ) );
  18314. currentBlendSrc = blendSrc;
  18315. currentBlendDst = blendDst;
  18316. currentBlendSrcAlpha = blendSrcAlpha;
  18317. currentBlendDstAlpha = blendDstAlpha;
  18318. }
  18319. } else {
  18320. currentBlendEquation = null;
  18321. currentBlendSrc = null;
  18322. currentBlendDst = null;
  18323. currentBlendEquationAlpha = null;
  18324. currentBlendSrcAlpha = null;
  18325. currentBlendDstAlpha = null;
  18326. }
  18327. };
  18328. this.setDepthFunc = function ( depthFunc ) {
  18329. if ( currentDepthFunc !== depthFunc ) {
  18330. if ( depthFunc ) {
  18331. switch ( depthFunc ) {
  18332. case THREE.NeverDepth:
  18333. gl.depthFunc( gl.NEVER );
  18334. break;
  18335. case THREE.AlwaysDepth:
  18336. gl.depthFunc( gl.ALWAYS );
  18337. break;
  18338. case THREE.LessDepth:
  18339. gl.depthFunc( gl.LESS );
  18340. break;
  18341. case THREE.LessEqualDepth:
  18342. gl.depthFunc( gl.LEQUAL );
  18343. break;
  18344. case THREE.EqualDepth:
  18345. gl.depthFunc( gl.EQUAL );
  18346. break;
  18347. case THREE.GreaterEqualDepth:
  18348. gl.depthFunc( gl.GEQUAL );
  18349. break;
  18350. case THREE.GreaterDepth:
  18351. gl.depthFunc( gl.GREATER );
  18352. break;
  18353. case THREE.NotEqualDepth:
  18354. gl.depthFunc( gl.NOTEQUAL );
  18355. break;
  18356. default:
  18357. gl.depthFunc( gl.LEQUAL );
  18358. }
  18359. } else {
  18360. gl.depthFunc( gl.LEQUAL );
  18361. }
  18362. currentDepthFunc = depthFunc;
  18363. }
  18364. };
  18365. this.setDepthTest = function ( depthTest ) {
  18366. if ( depthTest ) {
  18367. this.enable( gl.DEPTH_TEST );
  18368. } else {
  18369. this.disable( gl.DEPTH_TEST );
  18370. }
  18371. };
  18372. this.setDepthWrite = function ( depthWrite ) {
  18373. if ( currentDepthWrite !== depthWrite ) {
  18374. gl.depthMask( depthWrite );
  18375. currentDepthWrite = depthWrite;
  18376. }
  18377. };
  18378. this.setColorWrite = function ( colorWrite ) {
  18379. if ( currentColorWrite !== colorWrite ) {
  18380. gl.colorMask( colorWrite, colorWrite, colorWrite, colorWrite );
  18381. currentColorWrite = colorWrite;
  18382. }
  18383. };
  18384. this.setFlipSided = function ( flipSided ) {
  18385. if ( currentFlipSided !== flipSided ) {
  18386. if ( flipSided ) {
  18387. gl.frontFace( gl.CW );
  18388. } else {
  18389. gl.frontFace( gl.CCW );
  18390. }
  18391. currentFlipSided = flipSided;
  18392. }
  18393. };
  18394. this.setLineWidth = function ( width ) {
  18395. if ( width !== currentLineWidth ) {
  18396. gl.lineWidth( width );
  18397. currentLineWidth = width;
  18398. }
  18399. };
  18400. this.setPolygonOffset = function ( polygonOffset, factor, units ) {
  18401. if ( polygonOffset ) {
  18402. this.enable( gl.POLYGON_OFFSET_FILL );
  18403. } else {
  18404. this.disable( gl.POLYGON_OFFSET_FILL );
  18405. }
  18406. if ( polygonOffset && ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) ) {
  18407. gl.polygonOffset( factor, units );
  18408. currentPolygonOffsetFactor = factor;
  18409. currentPolygonOffsetUnits = units;
  18410. }
  18411. };
  18412. this.getScissorTest = function () {
  18413. return currentScissorTest;
  18414. };
  18415. this.setScissorTest = function ( scissorTest ) {
  18416. currentScissorTest = scissorTest;
  18417. if ( scissorTest ) {
  18418. this.enable( gl.SCISSOR_TEST );
  18419. } else {
  18420. this.disable( gl.SCISSOR_TEST );
  18421. }
  18422. };
  18423. // texture
  18424. this.activeTexture = function ( webglSlot ) {
  18425. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  18426. if ( currentTextureSlot !== webglSlot ) {
  18427. gl.activeTexture( webglSlot );
  18428. currentTextureSlot = webglSlot;
  18429. }
  18430. }
  18431. this.bindTexture = function ( webglType, webglTexture ) {
  18432. if ( currentTextureSlot === undefined ) {
  18433. _this.activeTexture();
  18434. }
  18435. var boundTexture = currentBoundTextures[ currentTextureSlot ];
  18436. if ( boundTexture === undefined ) {
  18437. boundTexture = { type: undefined, texture: undefined };
  18438. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  18439. }
  18440. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  18441. gl.bindTexture( webglType, webglTexture );
  18442. boundTexture.type = webglType;
  18443. boundTexture.texture = webglTexture;
  18444. }
  18445. };
  18446. this.compressedTexImage2D = function () {
  18447. try {
  18448. gl.compressedTexImage2D.apply( gl, arguments );
  18449. } catch ( error ) {
  18450. console.error( error );
  18451. }
  18452. };
  18453. this.texImage2D = function () {
  18454. try {
  18455. gl.texImage2D.apply( gl, arguments );
  18456. } catch ( error ) {
  18457. console.error( error );
  18458. }
  18459. };
  18460. //
  18461. this.reset = function () {
  18462. for ( var i = 0; i < enabledAttributes.length; i ++ ) {
  18463. if ( enabledAttributes[ i ] === 1 ) {
  18464. gl.disableVertexAttribArray( i );
  18465. enabledAttributes[ i ] = 0;
  18466. }
  18467. }
  18468. capabilities = {};
  18469. compressedTextureFormats = null;
  18470. currentBlending = null;
  18471. currentDepthWrite = null;
  18472. currentColorWrite = null;
  18473. currentFlipSided = null;
  18474. };
  18475. };
  18476. // File:src/renderers/webgl/plugins/LensFlarePlugin.js
  18477. /**
  18478. * @author mikael emtinger / http://gomo.se/
  18479. * @author alteredq / http://alteredqualia.com/
  18480. */
  18481. THREE.LensFlarePlugin = function ( renderer, flares ) {
  18482. var gl = renderer.context;
  18483. var state = renderer.state;
  18484. var vertexBuffer, elementBuffer;
  18485. var program, attributes, uniforms;
  18486. var hasVertexTexture;
  18487. var tempTexture, occlusionTexture;
  18488. function init() {
  18489. var vertices = new Float32Array( [
  18490. - 1, - 1, 0, 0,
  18491. 1, - 1, 1, 0,
  18492. 1, 1, 1, 1,
  18493. - 1, 1, 0, 1
  18494. ] );
  18495. var faces = new Uint16Array( [
  18496. 0, 1, 2,
  18497. 0, 2, 3
  18498. ] );
  18499. // buffers
  18500. vertexBuffer = gl.createBuffer();
  18501. elementBuffer = gl.createBuffer();
  18502. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  18503. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  18504. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  18505. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  18506. // textures
  18507. tempTexture = gl.createTexture();
  18508. occlusionTexture = gl.createTexture();
  18509. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  18510. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB, 16, 16, 0, gl.RGB, gl.UNSIGNED_BYTE, null );
  18511. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  18512. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  18513. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  18514. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  18515. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  18516. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, 16, 16, 0, gl.RGBA, gl.UNSIGNED_BYTE, null );
  18517. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  18518. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  18519. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  18520. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  18521. hasVertexTexture = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) > 0;
  18522. var shader;
  18523. if ( hasVertexTexture ) {
  18524. shader = {
  18525. vertexShader: [
  18526. "uniform lowp int renderType;",
  18527. "uniform vec3 screenPosition;",
  18528. "uniform vec2 scale;",
  18529. "uniform float rotation;",
  18530. "uniform sampler2D occlusionMap;",
  18531. "attribute vec2 position;",
  18532. "attribute vec2 uv;",
  18533. "varying vec2 vUV;",
  18534. "varying float vVisibility;",
  18535. "void main() {",
  18536. "vUV = uv;",
  18537. "vec2 pos = position;",
  18538. "if ( renderType == 2 ) {",
  18539. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  18540. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  18541. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  18542. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  18543. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  18544. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  18545. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  18546. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  18547. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  18548. "vVisibility = visibility.r / 9.0;",
  18549. "vVisibility *= 1.0 - visibility.g / 9.0;",
  18550. "vVisibility *= visibility.b / 9.0;",
  18551. "vVisibility *= 1.0 - visibility.a / 9.0;",
  18552. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  18553. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  18554. "}",
  18555. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  18556. "}"
  18557. ].join( "\n" ),
  18558. fragmentShader: [
  18559. "uniform lowp int renderType;",
  18560. "uniform sampler2D map;",
  18561. "uniform float opacity;",
  18562. "uniform vec3 color;",
  18563. "varying vec2 vUV;",
  18564. "varying float vVisibility;",
  18565. "void main() {",
  18566. // pink square
  18567. "if ( renderType == 0 ) {",
  18568. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  18569. // restore
  18570. "} else if ( renderType == 1 ) {",
  18571. "gl_FragColor = texture2D( map, vUV );",
  18572. // flare
  18573. "} else {",
  18574. "vec4 texture = texture2D( map, vUV );",
  18575. "texture.a *= opacity * vVisibility;",
  18576. "gl_FragColor = texture;",
  18577. "gl_FragColor.rgb *= color;",
  18578. "}",
  18579. "}"
  18580. ].join( "\n" )
  18581. };
  18582. } else {
  18583. shader = {
  18584. vertexShader: [
  18585. "uniform lowp int renderType;",
  18586. "uniform vec3 screenPosition;",
  18587. "uniform vec2 scale;",
  18588. "uniform float rotation;",
  18589. "attribute vec2 position;",
  18590. "attribute vec2 uv;",
  18591. "varying vec2 vUV;",
  18592. "void main() {",
  18593. "vUV = uv;",
  18594. "vec2 pos = position;",
  18595. "if ( renderType == 2 ) {",
  18596. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  18597. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  18598. "}",
  18599. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  18600. "}"
  18601. ].join( "\n" ),
  18602. fragmentShader: [
  18603. "precision mediump float;",
  18604. "uniform lowp int renderType;",
  18605. "uniform sampler2D map;",
  18606. "uniform sampler2D occlusionMap;",
  18607. "uniform float opacity;",
  18608. "uniform vec3 color;",
  18609. "varying vec2 vUV;",
  18610. "void main() {",
  18611. // pink square
  18612. "if ( renderType == 0 ) {",
  18613. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  18614. // restore
  18615. "} else if ( renderType == 1 ) {",
  18616. "gl_FragColor = texture2D( map, vUV );",
  18617. // flare
  18618. "} else {",
  18619. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a;",
  18620. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a;",
  18621. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a;",
  18622. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  18623. "visibility = ( 1.0 - visibility / 4.0 );",
  18624. "vec4 texture = texture2D( map, vUV );",
  18625. "texture.a *= opacity * visibility;",
  18626. "gl_FragColor = texture;",
  18627. "gl_FragColor.rgb *= color;",
  18628. "}",
  18629. "}"
  18630. ].join( "\n" )
  18631. };
  18632. }
  18633. program = createProgram( shader );
  18634. attributes = {
  18635. vertex: gl.getAttribLocation ( program, "position" ),
  18636. uv: gl.getAttribLocation ( program, "uv" )
  18637. };
  18638. uniforms = {
  18639. renderType: gl.getUniformLocation( program, "renderType" ),
  18640. map: gl.getUniformLocation( program, "map" ),
  18641. occlusionMap: gl.getUniformLocation( program, "occlusionMap" ),
  18642. opacity: gl.getUniformLocation( program, "opacity" ),
  18643. color: gl.getUniformLocation( program, "color" ),
  18644. scale: gl.getUniformLocation( program, "scale" ),
  18645. rotation: gl.getUniformLocation( program, "rotation" ),
  18646. screenPosition: gl.getUniformLocation( program, "screenPosition" )
  18647. };
  18648. }
  18649. /*
  18650. * Render lens flares
  18651. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  18652. * reads these back and calculates occlusion.
  18653. */
  18654. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  18655. if ( flares.length === 0 ) return;
  18656. var tempPosition = new THREE.Vector3();
  18657. var invAspect = viewportHeight / viewportWidth,
  18658. halfViewportWidth = viewportWidth * 0.5,
  18659. halfViewportHeight = viewportHeight * 0.5;
  18660. var size = 16 / viewportHeight,
  18661. scale = new THREE.Vector2( size * invAspect, size );
  18662. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  18663. screenPositionPixels = new THREE.Vector2( 1, 1 );
  18664. if ( program === undefined ) {
  18665. init();
  18666. }
  18667. gl.useProgram( program );
  18668. state.initAttributes();
  18669. state.enableAttribute( attributes.vertex );
  18670. state.enableAttribute( attributes.uv );
  18671. state.disableUnusedAttributes();
  18672. // loop through all lens flares to update their occlusion and positions
  18673. // setup gl and common used attribs/uniforms
  18674. gl.uniform1i( uniforms.occlusionMap, 0 );
  18675. gl.uniform1i( uniforms.map, 1 );
  18676. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  18677. gl.vertexAttribPointer( attributes.vertex, 2, gl.FLOAT, false, 2 * 8, 0 );
  18678. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  18679. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  18680. state.disable( gl.CULL_FACE );
  18681. gl.depthMask( false );
  18682. for ( var i = 0, l = flares.length; i < l; i ++ ) {
  18683. size = 16 / viewportHeight;
  18684. scale.set( size * invAspect, size );
  18685. // calc object screen position
  18686. var flare = flares[ i ];
  18687. tempPosition.set( flare.matrixWorld.elements[ 12 ], flare.matrixWorld.elements[ 13 ], flare.matrixWorld.elements[ 14 ] );
  18688. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  18689. tempPosition.applyProjection( camera.projectionMatrix );
  18690. // setup arrays for gl programs
  18691. screenPosition.copy( tempPosition );
  18692. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  18693. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  18694. // screen cull
  18695. if ( hasVertexTexture || (
  18696. screenPositionPixels.x > 0 &&
  18697. screenPositionPixels.x < viewportWidth &&
  18698. screenPositionPixels.y > 0 &&
  18699. screenPositionPixels.y < viewportHeight ) ) {
  18700. // save current RGB to temp texture
  18701. state.activeTexture( gl.TEXTURE0 );
  18702. state.bindTexture( gl.TEXTURE_2D, null );
  18703. state.activeTexture( gl.TEXTURE1 );
  18704. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  18705. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  18706. // render pink quad
  18707. gl.uniform1i( uniforms.renderType, 0 );
  18708. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  18709. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  18710. state.disable( gl.BLEND );
  18711. state.enable( gl.DEPTH_TEST );
  18712. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  18713. // copy result to occlusionMap
  18714. state.activeTexture( gl.TEXTURE0 );
  18715. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  18716. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  18717. // restore graphics
  18718. gl.uniform1i( uniforms.renderType, 1 );
  18719. state.disable( gl.DEPTH_TEST );
  18720. state.activeTexture( gl.TEXTURE1 );
  18721. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  18722. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  18723. // update object positions
  18724. flare.positionScreen.copy( screenPosition );
  18725. if ( flare.customUpdateCallback ) {
  18726. flare.customUpdateCallback( flare );
  18727. } else {
  18728. flare.updateLensFlares();
  18729. }
  18730. // render flares
  18731. gl.uniform1i( uniforms.renderType, 2 );
  18732. state.enable( gl.BLEND );
  18733. for ( var j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  18734. var sprite = flare.lensFlares[ j ];
  18735. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  18736. screenPosition.x = sprite.x;
  18737. screenPosition.y = sprite.y;
  18738. screenPosition.z = sprite.z;
  18739. size = sprite.size * sprite.scale / viewportHeight;
  18740. scale.x = size * invAspect;
  18741. scale.y = size;
  18742. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  18743. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  18744. gl.uniform1f( uniforms.rotation, sprite.rotation );
  18745. gl.uniform1f( uniforms.opacity, sprite.opacity );
  18746. gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  18747. state.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  18748. renderer.setTexture( sprite.texture, 1 );
  18749. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  18750. }
  18751. }
  18752. }
  18753. }
  18754. // restore gl
  18755. state.enable( gl.CULL_FACE );
  18756. state.enable( gl.DEPTH_TEST );
  18757. gl.depthMask( true );
  18758. renderer.resetGLState();
  18759. };
  18760. function createProgram ( shader ) {
  18761. var program = gl.createProgram();
  18762. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  18763. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  18764. var prefix = "precision " + renderer.getPrecision() + " float;\n";
  18765. gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  18766. gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  18767. gl.compileShader( fragmentShader );
  18768. gl.compileShader( vertexShader );
  18769. gl.attachShader( program, fragmentShader );
  18770. gl.attachShader( program, vertexShader );
  18771. gl.linkProgram( program );
  18772. return program;
  18773. }
  18774. };
  18775. // File:src/renderers/webgl/plugins/SpritePlugin.js
  18776. /**
  18777. * @author mikael emtinger / http://gomo.se/
  18778. * @author alteredq / http://alteredqualia.com/
  18779. */
  18780. THREE.SpritePlugin = function ( renderer, sprites ) {
  18781. var gl = renderer.context;
  18782. var state = renderer.state;
  18783. var vertexBuffer, elementBuffer;
  18784. var program, attributes, uniforms;
  18785. var texture;
  18786. // decompose matrixWorld
  18787. var spritePosition = new THREE.Vector3();
  18788. var spriteRotation = new THREE.Quaternion();
  18789. var spriteScale = new THREE.Vector3();
  18790. function init() {
  18791. var vertices = new Float32Array( [
  18792. - 0.5, - 0.5, 0, 0,
  18793. 0.5, - 0.5, 1, 0,
  18794. 0.5, 0.5, 1, 1,
  18795. - 0.5, 0.5, 0, 1
  18796. ] );
  18797. var faces = new Uint16Array( [
  18798. 0, 1, 2,
  18799. 0, 2, 3
  18800. ] );
  18801. vertexBuffer = gl.createBuffer();
  18802. elementBuffer = gl.createBuffer();
  18803. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  18804. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  18805. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  18806. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  18807. program = createProgram();
  18808. attributes = {
  18809. position: gl.getAttribLocation ( program, 'position' ),
  18810. uv: gl.getAttribLocation ( program, 'uv' )
  18811. };
  18812. uniforms = {
  18813. uvOffset: gl.getUniformLocation( program, 'uvOffset' ),
  18814. uvScale: gl.getUniformLocation( program, 'uvScale' ),
  18815. rotation: gl.getUniformLocation( program, 'rotation' ),
  18816. scale: gl.getUniformLocation( program, 'scale' ),
  18817. color: gl.getUniformLocation( program, 'color' ),
  18818. map: gl.getUniformLocation( program, 'map' ),
  18819. opacity: gl.getUniformLocation( program, 'opacity' ),
  18820. modelViewMatrix: gl.getUniformLocation( program, 'modelViewMatrix' ),
  18821. projectionMatrix: gl.getUniformLocation( program, 'projectionMatrix' ),
  18822. fogType: gl.getUniformLocation( program, 'fogType' ),
  18823. fogDensity: gl.getUniformLocation( program, 'fogDensity' ),
  18824. fogNear: gl.getUniformLocation( program, 'fogNear' ),
  18825. fogFar: gl.getUniformLocation( program, 'fogFar' ),
  18826. fogColor: gl.getUniformLocation( program, 'fogColor' ),
  18827. alphaTest: gl.getUniformLocation( program, 'alphaTest' )
  18828. };
  18829. var canvas = document.createElement( 'canvas' );
  18830. canvas.width = 8;
  18831. canvas.height = 8;
  18832. var context = canvas.getContext( '2d' );
  18833. context.fillStyle = 'white';
  18834. context.fillRect( 0, 0, 8, 8 );
  18835. texture = new THREE.Texture( canvas );
  18836. texture.needsUpdate = true;
  18837. }
  18838. this.render = function ( scene, camera ) {
  18839. if ( sprites.length === 0 ) return;
  18840. // setup gl
  18841. if ( program === undefined ) {
  18842. init();
  18843. }
  18844. gl.useProgram( program );
  18845. state.initAttributes();
  18846. state.enableAttribute( attributes.position );
  18847. state.enableAttribute( attributes.uv );
  18848. state.disableUnusedAttributes();
  18849. state.disable( gl.CULL_FACE );
  18850. state.enable( gl.BLEND );
  18851. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  18852. gl.vertexAttribPointer( attributes.position, 2, gl.FLOAT, false, 2 * 8, 0 );
  18853. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  18854. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  18855. gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  18856. state.activeTexture( gl.TEXTURE0 );
  18857. gl.uniform1i( uniforms.map, 0 );
  18858. var oldFogType = 0;
  18859. var sceneFogType = 0;
  18860. var fog = scene.fog;
  18861. if ( fog ) {
  18862. gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  18863. if ( fog instanceof THREE.Fog ) {
  18864. gl.uniform1f( uniforms.fogNear, fog.near );
  18865. gl.uniform1f( uniforms.fogFar, fog.far );
  18866. gl.uniform1i( uniforms.fogType, 1 );
  18867. oldFogType = 1;
  18868. sceneFogType = 1;
  18869. } else if ( fog instanceof THREE.FogExp2 ) {
  18870. gl.uniform1f( uniforms.fogDensity, fog.density );
  18871. gl.uniform1i( uniforms.fogType, 2 );
  18872. oldFogType = 2;
  18873. sceneFogType = 2;
  18874. }
  18875. } else {
  18876. gl.uniform1i( uniforms.fogType, 0 );
  18877. oldFogType = 0;
  18878. sceneFogType = 0;
  18879. }
  18880. // update positions and sort
  18881. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  18882. var sprite = sprites[ i ];
  18883. sprite.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  18884. sprite.z = - sprite.modelViewMatrix.elements[ 14 ];
  18885. }
  18886. sprites.sort( painterSortStable );
  18887. // render all sprites
  18888. var scale = [];
  18889. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  18890. var sprite = sprites[ i ];
  18891. var material = sprite.material;
  18892. gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  18893. gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite.modelViewMatrix.elements );
  18894. sprite.matrixWorld.decompose( spritePosition, spriteRotation, spriteScale );
  18895. scale[ 0 ] = spriteScale.x;
  18896. scale[ 1 ] = spriteScale.y;
  18897. var fogType = 0;
  18898. if ( scene.fog && material.fog ) {
  18899. fogType = sceneFogType;
  18900. }
  18901. if ( oldFogType !== fogType ) {
  18902. gl.uniform1i( uniforms.fogType, fogType );
  18903. oldFogType = fogType;
  18904. }
  18905. if ( material.map !== null ) {
  18906. gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y );
  18907. gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y );
  18908. } else {
  18909. gl.uniform2f( uniforms.uvOffset, 0, 0 );
  18910. gl.uniform2f( uniforms.uvScale, 1, 1 );
  18911. }
  18912. gl.uniform1f( uniforms.opacity, material.opacity );
  18913. gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  18914. gl.uniform1f( uniforms.rotation, material.rotation );
  18915. gl.uniform2fv( uniforms.scale, scale );
  18916. state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  18917. state.setDepthTest( material.depthTest );
  18918. state.setDepthWrite( material.depthWrite );
  18919. if ( material.map && material.map.image && material.map.image.width ) {
  18920. renderer.setTexture( material.map, 0 );
  18921. } else {
  18922. renderer.setTexture( texture, 0 );
  18923. }
  18924. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  18925. }
  18926. // restore gl
  18927. state.enable( gl.CULL_FACE );
  18928. renderer.resetGLState();
  18929. };
  18930. function createProgram () {
  18931. var program = gl.createProgram();
  18932. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  18933. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  18934. gl.shaderSource( vertexShader, [
  18935. 'precision ' + renderer.getPrecision() + ' float;',
  18936. 'uniform mat4 modelViewMatrix;',
  18937. 'uniform mat4 projectionMatrix;',
  18938. 'uniform float rotation;',
  18939. 'uniform vec2 scale;',
  18940. 'uniform vec2 uvOffset;',
  18941. 'uniform vec2 uvScale;',
  18942. 'attribute vec2 position;',
  18943. 'attribute vec2 uv;',
  18944. 'varying vec2 vUV;',
  18945. 'void main() {',
  18946. 'vUV = uvOffset + uv * uvScale;',
  18947. 'vec2 alignedPosition = position * scale;',
  18948. 'vec2 rotatedPosition;',
  18949. 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  18950. 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  18951. 'vec4 finalPosition;',
  18952. 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  18953. 'finalPosition.xy += rotatedPosition;',
  18954. 'finalPosition = projectionMatrix * finalPosition;',
  18955. 'gl_Position = finalPosition;',
  18956. '}'
  18957. ].join( '\n' ) );
  18958. gl.shaderSource( fragmentShader, [
  18959. 'precision ' + renderer.getPrecision() + ' float;',
  18960. 'uniform vec3 color;',
  18961. 'uniform sampler2D map;',
  18962. 'uniform float opacity;',
  18963. 'uniform int fogType;',
  18964. 'uniform vec3 fogColor;',
  18965. 'uniform float fogDensity;',
  18966. 'uniform float fogNear;',
  18967. 'uniform float fogFar;',
  18968. 'uniform float alphaTest;',
  18969. 'varying vec2 vUV;',
  18970. 'void main() {',
  18971. 'vec4 texture = texture2D( map, vUV );',
  18972. 'if ( texture.a < alphaTest ) discard;',
  18973. 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  18974. 'if ( fogType > 0 ) {',
  18975. 'float depth = gl_FragCoord.z / gl_FragCoord.w;',
  18976. 'float fogFactor = 0.0;',
  18977. 'if ( fogType == 1 ) {',
  18978. 'fogFactor = smoothstep( fogNear, fogFar, depth );',
  18979. '} else {',
  18980. 'const float LOG2 = 1.442695;',
  18981. 'fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );',
  18982. 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  18983. '}',
  18984. 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );',
  18985. '}',
  18986. '}'
  18987. ].join( '\n' ) );
  18988. gl.compileShader( vertexShader );
  18989. gl.compileShader( fragmentShader );
  18990. gl.attachShader( program, vertexShader );
  18991. gl.attachShader( program, fragmentShader );
  18992. gl.linkProgram( program );
  18993. return program;
  18994. }
  18995. function painterSortStable ( a, b ) {
  18996. if ( a.z !== b.z ) {
  18997. return b.z - a.z;
  18998. } else {
  18999. return b.id - a.id;
  19000. }
  19001. }
  19002. };
  19003. // File:src/Three.Legacy.js
  19004. /**
  19005. * @author mrdoob / http://mrdoob.com/
  19006. */
  19007. Object.defineProperties( THREE.Box2.prototype, {
  19008. isIntersectionBox: {
  19009. value: function ( box ) {
  19010. console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
  19011. return this.intersectsBox( box );
  19012. }
  19013. }
  19014. } );
  19015. Object.defineProperties( THREE.Box3.prototype, {
  19016. isIntersectionBox: {
  19017. value: function ( box ) {
  19018. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  19019. return this.intersectsBox( box );
  19020. }
  19021. },
  19022. isIntersectionSphere: {
  19023. value: function ( sphere ) {
  19024. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  19025. return this.intersectsSphere( sphere );
  19026. }
  19027. }
  19028. } );
  19029. Object.defineProperties( THREE.Matrix3.prototype, {
  19030. multiplyVector3: {
  19031. value: function ( vector ) {
  19032. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  19033. return vector.applyMatrix3( this );
  19034. }
  19035. },
  19036. multiplyVector3Array: {
  19037. value: function ( a ) {
  19038. console.warn( 'THREE.Matrix3: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  19039. return this.applyToVector3Array( a );
  19040. }
  19041. }
  19042. } );
  19043. Object.defineProperties( THREE.Matrix4.prototype, {
  19044. extractPosition: {
  19045. value: function ( m ) {
  19046. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  19047. return this.copyPosition( m );
  19048. }
  19049. },
  19050. setRotationFromQuaternion: {
  19051. value: function ( q ) {
  19052. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  19053. return this.makeRotationFromQuaternion( q );
  19054. }
  19055. },
  19056. multiplyVector3: {
  19057. value: function ( vector ) {
  19058. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  19059. return vector.applyProjection( this );
  19060. }
  19061. },
  19062. multiplyVector4: {
  19063. value: function ( vector ) {
  19064. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  19065. return vector.applyMatrix4( this );
  19066. }
  19067. },
  19068. multiplyVector3Array: {
  19069. value: function ( a ) {
  19070. console.warn( 'THREE.Matrix4: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  19071. return this.applyToVector3Array( a );
  19072. }
  19073. },
  19074. rotateAxis: {
  19075. value: function ( v ) {
  19076. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  19077. v.transformDirection( this );
  19078. }
  19079. },
  19080. crossVector: {
  19081. value: function ( vector ) {
  19082. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  19083. return vector.applyMatrix4( this );
  19084. }
  19085. },
  19086. translate: {
  19087. value: function ( v ) {
  19088. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  19089. }
  19090. },
  19091. rotateX: {
  19092. value: function ( angle ) {
  19093. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  19094. }
  19095. },
  19096. rotateY: {
  19097. value: function ( angle ) {
  19098. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  19099. }
  19100. },
  19101. rotateZ: {
  19102. value: function ( angle ) {
  19103. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  19104. }
  19105. },
  19106. rotateByAxis: {
  19107. value: function ( axis, angle ) {
  19108. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  19109. }
  19110. }
  19111. } );
  19112. Object.defineProperties( THREE.Plane.prototype, {
  19113. isIntersectionLine: {
  19114. value: function ( line ) {
  19115. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  19116. return this.intersectsLine( line );
  19117. }
  19118. }
  19119. } );
  19120. Object.defineProperties( THREE.Quaternion.prototype, {
  19121. multiplyVector3: {
  19122. value: function ( vector ) {
  19123. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  19124. return vector.applyQuaternion( this );
  19125. }
  19126. }
  19127. } );
  19128. Object.defineProperties( THREE.Ray.prototype, {
  19129. isIntersectionBox: {
  19130. value: function ( box ) {
  19131. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  19132. return this.intersectsBox( box );
  19133. }
  19134. },
  19135. isIntersectionPlane: {
  19136. value: function ( plane ) {
  19137. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  19138. return this.intersectsPlane( plane );
  19139. }
  19140. },
  19141. isIntersectionSphere: {
  19142. value: function ( sphere ) {
  19143. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  19144. return this.intersectsSphere( sphere );
  19145. }
  19146. }
  19147. } );
  19148. Object.defineProperties( THREE.Vector3.prototype, {
  19149. setEulerFromRotationMatrix: {
  19150. value: function () {
  19151. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  19152. }
  19153. },
  19154. setEulerFromQuaternion: {
  19155. value: function () {
  19156. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  19157. }
  19158. },
  19159. getPositionFromMatrix: {
  19160. value: function ( m ) {
  19161. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  19162. return this.setFromMatrixPosition( m );
  19163. }
  19164. },
  19165. getScaleFromMatrix: {
  19166. value: function ( m ) {
  19167. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  19168. return this.setFromMatrixScale( m );
  19169. }
  19170. },
  19171. getColumnFromMatrix: {
  19172. value: function ( index, matrix ) {
  19173. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  19174. return this.setFromMatrixColumn( index, matrix );
  19175. }
  19176. }
  19177. } );
  19178. //
  19179. Object.defineProperties( THREE.Object3D.prototype, {
  19180. eulerOrder: {
  19181. get: function () {
  19182. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  19183. return this.rotation.order;
  19184. },
  19185. set: function ( value ) {
  19186. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  19187. this.rotation.order = value;
  19188. }
  19189. },
  19190. getChildByName: {
  19191. value: function ( name ) {
  19192. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  19193. return this.getObjectByName( name );
  19194. }
  19195. },
  19196. renderDepth: {
  19197. set: function ( value ) {
  19198. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  19199. }
  19200. },
  19201. translate: {
  19202. value: function ( distance, axis ) {
  19203. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  19204. return this.translateOnAxis( axis, distance );
  19205. }
  19206. },
  19207. useQuaternion: {
  19208. get: function () {
  19209. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  19210. },
  19211. set: function ( value ) {
  19212. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  19213. }
  19214. }
  19215. } );
  19216. //
  19217. Object.defineProperties( THREE, {
  19218. PointCloud: {
  19219. value: function ( geometry, material ) {
  19220. console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
  19221. return new THREE.Points( geometry, material );
  19222. }
  19223. },
  19224. ParticleSystem: {
  19225. value: function ( geometry, material ) {
  19226. console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
  19227. return new THREE.Points( geometry, material );
  19228. }
  19229. }
  19230. } );
  19231. //
  19232. Object.defineProperties( THREE.Light.prototype, {
  19233. onlyShadow: {
  19234. set: function ( value ) {
  19235. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  19236. }
  19237. },
  19238. shadowCameraFov: {
  19239. set: function ( value ) {
  19240. this.shadow.camera.fov = value;
  19241. }
  19242. },
  19243. shadowCameraLeft: {
  19244. set: function ( value ) {
  19245. this.shadow.camera.left = value;
  19246. }
  19247. },
  19248. shadowCameraRight: {
  19249. set: function ( value ) {
  19250. this.shadow.camera.right = value;
  19251. }
  19252. },
  19253. shadowCameraTop: {
  19254. set: function ( value ) {
  19255. this.shadow.camera.top = value;
  19256. }
  19257. },
  19258. shadowCameraBottom: {
  19259. set: function ( value ) {
  19260. this.shadow.camera.bottom = value;
  19261. }
  19262. },
  19263. shadowCameraNear: {
  19264. set: function ( value ) {
  19265. this.shadow.camera.near = value;
  19266. }
  19267. },
  19268. shadowCameraFar: {
  19269. set: function ( value ) {
  19270. this.shadow.camera.far = value;
  19271. }
  19272. },
  19273. shadowCameraVisible: {
  19274. set: function ( value ) {
  19275. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );
  19276. }
  19277. },
  19278. shadowBias: {
  19279. set: function ( value ) {
  19280. this.shadow.bias = value;
  19281. }
  19282. },
  19283. shadowDarkness: {
  19284. set: function ( value ) {
  19285. this.shadow.darkness = value;
  19286. }
  19287. },
  19288. shadowMapWidth: {
  19289. set: function ( value ) {
  19290. this.shadow.mapSize.width = value;
  19291. }
  19292. },
  19293. shadowMapHeight: {
  19294. set: function ( value ) {
  19295. this.shadow.mapSize.height = value;
  19296. }
  19297. }
  19298. } );
  19299. //
  19300. Object.defineProperties( THREE.BufferAttribute.prototype, {
  19301. length: {
  19302. get: function () {
  19303. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Please use .count.' );
  19304. return this.array.length;
  19305. }
  19306. }
  19307. } );
  19308. //
  19309. Object.defineProperties( THREE.Material.prototype, {
  19310. wrapAround: {
  19311. get: function () {
  19312. console.warn( 'THREE.' + this.type + ': .wrapAround has been removed.' );
  19313. },
  19314. set: function ( value ) {
  19315. console.warn( 'THREE.' + this.type + ': .wrapAround has been removed.' );
  19316. }
  19317. },
  19318. wrapRGB: {
  19319. get: function () {
  19320. console.warn( 'THREE.' + this.type + ': .wrapRGB has been removed.' );
  19321. return new THREE.Color();
  19322. }
  19323. }
  19324. } );
  19325. Object.defineProperties( THREE, {
  19326. PointCloudMaterial: {
  19327. value: function ( parameters ) {
  19328. console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
  19329. return new THREE.PointsMaterial( parameters );
  19330. }
  19331. },
  19332. ParticleBasicMaterial: {
  19333. value: function ( parameters ) {
  19334. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
  19335. return new THREE.PointsMaterial( parameters );
  19336. }
  19337. },
  19338. ParticleSystemMaterial:{
  19339. value: function ( parameters ) {
  19340. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
  19341. return new THREE.PointsMaterial( parameters );
  19342. }
  19343. }
  19344. } );
  19345. Object.defineProperties( THREE.MeshPhongMaterial.prototype, {
  19346. metal: {
  19347. get: function () {
  19348. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' );
  19349. return false;
  19350. },
  19351. set: function ( value ) {
  19352. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' );
  19353. }
  19354. }
  19355. } );
  19356. Object.defineProperties( THREE.ShaderMaterial.prototype, {
  19357. derivatives: {
  19358. get: function () {
  19359. console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  19360. return this.extensions.derivatives;
  19361. },
  19362. set: function ( value ) {
  19363. console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  19364. this.extensions.derivatives = value;
  19365. }
  19366. }
  19367. } );
  19368. //
  19369. Object.defineProperties( THREE.WebGLRenderer.prototype, {
  19370. supportsFloatTextures: {
  19371. value: function () {
  19372. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  19373. return this.extensions.get( 'OES_texture_float' );
  19374. }
  19375. },
  19376. supportsHalfFloatTextures: {
  19377. value: function () {
  19378. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  19379. return this.extensions.get( 'OES_texture_half_float' );
  19380. }
  19381. },
  19382. supportsStandardDerivatives: {
  19383. value: function () {
  19384. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  19385. return this.extensions.get( 'OES_standard_derivatives' );
  19386. }
  19387. },
  19388. supportsCompressedTextureS3TC: {
  19389. value: function () {
  19390. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  19391. return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  19392. }
  19393. },
  19394. supportsCompressedTexturePVRTC: {
  19395. value: function () {
  19396. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  19397. return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  19398. }
  19399. },
  19400. supportsBlendMinMax: {
  19401. value: function () {
  19402. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  19403. return this.extensions.get( 'EXT_blend_minmax' );
  19404. }
  19405. },
  19406. supportsVertexTextures: {
  19407. value: function () {
  19408. return this.capabilities.vertexTextures;
  19409. }
  19410. },
  19411. supportsInstancedArrays: {
  19412. value: function () {
  19413. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  19414. return this.extensions.get( 'ANGLE_instanced_arrays' );
  19415. }
  19416. },
  19417. initMaterial: {
  19418. value: function () {
  19419. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  19420. }
  19421. },
  19422. addPrePlugin: {
  19423. value: function () {
  19424. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  19425. }
  19426. },
  19427. addPostPlugin: {
  19428. value: function () {
  19429. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  19430. }
  19431. },
  19432. updateShadowMap: {
  19433. value: function () {
  19434. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  19435. }
  19436. },
  19437. shadowMapEnabled: {
  19438. get: function () {
  19439. return this.shadowMap.enabled;
  19440. },
  19441. set: function ( value ) {
  19442. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  19443. this.shadowMap.enabled = value;
  19444. }
  19445. },
  19446. shadowMapType: {
  19447. get: function () {
  19448. return this.shadowMap.type;
  19449. },
  19450. set: function ( value ) {
  19451. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  19452. this.shadowMap.type = value;
  19453. }
  19454. },
  19455. shadowMapCullFace: {
  19456. get: function () {
  19457. return this.shadowMap.cullFace;
  19458. },
  19459. set: function ( value ) {
  19460. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace is now .shadowMap.cullFace.' );
  19461. this.shadowMap.cullFace = value;
  19462. }
  19463. },
  19464. shadowMapDebug: {
  19465. get: function () {
  19466. return this.shadowMap.debug;
  19467. },
  19468. set: function ( value ) {
  19469. console.warn( 'THREE.WebGLRenderer: .shadowMapDebug is now .shadowMap.debug.' );
  19470. this.shadowMap.debug = value;
  19471. }
  19472. }
  19473. } );
  19474. //
  19475. Object.defineProperties( THREE.WebGLRenderTarget.prototype, {
  19476. wrapS: {
  19477. get: function () {
  19478. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  19479. return this.texture.wrapS;
  19480. },
  19481. set: function ( value ) {
  19482. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  19483. this.texture.wrapS = value;
  19484. }
  19485. },
  19486. wrapT: {
  19487. get: function () {
  19488. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  19489. return this.texture.wrapT;
  19490. },
  19491. set: function ( value ) {
  19492. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  19493. this.texture.wrapT = value;
  19494. }
  19495. },
  19496. magFilter: {
  19497. get: function () {
  19498. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  19499. return this.texture.magFilter;
  19500. },
  19501. set: function ( value ) {
  19502. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  19503. this.texture.magFilter = value;
  19504. }
  19505. },
  19506. minFilter: {
  19507. get: function () {
  19508. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  19509. return this.texture.minFilter;
  19510. },
  19511. set: function ( value ) {
  19512. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  19513. this.texture.minFilter = value;
  19514. }
  19515. },
  19516. anisotropy: {
  19517. get: function () {
  19518. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  19519. return this.texture.anisotropy;
  19520. },
  19521. set: function ( value ) {
  19522. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  19523. this.texture.anisotropy = value;
  19524. }
  19525. },
  19526. offset: {
  19527. get: function () {
  19528. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  19529. return this.texture.offset;
  19530. },
  19531. set: function ( value ) {
  19532. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  19533. this.texture.offset = value;
  19534. }
  19535. },
  19536. repeat: {
  19537. get: function () {
  19538. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  19539. return this.texture.repeat;
  19540. },
  19541. set: function ( value ) {
  19542. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  19543. this.texture.repeat = value;
  19544. }
  19545. },
  19546. format: {
  19547. get: function () {
  19548. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  19549. return this.texture.format;
  19550. },
  19551. set: function ( value ) {
  19552. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  19553. this.texture.format = value;
  19554. }
  19555. },
  19556. type: {
  19557. get: function () {
  19558. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  19559. return this.texture.type;
  19560. },
  19561. set: function ( value ) {
  19562. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  19563. this.texture.type = value;
  19564. }
  19565. },
  19566. generateMipmaps: {
  19567. get: function () {
  19568. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  19569. return this.texture.generateMipmaps;
  19570. },
  19571. set: function ( value ) {
  19572. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  19573. this.texture.generateMipmaps = value;
  19574. }
  19575. }
  19576. } );
  19577. //
  19578. THREE.GeometryUtils = {
  19579. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  19580. console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  19581. var matrix;
  19582. if ( geometry2 instanceof THREE.Mesh ) {
  19583. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  19584. matrix = geometry2.matrix;
  19585. geometry2 = geometry2.geometry;
  19586. }
  19587. geometry1.merge( geometry2, matrix, materialIndexOffset );
  19588. },
  19589. center: function ( geometry ) {
  19590. console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
  19591. return geometry.center();
  19592. }
  19593. };
  19594. THREE.ImageUtils = {
  19595. crossOrigin: undefined,
  19596. loadTexture: function ( url, mapping, onLoad, onError ) {
  19597. console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
  19598. var loader = new THREE.TextureLoader();
  19599. loader.setCrossOrigin( this.crossOrigin );
  19600. var texture = loader.load( url, onLoad, undefined, onError );
  19601. if ( mapping ) texture.mapping = mapping;
  19602. return texture;
  19603. },
  19604. loadTextureCube: function ( urls, mapping, onLoad, onError ) {
  19605. console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
  19606. var loader = new THREE.CubeTextureLoader();
  19607. loader.setCrossOrigin( this.crossOrigin );
  19608. var texture = loader.load( urls, onLoad, undefined, onError );
  19609. if ( mapping ) texture.mapping = mapping;
  19610. return texture;
  19611. },
  19612. loadCompressedTexture: function () {
  19613. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' )
  19614. },
  19615. loadCompressedTextureCube: function () {
  19616. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' )
  19617. }
  19618. };
  19619. //
  19620. THREE.Projector = function () {
  19621. console.error( 'THREE.Projector has been moved to /examples/js/renderers/Projector.js.' );
  19622. this.projectVector = function ( vector, camera ) {
  19623. console.warn( 'THREE.Projector: .projectVector() is now vector.project().' );
  19624. vector.project( camera );
  19625. };
  19626. this.unprojectVector = function ( vector, camera ) {
  19627. console.warn( 'THREE.Projector: .unprojectVector() is now vector.unproject().' );
  19628. vector.unproject( camera );
  19629. };
  19630. this.pickingRay = function ( vector, camera ) {
  19631. console.error( 'THREE.Projector: .pickingRay() is now raycaster.setFromCamera().' );
  19632. };
  19633. };
  19634. //
  19635. THREE.CanvasRenderer = function () {
  19636. console.error( 'THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js' );
  19637. this.domElement = document.createElement( 'canvas' );
  19638. this.clear = function () {};
  19639. this.render = function () {};
  19640. this.setClearColor = function () {};
  19641. this.setSize = function () {};
  19642. };
  19643. //
  19644. THREE.TextGeometry = function () {
  19645. console.error( 'THREE.TextGeometry has been moved to /examples/js/geometries/TextGeometry.js' );
  19646. console.error( 'THREE.FontUtils has been moved to /examples/js/utils/FontUtils.js' );
  19647. };
  19648. //
  19649. THREE.MeshFaceMaterial = THREE.MultiMaterial;
  19650. // File:src/extras/CurveUtils.js
  19651. /**
  19652. * @author zz85 / http://www.lab4games.net/zz85/blog
  19653. */
  19654. THREE.CurveUtils = {
  19655. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  19656. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  19657. },
  19658. // Puay Bing, thanks for helping with this derivative!
  19659. tangentCubicBezier: function ( t, p0, p1, p2, p3 ) {
  19660. return - 3 * p0 * ( 1 - t ) * ( 1 - t ) +
  19661. 3 * p1 * ( 1 - t ) * ( 1 - t ) - 6 * t * p1 * ( 1 - t ) +
  19662. 6 * t * p2 * ( 1 - t ) - 3 * t * t * p2 +
  19663. 3 * t * t * p3;
  19664. },
  19665. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  19666. // To check if my formulas are correct
  19667. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  19668. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  19669. var h01 = - 6 * t * t + 6 * t; // − 2t3 + 3t2
  19670. var h11 = 3 * t * t - 2 * t; // t3 − t2
  19671. return h00 + h10 + h01 + h11;
  19672. },
  19673. // Catmull-Rom
  19674. interpolate: function( p0, p1, p2, p3, t ) {
  19675. var v0 = ( p2 - p0 ) * 0.5;
  19676. var v1 = ( p3 - p1 ) * 0.5;
  19677. var t2 = t * t;
  19678. var t3 = t * t2;
  19679. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  19680. }
  19681. };
  19682. // File:src/extras/SceneUtils.js
  19683. /**
  19684. * @author alteredq / http://alteredqualia.com/
  19685. */
  19686. THREE.SceneUtils = {
  19687. createMultiMaterialObject: function ( geometry, materials ) {
  19688. var group = new THREE.Group();
  19689. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  19690. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  19691. }
  19692. return group;
  19693. },
  19694. detach: function ( child, parent, scene ) {
  19695. child.applyMatrix( parent.matrixWorld );
  19696. parent.remove( child );
  19697. scene.add( child );
  19698. },
  19699. attach: function ( child, scene, parent ) {
  19700. var matrixWorldInverse = new THREE.Matrix4();
  19701. matrixWorldInverse.getInverse( parent.matrixWorld );
  19702. child.applyMatrix( matrixWorldInverse );
  19703. scene.remove( child );
  19704. parent.add( child );
  19705. }
  19706. };
  19707. // File:src/extras/ShapeUtils.js
  19708. /**
  19709. * @author zz85 / http://www.lab4games.net/zz85/blog
  19710. */
  19711. THREE.ShapeUtils = {
  19712. // calculate area of the contour polygon
  19713. area: function ( contour ) {
  19714. var n = contour.length;
  19715. var a = 0.0;
  19716. for ( var p = n - 1, q = 0; q < n; p = q ++ ) {
  19717. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  19718. }
  19719. return a * 0.5;
  19720. },
  19721. triangulate: ( function () {
  19722. /**
  19723. * This code is a quick port of code written in C++ which was submitted to
  19724. * flipcode.com by John W. Ratcliff // July 22, 2000
  19725. * See original code and more information here:
  19726. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  19727. *
  19728. * ported to actionscript by Zevan Rosser
  19729. * www.actionsnippet.com
  19730. *
  19731. * ported to javascript by Joshua Koo
  19732. * http://www.lab4games.net/zz85/blog
  19733. *
  19734. */
  19735. function snip( contour, u, v, w, n, verts ) {
  19736. var p;
  19737. var ax, ay, bx, by;
  19738. var cx, cy, px, py;
  19739. ax = contour[ verts[ u ] ].x;
  19740. ay = contour[ verts[ u ] ].y;
  19741. bx = contour[ verts[ v ] ].x;
  19742. by = contour[ verts[ v ] ].y;
  19743. cx = contour[ verts[ w ] ].x;
  19744. cy = contour[ verts[ w ] ].y;
  19745. if ( Number.EPSILON > ( ( ( bx - ax ) * ( cy - ay ) ) - ( ( by - ay ) * ( cx - ax ) ) ) ) return false;
  19746. var aX, aY, bX, bY, cX, cY;
  19747. var apx, apy, bpx, bpy, cpx, cpy;
  19748. var cCROSSap, bCROSScp, aCROSSbp;
  19749. aX = cx - bx; aY = cy - by;
  19750. bX = ax - cx; bY = ay - cy;
  19751. cX = bx - ax; cY = by - ay;
  19752. for ( p = 0; p < n; p ++ ) {
  19753. px = contour[ verts[ p ] ].x;
  19754. py = contour[ verts[ p ] ].y;
  19755. if ( ( ( px === ax ) && ( py === ay ) ) ||
  19756. ( ( px === bx ) && ( py === by ) ) ||
  19757. ( ( px === cx ) && ( py === cy ) ) ) continue;
  19758. apx = px - ax; apy = py - ay;
  19759. bpx = px - bx; bpy = py - by;
  19760. cpx = px - cx; cpy = py - cy;
  19761. // see if p is inside triangle abc
  19762. aCROSSbp = aX * bpy - aY * bpx;
  19763. cCROSSap = cX * apy - cY * apx;
  19764. bCROSScp = bX * cpy - bY * cpx;
  19765. if ( ( aCROSSbp >= - Number.EPSILON ) && ( bCROSScp >= - Number.EPSILON ) && ( cCROSSap >= - Number.EPSILON ) ) return false;
  19766. }
  19767. return true;
  19768. }
  19769. // takes in an contour array and returns
  19770. return function ( contour, indices ) {
  19771. var n = contour.length;
  19772. if ( n < 3 ) return null;
  19773. var result = [],
  19774. verts = [],
  19775. vertIndices = [];
  19776. /* we want a counter-clockwise polygon in verts */
  19777. var u, v, w;
  19778. if ( THREE.ShapeUtils.area( contour ) > 0.0 ) {
  19779. for ( v = 0; v < n; v ++ ) verts[ v ] = v;
  19780. } else {
  19781. for ( v = 0; v < n; v ++ ) verts[ v ] = ( n - 1 ) - v;
  19782. }
  19783. var nv = n;
  19784. /* remove nv - 2 vertices, creating 1 triangle every time */
  19785. var count = 2 * nv; /* error detection */
  19786. for ( v = nv - 1; nv > 2; ) {
  19787. /* if we loop, it is probably a non-simple polygon */
  19788. if ( ( count -- ) <= 0 ) {
  19789. //** Triangulate: ERROR - probable bad polygon!
  19790. //throw ( "Warning, unable to triangulate polygon!" );
  19791. //return null;
  19792. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  19793. console.warn( 'THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()' );
  19794. if ( indices ) return vertIndices;
  19795. return result;
  19796. }
  19797. /* three consecutive vertices in current polygon, <u,v,w> */
  19798. u = v; if ( nv <= u ) u = 0; /* previous */
  19799. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  19800. w = v + 1; if ( nv <= w ) w = 0; /* next */
  19801. if ( snip( contour, u, v, w, nv, verts ) ) {
  19802. var a, b, c, s, t;
  19803. /* true names of the vertices */
  19804. a = verts[ u ];
  19805. b = verts[ v ];
  19806. c = verts[ w ];
  19807. /* output Triangle */
  19808. result.push( [ contour[ a ],
  19809. contour[ b ],
  19810. contour[ c ] ] );
  19811. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  19812. /* remove v from the remaining polygon */
  19813. for ( s = v, t = v + 1; t < nv; s ++, t ++ ) {
  19814. verts[ s ] = verts[ t ];
  19815. }
  19816. nv --;
  19817. /* reset error detection counter */
  19818. count = 2 * nv;
  19819. }
  19820. }
  19821. if ( indices ) return vertIndices;
  19822. return result;
  19823. }
  19824. } )(),
  19825. triangulateShape: function ( contour, holes ) {
  19826. function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) {
  19827. // inOtherPt needs to be collinear to the inSegment
  19828. if ( inSegPt1.x !== inSegPt2.x ) {
  19829. if ( inSegPt1.x < inSegPt2.x ) {
  19830. return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) );
  19831. } else {
  19832. return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) );
  19833. }
  19834. } else {
  19835. if ( inSegPt1.y < inSegPt2.y ) {
  19836. return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) );
  19837. } else {
  19838. return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) );
  19839. }
  19840. }
  19841. }
  19842. function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) {
  19843. var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y;
  19844. var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y;
  19845. var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x;
  19846. var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y;
  19847. var limit = seg1dy * seg2dx - seg1dx * seg2dy;
  19848. var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy;
  19849. if ( Math.abs( limit ) > Number.EPSILON ) {
  19850. // not parallel
  19851. var perpSeg2;
  19852. if ( limit > 0 ) {
  19853. if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return [];
  19854. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  19855. if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return [];
  19856. } else {
  19857. if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return [];
  19858. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  19859. if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return [];
  19860. }
  19861. // i.e. to reduce rounding errors
  19862. // intersection at endpoint of segment#1?
  19863. if ( perpSeg2 === 0 ) {
  19864. if ( ( inExcludeAdjacentSegs ) &&
  19865. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  19866. return [ inSeg1Pt1 ];
  19867. }
  19868. if ( perpSeg2 === limit ) {
  19869. if ( ( inExcludeAdjacentSegs ) &&
  19870. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  19871. return [ inSeg1Pt2 ];
  19872. }
  19873. // intersection at endpoint of segment#2?
  19874. if ( perpSeg1 === 0 ) return [ inSeg2Pt1 ];
  19875. if ( perpSeg1 === limit ) return [ inSeg2Pt2 ];
  19876. // return real intersection point
  19877. var factorSeg1 = perpSeg2 / limit;
  19878. return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx,
  19879. y: inSeg1Pt1.y + factorSeg1 * seg1dy } ];
  19880. } else {
  19881. // parallel or collinear
  19882. if ( ( perpSeg1 !== 0 ) ||
  19883. ( seg2dy * seg1seg2dx !== seg2dx * seg1seg2dy ) ) return [];
  19884. // they are collinear or degenerate
  19885. var seg1Pt = ( ( seg1dx === 0 ) && ( seg1dy === 0 ) ); // segment1 is just a point?
  19886. var seg2Pt = ( ( seg2dx === 0 ) && ( seg2dy === 0 ) ); // segment2 is just a point?
  19887. // both segments are points
  19888. if ( seg1Pt && seg2Pt ) {
  19889. if ( ( inSeg1Pt1.x !== inSeg2Pt1.x ) ||
  19890. ( inSeg1Pt1.y !== inSeg2Pt1.y ) ) return []; // they are distinct points
  19891. return [ inSeg1Pt1 ]; // they are the same point
  19892. }
  19893. // segment#1 is a single point
  19894. if ( seg1Pt ) {
  19895. if ( ! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2
  19896. return [ inSeg1Pt1 ];
  19897. }
  19898. // segment#2 is a single point
  19899. if ( seg2Pt ) {
  19900. if ( ! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1
  19901. return [ inSeg2Pt1 ];
  19902. }
  19903. // they are collinear segments, which might overlap
  19904. var seg1min, seg1max, seg1minVal, seg1maxVal;
  19905. var seg2min, seg2max, seg2minVal, seg2maxVal;
  19906. if ( seg1dx !== 0 ) {
  19907. // the segments are NOT on a vertical line
  19908. if ( inSeg1Pt1.x < inSeg1Pt2.x ) {
  19909. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x;
  19910. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x;
  19911. } else {
  19912. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x;
  19913. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x;
  19914. }
  19915. if ( inSeg2Pt1.x < inSeg2Pt2.x ) {
  19916. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x;
  19917. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x;
  19918. } else {
  19919. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x;
  19920. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x;
  19921. }
  19922. } else {
  19923. // the segments are on a vertical line
  19924. if ( inSeg1Pt1.y < inSeg1Pt2.y ) {
  19925. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y;
  19926. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y;
  19927. } else {
  19928. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y;
  19929. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y;
  19930. }
  19931. if ( inSeg2Pt1.y < inSeg2Pt2.y ) {
  19932. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y;
  19933. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y;
  19934. } else {
  19935. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y;
  19936. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y;
  19937. }
  19938. }
  19939. if ( seg1minVal <= seg2minVal ) {
  19940. if ( seg1maxVal < seg2minVal ) return [];
  19941. if ( seg1maxVal === seg2minVal ) {
  19942. if ( inExcludeAdjacentSegs ) return [];
  19943. return [ seg2min ];
  19944. }
  19945. if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ];
  19946. return [ seg2min, seg2max ];
  19947. } else {
  19948. if ( seg1minVal > seg2maxVal ) return [];
  19949. if ( seg1minVal === seg2maxVal ) {
  19950. if ( inExcludeAdjacentSegs ) return [];
  19951. return [ seg1min ];
  19952. }
  19953. if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ];
  19954. return [ seg1min, seg2max ];
  19955. }
  19956. }
  19957. }
  19958. function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) {
  19959. // The order of legs is important
  19960. // translation of all points, so that Vertex is at (0,0)
  19961. var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y;
  19962. var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y;
  19963. var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y;
  19964. // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg.
  19965. var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX;
  19966. var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX;
  19967. if ( Math.abs( from2toAngle ) > Number.EPSILON ) {
  19968. // angle != 180 deg.
  19969. var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX;
  19970. // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle );
  19971. if ( from2toAngle > 0 ) {
  19972. // main angle < 180 deg.
  19973. return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) );
  19974. } else {
  19975. // main angle > 180 deg.
  19976. return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) );
  19977. }
  19978. } else {
  19979. // angle == 180 deg.
  19980. // console.log( "from2to: 180 deg., from2other: " + from2otherAngle );
  19981. return ( from2otherAngle > 0 );
  19982. }
  19983. }
  19984. function removeHoles( contour, holes ) {
  19985. var shape = contour.concat(); // work on this shape
  19986. var hole;
  19987. function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) {
  19988. // Check if hole point lies within angle around shape point
  19989. var lastShapeIdx = shape.length - 1;
  19990. var prevShapeIdx = inShapeIdx - 1;
  19991. if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx;
  19992. var nextShapeIdx = inShapeIdx + 1;
  19993. if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0;
  19994. var insideAngle = isPointInsideAngle( shape[ inShapeIdx ], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[ inHoleIdx ] );
  19995. if ( ! insideAngle ) {
  19996. // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y );
  19997. return false;
  19998. }
  19999. // Check if shape point lies within angle around hole point
  20000. var lastHoleIdx = hole.length - 1;
  20001. var prevHoleIdx = inHoleIdx - 1;
  20002. if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx;
  20003. var nextHoleIdx = inHoleIdx + 1;
  20004. if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0;
  20005. insideAngle = isPointInsideAngle( hole[ inHoleIdx ], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[ inShapeIdx ] );
  20006. if ( ! insideAngle ) {
  20007. // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y );
  20008. return false;
  20009. }
  20010. return true;
  20011. }
  20012. function intersectsShapeEdge( inShapePt, inHolePt ) {
  20013. // checks for intersections with shape edges
  20014. var sIdx, nextIdx, intersection;
  20015. for ( sIdx = 0; sIdx < shape.length; sIdx ++ ) {
  20016. nextIdx = sIdx + 1; nextIdx %= shape.length;
  20017. intersection = intersect_segments_2D( inShapePt, inHolePt, shape[ sIdx ], shape[ nextIdx ], true );
  20018. if ( intersection.length > 0 ) return true;
  20019. }
  20020. return false;
  20021. }
  20022. var indepHoles = [];
  20023. function intersectsHoleEdge( inShapePt, inHolePt ) {
  20024. // checks for intersections with hole edges
  20025. var ihIdx, chkHole,
  20026. hIdx, nextIdx, intersection;
  20027. for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx ++ ) {
  20028. chkHole = holes[ indepHoles[ ihIdx ]];
  20029. for ( hIdx = 0; hIdx < chkHole.length; hIdx ++ ) {
  20030. nextIdx = hIdx + 1; nextIdx %= chkHole.length;
  20031. intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[ hIdx ], chkHole[ nextIdx ], true );
  20032. if ( intersection.length > 0 ) return true;
  20033. }
  20034. }
  20035. return false;
  20036. }
  20037. var holeIndex, shapeIndex,
  20038. shapePt, holePt,
  20039. holeIdx, cutKey, failedCuts = [],
  20040. tmpShape1, tmpShape2,
  20041. tmpHole1, tmpHole2;
  20042. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  20043. indepHoles.push( h );
  20044. }
  20045. var minShapeIndex = 0;
  20046. var counter = indepHoles.length * 2;
  20047. while ( indepHoles.length > 0 ) {
  20048. counter --;
  20049. if ( counter < 0 ) {
  20050. console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" );
  20051. break;
  20052. }
  20053. // search for shape-vertex and hole-vertex,
  20054. // which can be connected without intersections
  20055. for ( shapeIndex = minShapeIndex; shapeIndex < shape.length; shapeIndex ++ ) {
  20056. shapePt = shape[ shapeIndex ];
  20057. holeIndex = - 1;
  20058. // search for hole which can be reached without intersections
  20059. for ( var h = 0; h < indepHoles.length; h ++ ) {
  20060. holeIdx = indepHoles[ h ];
  20061. // prevent multiple checks
  20062. cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx;
  20063. if ( failedCuts[ cutKey ] !== undefined ) continue;
  20064. hole = holes[ holeIdx ];
  20065. for ( var h2 = 0; h2 < hole.length; h2 ++ ) {
  20066. holePt = hole[ h2 ];
  20067. if ( ! isCutLineInsideAngles( shapeIndex, h2 ) ) continue;
  20068. if ( intersectsShapeEdge( shapePt, holePt ) ) continue;
  20069. if ( intersectsHoleEdge( shapePt, holePt ) ) continue;
  20070. holeIndex = h2;
  20071. indepHoles.splice( h, 1 );
  20072. tmpShape1 = shape.slice( 0, shapeIndex + 1 );
  20073. tmpShape2 = shape.slice( shapeIndex );
  20074. tmpHole1 = hole.slice( holeIndex );
  20075. tmpHole2 = hole.slice( 0, holeIndex + 1 );
  20076. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  20077. minShapeIndex = shapeIndex;
  20078. // Debug only, to show the selected cuts
  20079. // glob_CutLines.push( [ shapePt, holePt ] );
  20080. break;
  20081. }
  20082. if ( holeIndex >= 0 ) break; // hole-vertex found
  20083. failedCuts[ cutKey ] = true; // remember failure
  20084. }
  20085. if ( holeIndex >= 0 ) break; // hole-vertex found
  20086. }
  20087. }
  20088. return shape; /* shape with no holes */
  20089. }
  20090. var i, il, f, face,
  20091. key, index,
  20092. allPointsMap = {};
  20093. // 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.
  20094. var allpoints = contour.concat();
  20095. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  20096. Array.prototype.push.apply( allpoints, holes[ h ] );
  20097. }
  20098. //console.log( "allpoints",allpoints, allpoints.length );
  20099. // prepare all points map
  20100. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  20101. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  20102. if ( allPointsMap[ key ] !== undefined ) {
  20103. console.warn( "THREE.Shape: Duplicate point", key );
  20104. }
  20105. allPointsMap[ key ] = i;
  20106. }
  20107. // remove holes by cutting paths to holes and adding them to the shape
  20108. var shapeWithoutHoles = removeHoles( contour, holes );
  20109. var triangles = THREE.ShapeUtils.triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape
  20110. //console.log( "triangles",triangles, triangles.length );
  20111. // check all face vertices against all points map
  20112. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  20113. face = triangles[ i ];
  20114. for ( f = 0; f < 3; f ++ ) {
  20115. key = face[ f ].x + ":" + face[ f ].y;
  20116. index = allPointsMap[ key ];
  20117. if ( index !== undefined ) {
  20118. face[ f ] = index;
  20119. }
  20120. }
  20121. }
  20122. return triangles.concat();
  20123. },
  20124. isClockWise: function ( pts ) {
  20125. return THREE.ShapeUtils.area( pts ) < 0;
  20126. },
  20127. // Bezier Curves formulas obtained from
  20128. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  20129. // Quad Bezier Functions
  20130. b2: ( function () {
  20131. function b2p0( t, p ) {
  20132. var k = 1 - t;
  20133. return k * k * p;
  20134. }
  20135. function b2p1( t, p ) {
  20136. return 2 * ( 1 - t ) * t * p;
  20137. }
  20138. function b2p2( t, p ) {
  20139. return t * t * p;
  20140. }
  20141. return function ( t, p0, p1, p2 ) {
  20142. return b2p0( t, p0 ) + b2p1( t, p1 ) + b2p2( t, p2 );
  20143. };
  20144. } )(),
  20145. // Cubic Bezier Functions
  20146. b3: ( function () {
  20147. function b3p0( t, p ) {
  20148. var k = 1 - t;
  20149. return k * k * k * p;
  20150. }
  20151. function b3p1( t, p ) {
  20152. var k = 1 - t;
  20153. return 3 * k * k * t * p;
  20154. }
  20155. function b3p2( t, p ) {
  20156. var k = 1 - t;
  20157. return 3 * k * t * t * p;
  20158. }
  20159. function b3p3( t, p ) {
  20160. return t * t * t * p;
  20161. }
  20162. return function ( t, p0, p1, p2, p3 ) {
  20163. return b3p0( t, p0 ) + b3p1( t, p1 ) + b3p2( t, p2 ) + b3p3( t, p3 );
  20164. };
  20165. } )()
  20166. };
  20167. // File:src/extras/core/Curve.js
  20168. /**
  20169. * @author zz85 / http://www.lab4games.net/zz85/blog
  20170. * Extensible curve object
  20171. *
  20172. * Some common of Curve methods
  20173. * .getPoint(t), getTangent(t)
  20174. * .getPointAt(u), getTagentAt(u)
  20175. * .getPoints(), .getSpacedPoints()
  20176. * .getLength()
  20177. * .updateArcLengths()
  20178. *
  20179. * This following classes subclasses THREE.Curve:
  20180. *
  20181. * -- 2d classes --
  20182. * THREE.LineCurve
  20183. * THREE.QuadraticBezierCurve
  20184. * THREE.CubicBezierCurve
  20185. * THREE.SplineCurve
  20186. * THREE.ArcCurve
  20187. * THREE.EllipseCurve
  20188. *
  20189. * -- 3d classes --
  20190. * THREE.LineCurve3
  20191. * THREE.QuadraticBezierCurve3
  20192. * THREE.CubicBezierCurve3
  20193. * THREE.SplineCurve3
  20194. * THREE.ClosedSplineCurve3
  20195. *
  20196. * A series of curves can be represented as a THREE.CurvePath
  20197. *
  20198. **/
  20199. /**************************************************************
  20200. * Abstract Curve base class
  20201. **************************************************************/
  20202. THREE.Curve = function () {
  20203. };
  20204. THREE.Curve.prototype = {
  20205. constructor: THREE.Curve,
  20206. // Virtual base class method to overwrite and implement in subclasses
  20207. // - t [0 .. 1]
  20208. getPoint: function ( t ) {
  20209. console.warn( "THREE.Curve: Warning, getPoint() not implemented!" );
  20210. return null;
  20211. },
  20212. // Get point at relative position in curve according to arc length
  20213. // - u [0 .. 1]
  20214. getPointAt: function ( u ) {
  20215. var t = this.getUtoTmapping( u );
  20216. return this.getPoint( t );
  20217. },
  20218. // Get sequence of points using getPoint( t )
  20219. getPoints: function ( divisions ) {
  20220. if ( ! divisions ) divisions = 5;
  20221. var d, pts = [];
  20222. for ( d = 0; d <= divisions; d ++ ) {
  20223. pts.push( this.getPoint( d / divisions ) );
  20224. }
  20225. return pts;
  20226. },
  20227. // Get sequence of points using getPointAt( u )
  20228. getSpacedPoints: function ( divisions ) {
  20229. if ( ! divisions ) divisions = 5;
  20230. var d, pts = [];
  20231. for ( d = 0; d <= divisions; d ++ ) {
  20232. pts.push( this.getPointAt( d / divisions ) );
  20233. }
  20234. return pts;
  20235. },
  20236. // Get total curve arc length
  20237. getLength: function () {
  20238. var lengths = this.getLengths();
  20239. return lengths[ lengths.length - 1 ];
  20240. },
  20241. // Get list of cumulative segment lengths
  20242. getLengths: function ( divisions ) {
  20243. if ( ! divisions ) divisions = ( this.__arcLengthDivisions ) ? ( this.__arcLengthDivisions ) : 200;
  20244. if ( this.cacheArcLengths
  20245. && ( this.cacheArcLengths.length === divisions + 1 )
  20246. && ! this.needsUpdate ) {
  20247. //console.log( "cached", this.cacheArcLengths );
  20248. return this.cacheArcLengths;
  20249. }
  20250. this.needsUpdate = false;
  20251. var cache = [];
  20252. var current, last = this.getPoint( 0 );
  20253. var p, sum = 0;
  20254. cache.push( 0 );
  20255. for ( p = 1; p <= divisions; p ++ ) {
  20256. current = this.getPoint ( p / divisions );
  20257. sum += current.distanceTo( last );
  20258. cache.push( sum );
  20259. last = current;
  20260. }
  20261. this.cacheArcLengths = cache;
  20262. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  20263. },
  20264. updateArcLengths: function() {
  20265. this.needsUpdate = true;
  20266. this.getLengths();
  20267. },
  20268. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  20269. getUtoTmapping: function ( u, distance ) {
  20270. var arcLengths = this.getLengths();
  20271. var i = 0, il = arcLengths.length;
  20272. var targetArcLength; // The targeted u distance value to get
  20273. if ( distance ) {
  20274. targetArcLength = distance;
  20275. } else {
  20276. targetArcLength = u * arcLengths[ il - 1 ];
  20277. }
  20278. //var time = Date.now();
  20279. // binary search for the index with largest value smaller than target u distance
  20280. var low = 0, high = il - 1, comparison;
  20281. while ( low <= high ) {
  20282. 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
  20283. comparison = arcLengths[ i ] - targetArcLength;
  20284. if ( comparison < 0 ) {
  20285. low = i + 1;
  20286. } else if ( comparison > 0 ) {
  20287. high = i - 1;
  20288. } else {
  20289. high = i;
  20290. break;
  20291. // DONE
  20292. }
  20293. }
  20294. i = high;
  20295. //console.log('b' , i, low, high, Date.now()- time);
  20296. if ( arcLengths[ i ] === targetArcLength ) {
  20297. var t = i / ( il - 1 );
  20298. return t;
  20299. }
  20300. // we could get finer grain at lengths, or use simple interpolation between two points
  20301. var lengthBefore = arcLengths[ i ];
  20302. var lengthAfter = arcLengths[ i + 1 ];
  20303. var segmentLength = lengthAfter - lengthBefore;
  20304. // determine where we are between the 'before' and 'after' points
  20305. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  20306. // add that fractional amount to t
  20307. var t = ( i + segmentFraction ) / ( il - 1 );
  20308. return t;
  20309. },
  20310. // Returns a unit vector tangent at t
  20311. // In case any sub curve does not implement its tangent derivation,
  20312. // 2 points a small delta apart will be used to find its gradient
  20313. // which seems to give a reasonable approximation
  20314. getTangent: function( t ) {
  20315. var delta = 0.0001;
  20316. var t1 = t - delta;
  20317. var t2 = t + delta;
  20318. // Capping in case of danger
  20319. if ( t1 < 0 ) t1 = 0;
  20320. if ( t2 > 1 ) t2 = 1;
  20321. var pt1 = this.getPoint( t1 );
  20322. var pt2 = this.getPoint( t2 );
  20323. var vec = pt2.clone().sub( pt1 );
  20324. return vec.normalize();
  20325. },
  20326. getTangentAt: function ( u ) {
  20327. var t = this.getUtoTmapping( u );
  20328. return this.getTangent( t );
  20329. }
  20330. }
  20331. THREE.Curve.Utils = THREE.CurveUtils; // backwards compatibility
  20332. // TODO: Transformation for Curves?
  20333. /**************************************************************
  20334. * 3D Curves
  20335. **************************************************************/
  20336. // A Factory method for creating new curve subclasses
  20337. THREE.Curve.create = function ( constructor, getPointFunc ) {
  20338. constructor.prototype = Object.create( THREE.Curve.prototype );
  20339. constructor.prototype.constructor = constructor;
  20340. constructor.prototype.getPoint = getPointFunc;
  20341. return constructor;
  20342. };
  20343. // File:src/extras/core/CurvePath.js
  20344. /**
  20345. * @author zz85 / http://www.lab4games.net/zz85/blog
  20346. *
  20347. **/
  20348. /**************************************************************
  20349. * Curved Path - a curve path is simply a array of connected
  20350. * curves, but retains the api of a curve
  20351. **************************************************************/
  20352. THREE.CurvePath = function () {
  20353. this.curves = [];
  20354. this.autoClose = false; // Automatically closes the path
  20355. };
  20356. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  20357. THREE.CurvePath.prototype.constructor = THREE.CurvePath;
  20358. THREE.CurvePath.prototype.add = function ( curve ) {
  20359. this.curves.push( curve );
  20360. };
  20361. /*
  20362. THREE.CurvePath.prototype.checkConnection = function() {
  20363. // TODO
  20364. // If the ending of curve is not connected to the starting
  20365. // or the next curve, then, this is not a real path
  20366. };
  20367. */
  20368. THREE.CurvePath.prototype.closePath = function() {
  20369. // TODO Test
  20370. // and verify for vector3 (needs to implement equals)
  20371. // Add a line curve if start and end of lines are not connected
  20372. var startPoint = this.curves[ 0 ].getPoint( 0 );
  20373. var endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  20374. if ( ! startPoint.equals( endPoint ) ) {
  20375. this.curves.push( new THREE.LineCurve( endPoint, startPoint ) );
  20376. }
  20377. };
  20378. // To get accurate point with reference to
  20379. // entire path distance at time t,
  20380. // following has to be done:
  20381. // 1. Length of each sub path have to be known
  20382. // 2. Locate and identify type of curve
  20383. // 3. Get t for the curve
  20384. // 4. Return curve.getPointAt(t')
  20385. THREE.CurvePath.prototype.getPoint = function( t ) {
  20386. var d = t * this.getLength();
  20387. var curveLengths = this.getCurveLengths();
  20388. var i = 0;
  20389. // To think about boundaries points.
  20390. while ( i < curveLengths.length ) {
  20391. if ( curveLengths[ i ] >= d ) {
  20392. var diff = curveLengths[ i ] - d;
  20393. var curve = this.curves[ i ];
  20394. var u = 1 - diff / curve.getLength();
  20395. return curve.getPointAt( u );
  20396. }
  20397. i ++;
  20398. }
  20399. return null;
  20400. // loop where sum != 0, sum > d , sum+1 <d
  20401. };
  20402. /*
  20403. THREE.CurvePath.prototype.getTangent = function( t ) {
  20404. };
  20405. */
  20406. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  20407. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  20408. // getPoint() depends on getLength
  20409. THREE.CurvePath.prototype.getLength = function() {
  20410. var lens = this.getCurveLengths();
  20411. return lens[ lens.length - 1 ];
  20412. };
  20413. // Compute lengths and cache them
  20414. // We cannot overwrite getLengths() because UtoT mapping uses it.
  20415. THREE.CurvePath.prototype.getCurveLengths = function() {
  20416. // We use cache values if curves and cache array are same length
  20417. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  20418. return this.cacheLengths;
  20419. }
  20420. // Get length of sub-curve
  20421. // Push sums into cached array
  20422. var lengths = [], sums = 0;
  20423. for ( var i = 0, l = this.curves.length; i < l; i ++ ) {
  20424. sums += this.curves[ i ].getLength();
  20425. lengths.push( sums );
  20426. }
  20427. this.cacheLengths = lengths;
  20428. return lengths;
  20429. };
  20430. /**************************************************************
  20431. * Create Geometries Helpers
  20432. **************************************************************/
  20433. /// Generate geometry from path points (for Line or Points objects)
  20434. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  20435. var pts = this.getPoints( divisions );
  20436. return this.createGeometry( pts );
  20437. };
  20438. // Generate geometry from equidistant sampling along the path
  20439. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  20440. var pts = this.getSpacedPoints( divisions );
  20441. return this.createGeometry( pts );
  20442. };
  20443. THREE.CurvePath.prototype.createGeometry = function( points ) {
  20444. var geometry = new THREE.Geometry();
  20445. for ( var i = 0, l = points.length; i < l; i ++ ) {
  20446. var point = points[ i ];
  20447. geometry.vertices.push( new THREE.Vector3( point.x, point.y, point.z || 0 ) );
  20448. }
  20449. return geometry;
  20450. };
  20451. // File:src/extras/core/Path.js
  20452. /**
  20453. * @author zz85 / http://www.lab4games.net/zz85/blog
  20454. * Creates free form 2d path using series of points, lines or curves.
  20455. *
  20456. **/
  20457. THREE.Path = function ( points ) {
  20458. THREE.CurvePath.call( this );
  20459. this.actions = [];
  20460. if ( points ) {
  20461. this.fromPoints( points );
  20462. }
  20463. };
  20464. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  20465. THREE.Path.prototype.constructor = THREE.Path;
  20466. // TODO Clean up PATH API
  20467. // Create path using straight lines to connect all points
  20468. // - vectors: array of Vector2
  20469. THREE.Path.prototype.fromPoints = function ( vectors ) {
  20470. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  20471. for ( var i = 1, l = vectors.length; i < l; i ++ ) {
  20472. this.lineTo( vectors[ i ].x, vectors[ i ].y );
  20473. }
  20474. };
  20475. // startPath() endPath()?
  20476. THREE.Path.prototype.moveTo = function ( x, y ) {
  20477. this.actions.push( { action: 'moveTo', args: [ x, y ] } );
  20478. };
  20479. THREE.Path.prototype.lineTo = function ( x, y ) {
  20480. var lastargs = this.actions[ this.actions.length - 1 ].args;
  20481. var x0 = lastargs[ lastargs.length - 2 ];
  20482. var y0 = lastargs[ lastargs.length - 1 ];
  20483. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  20484. this.curves.push( curve );
  20485. this.actions.push( { action: 'lineTo', args: [ x, y ] } );
  20486. };
  20487. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  20488. var lastargs = this.actions[ this.actions.length - 1 ].args;
  20489. var x0 = lastargs[ lastargs.length - 2 ];
  20490. var y0 = lastargs[ lastargs.length - 1 ];
  20491. var curve = new THREE.QuadraticBezierCurve(
  20492. new THREE.Vector2( x0, y0 ),
  20493. new THREE.Vector2( aCPx, aCPy ),
  20494. new THREE.Vector2( aX, aY )
  20495. );
  20496. this.curves.push( curve );
  20497. this.actions.push( { action: 'quadraticCurveTo', args: [ aCPx, aCPy, aX, aY ] } );
  20498. };
  20499. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  20500. var lastargs = this.actions[ this.actions.length - 1 ].args;
  20501. var x0 = lastargs[ lastargs.length - 2 ];
  20502. var y0 = lastargs[ lastargs.length - 1 ];
  20503. var curve = new THREE.CubicBezierCurve(
  20504. new THREE.Vector2( x0, y0 ),
  20505. new THREE.Vector2( aCP1x, aCP1y ),
  20506. new THREE.Vector2( aCP2x, aCP2y ),
  20507. new THREE.Vector2( aX, aY )
  20508. );
  20509. this.curves.push( curve );
  20510. this.actions.push( { action: 'bezierCurveTo', args: [ aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ] } );
  20511. };
  20512. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  20513. var args = Array.prototype.slice.call( arguments );
  20514. var lastargs = this.actions[ this.actions.length - 1 ].args;
  20515. var x0 = lastargs[ lastargs.length - 2 ];
  20516. var y0 = lastargs[ lastargs.length - 1 ];
  20517. var npts = [ new THREE.Vector2( x0, y0 ) ];
  20518. Array.prototype.push.apply( npts, pts );
  20519. var curve = new THREE.SplineCurve( npts );
  20520. this.curves.push( curve );
  20521. this.actions.push( { action: 'splineThru', args: args } );
  20522. };
  20523. // FUTURE: Change the API or follow canvas API?
  20524. THREE.Path.prototype.arc = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  20525. var lastargs = this.actions[ this.actions.length - 1 ].args;
  20526. var x0 = lastargs[ lastargs.length - 2 ];
  20527. var y0 = lastargs[ lastargs.length - 1 ];
  20528. this.absarc( aX + x0, aY + y0, aRadius,
  20529. aStartAngle, aEndAngle, aClockwise );
  20530. };
  20531. THREE.Path.prototype.absarc = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  20532. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  20533. };
  20534. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  20535. var lastargs = this.actions[ this.actions.length - 1 ].args;
  20536. var x0 = lastargs[ lastargs.length - 2 ];
  20537. var y0 = lastargs[ lastargs.length - 1 ];
  20538. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  20539. };
  20540. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  20541. var args = [
  20542. aX, aY,
  20543. xRadius, yRadius,
  20544. aStartAngle, aEndAngle,
  20545. aClockwise,
  20546. aRotation || 0 // aRotation is optional.
  20547. ];
  20548. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  20549. this.curves.push( curve );
  20550. var lastPoint = curve.getPoint( 1 );
  20551. args.push( lastPoint.x );
  20552. args.push( lastPoint.y );
  20553. this.actions.push( { action: 'ellipse', args: args } );
  20554. };
  20555. THREE.Path.prototype.getSpacedPoints = function ( divisions ) {
  20556. if ( ! divisions ) divisions = 40;
  20557. var points = [];
  20558. for ( var i = 0; i < divisions; i ++ ) {
  20559. points.push( this.getPoint( i / divisions ) );
  20560. //if ( !this.getPoint( i / divisions ) ) throw "DIE";
  20561. }
  20562. if ( this.autoClose ) {
  20563. points.push( points[ 0 ] );
  20564. }
  20565. return points;
  20566. };
  20567. /* Return an array of vectors based on contour of the path */
  20568. THREE.Path.prototype.getPoints = function( divisions ) {
  20569. divisions = divisions || 12;
  20570. var b2 = THREE.ShapeUtils.b2;
  20571. var b3 = THREE.ShapeUtils.b3;
  20572. var points = [];
  20573. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  20574. laste, tx, ty;
  20575. for ( var i = 0, l = this.actions.length; i < l; i ++ ) {
  20576. var item = this.actions[ i ];
  20577. var action = item.action;
  20578. var args = item.args;
  20579. switch ( action ) {
  20580. case 'moveTo':
  20581. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  20582. break;
  20583. case 'lineTo':
  20584. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  20585. break;
  20586. case 'quadraticCurveTo':
  20587. cpx = args[ 2 ];
  20588. cpy = args[ 3 ];
  20589. cpx1 = args[ 0 ];
  20590. cpy1 = args[ 1 ];
  20591. if ( points.length > 0 ) {
  20592. laste = points[ points.length - 1 ];
  20593. cpx0 = laste.x;
  20594. cpy0 = laste.y;
  20595. } else {
  20596. laste = this.actions[ i - 1 ].args;
  20597. cpx0 = laste[ laste.length - 2 ];
  20598. cpy0 = laste[ laste.length - 1 ];
  20599. }
  20600. for ( var j = 1; j <= divisions; j ++ ) {
  20601. var t = j / divisions;
  20602. tx = b2( t, cpx0, cpx1, cpx );
  20603. ty = b2( t, cpy0, cpy1, cpy );
  20604. points.push( new THREE.Vector2( tx, ty ) );
  20605. }
  20606. break;
  20607. case 'bezierCurveTo':
  20608. cpx = args[ 4 ];
  20609. cpy = args[ 5 ];
  20610. cpx1 = args[ 0 ];
  20611. cpy1 = args[ 1 ];
  20612. cpx2 = args[ 2 ];
  20613. cpy2 = args[ 3 ];
  20614. if ( points.length > 0 ) {
  20615. laste = points[ points.length - 1 ];
  20616. cpx0 = laste.x;
  20617. cpy0 = laste.y;
  20618. } else {
  20619. laste = this.actions[ i - 1 ].args;
  20620. cpx0 = laste[ laste.length - 2 ];
  20621. cpy0 = laste[ laste.length - 1 ];
  20622. }
  20623. for ( var j = 1; j <= divisions; j ++ ) {
  20624. var t = j / divisions;
  20625. tx = b3( t, cpx0, cpx1, cpx2, cpx );
  20626. ty = b3( t, cpy0, cpy1, cpy2, cpy );
  20627. points.push( new THREE.Vector2( tx, ty ) );
  20628. }
  20629. break;
  20630. case 'splineThru':
  20631. laste = this.actions[ i - 1 ].args;
  20632. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  20633. var spts = [ last ];
  20634. var n = divisions * args[ 0 ].length;
  20635. spts = spts.concat( args[ 0 ] );
  20636. var spline = new THREE.SplineCurve( spts );
  20637. for ( var j = 1; j <= n; j ++ ) {
  20638. points.push( spline.getPointAt( j / n ) );
  20639. }
  20640. break;
  20641. case 'arc':
  20642. var aX = args[ 0 ], aY = args[ 1 ],
  20643. aRadius = args[ 2 ],
  20644. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  20645. aClockwise = !! args[ 5 ];
  20646. var deltaAngle = aEndAngle - aStartAngle;
  20647. var angle;
  20648. var tdivisions = divisions * 2;
  20649. for ( var j = 1; j <= tdivisions; j ++ ) {
  20650. var t = j / tdivisions;
  20651. if ( ! aClockwise ) {
  20652. t = 1 - t;
  20653. }
  20654. angle = aStartAngle + t * deltaAngle;
  20655. tx = aX + aRadius * Math.cos( angle );
  20656. ty = aY + aRadius * Math.sin( angle );
  20657. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  20658. points.push( new THREE.Vector2( tx, ty ) );
  20659. }
  20660. //console.log(points);
  20661. break;
  20662. case 'ellipse':
  20663. var aX = args[ 0 ], aY = args[ 1 ],
  20664. xRadius = args[ 2 ],
  20665. yRadius = args[ 3 ],
  20666. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  20667. aClockwise = !! args[ 6 ],
  20668. aRotation = args[ 7 ];
  20669. var deltaAngle = aEndAngle - aStartAngle;
  20670. var angle;
  20671. var tdivisions = divisions * 2;
  20672. var cos, sin;
  20673. if ( aRotation !== 0 ) {
  20674. cos = Math.cos( aRotation );
  20675. sin = Math.sin( aRotation );
  20676. }
  20677. for ( var j = 1; j <= tdivisions; j ++ ) {
  20678. var t = j / tdivisions;
  20679. if ( ! aClockwise ) {
  20680. t = 1 - t;
  20681. }
  20682. angle = aStartAngle + t * deltaAngle;
  20683. tx = aX + xRadius * Math.cos( angle );
  20684. ty = aY + yRadius * Math.sin( angle );
  20685. if ( aRotation !== 0 ) {
  20686. var x = tx, y = ty;
  20687. // Rotate the point about the center of the ellipse.
  20688. tx = ( x - aX ) * cos - ( y - aY ) * sin + aX;
  20689. ty = ( x - aX ) * sin + ( y - aY ) * cos + aY;
  20690. }
  20691. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  20692. points.push( new THREE.Vector2( tx, ty ) );
  20693. }
  20694. //console.log(points);
  20695. break;
  20696. } // end switch
  20697. }
  20698. // Normalize to remove the closing point by default.
  20699. var lastPoint = points[ points.length - 1 ];
  20700. if ( Math.abs( lastPoint.x - points[ 0 ].x ) < Number.EPSILON &&
  20701. Math.abs( lastPoint.y - points[ 0 ].y ) < Number.EPSILON )
  20702. points.splice( points.length - 1, 1 );
  20703. if ( this.autoClose ) {
  20704. points.push( points[ 0 ] );
  20705. }
  20706. return points;
  20707. };
  20708. //
  20709. // Breaks path into shapes
  20710. //
  20711. // Assumptions (if parameter isCCW==true the opposite holds):
  20712. // - solid shapes are defined clockwise (CW)
  20713. // - holes are defined counterclockwise (CCW)
  20714. //
  20715. // If parameter noHoles==true:
  20716. // - all subPaths are regarded as solid shapes
  20717. // - definition order CW/CCW has no relevance
  20718. //
  20719. THREE.Path.prototype.toShapes = function( isCCW, noHoles ) {
  20720. function extractSubpaths( inActions ) {
  20721. var subPaths = [], lastPath = new THREE.Path();
  20722. for ( var i = 0, l = inActions.length; i < l; i ++ ) {
  20723. var item = inActions[ i ];
  20724. var args = item.args;
  20725. var action = item.action;
  20726. if ( action === 'moveTo' ) {
  20727. if ( lastPath.actions.length !== 0 ) {
  20728. subPaths.push( lastPath );
  20729. lastPath = new THREE.Path();
  20730. }
  20731. }
  20732. lastPath[ action ].apply( lastPath, args );
  20733. }
  20734. if ( lastPath.actions.length !== 0 ) {
  20735. subPaths.push( lastPath );
  20736. }
  20737. // console.log(subPaths);
  20738. return subPaths;
  20739. }
  20740. function toShapesNoHoles( inSubpaths ) {
  20741. var shapes = [];
  20742. for ( var i = 0, l = inSubpaths.length; i < l; i ++ ) {
  20743. var tmpPath = inSubpaths[ i ];
  20744. var tmpShape = new THREE.Shape();
  20745. tmpShape.actions = tmpPath.actions;
  20746. tmpShape.curves = tmpPath.curves;
  20747. shapes.push( tmpShape );
  20748. }
  20749. //console.log("shape", shapes);
  20750. return shapes;
  20751. }
  20752. function isPointInsidePolygon( inPt, inPolygon ) {
  20753. var polyLen = inPolygon.length;
  20754. // inPt on polygon contour => immediate success or
  20755. // toggling of inside/outside at every single! intersection point of an edge
  20756. // with the horizontal line through inPt, left of inPt
  20757. // not counting lowerY endpoints of edges and whole edges on that line
  20758. var inside = false;
  20759. for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  20760. var edgeLowPt = inPolygon[ p ];
  20761. var edgeHighPt = inPolygon[ q ];
  20762. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  20763. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  20764. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  20765. // not parallel
  20766. if ( edgeDy < 0 ) {
  20767. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  20768. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  20769. }
  20770. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  20771. if ( inPt.y === edgeLowPt.y ) {
  20772. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  20773. // continue; // no intersection or edgeLowPt => doesn't count !!!
  20774. } else {
  20775. var perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  20776. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  20777. if ( perpEdge < 0 ) continue;
  20778. inside = ! inside; // true intersection left of inPt
  20779. }
  20780. } else {
  20781. // parallel or collinear
  20782. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  20783. // edge lies on the same horizontal line as inPt
  20784. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  20785. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  20786. // continue;
  20787. }
  20788. }
  20789. return inside;
  20790. }
  20791. var isClockWise = THREE.ShapeUtils.isClockWise;
  20792. var subPaths = extractSubpaths( this.actions );
  20793. if ( subPaths.length === 0 ) return [];
  20794. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  20795. var solid, tmpPath, tmpShape, shapes = [];
  20796. if ( subPaths.length === 1 ) {
  20797. tmpPath = subPaths[ 0 ];
  20798. tmpShape = new THREE.Shape();
  20799. tmpShape.actions = tmpPath.actions;
  20800. tmpShape.curves = tmpPath.curves;
  20801. shapes.push( tmpShape );
  20802. return shapes;
  20803. }
  20804. var holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  20805. holesFirst = isCCW ? ! holesFirst : holesFirst;
  20806. // console.log("Holes first", holesFirst);
  20807. var betterShapeHoles = [];
  20808. var newShapes = [];
  20809. var newShapeHoles = [];
  20810. var mainIdx = 0;
  20811. var tmpPoints;
  20812. newShapes[ mainIdx ] = undefined;
  20813. newShapeHoles[ mainIdx ] = [];
  20814. for ( var i = 0, l = subPaths.length; i < l; i ++ ) {
  20815. tmpPath = subPaths[ i ];
  20816. tmpPoints = tmpPath.getPoints();
  20817. solid = isClockWise( tmpPoints );
  20818. solid = isCCW ? ! solid : solid;
  20819. if ( solid ) {
  20820. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  20821. newShapes[ mainIdx ] = { s: new THREE.Shape(), p: tmpPoints };
  20822. newShapes[ mainIdx ].s.actions = tmpPath.actions;
  20823. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  20824. if ( holesFirst ) mainIdx ++;
  20825. newShapeHoles[ mainIdx ] = [];
  20826. //console.log('cw', i);
  20827. } else {
  20828. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  20829. //console.log('ccw', i);
  20830. }
  20831. }
  20832. // only Holes? -> probably all Shapes with wrong orientation
  20833. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  20834. if ( newShapes.length > 1 ) {
  20835. var ambiguous = false;
  20836. var toChange = [];
  20837. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  20838. betterShapeHoles[ sIdx ] = [];
  20839. }
  20840. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  20841. var sho = newShapeHoles[ sIdx ];
  20842. for ( var hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  20843. var ho = sho[ hIdx ];
  20844. var hole_unassigned = true;
  20845. for ( var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  20846. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  20847. if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  20848. if ( hole_unassigned ) {
  20849. hole_unassigned = false;
  20850. betterShapeHoles[ s2Idx ].push( ho );
  20851. } else {
  20852. ambiguous = true;
  20853. }
  20854. }
  20855. }
  20856. if ( hole_unassigned ) {
  20857. betterShapeHoles[ sIdx ].push( ho );
  20858. }
  20859. }
  20860. }
  20861. // console.log("ambiguous: ", ambiguous);
  20862. if ( toChange.length > 0 ) {
  20863. // console.log("to change: ", toChange);
  20864. if ( ! ambiguous ) newShapeHoles = betterShapeHoles;
  20865. }
  20866. }
  20867. var tmpHoles;
  20868. for ( var i = 0, il = newShapes.length; i < il; i ++ ) {
  20869. tmpShape = newShapes[ i ].s;
  20870. shapes.push( tmpShape );
  20871. tmpHoles = newShapeHoles[ i ];
  20872. for ( var j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  20873. tmpShape.holes.push( tmpHoles[ j ].h );
  20874. }
  20875. }
  20876. //console.log("shape", shapes);
  20877. return shapes;
  20878. };
  20879. // File:src/extras/core/Shape.js
  20880. /**
  20881. * @author zz85 / http://www.lab4games.net/zz85/blog
  20882. * Defines a 2d shape plane using paths.
  20883. **/
  20884. // STEP 1 Create a path.
  20885. // STEP 2 Turn path into shape.
  20886. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  20887. // STEP 3a - Extract points from each shape, turn to vertices
  20888. // STEP 3b - Triangulate each shape, add faces.
  20889. THREE.Shape = function () {
  20890. THREE.Path.apply( this, arguments );
  20891. this.holes = [];
  20892. };
  20893. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  20894. THREE.Shape.prototype.constructor = THREE.Shape;
  20895. // Convenience method to return ExtrudeGeometry
  20896. THREE.Shape.prototype.extrude = function ( options ) {
  20897. return new THREE.ExtrudeGeometry( this, options );
  20898. };
  20899. // Convenience method to return ShapeGeometry
  20900. THREE.Shape.prototype.makeGeometry = function ( options ) {
  20901. return new THREE.ShapeGeometry( this, options );
  20902. };
  20903. // Get points of holes
  20904. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  20905. var holesPts = [];
  20906. for ( var i = 0, l = this.holes.length; i < l; i ++ ) {
  20907. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  20908. }
  20909. return holesPts;
  20910. };
  20911. // Get points of shape and holes (keypoints based on segments parameter)
  20912. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  20913. return {
  20914. shape: this.getPoints( divisions ),
  20915. holes: this.getPointsHoles( divisions )
  20916. };
  20917. };
  20918. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  20919. return this.extractAllPoints( divisions );
  20920. };
  20921. THREE.Shape.Utils = THREE.ShapeUtils; // backwards compatibility
  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. },
  21214. function ( t ) {
  21215. var points = this.points,
  21216. point, intPoint, weight, l;
  21217. l = points.length;
  21218. if ( l < 2 ) console.log( 'duh, you need at least 2 points' );
  21219. point = ( l - 1 ) * t;
  21220. intPoint = Math.floor( point );
  21221. weight = point - intPoint;
  21222. if ( weight === 0 && intPoint === l - 1 ) {
  21223. intPoint = l - 2;
  21224. weight = 1;
  21225. }
  21226. var p0, p1, p2, p3;
  21227. if ( intPoint === 0 ) {
  21228. // extrapolate first point
  21229. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  21230. p0 = tmp;
  21231. } else {
  21232. p0 = points[ intPoint - 1 ];
  21233. }
  21234. p1 = points[ intPoint ];
  21235. p2 = points[ intPoint + 1 ];
  21236. if ( intPoint + 2 < l ) {
  21237. p3 = points[ intPoint + 2 ]
  21238. } else {
  21239. // extrapolate last point
  21240. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 2 ] );
  21241. p3 = tmp;
  21242. }
  21243. if ( this.type === undefined || this.type === 'centripetal' || this.type === 'chordal' ) {
  21244. // init Centripetal / Chordal Catmull-Rom
  21245. var pow = this.type === 'chordal' ? 0.5 : 0.25;
  21246. var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  21247. var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  21248. var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  21249. // safety check for repeated points
  21250. if ( dt1 < 1e-4 ) dt1 = 1.0;
  21251. if ( dt0 < 1e-4 ) dt0 = dt1;
  21252. if ( dt2 < 1e-4 ) dt2 = dt1;
  21253. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  21254. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  21255. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  21256. } else if ( this.type === 'catmullrom' ) {
  21257. var tension = this.tension !== undefined ? this.tension : 0.5;
  21258. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, tension );
  21259. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, tension );
  21260. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, tension );
  21261. }
  21262. var v = new THREE.Vector3(
  21263. px.calc( weight ),
  21264. py.calc( weight ),
  21265. pz.calc( weight )
  21266. );
  21267. return v;
  21268. }
  21269. );
  21270. } )();
  21271. // File:src/extras/curves/ClosedSplineCurve3.js
  21272. /**************************************************************
  21273. * Closed Spline 3D curve
  21274. **************************************************************/
  21275. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  21276. function ( points /* array of Vector3 */ ) {
  21277. this.points = ( points == undefined ) ? [] : points;
  21278. },
  21279. function ( t ) {
  21280. var points = this.points;
  21281. var point = ( points.length - 0 ) * t; // This needs to be from 0-length +1
  21282. var intPoint = Math.floor( point );
  21283. var weight = point - intPoint;
  21284. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  21285. var point0 = points[ ( intPoint - 1 ) % points.length ];
  21286. var point1 = points[ ( intPoint ) % points.length ];
  21287. var point2 = points[ ( intPoint + 1 ) % points.length ];
  21288. var point3 = points[ ( intPoint + 2 ) % points.length ];
  21289. var interpolate = THREE.CurveUtils.interpolate;
  21290. return new THREE.Vector3(
  21291. interpolate( point0.x, point1.x, point2.x, point3.x, weight ),
  21292. interpolate( point0.y, point1.y, point2.y, point3.y, weight ),
  21293. interpolate( point0.z, point1.z, point2.z, point3.z, weight )
  21294. );
  21295. }
  21296. );
  21297. // File:src/extras/geometries/BoxGeometry.js
  21298. /**
  21299. * @author mrdoob / http://mrdoob.com/
  21300. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  21301. */
  21302. THREE.BoxGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  21303. THREE.Geometry.call( this );
  21304. this.type = 'BoxGeometry';
  21305. this.parameters = {
  21306. width: width,
  21307. height: height,
  21308. depth: depth,
  21309. widthSegments: widthSegments,
  21310. heightSegments: heightSegments,
  21311. depthSegments: depthSegments
  21312. };
  21313. this.widthSegments = widthSegments || 1;
  21314. this.heightSegments = heightSegments || 1;
  21315. this.depthSegments = depthSegments || 1;
  21316. var scope = this;
  21317. var width_half = width / 2;
  21318. var height_half = height / 2;
  21319. var depth_half = depth / 2;
  21320. buildPlane( 'z', 'y', - 1, - 1, depth, height, width_half, 0 ); // px
  21321. buildPlane( 'z', 'y', 1, - 1, depth, height, - width_half, 1 ); // nx
  21322. buildPlane( 'x', 'z', 1, 1, width, depth, height_half, 2 ); // py
  21323. buildPlane( 'x', 'z', 1, - 1, width, depth, - height_half, 3 ); // ny
  21324. buildPlane( 'x', 'y', 1, - 1, width, height, depth_half, 4 ); // pz
  21325. buildPlane( 'x', 'y', - 1, - 1, width, height, - depth_half, 5 ); // nz
  21326. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  21327. var w, ix, iy,
  21328. gridX = scope.widthSegments,
  21329. gridY = scope.heightSegments,
  21330. width_half = width / 2,
  21331. height_half = height / 2,
  21332. offset = scope.vertices.length;
  21333. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  21334. w = 'z';
  21335. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  21336. w = 'y';
  21337. gridY = scope.depthSegments;
  21338. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  21339. w = 'x';
  21340. gridX = scope.depthSegments;
  21341. }
  21342. var gridX1 = gridX + 1,
  21343. gridY1 = gridY + 1,
  21344. segment_width = width / gridX,
  21345. segment_height = height / gridY,
  21346. normal = new THREE.Vector3();
  21347. normal[ w ] = depth > 0 ? 1 : - 1;
  21348. for ( iy = 0; iy < gridY1; iy ++ ) {
  21349. for ( ix = 0; ix < gridX1; ix ++ ) {
  21350. var vector = new THREE.Vector3();
  21351. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  21352. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  21353. vector[ w ] = depth;
  21354. scope.vertices.push( vector );
  21355. }
  21356. }
  21357. for ( iy = 0; iy < gridY; iy ++ ) {
  21358. for ( ix = 0; ix < gridX; ix ++ ) {
  21359. var a = ix + gridX1 * iy;
  21360. var b = ix + gridX1 * ( iy + 1 );
  21361. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  21362. var d = ( ix + 1 ) + gridX1 * iy;
  21363. var uva = new THREE.Vector2( ix / gridX, 1 - iy / gridY );
  21364. var uvb = new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY );
  21365. var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iy + 1 ) / gridY );
  21366. var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY );
  21367. var face = new THREE.Face3( a + offset, b + offset, d + offset );
  21368. face.normal.copy( normal );
  21369. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  21370. face.materialIndex = materialIndex;
  21371. scope.faces.push( face );
  21372. scope.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  21373. face = new THREE.Face3( b + offset, c + offset, d + offset );
  21374. face.normal.copy( normal );
  21375. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  21376. face.materialIndex = materialIndex;
  21377. scope.faces.push( face );
  21378. scope.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  21379. }
  21380. }
  21381. }
  21382. this.mergeVertices();
  21383. };
  21384. THREE.BoxGeometry.prototype = Object.create( THREE.Geometry.prototype );
  21385. THREE.BoxGeometry.prototype.constructor = THREE.BoxGeometry;
  21386. THREE.CubeGeometry = THREE.BoxGeometry; // backwards compatibility
  21387. // File:src/extras/geometries/CircleGeometry.js
  21388. /**
  21389. * @author hughes
  21390. */
  21391. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  21392. THREE.Geometry.call( this );
  21393. this.type = 'CircleGeometry';
  21394. this.parameters = {
  21395. radius: radius,
  21396. segments: segments,
  21397. thetaStart: thetaStart,
  21398. thetaLength: thetaLength
  21399. };
  21400. this.fromBufferGeometry( new THREE.CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) );
  21401. };
  21402. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  21403. THREE.CircleGeometry.prototype.constructor = THREE.CircleGeometry;
  21404. // File:src/extras/geometries/CircleBufferGeometry.js
  21405. /**
  21406. * @author benaadams / https://twitter.com/ben_a_adams
  21407. */
  21408. THREE.CircleBufferGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  21409. THREE.BufferGeometry.call( this );
  21410. this.type = 'CircleBufferGeometry';
  21411. this.parameters = {
  21412. radius: radius,
  21413. segments: segments,
  21414. thetaStart: thetaStart,
  21415. thetaLength: thetaLength
  21416. };
  21417. radius = radius || 50;
  21418. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  21419. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  21420. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  21421. var vertices = segments + 2;
  21422. var positions = new Float32Array( vertices * 3 );
  21423. var normals = new Float32Array( vertices * 3 );
  21424. var uvs = new Float32Array( vertices * 2 );
  21425. // center data is already zero, but need to set a few extras
  21426. normals[ 2 ] = 1.0;
  21427. uvs[ 0 ] = 0.5;
  21428. uvs[ 1 ] = 0.5;
  21429. for ( var s = 0, i = 3, ii = 2 ; s <= segments; s ++, i += 3, ii += 2 ) {
  21430. var segment = thetaStart + s / segments * thetaLength;
  21431. positions[ i ] = radius * Math.cos( segment );
  21432. positions[ i + 1 ] = radius * Math.sin( segment );
  21433. normals[ i + 2 ] = 1; // normal z
  21434. uvs[ ii ] = ( positions[ i ] / radius + 1 ) / 2;
  21435. uvs[ ii + 1 ] = ( positions[ i + 1 ] / radius + 1 ) / 2;
  21436. }
  21437. var indices = [];
  21438. for ( var i = 1; i <= segments; i ++ ) {
  21439. indices.push( i, i + 1, 0 );
  21440. }
  21441. this.setIndex( new THREE.BufferAttribute( new Uint16Array( indices ), 1 ) );
  21442. this.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
  21443. this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
  21444. this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) );
  21445. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  21446. };
  21447. THREE.CircleBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  21448. THREE.CircleBufferGeometry.prototype.constructor = THREE.CircleBufferGeometry;
  21449. // File:src/extras/geometries/CylinderGeometry.js
  21450. /**
  21451. * @author mrdoob / http://mrdoob.com/
  21452. */
  21453. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  21454. THREE.Geometry.call( this );
  21455. this.type = 'CylinderGeometry';
  21456. this.parameters = {
  21457. radiusTop: radiusTop,
  21458. radiusBottom: radiusBottom,
  21459. height: height,
  21460. radialSegments: radialSegments,
  21461. heightSegments: heightSegments,
  21462. openEnded: openEnded,
  21463. thetaStart: thetaStart,
  21464. thetaLength: thetaLength
  21465. };
  21466. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  21467. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  21468. height = height !== undefined ? height : 100;
  21469. radialSegments = radialSegments || 8;
  21470. heightSegments = heightSegments || 1;
  21471. openEnded = openEnded !== undefined ? openEnded : false;
  21472. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  21473. thetaLength = thetaLength !== undefined ? thetaLength : 2 * Math.PI;
  21474. var heightHalf = height / 2;
  21475. var x, y, vertices = [], uvs = [];
  21476. for ( y = 0; y <= heightSegments; y ++ ) {
  21477. var verticesRow = [];
  21478. var uvsRow = [];
  21479. var v = y / heightSegments;
  21480. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  21481. for ( x = 0; x <= radialSegments; x ++ ) {
  21482. var u = x / radialSegments;
  21483. var vertex = new THREE.Vector3();
  21484. vertex.x = radius * Math.sin( u * thetaLength + thetaStart );
  21485. vertex.y = - v * height + heightHalf;
  21486. vertex.z = radius * Math.cos( u * thetaLength + thetaStart );
  21487. this.vertices.push( vertex );
  21488. verticesRow.push( this.vertices.length - 1 );
  21489. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  21490. }
  21491. vertices.push( verticesRow );
  21492. uvs.push( uvsRow );
  21493. }
  21494. var tanTheta = ( radiusBottom - radiusTop ) / height;
  21495. var na, nb;
  21496. for ( x = 0; x < radialSegments; x ++ ) {
  21497. if ( radiusTop !== 0 ) {
  21498. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  21499. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  21500. } else {
  21501. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  21502. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  21503. }
  21504. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  21505. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  21506. for ( y = 0; y < heightSegments; y ++ ) {
  21507. var v1 = vertices[ y ][ x ];
  21508. var v2 = vertices[ y + 1 ][ x ];
  21509. var v3 = vertices[ y + 1 ][ x + 1 ];
  21510. var v4 = vertices[ y ][ x + 1 ];
  21511. var n1 = na.clone();
  21512. var n2 = na.clone();
  21513. var n3 = nb.clone();
  21514. var n4 = nb.clone();
  21515. var uv1 = uvs[ y ][ x ].clone();
  21516. var uv2 = uvs[ y + 1 ][ x ].clone();
  21517. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  21518. var uv4 = uvs[ y ][ x + 1 ].clone();
  21519. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  21520. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  21521. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  21522. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  21523. }
  21524. }
  21525. // top cap
  21526. if ( openEnded === false && radiusTop > 0 ) {
  21527. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  21528. for ( x = 0; x < radialSegments; x ++ ) {
  21529. var v1 = vertices[ 0 ][ x ];
  21530. var v2 = vertices[ 0 ][ x + 1 ];
  21531. var v3 = this.vertices.length - 1;
  21532. var n1 = new THREE.Vector3( 0, 1, 0 );
  21533. var n2 = new THREE.Vector3( 0, 1, 0 );
  21534. var n3 = new THREE.Vector3( 0, 1, 0 );
  21535. var uv1 = uvs[ 0 ][ x ].clone();
  21536. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  21537. var uv3 = new THREE.Vector2( uv2.x, 0 );
  21538. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ], undefined, 1 ) );
  21539. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  21540. }
  21541. }
  21542. // bottom cap
  21543. if ( openEnded === false && radiusBottom > 0 ) {
  21544. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  21545. for ( x = 0; x < radialSegments; x ++ ) {
  21546. var v1 = vertices[ heightSegments ][ x + 1 ];
  21547. var v2 = vertices[ heightSegments ][ x ];
  21548. var v3 = this.vertices.length - 1;
  21549. var n1 = new THREE.Vector3( 0, - 1, 0 );
  21550. var n2 = new THREE.Vector3( 0, - 1, 0 );
  21551. var n3 = new THREE.Vector3( 0, - 1, 0 );
  21552. var uv1 = uvs[ heightSegments ][ x + 1 ].clone();
  21553. var uv2 = uvs[ heightSegments ][ x ].clone();
  21554. var uv3 = new THREE.Vector2( uv2.x, 1 );
  21555. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ], undefined, 2 ) );
  21556. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  21557. }
  21558. }
  21559. this.computeFaceNormals();
  21560. };
  21561. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  21562. THREE.CylinderGeometry.prototype.constructor = THREE.CylinderGeometry;
  21563. // File:src/extras/geometries/EdgesGeometry.js
  21564. /**
  21565. * @author WestLangley / http://github.com/WestLangley
  21566. */
  21567. THREE.EdgesGeometry = function ( geometry, thresholdAngle ) {
  21568. THREE.BufferGeometry.call( this );
  21569. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  21570. var thresholdDot = Math.cos( THREE.Math.degToRad( thresholdAngle ) );
  21571. var edge = [ 0, 0 ], hash = {};
  21572. function sortFunction( a, b ) {
  21573. return a - b;
  21574. }
  21575. var keys = [ 'a', 'b', 'c' ];
  21576. var geometry2;
  21577. if ( geometry instanceof THREE.BufferGeometry ) {
  21578. geometry2 = new THREE.Geometry();
  21579. geometry2.fromBufferGeometry( geometry );
  21580. } else {
  21581. geometry2 = geometry.clone();
  21582. }
  21583. geometry2.mergeVertices();
  21584. geometry2.computeFaceNormals();
  21585. var vertices = geometry2.vertices;
  21586. var faces = geometry2.faces;
  21587. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21588. var face = faces[ i ];
  21589. for ( var j = 0; j < 3; j ++ ) {
  21590. edge[ 0 ] = face[ keys[ j ] ];
  21591. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  21592. edge.sort( sortFunction );
  21593. var key = edge.toString();
  21594. if ( hash[ key ] === undefined ) {
  21595. hash[ key ] = { vert1: edge[ 0 ], vert2: edge[ 1 ], face1: i, face2: undefined };
  21596. } else {
  21597. hash[ key ].face2 = i;
  21598. }
  21599. }
  21600. }
  21601. var coords = [];
  21602. for ( var key in hash ) {
  21603. var h = hash[ key ];
  21604. if ( h.face2 === undefined || faces[ h.face1 ].normal.dot( faces[ h.face2 ].normal ) <= thresholdDot ) {
  21605. var vertex = vertices[ h.vert1 ];
  21606. coords.push( vertex.x );
  21607. coords.push( vertex.y );
  21608. coords.push( vertex.z );
  21609. vertex = vertices[ h.vert2 ];
  21610. coords.push( vertex.x );
  21611. coords.push( vertex.y );
  21612. coords.push( vertex.z );
  21613. }
  21614. }
  21615. this.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( coords ), 3 ) );
  21616. };
  21617. THREE.EdgesGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  21618. THREE.EdgesGeometry.prototype.constructor = THREE.EdgesGeometry;
  21619. // File:src/extras/geometries/ExtrudeGeometry.js
  21620. /**
  21621. * @author zz85 / http://www.lab4games.net/zz85/blog
  21622. *
  21623. * Creates extruded geometry from a path shape.
  21624. *
  21625. * parameters = {
  21626. *
  21627. * curveSegments: <int>, // number of points on the curves
  21628. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  21629. * amount: <int>, // Depth to extrude the shape
  21630. *
  21631. * bevelEnabled: <bool>, // turn on bevel
  21632. * bevelThickness: <float>, // how deep into the original shape bevel goes
  21633. * bevelSize: <float>, // how far from shape outline is bevel
  21634. * bevelSegments: <int>, // number of bevel layers
  21635. *
  21636. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  21637. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  21638. *
  21639. * uvGenerator: <Object> // object that provides UV generator functions
  21640. *
  21641. * }
  21642. **/
  21643. THREE.ExtrudeGeometry = function ( shapes, options ) {
  21644. if ( typeof( shapes ) === "undefined" ) {
  21645. shapes = [];
  21646. return;
  21647. }
  21648. THREE.Geometry.call( this );
  21649. this.type = 'ExtrudeGeometry';
  21650. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  21651. this.addShapeList( shapes, options );
  21652. this.computeFaceNormals();
  21653. // can't really use automatic vertex normals
  21654. // as then front and back sides get smoothed too
  21655. // should do separate smoothing just for sides
  21656. //this.computeVertexNormals();
  21657. //console.log( "took", ( Date.now() - startTime ) );
  21658. };
  21659. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  21660. THREE.ExtrudeGeometry.prototype.constructor = THREE.ExtrudeGeometry;
  21661. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  21662. var sl = shapes.length;
  21663. for ( var s = 0; s < sl; s ++ ) {
  21664. var shape = shapes[ s ];
  21665. this.addShape( shape, options );
  21666. }
  21667. };
  21668. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  21669. var amount = options.amount !== undefined ? options.amount : 100;
  21670. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  21671. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  21672. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  21673. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  21674. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  21675. var steps = options.steps !== undefined ? options.steps : 1;
  21676. var extrudePath = options.extrudePath;
  21677. var extrudePts, extrudeByPath = false;
  21678. // Use default WorldUVGenerator if no UV generators are specified.
  21679. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  21680. var splineTube, binormal, normal, position2;
  21681. if ( extrudePath ) {
  21682. extrudePts = extrudePath.getSpacedPoints( steps );
  21683. extrudeByPath = true;
  21684. bevelEnabled = false; // bevels not supported for path extrusion
  21685. // SETUP TNB variables
  21686. // Reuse TNB from TubeGeomtry for now.
  21687. // TODO1 - have a .isClosed in spline?
  21688. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames( extrudePath, steps, false );
  21689. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  21690. binormal = new THREE.Vector3();
  21691. normal = new THREE.Vector3();
  21692. position2 = new THREE.Vector3();
  21693. }
  21694. // Safeguards if bevels are not enabled
  21695. if ( ! bevelEnabled ) {
  21696. bevelSegments = 0;
  21697. bevelThickness = 0;
  21698. bevelSize = 0;
  21699. }
  21700. // Variables initialization
  21701. var ahole, h, hl; // looping of holes
  21702. var scope = this;
  21703. var shapesOffset = this.vertices.length;
  21704. var shapePoints = shape.extractPoints( curveSegments );
  21705. var vertices = shapePoints.shape;
  21706. var holes = shapePoints.holes;
  21707. var reverse = ! THREE.ShapeUtils.isClockWise( vertices );
  21708. if ( reverse ) {
  21709. vertices = vertices.reverse();
  21710. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  21711. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  21712. ahole = holes[ h ];
  21713. if ( THREE.ShapeUtils.isClockWise( ahole ) ) {
  21714. holes[ h ] = ahole.reverse();
  21715. }
  21716. }
  21717. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  21718. }
  21719. var faces = THREE.ShapeUtils.triangulateShape( vertices, holes );
  21720. /* Vertices */
  21721. var contour = vertices; // vertices has all points but contour has only points of circumference
  21722. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  21723. ahole = holes[ h ];
  21724. vertices = vertices.concat( ahole );
  21725. }
  21726. function scalePt2 ( pt, vec, size ) {
  21727. if ( ! vec ) console.error( "THREE.ExtrudeGeometry: vec does not exist" );
  21728. return vec.clone().multiplyScalar( size ).add( pt );
  21729. }
  21730. var b, bs, t, z,
  21731. vert, vlen = vertices.length,
  21732. face, flen = faces.length;
  21733. // Find directions for point movement
  21734. function getBevelVec( inPt, inPrev, inNext ) {
  21735. // computes for inPt the corresponding point inPt' on a new contour
  21736. // shifted by 1 unit (length of normalized vector) to the left
  21737. // if we walk along contour clockwise, this new contour is outside the old one
  21738. //
  21739. // inPt' is the intersection of the two lines parallel to the two
  21740. // adjacent edges of inPt at a distance of 1 unit on the left side.
  21741. var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt
  21742. // good reading for geometry algorithms (here: line-line intersection)
  21743. // http://geomalgorithms.com/a05-_intersect-1.html
  21744. var v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y;
  21745. var v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y;
  21746. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  21747. // check for collinear edges
  21748. var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  21749. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  21750. // not collinear
  21751. // length of vectors for normalizing
  21752. var v_prev_len = Math.sqrt( v_prev_lensq );
  21753. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  21754. // shift adjacent points by unit vectors to the left
  21755. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  21756. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  21757. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  21758. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  21759. // scaling factor for v_prev to intersection point
  21760. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  21761. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  21762. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  21763. // vector from inPt to intersection point
  21764. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  21765. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  21766. // Don't normalize!, otherwise sharp corners become ugly
  21767. // but prevent crazy spikes
  21768. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  21769. if ( v_trans_lensq <= 2 ) {
  21770. return new THREE.Vector2( v_trans_x, v_trans_y );
  21771. } else {
  21772. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  21773. }
  21774. } else {
  21775. // handle special case of collinear edges
  21776. var direction_eq = false; // assumes: opposite
  21777. if ( v_prev_x > Number.EPSILON ) {
  21778. if ( v_next_x > Number.EPSILON ) {
  21779. direction_eq = true;
  21780. }
  21781. } else {
  21782. if ( v_prev_x < - Number.EPSILON ) {
  21783. if ( v_next_x < - Number.EPSILON ) {
  21784. direction_eq = true;
  21785. }
  21786. } else {
  21787. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  21788. direction_eq = true;
  21789. }
  21790. }
  21791. }
  21792. if ( direction_eq ) {
  21793. // console.log("Warning: lines are a straight sequence");
  21794. v_trans_x = - v_prev_y;
  21795. v_trans_y = v_prev_x;
  21796. shrink_by = Math.sqrt( v_prev_lensq );
  21797. } else {
  21798. // console.log("Warning: lines are a straight spike");
  21799. v_trans_x = v_prev_x;
  21800. v_trans_y = v_prev_y;
  21801. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  21802. }
  21803. }
  21804. return new THREE.Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  21805. }
  21806. var contourMovements = [];
  21807. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  21808. if ( j === il ) j = 0;
  21809. if ( k === il ) k = 0;
  21810. // (j)---(i)---(k)
  21811. // console.log('i,j,k', i, j , k)
  21812. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  21813. }
  21814. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  21815. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  21816. ahole = holes[ h ];
  21817. oneHoleMovements = [];
  21818. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  21819. if ( j === il ) j = 0;
  21820. if ( k === il ) k = 0;
  21821. // (j)---(i)---(k)
  21822. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  21823. }
  21824. holesMovements.push( oneHoleMovements );
  21825. verticesMovements = verticesMovements.concat( oneHoleMovements );
  21826. }
  21827. // Loop bevelSegments, 1 for the front, 1 for the back
  21828. for ( b = 0; b < bevelSegments; b ++ ) {
  21829. //for ( b = bevelSegments; b > 0; b -- ) {
  21830. t = b / bevelSegments;
  21831. z = bevelThickness * ( 1 - t );
  21832. //z = bevelThickness * t;
  21833. bs = bevelSize * ( Math.sin ( t * Math.PI / 2 ) ); // curved
  21834. //bs = bevelSize * t; // linear
  21835. // contract shape
  21836. for ( i = 0, il = contour.length; i < il; i ++ ) {
  21837. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  21838. v( vert.x, vert.y, - z );
  21839. }
  21840. // expand holes
  21841. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  21842. ahole = holes[ h ];
  21843. oneHoleMovements = holesMovements[ h ];
  21844. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  21845. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  21846. v( vert.x, vert.y, - z );
  21847. }
  21848. }
  21849. }
  21850. bs = bevelSize;
  21851. // Back facing vertices
  21852. for ( i = 0; i < vlen; i ++ ) {
  21853. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  21854. if ( ! extrudeByPath ) {
  21855. v( vert.x, vert.y, 0 );
  21856. } else {
  21857. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  21858. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  21859. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  21860. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  21861. v( position2.x, position2.y, position2.z );
  21862. }
  21863. }
  21864. // Add stepped vertices...
  21865. // Including front facing vertices
  21866. var s;
  21867. for ( s = 1; s <= steps; s ++ ) {
  21868. for ( i = 0; i < vlen; i ++ ) {
  21869. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  21870. if ( ! extrudeByPath ) {
  21871. v( vert.x, vert.y, amount / steps * s );
  21872. } else {
  21873. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  21874. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  21875. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  21876. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  21877. v( position2.x, position2.y, position2.z );
  21878. }
  21879. }
  21880. }
  21881. // Add bevel segments planes
  21882. //for ( b = 1; b <= bevelSegments; b ++ ) {
  21883. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  21884. t = b / bevelSegments;
  21885. z = bevelThickness * ( 1 - t );
  21886. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  21887. bs = bevelSize * Math.sin ( t * Math.PI / 2 );
  21888. // contract shape
  21889. for ( i = 0, il = contour.length; i < il; i ++ ) {
  21890. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  21891. v( vert.x, vert.y, amount + z );
  21892. }
  21893. // expand holes
  21894. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  21895. ahole = holes[ h ];
  21896. oneHoleMovements = holesMovements[ h ];
  21897. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  21898. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  21899. if ( ! extrudeByPath ) {
  21900. v( vert.x, vert.y, amount + z );
  21901. } else {
  21902. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  21903. }
  21904. }
  21905. }
  21906. }
  21907. /* Faces */
  21908. // Top and bottom faces
  21909. buildLidFaces();
  21910. // Sides faces
  21911. buildSideFaces();
  21912. ///// Internal functions
  21913. function buildLidFaces() {
  21914. if ( bevelEnabled ) {
  21915. var layer = 0; // steps + 1
  21916. var offset = vlen * layer;
  21917. // Bottom faces
  21918. for ( i = 0; i < flen; i ++ ) {
  21919. face = faces[ i ];
  21920. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  21921. }
  21922. layer = steps + bevelSegments * 2;
  21923. offset = vlen * layer;
  21924. // Top faces
  21925. for ( i = 0; i < flen; i ++ ) {
  21926. face = faces[ i ];
  21927. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  21928. }
  21929. } else {
  21930. // Bottom faces
  21931. for ( i = 0; i < flen; i ++ ) {
  21932. face = faces[ i ];
  21933. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  21934. }
  21935. // Top faces
  21936. for ( i = 0; i < flen; i ++ ) {
  21937. face = faces[ i ];
  21938. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  21939. }
  21940. }
  21941. }
  21942. // Create faces for the z-sides of the shape
  21943. function buildSideFaces() {
  21944. var layeroffset = 0;
  21945. sidewalls( contour, layeroffset );
  21946. layeroffset += contour.length;
  21947. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  21948. ahole = holes[ h ];
  21949. sidewalls( ahole, layeroffset );
  21950. //, true
  21951. layeroffset += ahole.length;
  21952. }
  21953. }
  21954. function sidewalls( contour, layeroffset ) {
  21955. var j, k;
  21956. i = contour.length;
  21957. while ( -- i >= 0 ) {
  21958. j = i;
  21959. k = i - 1;
  21960. if ( k < 0 ) k = contour.length - 1;
  21961. //console.log('b', i,j, i-1, k,vertices.length);
  21962. var s = 0, sl = steps + bevelSegments * 2;
  21963. for ( s = 0; s < sl; s ++ ) {
  21964. var slen1 = vlen * s;
  21965. var slen2 = vlen * ( s + 1 );
  21966. var a = layeroffset + j + slen1,
  21967. b = layeroffset + k + slen1,
  21968. c = layeroffset + k + slen2,
  21969. d = layeroffset + j + slen2;
  21970. f4( a, b, c, d, contour, s, sl, j, k );
  21971. }
  21972. }
  21973. }
  21974. function v( x, y, z ) {
  21975. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  21976. }
  21977. function f3( a, b, c ) {
  21978. a += shapesOffset;
  21979. b += shapesOffset;
  21980. c += shapesOffset;
  21981. scope.faces.push( new THREE.Face3( a, b, c, null, null, 0 ) );
  21982. var uvs = uvgen.generateTopUV( scope, a, b, c );
  21983. scope.faceVertexUvs[ 0 ].push( uvs );
  21984. }
  21985. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  21986. a += shapesOffset;
  21987. b += shapesOffset;
  21988. c += shapesOffset;
  21989. d += shapesOffset;
  21990. scope.faces.push( new THREE.Face3( a, b, d, null, null, 1 ) );
  21991. scope.faces.push( new THREE.Face3( b, c, d, null, null, 1 ) );
  21992. var uvs = uvgen.generateSideWallUV( scope, a, b, c, d );
  21993. scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] );
  21994. scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] );
  21995. }
  21996. };
  21997. THREE.ExtrudeGeometry.WorldUVGenerator = {
  21998. generateTopUV: function ( geometry, indexA, indexB, indexC ) {
  21999. var vertices = geometry.vertices;
  22000. var a = vertices[ indexA ];
  22001. var b = vertices[ indexB ];
  22002. var c = vertices[ indexC ];
  22003. return [
  22004. new THREE.Vector2( a.x, a.y ),
  22005. new THREE.Vector2( b.x, b.y ),
  22006. new THREE.Vector2( c.x, c.y )
  22007. ];
  22008. },
  22009. generateSideWallUV: function ( geometry, indexA, indexB, indexC, indexD ) {
  22010. var vertices = geometry.vertices;
  22011. var a = vertices[ indexA ];
  22012. var b = vertices[ indexB ];
  22013. var c = vertices[ indexC ];
  22014. var d = vertices[ indexD ];
  22015. if ( Math.abs( a.y - b.y ) < 0.01 ) {
  22016. return [
  22017. new THREE.Vector2( a.x, 1 - a.z ),
  22018. new THREE.Vector2( b.x, 1 - b.z ),
  22019. new THREE.Vector2( c.x, 1 - c.z ),
  22020. new THREE.Vector2( d.x, 1 - d.z )
  22021. ];
  22022. } else {
  22023. return [
  22024. new THREE.Vector2( a.y, 1 - a.z ),
  22025. new THREE.Vector2( b.y, 1 - b.z ),
  22026. new THREE.Vector2( c.y, 1 - c.z ),
  22027. new THREE.Vector2( d.y, 1 - d.z )
  22028. ];
  22029. }
  22030. }
  22031. };
  22032. // File:src/extras/geometries/ShapeGeometry.js
  22033. /**
  22034. * @author jonobr1 / http://jonobr1.com
  22035. *
  22036. * Creates a one-sided polygonal geometry from a path shape. Similar to
  22037. * ExtrudeGeometry.
  22038. *
  22039. * parameters = {
  22040. *
  22041. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  22042. *
  22043. * material: <int> // material index for front and back faces
  22044. * uvGenerator: <Object> // object that provides UV generator functions
  22045. *
  22046. * }
  22047. **/
  22048. THREE.ShapeGeometry = function ( shapes, options ) {
  22049. THREE.Geometry.call( this );
  22050. this.type = 'ShapeGeometry';
  22051. if ( Array.isArray( shapes ) === false ) shapes = [ shapes ];
  22052. this.addShapeList( shapes, options );
  22053. this.computeFaceNormals();
  22054. };
  22055. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  22056. THREE.ShapeGeometry.prototype.constructor = THREE.ShapeGeometry;
  22057. /**
  22058. * Add an array of shapes to THREE.ShapeGeometry.
  22059. */
  22060. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  22061. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  22062. this.addShape( shapes[ i ], options );
  22063. }
  22064. return this;
  22065. };
  22066. /**
  22067. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  22068. */
  22069. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  22070. if ( options === undefined ) options = {};
  22071. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  22072. var material = options.material;
  22073. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  22074. //
  22075. var i, l, hole;
  22076. var shapesOffset = this.vertices.length;
  22077. var shapePoints = shape.extractPoints( curveSegments );
  22078. var vertices = shapePoints.shape;
  22079. var holes = shapePoints.holes;
  22080. var reverse = ! THREE.ShapeUtils.isClockWise( vertices );
  22081. if ( reverse ) {
  22082. vertices = vertices.reverse();
  22083. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  22084. for ( i = 0, l = holes.length; i < l; i ++ ) {
  22085. hole = holes[ i ];
  22086. if ( THREE.ShapeUtils.isClockWise( hole ) ) {
  22087. holes[ i ] = hole.reverse();
  22088. }
  22089. }
  22090. reverse = false;
  22091. }
  22092. var faces = THREE.ShapeUtils.triangulateShape( vertices, holes );
  22093. // Vertices
  22094. for ( i = 0, l = holes.length; i < l; i ++ ) {
  22095. hole = holes[ i ];
  22096. vertices = vertices.concat( hole );
  22097. }
  22098. //
  22099. var vert, vlen = vertices.length;
  22100. var face, flen = faces.length;
  22101. for ( i = 0; i < vlen; i ++ ) {
  22102. vert = vertices[ i ];
  22103. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  22104. }
  22105. for ( i = 0; i < flen; i ++ ) {
  22106. face = faces[ i ];
  22107. var a = face[ 0 ] + shapesOffset;
  22108. var b = face[ 1 ] + shapesOffset;
  22109. var c = face[ 2 ] + shapesOffset;
  22110. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  22111. this.faceVertexUvs[ 0 ].push( uvgen.generateTopUV( this, a, b, c ) );
  22112. }
  22113. };
  22114. // File:src/extras/geometries/LatheGeometry.js
  22115. /**
  22116. * @author astrodud / http://astrodud.isgreat.org/
  22117. * @author zz85 / https://github.com/zz85
  22118. * @author bhouston / http://clara.io
  22119. */
  22120. // points - to create a closed torus, one must use a set of points
  22121. // like so: [ a, b, c, d, a ], see first is the same as last.
  22122. // segments - the number of circumference segments to create
  22123. // phiStart - the starting radian
  22124. // phiLength - the radian (0 to 2*PI) range of the lathed section
  22125. // 2*pi is a closed lathe, less than 2PI is a portion.
  22126. THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
  22127. THREE.Geometry.call( this );
  22128. this.type = 'LatheGeometry';
  22129. this.parameters = {
  22130. points: points,
  22131. segments: segments,
  22132. phiStart: phiStart,
  22133. phiLength: phiLength
  22134. };
  22135. segments = segments || 12;
  22136. phiStart = phiStart || 0;
  22137. phiLength = phiLength || 2 * Math.PI;
  22138. var inversePointLength = 1.0 / ( points.length - 1 );
  22139. var inverseSegments = 1.0 / segments;
  22140. for ( var i = 0, il = segments; i <= il; i ++ ) {
  22141. var phi = phiStart + i * inverseSegments * phiLength;
  22142. var c = Math.cos( phi ),
  22143. s = Math.sin( phi );
  22144. for ( var j = 0, jl = points.length; j < jl; j ++ ) {
  22145. var pt = points[ j ];
  22146. var vertex = new THREE.Vector3();
  22147. vertex.x = c * pt.x - s * pt.y;
  22148. vertex.y = s * pt.x + c * pt.y;
  22149. vertex.z = pt.z;
  22150. this.vertices.push( vertex );
  22151. }
  22152. }
  22153. var np = points.length;
  22154. for ( var i = 0, il = segments; i < il; i ++ ) {
  22155. for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) {
  22156. var base = j + np * i;
  22157. var a = base;
  22158. var b = base + np;
  22159. var c = base + 1 + np;
  22160. var d = base + 1;
  22161. var u0 = i * inverseSegments;
  22162. var v0 = j * inversePointLength;
  22163. var u1 = u0 + inverseSegments;
  22164. var v1 = v0 + inversePointLength;
  22165. this.faces.push( new THREE.Face3( a, b, d ) );
  22166. this.faceVertexUvs[ 0 ].push( [
  22167. new THREE.Vector2( u0, v0 ),
  22168. new THREE.Vector2( u1, v0 ),
  22169. new THREE.Vector2( u0, v1 )
  22170. ] );
  22171. this.faces.push( new THREE.Face3( b, c, d ) );
  22172. this.faceVertexUvs[ 0 ].push( [
  22173. new THREE.Vector2( u1, v0 ),
  22174. new THREE.Vector2( u1, v1 ),
  22175. new THREE.Vector2( u0, v1 )
  22176. ] );
  22177. }
  22178. }
  22179. this.mergeVertices();
  22180. this.computeFaceNormals();
  22181. this.computeVertexNormals();
  22182. };
  22183. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  22184. THREE.LatheGeometry.prototype.constructor = THREE.LatheGeometry;
  22185. // File:src/extras/geometries/PlaneGeometry.js
  22186. /**
  22187. * @author mrdoob / http://mrdoob.com/
  22188. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  22189. */
  22190. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  22191. THREE.Geometry.call( this );
  22192. this.type = 'PlaneGeometry';
  22193. this.parameters = {
  22194. width: width,
  22195. height: height,
  22196. widthSegments: widthSegments,
  22197. heightSegments: heightSegments
  22198. };
  22199. this.fromBufferGeometry( new THREE.PlaneBufferGeometry( width, height, widthSegments, heightSegments ) );
  22200. };
  22201. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  22202. THREE.PlaneGeometry.prototype.constructor = THREE.PlaneGeometry;
  22203. // File:src/extras/geometries/PlaneBufferGeometry.js
  22204. /**
  22205. * @author mrdoob / http://mrdoob.com/
  22206. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  22207. */
  22208. THREE.PlaneBufferGeometry = function ( width, height, widthSegments, heightSegments ) {
  22209. THREE.BufferGeometry.call( this );
  22210. this.type = 'PlaneBufferGeometry';
  22211. this.parameters = {
  22212. width: width,
  22213. height: height,
  22214. widthSegments: widthSegments,
  22215. heightSegments: heightSegments
  22216. };
  22217. var width_half = width / 2;
  22218. var height_half = height / 2;
  22219. var gridX = Math.floor( widthSegments ) || 1;
  22220. var gridY = Math.floor( heightSegments ) || 1;
  22221. var gridX1 = gridX + 1;
  22222. var gridY1 = gridY + 1;
  22223. var segment_width = width / gridX;
  22224. var segment_height = height / gridY;
  22225. var vertices = new Float32Array( gridX1 * gridY1 * 3 );
  22226. var normals = new Float32Array( gridX1 * gridY1 * 3 );
  22227. var uvs = new Float32Array( gridX1 * gridY1 * 2 );
  22228. var offset = 0;
  22229. var offset2 = 0;
  22230. for ( var iy = 0; iy < gridY1; iy ++ ) {
  22231. var y = iy * segment_height - height_half;
  22232. for ( var ix = 0; ix < gridX1; ix ++ ) {
  22233. var x = ix * segment_width - width_half;
  22234. vertices[ offset ] = x;
  22235. vertices[ offset + 1 ] = - y;
  22236. normals[ offset + 2 ] = 1;
  22237. uvs[ offset2 ] = ix / gridX;
  22238. uvs[ offset2 + 1 ] = 1 - ( iy / gridY );
  22239. offset += 3;
  22240. offset2 += 2;
  22241. }
  22242. }
  22243. offset = 0;
  22244. var indices = new ( ( vertices.length / 3 ) > 65535 ? Uint32Array : Uint16Array )( gridX * gridY * 6 );
  22245. for ( var iy = 0; iy < gridY; iy ++ ) {
  22246. for ( var ix = 0; ix < gridX; ix ++ ) {
  22247. var a = ix + gridX1 * iy;
  22248. var b = ix + gridX1 * ( iy + 1 );
  22249. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  22250. var d = ( ix + 1 ) + gridX1 * iy;
  22251. indices[ offset ] = a;
  22252. indices[ offset + 1 ] = b;
  22253. indices[ offset + 2 ] = d;
  22254. indices[ offset + 3 ] = b;
  22255. indices[ offset + 4 ] = c;
  22256. indices[ offset + 5 ] = d;
  22257. offset += 6;
  22258. }
  22259. }
  22260. this.setIndex( new THREE.BufferAttribute( indices, 1 ) );
  22261. this.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  22262. this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
  22263. this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) );
  22264. };
  22265. THREE.PlaneBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  22266. THREE.PlaneBufferGeometry.prototype.constructor = THREE.PlaneBufferGeometry;
  22267. // File:src/extras/geometries/RingGeometry.js
  22268. /**
  22269. * @author Kaleb Murphy
  22270. */
  22271. THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  22272. THREE.Geometry.call( this );
  22273. this.type = 'RingGeometry';
  22274. this.parameters = {
  22275. innerRadius: innerRadius,
  22276. outerRadius: outerRadius,
  22277. thetaSegments: thetaSegments,
  22278. phiSegments: phiSegments,
  22279. thetaStart: thetaStart,
  22280. thetaLength: thetaLength
  22281. };
  22282. innerRadius = innerRadius || 0;
  22283. outerRadius = outerRadius || 50;
  22284. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  22285. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  22286. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  22287. phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 8;
  22288. var i, o, uvs = [], radius = innerRadius, radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  22289. for ( i = 0; i < phiSegments + 1; i ++ ) {
  22290. // concentric circles inside ring
  22291. for ( o = 0; o < thetaSegments + 1; o ++ ) {
  22292. // number of segments per circle
  22293. var vertex = new THREE.Vector3();
  22294. var segment = thetaStart + o / thetaSegments * thetaLength;
  22295. vertex.x = radius * Math.cos( segment );
  22296. vertex.y = radius * Math.sin( segment );
  22297. this.vertices.push( vertex );
  22298. uvs.push( new THREE.Vector2( ( vertex.x / outerRadius + 1 ) / 2, ( vertex.y / outerRadius + 1 ) / 2 ) );
  22299. }
  22300. radius += radiusStep;
  22301. }
  22302. var n = new THREE.Vector3( 0, 0, 1 );
  22303. for ( i = 0; i < phiSegments; i ++ ) {
  22304. // concentric circles inside ring
  22305. var thetaSegment = i * ( thetaSegments + 1 );
  22306. for ( o = 0; o < thetaSegments ; o ++ ) {
  22307. // number of segments per circle
  22308. var segment = o + thetaSegment;
  22309. var v1 = segment;
  22310. var v2 = segment + thetaSegments + 1;
  22311. var v3 = segment + thetaSegments + 2;
  22312. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  22313. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ] );
  22314. v1 = segment;
  22315. v2 = segment + thetaSegments + 2;
  22316. v3 = segment + 1;
  22317. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  22318. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ] );
  22319. }
  22320. }
  22321. this.computeFaceNormals();
  22322. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  22323. };
  22324. THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype );
  22325. THREE.RingGeometry.prototype.constructor = THREE.RingGeometry;
  22326. // File:src/extras/geometries/SphereGeometry.js
  22327. /**
  22328. * @author mrdoob / http://mrdoob.com/
  22329. */
  22330. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  22331. THREE.Geometry.call( this );
  22332. this.type = 'SphereGeometry';
  22333. this.parameters = {
  22334. radius: radius,
  22335. widthSegments: widthSegments,
  22336. heightSegments: heightSegments,
  22337. phiStart: phiStart,
  22338. phiLength: phiLength,
  22339. thetaStart: thetaStart,
  22340. thetaLength: thetaLength
  22341. };
  22342. this.fromBufferGeometry( new THREE.SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) );
  22343. };
  22344. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  22345. THREE.SphereGeometry.prototype.constructor = THREE.SphereGeometry;
  22346. // File:src/extras/geometries/SphereBufferGeometry.js
  22347. /**
  22348. * @author benaadams / https://twitter.com/ben_a_adams
  22349. * based on THREE.SphereGeometry
  22350. */
  22351. THREE.SphereBufferGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  22352. THREE.BufferGeometry.call( this );
  22353. this.type = 'SphereBufferGeometry';
  22354. this.parameters = {
  22355. radius: radius,
  22356. widthSegments: widthSegments,
  22357. heightSegments: heightSegments,
  22358. phiStart: phiStart,
  22359. phiLength: phiLength,
  22360. thetaStart: thetaStart,
  22361. thetaLength: thetaLength
  22362. };
  22363. radius = radius || 50;
  22364. widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  22365. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  22366. phiStart = phiStart !== undefined ? phiStart : 0;
  22367. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  22368. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  22369. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  22370. var thetaEnd = thetaStart + thetaLength;
  22371. var vertexCount = ( ( widthSegments + 1 ) * ( heightSegments + 1 ) );
  22372. var positions = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  22373. var normals = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  22374. var uvs = new THREE.BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  22375. var index = 0, vertices = [], normal = new THREE.Vector3();
  22376. for ( var y = 0; y <= heightSegments; y ++ ) {
  22377. var verticesRow = [];
  22378. var v = y / heightSegments;
  22379. for ( var x = 0; x <= widthSegments; x ++ ) {
  22380. var u = x / widthSegments;
  22381. var px = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  22382. var py = radius * Math.cos( thetaStart + v * thetaLength );
  22383. var pz = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  22384. normal.set( px, py, pz ).normalize();
  22385. positions.setXYZ( index, px, py, pz );
  22386. normals.setXYZ( index, normal.x, normal.y, normal.z );
  22387. uvs.setXY( index, u, 1 - v );
  22388. verticesRow.push( index );
  22389. index ++;
  22390. }
  22391. vertices.push( verticesRow );
  22392. }
  22393. var indices = [];
  22394. for ( var y = 0; y < heightSegments; y ++ ) {
  22395. for ( var x = 0; x < widthSegments; x ++ ) {
  22396. var v1 = vertices[ y ][ x + 1 ];
  22397. var v2 = vertices[ y ][ x ];
  22398. var v3 = vertices[ y + 1 ][ x ];
  22399. var v4 = vertices[ y + 1 ][ x + 1 ];
  22400. if ( y !== 0 || thetaStart > 0 ) indices.push( v1, v2, v4 );
  22401. if ( y !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( v2, v3, v4 );
  22402. }
  22403. }
  22404. this.setIndex( new ( positions.count > 65535 ? THREE.Uint32Attribute : THREE.Uint16Attribute )( indices, 1 ) );
  22405. this.addAttribute( 'position', positions );
  22406. this.addAttribute( 'normal', normals );
  22407. this.addAttribute( 'uv', uvs );
  22408. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  22409. };
  22410. THREE.SphereBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  22411. THREE.SphereBufferGeometry.prototype.constructor = THREE.SphereBufferGeometry;
  22412. // File:src/extras/geometries/TorusGeometry.js
  22413. /**
  22414. * @author oosmoxiecode
  22415. * @author mrdoob / http://mrdoob.com/
  22416. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  22417. */
  22418. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  22419. THREE.Geometry.call( this );
  22420. this.type = 'TorusGeometry';
  22421. this.parameters = {
  22422. radius: radius,
  22423. tube: tube,
  22424. radialSegments: radialSegments,
  22425. tubularSegments: tubularSegments,
  22426. arc: arc
  22427. };
  22428. radius = radius || 100;
  22429. tube = tube || 40;
  22430. radialSegments = radialSegments || 8;
  22431. tubularSegments = tubularSegments || 6;
  22432. arc = arc || Math.PI * 2;
  22433. var center = new THREE.Vector3(), uvs = [], normals = [];
  22434. for ( var j = 0; j <= radialSegments; j ++ ) {
  22435. for ( var i = 0; i <= tubularSegments; i ++ ) {
  22436. var u = i / tubularSegments * arc;
  22437. var v = j / radialSegments * Math.PI * 2;
  22438. center.x = radius * Math.cos( u );
  22439. center.y = radius * Math.sin( u );
  22440. var vertex = new THREE.Vector3();
  22441. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  22442. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  22443. vertex.z = tube * Math.sin( v );
  22444. this.vertices.push( vertex );
  22445. uvs.push( new THREE.Vector2( i / tubularSegments, j / radialSegments ) );
  22446. normals.push( vertex.clone().sub( center ).normalize() );
  22447. }
  22448. }
  22449. for ( var j = 1; j <= radialSegments; j ++ ) {
  22450. for ( var i = 1; i <= tubularSegments; i ++ ) {
  22451. var a = ( tubularSegments + 1 ) * j + i - 1;
  22452. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  22453. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  22454. var d = ( tubularSegments + 1 ) * j + i;
  22455. var face = new THREE.Face3( a, b, d, [ normals[ a ].clone(), normals[ b ].clone(), normals[ d ].clone() ] );
  22456. this.faces.push( face );
  22457. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ d ].clone() ] );
  22458. face = new THREE.Face3( b, c, d, [ normals[ b ].clone(), normals[ c ].clone(), normals[ d ].clone() ] );
  22459. this.faces.push( face );
  22460. this.faceVertexUvs[ 0 ].push( [ uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  22461. }
  22462. }
  22463. this.computeFaceNormals();
  22464. };
  22465. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  22466. THREE.TorusGeometry.prototype.constructor = THREE.TorusGeometry;
  22467. // File:src/extras/geometries/TorusKnotGeometry.js
  22468. /**
  22469. * @author oosmoxiecode
  22470. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  22471. */
  22472. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  22473. THREE.Geometry.call( this );
  22474. this.type = 'TorusKnotGeometry';
  22475. this.parameters = {
  22476. radius: radius,
  22477. tube: tube,
  22478. radialSegments: radialSegments,
  22479. tubularSegments: tubularSegments,
  22480. p: p,
  22481. q: q,
  22482. heightScale: heightScale
  22483. };
  22484. radius = radius || 100;
  22485. tube = tube || 40;
  22486. radialSegments = radialSegments || 64;
  22487. tubularSegments = tubularSegments || 8;
  22488. p = p || 2;
  22489. q = q || 3;
  22490. heightScale = heightScale || 1;
  22491. var grid = new Array( radialSegments );
  22492. var tang = new THREE.Vector3();
  22493. var n = new THREE.Vector3();
  22494. var bitan = new THREE.Vector3();
  22495. for ( var i = 0; i < radialSegments; ++ i ) {
  22496. grid[ i ] = new Array( tubularSegments );
  22497. var u = i / radialSegments * 2 * p * Math.PI;
  22498. var p1 = getPos( u, q, p, radius, heightScale );
  22499. var p2 = getPos( u + 0.01, q, p, radius, heightScale );
  22500. tang.subVectors( p2, p1 );
  22501. n.addVectors( p2, p1 );
  22502. bitan.crossVectors( tang, n );
  22503. n.crossVectors( bitan, tang );
  22504. bitan.normalize();
  22505. n.normalize();
  22506. for ( var j = 0; j < tubularSegments; ++ j ) {
  22507. var v = j / tubularSegments * 2 * Math.PI;
  22508. var cx = - tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  22509. var cy = tube * Math.sin( v );
  22510. var pos = new THREE.Vector3();
  22511. pos.x = p1.x + cx * n.x + cy * bitan.x;
  22512. pos.y = p1.y + cx * n.y + cy * bitan.y;
  22513. pos.z = p1.z + cx * n.z + cy * bitan.z;
  22514. grid[ i ][ j ] = this.vertices.push( pos ) - 1;
  22515. }
  22516. }
  22517. for ( var i = 0; i < radialSegments; ++ i ) {
  22518. for ( var j = 0; j < tubularSegments; ++ j ) {
  22519. var ip = ( i + 1 ) % radialSegments;
  22520. var jp = ( j + 1 ) % tubularSegments;
  22521. var a = grid[ i ][ j ];
  22522. var b = grid[ ip ][ j ];
  22523. var c = grid[ ip ][ jp ];
  22524. var d = grid[ i ][ jp ];
  22525. var uva = new THREE.Vector2( i / radialSegments, j / tubularSegments );
  22526. var uvb = new THREE.Vector2( ( i + 1 ) / radialSegments, j / tubularSegments );
  22527. var uvc = new THREE.Vector2( ( i + 1 ) / radialSegments, ( j + 1 ) / tubularSegments );
  22528. var uvd = new THREE.Vector2( i / radialSegments, ( j + 1 ) / tubularSegments );
  22529. this.faces.push( new THREE.Face3( a, b, d ) );
  22530. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  22531. this.faces.push( new THREE.Face3( b, c, d ) );
  22532. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  22533. }
  22534. }
  22535. this.computeFaceNormals();
  22536. this.computeVertexNormals();
  22537. function getPos( u, in_q, in_p, radius, heightScale ) {
  22538. var cu = Math.cos( u );
  22539. var su = Math.sin( u );
  22540. var quOverP = in_q / in_p * u;
  22541. var cs = Math.cos( quOverP );
  22542. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  22543. var ty = radius * ( 2 + cs ) * su * 0.5;
  22544. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  22545. return new THREE.Vector3( tx, ty, tz );
  22546. }
  22547. };
  22548. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  22549. THREE.TorusKnotGeometry.prototype.constructor = THREE.TorusKnotGeometry;
  22550. // File:src/extras/geometries/TubeGeometry.js
  22551. /**
  22552. * @author WestLangley / https://github.com/WestLangley
  22553. * @author zz85 / https://github.com/zz85
  22554. * @author miningold / https://github.com/miningold
  22555. * @author jonobr1 / https://github.com/jonobr1
  22556. *
  22557. * Modified from the TorusKnotGeometry by @oosmoxiecode
  22558. *
  22559. * Creates a tube which extrudes along a 3d spline
  22560. *
  22561. * Uses parallel transport frames as described in
  22562. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  22563. */
  22564. THREE.TubeGeometry = function ( path, segments, radius, radialSegments, closed, taper ) {
  22565. THREE.Geometry.call( this );
  22566. this.type = 'TubeGeometry';
  22567. this.parameters = {
  22568. path: path,
  22569. segments: segments,
  22570. radius: radius,
  22571. radialSegments: radialSegments,
  22572. closed: closed,
  22573. taper: taper
  22574. };
  22575. segments = segments || 64;
  22576. radius = radius || 1;
  22577. radialSegments = radialSegments || 8;
  22578. closed = closed || false;
  22579. taper = taper || THREE.TubeGeometry.NoTaper;
  22580. var grid = [];
  22581. var scope = this,
  22582. tangent,
  22583. normal,
  22584. binormal,
  22585. numpoints = segments + 1,
  22586. u, v, r,
  22587. cx, cy,
  22588. pos, pos2 = new THREE.Vector3(),
  22589. i, j,
  22590. ip, jp,
  22591. a, b, c, d,
  22592. uva, uvb, uvc, uvd;
  22593. var frames = new THREE.TubeGeometry.FrenetFrames( path, segments, closed ),
  22594. tangents = frames.tangents,
  22595. normals = frames.normals,
  22596. binormals = frames.binormals;
  22597. // proxy internals
  22598. this.tangents = tangents;
  22599. this.normals = normals;
  22600. this.binormals = binormals;
  22601. function vert( x, y, z ) {
  22602. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  22603. }
  22604. // construct the grid
  22605. for ( i = 0; i < numpoints; i ++ ) {
  22606. grid[ i ] = [];
  22607. u = i / ( numpoints - 1 );
  22608. pos = path.getPointAt( u );
  22609. tangent = tangents[ i ];
  22610. normal = normals[ i ];
  22611. binormal = binormals[ i ];
  22612. r = radius * taper( u );
  22613. for ( j = 0; j < radialSegments; j ++ ) {
  22614. v = j / radialSegments * 2 * Math.PI;
  22615. cx = - r * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  22616. cy = r * Math.sin( v );
  22617. pos2.copy( pos );
  22618. pos2.x += cx * normal.x + cy * binormal.x;
  22619. pos2.y += cx * normal.y + cy * binormal.y;
  22620. pos2.z += cx * normal.z + cy * binormal.z;
  22621. grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  22622. }
  22623. }
  22624. // construct the mesh
  22625. for ( i = 0; i < segments; i ++ ) {
  22626. for ( j = 0; j < radialSegments; j ++ ) {
  22627. ip = ( closed ) ? ( i + 1 ) % segments : i + 1;
  22628. jp = ( j + 1 ) % radialSegments;
  22629. a = grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  22630. b = grid[ ip ][ j ];
  22631. c = grid[ ip ][ jp ];
  22632. d = grid[ i ][ jp ];
  22633. uva = new THREE.Vector2( i / segments, j / radialSegments );
  22634. uvb = new THREE.Vector2( ( i + 1 ) / segments, j / radialSegments );
  22635. uvc = new THREE.Vector2( ( i + 1 ) / segments, ( j + 1 ) / radialSegments );
  22636. uvd = new THREE.Vector2( i / segments, ( j + 1 ) / radialSegments );
  22637. this.faces.push( new THREE.Face3( a, b, d ) );
  22638. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  22639. this.faces.push( new THREE.Face3( b, c, d ) );
  22640. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  22641. }
  22642. }
  22643. this.computeFaceNormals();
  22644. this.computeVertexNormals();
  22645. };
  22646. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  22647. THREE.TubeGeometry.prototype.constructor = THREE.TubeGeometry;
  22648. THREE.TubeGeometry.NoTaper = function ( u ) {
  22649. return 1;
  22650. };
  22651. THREE.TubeGeometry.SinusoidalTaper = function ( u ) {
  22652. return Math.sin( Math.PI * u );
  22653. };
  22654. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  22655. THREE.TubeGeometry.FrenetFrames = function ( path, segments, closed ) {
  22656. var normal = new THREE.Vector3(),
  22657. tangents = [],
  22658. normals = [],
  22659. binormals = [],
  22660. vec = new THREE.Vector3(),
  22661. mat = new THREE.Matrix4(),
  22662. numpoints = segments + 1,
  22663. theta,
  22664. smallest,
  22665. tx, ty, tz,
  22666. i, u;
  22667. // expose internals
  22668. this.tangents = tangents;
  22669. this.normals = normals;
  22670. this.binormals = binormals;
  22671. // compute the tangent vectors for each segment on the path
  22672. for ( i = 0; i < numpoints; i ++ ) {
  22673. u = i / ( numpoints - 1 );
  22674. tangents[ i ] = path.getTangentAt( u );
  22675. tangents[ i ].normalize();
  22676. }
  22677. initialNormal3();
  22678. /*
  22679. function initialNormal1(lastBinormal) {
  22680. // fixed start binormal. Has dangers of 0 vectors
  22681. normals[ 0 ] = new THREE.Vector3();
  22682. binormals[ 0 ] = new THREE.Vector3();
  22683. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  22684. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  22685. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  22686. }
  22687. function initialNormal2() {
  22688. // This uses the Frenet-Serret formula for deriving binormal
  22689. var t2 = path.getTangentAt( epsilon );
  22690. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  22691. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  22692. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  22693. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  22694. }
  22695. */
  22696. function initialNormal3() {
  22697. // select an initial normal vector perpendicular to the first tangent vector,
  22698. // and in the direction of the smallest tangent xyz component
  22699. normals[ 0 ] = new THREE.Vector3();
  22700. binormals[ 0 ] = new THREE.Vector3();
  22701. smallest = Number.MAX_VALUE;
  22702. tx = Math.abs( tangents[ 0 ].x );
  22703. ty = Math.abs( tangents[ 0 ].y );
  22704. tz = Math.abs( tangents[ 0 ].z );
  22705. if ( tx <= smallest ) {
  22706. smallest = tx;
  22707. normal.set( 1, 0, 0 );
  22708. }
  22709. if ( ty <= smallest ) {
  22710. smallest = ty;
  22711. normal.set( 0, 1, 0 );
  22712. }
  22713. if ( tz <= smallest ) {
  22714. normal.set( 0, 0, 1 );
  22715. }
  22716. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  22717. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  22718. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  22719. }
  22720. // compute the slowly-varying normal and binormal vectors for each segment on the path
  22721. for ( i = 1; i < numpoints; i ++ ) {
  22722. normals[ i ] = normals[ i - 1 ].clone();
  22723. binormals[ i ] = binormals[ i - 1 ].clone();
  22724. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  22725. if ( vec.length() > Number.EPSILON ) {
  22726. vec.normalize();
  22727. theta = Math.acos( THREE.Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  22728. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  22729. }
  22730. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  22731. }
  22732. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  22733. if ( closed ) {
  22734. theta = Math.acos( THREE.Math.clamp( normals[ 0 ].dot( normals[ numpoints - 1 ] ), - 1, 1 ) );
  22735. theta /= ( numpoints - 1 );
  22736. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints - 1 ] ) ) > 0 ) {
  22737. theta = - theta;
  22738. }
  22739. for ( i = 1; i < numpoints; i ++ ) {
  22740. // twist a little...
  22741. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  22742. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  22743. }
  22744. }
  22745. };
  22746. // File:src/extras/geometries/PolyhedronGeometry.js
  22747. /**
  22748. * @author clockworkgeek / https://github.com/clockworkgeek
  22749. * @author timothypratley / https://github.com/timothypratley
  22750. * @author WestLangley / http://github.com/WestLangley
  22751. */
  22752. THREE.PolyhedronGeometry = function ( vertices, indices, radius, detail ) {
  22753. THREE.Geometry.call( this );
  22754. this.type = 'PolyhedronGeometry';
  22755. this.parameters = {
  22756. vertices: vertices,
  22757. indices: indices,
  22758. radius: radius,
  22759. detail: detail
  22760. };
  22761. radius = radius || 1;
  22762. detail = detail || 0;
  22763. var that = this;
  22764. for ( var i = 0, l = vertices.length; i < l; i += 3 ) {
  22765. prepare( new THREE.Vector3( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] ) );
  22766. }
  22767. var p = this.vertices;
  22768. var faces = [];
  22769. for ( var i = 0, j = 0, l = indices.length; i < l; i += 3, j ++ ) {
  22770. var v1 = p[ indices[ i ] ];
  22771. var v2 = p[ indices[ i + 1 ] ];
  22772. var v3 = p[ indices[ i + 2 ] ];
  22773. faces[ j ] = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ], undefined, j );
  22774. }
  22775. var centroid = new THREE.Vector3();
  22776. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  22777. subdivide( faces[ i ], detail );
  22778. }
  22779. // Handle case when face straddles the seam
  22780. for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) {
  22781. var uvs = this.faceVertexUvs[ 0 ][ i ];
  22782. var x0 = uvs[ 0 ].x;
  22783. var x1 = uvs[ 1 ].x;
  22784. var x2 = uvs[ 2 ].x;
  22785. var max = Math.max( x0, x1, x2 );
  22786. var min = Math.min( x0, x1, x2 );
  22787. if ( max > 0.9 && min < 0.1 ) {
  22788. // 0.9 is somewhat arbitrary
  22789. if ( x0 < 0.2 ) uvs[ 0 ].x += 1;
  22790. if ( x1 < 0.2 ) uvs[ 1 ].x += 1;
  22791. if ( x2 < 0.2 ) uvs[ 2 ].x += 1;
  22792. }
  22793. }
  22794. // Apply radius
  22795. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  22796. this.vertices[ i ].multiplyScalar( radius );
  22797. }
  22798. // Merge vertices
  22799. this.mergeVertices();
  22800. this.computeFaceNormals();
  22801. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  22802. // Project vector onto sphere's surface
  22803. function prepare( vector ) {
  22804. var vertex = vector.normalize().clone();
  22805. vertex.index = that.vertices.push( vertex ) - 1;
  22806. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  22807. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  22808. var v = inclination( vector ) / Math.PI + 0.5;
  22809. vertex.uv = new THREE.Vector2( u, 1 - v );
  22810. return vertex;
  22811. }
  22812. // Approximate a curved face with recursively sub-divided triangles.
  22813. function make( v1, v2, v3, materialIndex ) {
  22814. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ], undefined, materialIndex );
  22815. that.faces.push( face );
  22816. centroid.copy( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  22817. var azi = azimuth( centroid );
  22818. that.faceVertexUvs[ 0 ].push( [
  22819. correctUV( v1.uv, v1, azi ),
  22820. correctUV( v2.uv, v2, azi ),
  22821. correctUV( v3.uv, v3, azi )
  22822. ] );
  22823. }
  22824. // Analytically subdivide a face to the required detail level.
  22825. function subdivide( face, detail ) {
  22826. var cols = Math.pow( 2, detail );
  22827. var a = prepare( that.vertices[ face.a ] );
  22828. var b = prepare( that.vertices[ face.b ] );
  22829. var c = prepare( that.vertices[ face.c ] );
  22830. var v = [];
  22831. var materialIndex = face.materialIndex;
  22832. // Construct all of the vertices for this subdivision.
  22833. for ( var i = 0 ; i <= cols; i ++ ) {
  22834. v[ i ] = [];
  22835. var aj = prepare( a.clone().lerp( c, i / cols ) );
  22836. var bj = prepare( b.clone().lerp( c, i / cols ) );
  22837. var rows = cols - i;
  22838. for ( var j = 0; j <= rows; j ++ ) {
  22839. if ( j === 0 && i === cols ) {
  22840. v[ i ][ j ] = aj;
  22841. } else {
  22842. v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) );
  22843. }
  22844. }
  22845. }
  22846. // Construct all of the faces.
  22847. for ( var i = 0; i < cols ; i ++ ) {
  22848. for ( var j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  22849. var k = Math.floor( j / 2 );
  22850. if ( j % 2 === 0 ) {
  22851. make(
  22852. v[ i ][ k + 1 ],
  22853. v[ i + 1 ][ k ],
  22854. v[ i ][ k ],
  22855. materialIndex
  22856. );
  22857. } else {
  22858. make(
  22859. v[ i ][ k + 1 ],
  22860. v[ i + 1 ][ k + 1 ],
  22861. v[ i + 1 ][ k ],
  22862. materialIndex
  22863. );
  22864. }
  22865. }
  22866. }
  22867. }
  22868. // Angle around the Y axis, counter-clockwise when looking from above.
  22869. function azimuth( vector ) {
  22870. return Math.atan2( vector.z, - vector.x );
  22871. }
  22872. // Angle above the XZ plane.
  22873. function inclination( vector ) {
  22874. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  22875. }
  22876. // Texture fixing helper. Spheres have some odd behaviours.
  22877. function correctUV( uv, vector, azimuth ) {
  22878. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  22879. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  22880. return uv.clone();
  22881. }
  22882. };
  22883. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  22884. THREE.PolyhedronGeometry.prototype.constructor = THREE.PolyhedronGeometry;
  22885. // File:src/extras/geometries/DodecahedronGeometry.js
  22886. /**
  22887. * @author Abe Pazos / https://hamoid.com
  22888. */
  22889. THREE.DodecahedronGeometry = function ( radius, detail ) {
  22890. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  22891. var r = 1 / t;
  22892. var vertices = [
  22893. // (±1, ±1, ±1)
  22894. - 1, - 1, - 1, - 1, - 1, 1,
  22895. - 1, 1, - 1, - 1, 1, 1,
  22896. 1, - 1, - 1, 1, - 1, 1,
  22897. 1, 1, - 1, 1, 1, 1,
  22898. // (0, ±1/φ, ±φ)
  22899. 0, - r, - t, 0, - r, t,
  22900. 0, r, - t, 0, r, t,
  22901. // (±1/φ, ±φ, 0)
  22902. - r, - t, 0, - r, t, 0,
  22903. r, - t, 0, r, t, 0,
  22904. // (±φ, 0, ±1/φ)
  22905. - t, 0, - r, t, 0, - r,
  22906. - t, 0, r, t, 0, r
  22907. ];
  22908. var indices = [
  22909. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  22910. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  22911. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  22912. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  22913. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  22914. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  22915. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  22916. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  22917. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  22918. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  22919. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  22920. 1, 12, 14, 1, 14, 5, 1, 5, 9
  22921. ];
  22922. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  22923. this.type = 'DodecahedronGeometry';
  22924. this.parameters = {
  22925. radius: radius,
  22926. detail: detail
  22927. };
  22928. };
  22929. THREE.DodecahedronGeometry.prototype = Object.create( THREE.PolyhedronGeometry.prototype );
  22930. THREE.DodecahedronGeometry.prototype.constructor = THREE.DodecahedronGeometry;
  22931. // File:src/extras/geometries/IcosahedronGeometry.js
  22932. /**
  22933. * @author timothypratley / https://github.com/timothypratley
  22934. */
  22935. THREE.IcosahedronGeometry = function ( radius, detail ) {
  22936. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  22937. var vertices = [
  22938. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  22939. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  22940. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  22941. ];
  22942. var indices = [
  22943. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  22944. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  22945. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  22946. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  22947. ];
  22948. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  22949. this.type = 'IcosahedronGeometry';
  22950. this.parameters = {
  22951. radius: radius,
  22952. detail: detail
  22953. };
  22954. };
  22955. THREE.IcosahedronGeometry.prototype = Object.create( THREE.PolyhedronGeometry.prototype );
  22956. THREE.IcosahedronGeometry.prototype.constructor = THREE.IcosahedronGeometry;
  22957. // File:src/extras/geometries/OctahedronGeometry.js
  22958. /**
  22959. * @author timothypratley / https://github.com/timothypratley
  22960. */
  22961. THREE.OctahedronGeometry = function ( radius, detail ) {
  22962. var vertices = [
  22963. 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  22964. ];
  22965. var indices = [
  22966. 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2
  22967. ];
  22968. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  22969. this.type = 'OctahedronGeometry';
  22970. this.parameters = {
  22971. radius: radius,
  22972. detail: detail
  22973. };
  22974. };
  22975. THREE.OctahedronGeometry.prototype = Object.create( THREE.PolyhedronGeometry.prototype );
  22976. THREE.OctahedronGeometry.prototype.constructor = THREE.OctahedronGeometry;
  22977. // File:src/extras/geometries/TetrahedronGeometry.js
  22978. /**
  22979. * @author timothypratley / https://github.com/timothypratley
  22980. */
  22981. THREE.TetrahedronGeometry = function ( radius, detail ) {
  22982. var vertices = [
  22983. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  22984. ];
  22985. var indices = [
  22986. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  22987. ];
  22988. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  22989. this.type = 'TetrahedronGeometry';
  22990. this.parameters = {
  22991. radius: radius,
  22992. detail: detail
  22993. };
  22994. };
  22995. THREE.TetrahedronGeometry.prototype = Object.create( THREE.PolyhedronGeometry.prototype );
  22996. THREE.TetrahedronGeometry.prototype.constructor = THREE.TetrahedronGeometry;
  22997. // File:src/extras/geometries/ParametricGeometry.js
  22998. /**
  22999. * @author zz85 / https://github.com/zz85
  23000. * Parametric Surfaces Geometry
  23001. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  23002. *
  23003. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements );
  23004. *
  23005. */
  23006. THREE.ParametricGeometry = function ( func, slices, stacks ) {
  23007. THREE.Geometry.call( this );
  23008. this.type = 'ParametricGeometry';
  23009. this.parameters = {
  23010. func: func,
  23011. slices: slices,
  23012. stacks: stacks
  23013. };
  23014. var verts = this.vertices;
  23015. var faces = this.faces;
  23016. var uvs = this.faceVertexUvs[ 0 ];
  23017. var i, j, p;
  23018. var u, v;
  23019. var sliceCount = slices + 1;
  23020. for ( i = 0; i <= stacks; i ++ ) {
  23021. v = i / stacks;
  23022. for ( j = 0; j <= slices; j ++ ) {
  23023. u = j / slices;
  23024. p = func( u, v );
  23025. verts.push( p );
  23026. }
  23027. }
  23028. var a, b, c, d;
  23029. var uva, uvb, uvc, uvd;
  23030. for ( i = 0; i < stacks; i ++ ) {
  23031. for ( j = 0; j < slices; j ++ ) {
  23032. a = i * sliceCount + j;
  23033. b = i * sliceCount + j + 1;
  23034. c = ( i + 1 ) * sliceCount + j + 1;
  23035. d = ( i + 1 ) * sliceCount + j;
  23036. uva = new THREE.Vector2( j / slices, i / stacks );
  23037. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  23038. uvc = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  23039. uvd = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  23040. faces.push( new THREE.Face3( a, b, d ) );
  23041. uvs.push( [ uva, uvb, uvd ] );
  23042. faces.push( new THREE.Face3( b, c, d ) );
  23043. uvs.push( [ uvb.clone(), uvc, uvd.clone() ] );
  23044. }
  23045. }
  23046. // console.log(this);
  23047. // magic bullet
  23048. // var diff = this.mergeVertices();
  23049. // console.log('removed ', diff, ' vertices by merging');
  23050. this.computeFaceNormals();
  23051. this.computeVertexNormals();
  23052. };
  23053. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  23054. THREE.ParametricGeometry.prototype.constructor = THREE.ParametricGeometry;
  23055. // File:src/extras/geometries/WireframeGeometry.js
  23056. /**
  23057. * @author mrdoob / http://mrdoob.com/
  23058. */
  23059. THREE.WireframeGeometry = function ( geometry ) {
  23060. THREE.BufferGeometry.call( this );
  23061. var edge = [ 0, 0 ], hash = {};
  23062. function sortFunction( a, b ) {
  23063. return a - b;
  23064. }
  23065. var keys = [ 'a', 'b', 'c' ];
  23066. if ( geometry instanceof THREE.Geometry ) {
  23067. var vertices = geometry.vertices;
  23068. var faces = geometry.faces;
  23069. var numEdges = 0;
  23070. // allocate maximal size
  23071. var edges = new Uint32Array( 6 * faces.length );
  23072. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  23073. var face = faces[ i ];
  23074. for ( var j = 0; j < 3; j ++ ) {
  23075. edge[ 0 ] = face[ keys[ j ] ];
  23076. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  23077. edge.sort( sortFunction );
  23078. var key = edge.toString();
  23079. if ( hash[ key ] === undefined ) {
  23080. edges[ 2 * numEdges ] = edge[ 0 ];
  23081. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  23082. hash[ key ] = true;
  23083. numEdges ++;
  23084. }
  23085. }
  23086. }
  23087. var coords = new Float32Array( numEdges * 2 * 3 );
  23088. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  23089. for ( var j = 0; j < 2; j ++ ) {
  23090. var vertex = vertices[ edges [ 2 * i + j ] ];
  23091. var index = 6 * i + 3 * j;
  23092. coords[ index + 0 ] = vertex.x;
  23093. coords[ index + 1 ] = vertex.y;
  23094. coords[ index + 2 ] = vertex.z;
  23095. }
  23096. }
  23097. this.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  23098. } else if ( geometry instanceof THREE.BufferGeometry ) {
  23099. if ( geometry.index !== null ) {
  23100. // Indexed BufferGeometry
  23101. var indices = geometry.index.array;
  23102. var vertices = geometry.attributes.position;
  23103. var groups = geometry.groups;
  23104. var numEdges = 0;
  23105. if ( groups.length === 0 ) {
  23106. geometry.addGroup( 0, indices.length );
  23107. }
  23108. // allocate maximal size
  23109. var edges = new Uint32Array( 2 * indices.length );
  23110. for ( var o = 0, ol = groups.length; o < ol; ++ o ) {
  23111. var group = groups[ o ];
  23112. var start = group.start;
  23113. var count = group.count;
  23114. for ( var i = start, il = start + count; i < il; i += 3 ) {
  23115. for ( var j = 0; j < 3; j ++ ) {
  23116. edge[ 0 ] = indices[ i + j ];
  23117. edge[ 1 ] = indices[ i + ( j + 1 ) % 3 ];
  23118. edge.sort( sortFunction );
  23119. var key = edge.toString();
  23120. if ( hash[ key ] === undefined ) {
  23121. edges[ 2 * numEdges ] = edge[ 0 ];
  23122. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  23123. hash[ key ] = true;
  23124. numEdges ++;
  23125. }
  23126. }
  23127. }
  23128. }
  23129. var coords = new Float32Array( numEdges * 2 * 3 );
  23130. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  23131. for ( var j = 0; j < 2; j ++ ) {
  23132. var index = 6 * i + 3 * j;
  23133. var index2 = edges[ 2 * i + j ];
  23134. coords[ index + 0 ] = vertices.getX( index2 );
  23135. coords[ index + 1 ] = vertices.getY( index2 );
  23136. coords[ index + 2 ] = vertices.getZ( index2 );
  23137. }
  23138. }
  23139. this.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  23140. } else {
  23141. // non-indexed BufferGeometry
  23142. var vertices = geometry.attributes.position.array;
  23143. var numEdges = vertices.length / 3;
  23144. var numTris = numEdges / 3;
  23145. var coords = new Float32Array( numEdges * 2 * 3 );
  23146. for ( var i = 0, l = numTris; i < l; i ++ ) {
  23147. for ( var j = 0; j < 3; j ++ ) {
  23148. var index = 18 * i + 6 * j;
  23149. var index1 = 9 * i + 3 * j;
  23150. coords[ index + 0 ] = vertices[ index1 ];
  23151. coords[ index + 1 ] = vertices[ index1 + 1 ];
  23152. coords[ index + 2 ] = vertices[ index1 + 2 ];
  23153. var index2 = 9 * i + 3 * ( ( j + 1 ) % 3 );
  23154. coords[ index + 3 ] = vertices[ index2 ];
  23155. coords[ index + 4 ] = vertices[ index2 + 1 ];
  23156. coords[ index + 5 ] = vertices[ index2 + 2 ];
  23157. }
  23158. }
  23159. this.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  23160. }
  23161. }
  23162. };
  23163. THREE.WireframeGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  23164. THREE.WireframeGeometry.prototype.constructor = THREE.WireframeGeometry;
  23165. // File:src/extras/helpers/AxisHelper.js
  23166. /**
  23167. * @author sroucheray / http://sroucheray.org/
  23168. * @author mrdoob / http://mrdoob.com/
  23169. */
  23170. THREE.AxisHelper = function ( size ) {
  23171. size = size || 1;
  23172. var vertices = new Float32Array( [
  23173. 0, 0, 0, size, 0, 0,
  23174. 0, 0, 0, 0, size, 0,
  23175. 0, 0, 0, 0, 0, size
  23176. ] );
  23177. var colors = new Float32Array( [
  23178. 1, 0, 0, 1, 0.6, 0,
  23179. 0, 1, 0, 0.6, 1, 0,
  23180. 0, 0, 1, 0, 0.6, 1
  23181. ] );
  23182. var geometry = new THREE.BufferGeometry();
  23183. geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  23184. geometry.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) );
  23185. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  23186. THREE.LineSegments.call( this, geometry, material );
  23187. };
  23188. THREE.AxisHelper.prototype = Object.create( THREE.LineSegments.prototype );
  23189. THREE.AxisHelper.prototype.constructor = THREE.AxisHelper;
  23190. // File:src/extras/helpers/ArrowHelper.js
  23191. /**
  23192. * @author WestLangley / http://github.com/WestLangley
  23193. * @author zz85 / http://github.com/zz85
  23194. * @author bhouston / http://clara.io
  23195. *
  23196. * Creates an arrow for visualizing directions
  23197. *
  23198. * Parameters:
  23199. * dir - Vector3
  23200. * origin - Vector3
  23201. * length - Number
  23202. * color - color in hex value
  23203. * headLength - Number
  23204. * headWidth - Number
  23205. */
  23206. THREE.ArrowHelper = ( function () {
  23207. var lineGeometry = new THREE.Geometry();
  23208. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, 1, 0 ) );
  23209. var coneGeometry = new THREE.CylinderGeometry( 0, 0.5, 1, 5, 1 );
  23210. coneGeometry.translate( 0, - 0.5, 0 );
  23211. return function ArrowHelper( dir, origin, length, color, headLength, headWidth ) {
  23212. // dir is assumed to be normalized
  23213. THREE.Object3D.call( this );
  23214. if ( color === undefined ) color = 0xffff00;
  23215. if ( length === undefined ) length = 1;
  23216. if ( headLength === undefined ) headLength = 0.2 * length;
  23217. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  23218. this.position.copy( origin );
  23219. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: color } ) );
  23220. this.line.matrixAutoUpdate = false;
  23221. this.add( this.line );
  23222. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: color } ) );
  23223. this.cone.matrixAutoUpdate = false;
  23224. this.add( this.cone );
  23225. this.setDirection( dir );
  23226. this.setLength( length, headLength, headWidth );
  23227. }
  23228. }() );
  23229. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  23230. THREE.ArrowHelper.prototype.constructor = THREE.ArrowHelper;
  23231. THREE.ArrowHelper.prototype.setDirection = ( function () {
  23232. var axis = new THREE.Vector3();
  23233. var radians;
  23234. return function setDirection( dir ) {
  23235. // dir is assumed to be normalized
  23236. if ( dir.y > 0.99999 ) {
  23237. this.quaternion.set( 0, 0, 0, 1 );
  23238. } else if ( dir.y < - 0.99999 ) {
  23239. this.quaternion.set( 1, 0, 0, 0 );
  23240. } else {
  23241. axis.set( dir.z, 0, - dir.x ).normalize();
  23242. radians = Math.acos( dir.y );
  23243. this.quaternion.setFromAxisAngle( axis, radians );
  23244. }
  23245. };
  23246. }() );
  23247. THREE.ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  23248. if ( headLength === undefined ) headLength = 0.2 * length;
  23249. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  23250. this.line.scale.set( 1, Math.max( 0, length - headLength ), 1 );
  23251. this.line.updateMatrix();
  23252. this.cone.scale.set( headWidth, headLength, headWidth );
  23253. this.cone.position.y = length;
  23254. this.cone.updateMatrix();
  23255. };
  23256. THREE.ArrowHelper.prototype.setColor = function ( color ) {
  23257. this.line.material.color.set( color );
  23258. this.cone.material.color.set( color );
  23259. };
  23260. // File:src/extras/helpers/BoxHelper.js
  23261. /**
  23262. * @author mrdoob / http://mrdoob.com/
  23263. */
  23264. THREE.BoxHelper = function ( object ) {
  23265. 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 ] );
  23266. var positions = new Float32Array( 8 * 3 );
  23267. var geometry = new THREE.BufferGeometry();
  23268. geometry.setIndex( new THREE.BufferAttribute( indices, 1 ) );
  23269. geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
  23270. THREE.LineSegments.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffff00 } ) );
  23271. if ( object !== undefined ) {
  23272. this.update( object );
  23273. }
  23274. };
  23275. THREE.BoxHelper.prototype = Object.create( THREE.LineSegments.prototype );
  23276. THREE.BoxHelper.prototype.constructor = THREE.BoxHelper;
  23277. THREE.BoxHelper.prototype.update = ( function () {
  23278. var box = new THREE.Box3();
  23279. return function ( object ) {
  23280. box.setFromObject( object );
  23281. if ( box.empty() ) return;
  23282. var min = box.min;
  23283. var max = box.max;
  23284. /*
  23285. 5____4
  23286. 1/___0/|
  23287. | 6__|_7
  23288. 2/___3/
  23289. 0: max.x, max.y, max.z
  23290. 1: min.x, max.y, max.z
  23291. 2: min.x, min.y, max.z
  23292. 3: max.x, min.y, max.z
  23293. 4: max.x, max.y, min.z
  23294. 5: min.x, max.y, min.z
  23295. 6: min.x, min.y, min.z
  23296. 7: max.x, min.y, min.z
  23297. */
  23298. var position = this.geometry.attributes.position;
  23299. var array = position.array;
  23300. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  23301. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  23302. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  23303. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  23304. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  23305. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  23306. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  23307. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  23308. position.needsUpdate = true;
  23309. this.geometry.computeBoundingSphere();
  23310. }
  23311. } )();
  23312. // File:src/extras/helpers/BoundingBoxHelper.js
  23313. /**
  23314. * @author WestLangley / http://github.com/WestLangley
  23315. */
  23316. // a helper to show the world-axis-aligned bounding box for an object
  23317. THREE.BoundingBoxHelper = function ( object, hex ) {
  23318. var color = ( hex !== undefined ) ? hex : 0x888888;
  23319. this.object = object;
  23320. this.box = new THREE.Box3();
  23321. THREE.Mesh.call( this, new THREE.BoxGeometry( 1, 1, 1 ), new THREE.MeshBasicMaterial( { color: color, wireframe: true } ) );
  23322. };
  23323. THREE.BoundingBoxHelper.prototype = Object.create( THREE.Mesh.prototype );
  23324. THREE.BoundingBoxHelper.prototype.constructor = THREE.BoundingBoxHelper;
  23325. THREE.BoundingBoxHelper.prototype.update = function () {
  23326. this.box.setFromObject( this.object );
  23327. this.box.size( this.scale );
  23328. this.box.center( this.position );
  23329. };
  23330. // File:src/extras/helpers/CameraHelper.js
  23331. /**
  23332. * @author alteredq / http://alteredqualia.com/
  23333. *
  23334. * - shows frustum, line of sight and up of the camera
  23335. * - suitable for fast updates
  23336. * - based on frustum visualization in lightgl.js shadowmap example
  23337. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  23338. */
  23339. THREE.CameraHelper = function ( camera ) {
  23340. var geometry = new THREE.Geometry();
  23341. var material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  23342. var pointMap = {};
  23343. // colors
  23344. var hexFrustum = 0xffaa00;
  23345. var hexCone = 0xff0000;
  23346. var hexUp = 0x00aaff;
  23347. var hexTarget = 0xffffff;
  23348. var hexCross = 0x333333;
  23349. // near
  23350. addLine( "n1", "n2", hexFrustum );
  23351. addLine( "n2", "n4", hexFrustum );
  23352. addLine( "n4", "n3", hexFrustum );
  23353. addLine( "n3", "n1", hexFrustum );
  23354. // far
  23355. addLine( "f1", "f2", hexFrustum );
  23356. addLine( "f2", "f4", hexFrustum );
  23357. addLine( "f4", "f3", hexFrustum );
  23358. addLine( "f3", "f1", hexFrustum );
  23359. // sides
  23360. addLine( "n1", "f1", hexFrustum );
  23361. addLine( "n2", "f2", hexFrustum );
  23362. addLine( "n3", "f3", hexFrustum );
  23363. addLine( "n4", "f4", hexFrustum );
  23364. // cone
  23365. addLine( "p", "n1", hexCone );
  23366. addLine( "p", "n2", hexCone );
  23367. addLine( "p", "n3", hexCone );
  23368. addLine( "p", "n4", hexCone );
  23369. // up
  23370. addLine( "u1", "u2", hexUp );
  23371. addLine( "u2", "u3", hexUp );
  23372. addLine( "u3", "u1", hexUp );
  23373. // target
  23374. addLine( "c", "t", hexTarget );
  23375. addLine( "p", "c", hexCross );
  23376. // cross
  23377. addLine( "cn1", "cn2", hexCross );
  23378. addLine( "cn3", "cn4", hexCross );
  23379. addLine( "cf1", "cf2", hexCross );
  23380. addLine( "cf3", "cf4", hexCross );
  23381. function addLine( a, b, hex ) {
  23382. addPoint( a, hex );
  23383. addPoint( b, hex );
  23384. }
  23385. function addPoint( id, hex ) {
  23386. geometry.vertices.push( new THREE.Vector3() );
  23387. geometry.colors.push( new THREE.Color( hex ) );
  23388. if ( pointMap[ id ] === undefined ) {
  23389. pointMap[ id ] = [];
  23390. }
  23391. pointMap[ id ].push( geometry.vertices.length - 1 );
  23392. }
  23393. THREE.LineSegments.call( this, geometry, material );
  23394. this.camera = camera;
  23395. this.camera.updateProjectionMatrix();
  23396. this.matrix = camera.matrixWorld;
  23397. this.matrixAutoUpdate = false;
  23398. this.pointMap = pointMap;
  23399. this.update();
  23400. };
  23401. THREE.CameraHelper.prototype = Object.create( THREE.LineSegments.prototype );
  23402. THREE.CameraHelper.prototype.constructor = THREE.CameraHelper;
  23403. THREE.CameraHelper.prototype.update = function () {
  23404. var geometry, pointMap;
  23405. var vector = new THREE.Vector3();
  23406. var camera = new THREE.Camera();
  23407. function setPoint( point, x, y, z ) {
  23408. vector.set( x, y, z ).unproject( camera );
  23409. var points = pointMap[ point ];
  23410. if ( points !== undefined ) {
  23411. for ( var i = 0, il = points.length; i < il; i ++ ) {
  23412. geometry.vertices[ points[ i ] ].copy( vector );
  23413. }
  23414. }
  23415. }
  23416. return function () {
  23417. geometry = this.geometry;
  23418. pointMap = this.pointMap;
  23419. var w = 1, h = 1;
  23420. // we need just camera projection matrix
  23421. // world matrix must be identity
  23422. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  23423. // center / target
  23424. setPoint( "c", 0, 0, - 1 );
  23425. setPoint( "t", 0, 0, 1 );
  23426. // near
  23427. setPoint( "n1", - w, - h, - 1 );
  23428. setPoint( "n2", w, - h, - 1 );
  23429. setPoint( "n3", - w, h, - 1 );
  23430. setPoint( "n4", w, h, - 1 );
  23431. // far
  23432. setPoint( "f1", - w, - h, 1 );
  23433. setPoint( "f2", w, - h, 1 );
  23434. setPoint( "f3", - w, h, 1 );
  23435. setPoint( "f4", w, h, 1 );
  23436. // up
  23437. setPoint( "u1", w * 0.7, h * 1.1, - 1 );
  23438. setPoint( "u2", - w * 0.7, h * 1.1, - 1 );
  23439. setPoint( "u3", 0, h * 2, - 1 );
  23440. // cross
  23441. setPoint( "cf1", - w, 0, 1 );
  23442. setPoint( "cf2", w, 0, 1 );
  23443. setPoint( "cf3", 0, - h, 1 );
  23444. setPoint( "cf4", 0, h, 1 );
  23445. setPoint( "cn1", - w, 0, - 1 );
  23446. setPoint( "cn2", w, 0, - 1 );
  23447. setPoint( "cn3", 0, - h, - 1 );
  23448. setPoint( "cn4", 0, h, - 1 );
  23449. geometry.verticesNeedUpdate = true;
  23450. };
  23451. }();
  23452. // File:src/extras/helpers/DirectionalLightHelper.js
  23453. /**
  23454. * @author alteredq / http://alteredqualia.com/
  23455. * @author mrdoob / http://mrdoob.com/
  23456. * @author WestLangley / http://github.com/WestLangley
  23457. */
  23458. THREE.DirectionalLightHelper = function ( light, size ) {
  23459. THREE.Object3D.call( this );
  23460. this.light = light;
  23461. this.light.updateMatrixWorld();
  23462. this.matrix = light.matrixWorld;
  23463. this.matrixAutoUpdate = false;
  23464. size = size || 1;
  23465. var geometry = new THREE.Geometry();
  23466. geometry.vertices.push(
  23467. new THREE.Vector3( - size, size, 0 ),
  23468. new THREE.Vector3( size, size, 0 ),
  23469. new THREE.Vector3( size, - size, 0 ),
  23470. new THREE.Vector3( - size, - size, 0 ),
  23471. new THREE.Vector3( - size, size, 0 )
  23472. );
  23473. var material = new THREE.LineBasicMaterial( { fog: false } );
  23474. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  23475. this.lightPlane = new THREE.Line( geometry, material );
  23476. this.add( this.lightPlane );
  23477. geometry = new THREE.Geometry();
  23478. geometry.vertices.push(
  23479. new THREE.Vector3(),
  23480. new THREE.Vector3()
  23481. );
  23482. material = new THREE.LineBasicMaterial( { fog: false } );
  23483. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  23484. this.targetLine = new THREE.Line( geometry, material );
  23485. this.add( this.targetLine );
  23486. this.update();
  23487. };
  23488. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  23489. THREE.DirectionalLightHelper.prototype.constructor = THREE.DirectionalLightHelper;
  23490. THREE.DirectionalLightHelper.prototype.dispose = function () {
  23491. this.lightPlane.geometry.dispose();
  23492. this.lightPlane.material.dispose();
  23493. this.targetLine.geometry.dispose();
  23494. this.targetLine.material.dispose();
  23495. };
  23496. THREE.DirectionalLightHelper.prototype.update = function () {
  23497. var v1 = new THREE.Vector3();
  23498. var v2 = new THREE.Vector3();
  23499. var v3 = new THREE.Vector3();
  23500. return function () {
  23501. v1.setFromMatrixPosition( this.light.matrixWorld );
  23502. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  23503. v3.subVectors( v2, v1 );
  23504. this.lightPlane.lookAt( v3 );
  23505. this.lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  23506. this.targetLine.geometry.vertices[ 1 ].copy( v3 );
  23507. this.targetLine.geometry.verticesNeedUpdate = true;
  23508. this.targetLine.material.color.copy( this.lightPlane.material.color );
  23509. };
  23510. }();
  23511. // File:src/extras/helpers/EdgesHelper.js
  23512. /**
  23513. * @author WestLangley / http://github.com/WestLangley
  23514. * @param object THREE.Mesh whose geometry will be used
  23515. * @param hex line color
  23516. * @param thresholdAngle the minimum angle (in degrees),
  23517. * between the face normals of adjacent faces,
  23518. * that is required to render an edge. A value of 10 means
  23519. * an edge is only rendered if the angle is at least 10 degrees.
  23520. */
  23521. THREE.EdgesHelper = function ( object, hex, thresholdAngle ) {
  23522. var color = ( hex !== undefined ) ? hex : 0xffffff;
  23523. THREE.LineSegments.call( this, new THREE.EdgesGeometry( object.geometry, thresholdAngle ), new THREE.LineBasicMaterial( { color: color } ) );
  23524. this.matrix = object.matrixWorld;
  23525. this.matrixAutoUpdate = false;
  23526. };
  23527. THREE.EdgesHelper.prototype = Object.create( THREE.LineSegments.prototype );
  23528. THREE.EdgesHelper.prototype.constructor = THREE.EdgesHelper;
  23529. // File:src/extras/helpers/FaceNormalsHelper.js
  23530. /**
  23531. * @author mrdoob / http://mrdoob.com/
  23532. * @author WestLangley / http://github.com/WestLangley
  23533. */
  23534. THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) {
  23535. // FaceNormalsHelper only supports THREE.Geometry
  23536. this.object = object;
  23537. this.size = ( size !== undefined ) ? size : 1;
  23538. var color = ( hex !== undefined ) ? hex : 0xffff00;
  23539. var width = ( linewidth !== undefined ) ? linewidth : 1;
  23540. //
  23541. var nNormals = 0;
  23542. var objGeometry = this.object.geometry;
  23543. if ( objGeometry instanceof THREE.Geometry ) {
  23544. nNormals = objGeometry.faces.length;
  23545. } else {
  23546. console.warn( 'THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.' );
  23547. }
  23548. //
  23549. var geometry = new THREE.BufferGeometry();
  23550. var positions = new THREE.Float32Attribute( nNormals * 2 * 3, 3 );
  23551. geometry.addAttribute( 'position', positions );
  23552. THREE.LineSegments.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ) );
  23553. //
  23554. this.matrixAutoUpdate = false;
  23555. this.update();
  23556. };
  23557. THREE.FaceNormalsHelper.prototype = Object.create( THREE.LineSegments.prototype );
  23558. THREE.FaceNormalsHelper.prototype.constructor = THREE.FaceNormalsHelper;
  23559. THREE.FaceNormalsHelper.prototype.update = ( function () {
  23560. var v1 = new THREE.Vector3();
  23561. var v2 = new THREE.Vector3();
  23562. var normalMatrix = new THREE.Matrix3();
  23563. return function update() {
  23564. this.object.updateMatrixWorld( true );
  23565. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  23566. var matrixWorld = this.object.matrixWorld;
  23567. var position = this.geometry.attributes.position;
  23568. //
  23569. var objGeometry = this.object.geometry;
  23570. var vertices = objGeometry.vertices;
  23571. var faces = objGeometry.faces;
  23572. var idx = 0;
  23573. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  23574. var face = faces[ i ];
  23575. var normal = face.normal;
  23576. v1.copy( vertices[ face.a ] )
  23577. .add( vertices[ face.b ] )
  23578. .add( vertices[ face.c ] )
  23579. .divideScalar( 3 )
  23580. .applyMatrix4( matrixWorld );
  23581. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  23582. position.setXYZ( idx, v1.x, v1.y, v1.z );
  23583. idx = idx + 1;
  23584. position.setXYZ( idx, v2.x, v2.y, v2.z );
  23585. idx = idx + 1;
  23586. }
  23587. position.needsUpdate = true;
  23588. return this;
  23589. }
  23590. }() );
  23591. // File:src/extras/helpers/GridHelper.js
  23592. /**
  23593. * @author mrdoob / http://mrdoob.com/
  23594. */
  23595. THREE.GridHelper = function ( size, step ) {
  23596. var geometry = new THREE.Geometry();
  23597. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  23598. this.color1 = new THREE.Color( 0x444444 );
  23599. this.color2 = new THREE.Color( 0x888888 );
  23600. for ( var i = - size; i <= size; i += step ) {
  23601. geometry.vertices.push(
  23602. new THREE.Vector3( - size, 0, i ), new THREE.Vector3( size, 0, i ),
  23603. new THREE.Vector3( i, 0, - size ), new THREE.Vector3( i, 0, size )
  23604. );
  23605. var color = i === 0 ? this.color1 : this.color2;
  23606. geometry.colors.push( color, color, color, color );
  23607. }
  23608. THREE.LineSegments.call( this, geometry, material );
  23609. };
  23610. THREE.GridHelper.prototype = Object.create( THREE.LineSegments.prototype );
  23611. THREE.GridHelper.prototype.constructor = THREE.GridHelper;
  23612. THREE.GridHelper.prototype.setColors = function( colorCenterLine, colorGrid ) {
  23613. this.color1.set( colorCenterLine );
  23614. this.color2.set( colorGrid );
  23615. this.geometry.colorsNeedUpdate = true;
  23616. };
  23617. // File:src/extras/helpers/HemisphereLightHelper.js
  23618. /**
  23619. * @author alteredq / http://alteredqualia.com/
  23620. * @author mrdoob / http://mrdoob.com/
  23621. */
  23622. THREE.HemisphereLightHelper = function ( light, sphereSize ) {
  23623. THREE.Object3D.call( this );
  23624. this.light = light;
  23625. this.light.updateMatrixWorld();
  23626. this.matrix = light.matrixWorld;
  23627. this.matrixAutoUpdate = false;
  23628. this.colors = [ new THREE.Color(), new THREE.Color() ];
  23629. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  23630. geometry.rotateX( - Math.PI / 2 );
  23631. for ( var i = 0, il = 8; i < il; i ++ ) {
  23632. geometry.faces[ i ].color = this.colors[ i < 4 ? 0 : 1 ];
  23633. }
  23634. var material = new THREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors, wireframe: true } );
  23635. this.lightSphere = new THREE.Mesh( geometry, material );
  23636. this.add( this.lightSphere );
  23637. this.update();
  23638. };
  23639. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  23640. THREE.HemisphereLightHelper.prototype.constructor = THREE.HemisphereLightHelper;
  23641. THREE.HemisphereLightHelper.prototype.dispose = function () {
  23642. this.lightSphere.geometry.dispose();
  23643. this.lightSphere.material.dispose();
  23644. };
  23645. THREE.HemisphereLightHelper.prototype.update = function () {
  23646. var vector = new THREE.Vector3();
  23647. return function () {
  23648. this.colors[ 0 ].copy( this.light.color ).multiplyScalar( this.light.intensity );
  23649. this.colors[ 1 ].copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  23650. this.lightSphere.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  23651. this.lightSphere.geometry.colorsNeedUpdate = true;
  23652. }
  23653. }();
  23654. // File:src/extras/helpers/PointLightHelper.js
  23655. /**
  23656. * @author alteredq / http://alteredqualia.com/
  23657. * @author mrdoob / http://mrdoob.com/
  23658. */
  23659. THREE.PointLightHelper = function ( light, sphereSize ) {
  23660. this.light = light;
  23661. this.light.updateMatrixWorld();
  23662. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  23663. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  23664. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  23665. THREE.Mesh.call( this, geometry, material );
  23666. this.matrix = this.light.matrixWorld;
  23667. this.matrixAutoUpdate = false;
  23668. /*
  23669. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  23670. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  23671. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  23672. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  23673. var d = light.distance;
  23674. if ( d === 0.0 ) {
  23675. this.lightDistance.visible = false;
  23676. } else {
  23677. this.lightDistance.scale.set( d, d, d );
  23678. }
  23679. this.add( this.lightDistance );
  23680. */
  23681. };
  23682. THREE.PointLightHelper.prototype = Object.create( THREE.Mesh.prototype );
  23683. THREE.PointLightHelper.prototype.constructor = THREE.PointLightHelper;
  23684. THREE.PointLightHelper.prototype.dispose = function () {
  23685. this.geometry.dispose();
  23686. this.material.dispose();
  23687. };
  23688. THREE.PointLightHelper.prototype.update = function () {
  23689. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  23690. /*
  23691. var d = this.light.distance;
  23692. if ( d === 0.0 ) {
  23693. this.lightDistance.visible = false;
  23694. } else {
  23695. this.lightDistance.visible = true;
  23696. this.lightDistance.scale.set( d, d, d );
  23697. }
  23698. */
  23699. };
  23700. // File:src/extras/helpers/SkeletonHelper.js
  23701. /**
  23702. * @author Sean Griffin / http://twitter.com/sgrif
  23703. * @author Michael Guerrero / http://realitymeltdown.com
  23704. * @author mrdoob / http://mrdoob.com/
  23705. * @author ikerr / http://verold.com
  23706. */
  23707. THREE.SkeletonHelper = function ( object ) {
  23708. this.bones = this.getBoneList( object );
  23709. var geometry = new THREE.Geometry();
  23710. for ( var i = 0; i < this.bones.length; i ++ ) {
  23711. var bone = this.bones[ i ];
  23712. if ( bone.parent instanceof THREE.Bone ) {
  23713. geometry.vertices.push( new THREE.Vector3() );
  23714. geometry.vertices.push( new THREE.Vector3() );
  23715. geometry.colors.push( new THREE.Color( 0, 0, 1 ) );
  23716. geometry.colors.push( new THREE.Color( 0, 1, 0 ) );
  23717. }
  23718. }
  23719. geometry.dynamic = true;
  23720. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors, depthTest: false, depthWrite: false, transparent: true } );
  23721. THREE.LineSegments.call( this, geometry, material );
  23722. this.root = object;
  23723. this.matrix = object.matrixWorld;
  23724. this.matrixAutoUpdate = false;
  23725. this.update();
  23726. };
  23727. THREE.SkeletonHelper.prototype = Object.create( THREE.LineSegments.prototype );
  23728. THREE.SkeletonHelper.prototype.constructor = THREE.SkeletonHelper;
  23729. THREE.SkeletonHelper.prototype.getBoneList = function( object ) {
  23730. var boneList = [];
  23731. if ( object instanceof THREE.Bone ) {
  23732. boneList.push( object );
  23733. }
  23734. for ( var i = 0; i < object.children.length; i ++ ) {
  23735. boneList.push.apply( boneList, this.getBoneList( object.children[ i ] ) );
  23736. }
  23737. return boneList;
  23738. };
  23739. THREE.SkeletonHelper.prototype.update = function () {
  23740. var geometry = this.geometry;
  23741. var matrixWorldInv = new THREE.Matrix4().getInverse( this.root.matrixWorld );
  23742. var boneMatrix = new THREE.Matrix4();
  23743. var j = 0;
  23744. for ( var i = 0; i < this.bones.length; i ++ ) {
  23745. var bone = this.bones[ i ];
  23746. if ( bone.parent instanceof THREE.Bone ) {
  23747. boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld );
  23748. geometry.vertices[ j ].setFromMatrixPosition( boneMatrix );
  23749. boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld );
  23750. geometry.vertices[ j + 1 ].setFromMatrixPosition( boneMatrix );
  23751. j += 2;
  23752. }
  23753. }
  23754. geometry.verticesNeedUpdate = true;
  23755. geometry.computeBoundingSphere();
  23756. };
  23757. // File:src/extras/helpers/SpotLightHelper.js
  23758. /**
  23759. * @author alteredq / http://alteredqualia.com/
  23760. * @author mrdoob / http://mrdoob.com/
  23761. * @author WestLangley / http://github.com/WestLangley
  23762. */
  23763. THREE.SpotLightHelper = function ( light ) {
  23764. THREE.Object3D.call( this );
  23765. this.light = light;
  23766. this.light.updateMatrixWorld();
  23767. this.matrix = light.matrixWorld;
  23768. this.matrixAutoUpdate = false;
  23769. var geometry = new THREE.CylinderGeometry( 0, 1, 1, 8, 1, true );
  23770. geometry.translate( 0, - 0.5, 0 );
  23771. geometry.rotateX( - Math.PI / 2 );
  23772. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  23773. this.cone = new THREE.Mesh( geometry, material );
  23774. this.add( this.cone );
  23775. this.update();
  23776. };
  23777. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  23778. THREE.SpotLightHelper.prototype.constructor = THREE.SpotLightHelper;
  23779. THREE.SpotLightHelper.prototype.dispose = function () {
  23780. this.cone.geometry.dispose();
  23781. this.cone.material.dispose();
  23782. };
  23783. THREE.SpotLightHelper.prototype.update = function () {
  23784. var vector = new THREE.Vector3();
  23785. var vector2 = new THREE.Vector3();
  23786. return function () {
  23787. var coneLength = this.light.distance ? this.light.distance : 10000;
  23788. var coneWidth = coneLength * Math.tan( this.light.angle );
  23789. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  23790. vector.setFromMatrixPosition( this.light.matrixWorld );
  23791. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  23792. this.cone.lookAt( vector2.sub( vector ) );
  23793. this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  23794. };
  23795. }();
  23796. // File:src/extras/helpers/VertexNormalsHelper.js
  23797. /**
  23798. * @author mrdoob / http://mrdoob.com/
  23799. * @author WestLangley / http://github.com/WestLangley
  23800. */
  23801. THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) {
  23802. this.object = object;
  23803. this.size = ( size !== undefined ) ? size : 1;
  23804. var color = ( hex !== undefined ) ? hex : 0xff0000;
  23805. var width = ( linewidth !== undefined ) ? linewidth : 1;
  23806. //
  23807. var nNormals = 0;
  23808. var objGeometry = this.object.geometry;
  23809. if ( objGeometry instanceof THREE.Geometry ) {
  23810. nNormals = objGeometry.faces.length * 3;
  23811. } else if ( objGeometry instanceof THREE.BufferGeometry ) {
  23812. nNormals = objGeometry.attributes.normal.count
  23813. }
  23814. //
  23815. var geometry = new THREE.BufferGeometry();
  23816. var positions = new THREE.Float32Attribute( nNormals * 2 * 3, 3 );
  23817. geometry.addAttribute( 'position', positions );
  23818. THREE.LineSegments.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ) );
  23819. //
  23820. this.matrixAutoUpdate = false;
  23821. this.update();
  23822. };
  23823. THREE.VertexNormalsHelper.prototype = Object.create( THREE.LineSegments.prototype );
  23824. THREE.VertexNormalsHelper.prototype.constructor = THREE.VertexNormalsHelper;
  23825. THREE.VertexNormalsHelper.prototype.update = ( function () {
  23826. var v1 = new THREE.Vector3();
  23827. var v2 = new THREE.Vector3();
  23828. var normalMatrix = new THREE.Matrix3();
  23829. return function update() {
  23830. var keys = [ 'a', 'b', 'c' ];
  23831. this.object.updateMatrixWorld( true );
  23832. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  23833. var matrixWorld = this.object.matrixWorld;
  23834. var position = this.geometry.attributes.position;
  23835. //
  23836. var objGeometry = this.object.geometry;
  23837. if ( objGeometry instanceof THREE.Geometry ) {
  23838. var vertices = objGeometry.vertices;
  23839. var faces = objGeometry.faces;
  23840. var idx = 0;
  23841. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  23842. var face = faces[ i ];
  23843. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  23844. var vertex = vertices[ face[ keys[ j ] ] ];
  23845. var normal = face.vertexNormals[ j ];
  23846. v1.copy( vertex ).applyMatrix4( matrixWorld );
  23847. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  23848. position.setXYZ( idx, v1.x, v1.y, v1.z );
  23849. idx = idx + 1;
  23850. position.setXYZ( idx, v2.x, v2.y, v2.z );
  23851. idx = idx + 1;
  23852. }
  23853. }
  23854. } else if ( objGeometry instanceof THREE.BufferGeometry ) {
  23855. var objPos = objGeometry.attributes.position;
  23856. var objNorm = objGeometry.attributes.normal;
  23857. var idx = 0;
  23858. // for simplicity, ignore index and drawcalls, and render every normal
  23859. for ( var j = 0, jl = objPos.count; j < jl; j ++ ) {
  23860. v1.set( objPos.getX( j ), objPos.getY( j ), objPos.getZ( j ) ).applyMatrix4( matrixWorld );
  23861. v2.set( objNorm.getX( j ), objNorm.getY( j ), objNorm.getZ( j ) );
  23862. v2.applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  23863. position.setXYZ( idx, v1.x, v1.y, v1.z );
  23864. idx = idx + 1;
  23865. position.setXYZ( idx, v2.x, v2.y, v2.z );
  23866. idx = idx + 1;
  23867. }
  23868. }
  23869. position.needsUpdate = true;
  23870. return this;
  23871. }
  23872. }() );
  23873. // File:src/extras/helpers/WireframeHelper.js
  23874. /**
  23875. * @author mrdoob / http://mrdoob.com/
  23876. */
  23877. THREE.WireframeHelper = function ( object, hex ) {
  23878. var color = ( hex !== undefined ) ? hex : 0xffffff;
  23879. THREE.LineSegments.call( this, new THREE.WireframeGeometry( object.geometry ), new THREE.LineBasicMaterial( { color: color } ) );
  23880. this.matrix = object.matrixWorld;
  23881. this.matrixAutoUpdate = false;
  23882. };
  23883. THREE.WireframeHelper.prototype = Object.create( THREE.LineSegments.prototype );
  23884. THREE.WireframeHelper.prototype.constructor = THREE.WireframeHelper;
  23885. // File:src/extras/objects/ImmediateRenderObject.js
  23886. /**
  23887. * @author alteredq / http://alteredqualia.com/
  23888. */
  23889. THREE.ImmediateRenderObject = function ( material ) {
  23890. THREE.Object3D.call( this );
  23891. this.material = material;
  23892. this.render = function ( renderCallback ) {};
  23893. };
  23894. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  23895. THREE.ImmediateRenderObject.prototype.constructor = THREE.ImmediateRenderObject;
  23896. // File:src/extras/objects/MorphBlendMesh.js
  23897. /**
  23898. * @author alteredq / http://alteredqualia.com/
  23899. */
  23900. THREE.MorphBlendMesh = function( geometry, material ) {
  23901. THREE.Mesh.call( this, geometry, material );
  23902. this.animationsMap = {};
  23903. this.animationsList = [];
  23904. // prepare default animation
  23905. // (all frames played together in 1 second)
  23906. var numFrames = this.geometry.morphTargets.length;
  23907. var name = "__default";
  23908. var startFrame = 0;
  23909. var endFrame = numFrames - 1;
  23910. var fps = numFrames / 1;
  23911. this.createAnimation( name, startFrame, endFrame, fps );
  23912. this.setAnimationWeight( name, 1 );
  23913. };
  23914. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  23915. THREE.MorphBlendMesh.prototype.constructor = THREE.MorphBlendMesh;
  23916. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  23917. var animation = {
  23918. start: start,
  23919. end: end,
  23920. length: end - start + 1,
  23921. fps: fps,
  23922. duration: ( end - start ) / fps,
  23923. lastFrame: 0,
  23924. currentFrame: 0,
  23925. active: false,
  23926. time: 0,
  23927. direction: 1,
  23928. weight: 1,
  23929. directionBackwards: false,
  23930. mirroredLoop: false
  23931. };
  23932. this.animationsMap[ name ] = animation;
  23933. this.animationsList.push( animation );
  23934. };
  23935. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  23936. var pattern = /([a-z]+)_?(\d+)/i;
  23937. var firstAnimation, frameRanges = {};
  23938. var geometry = this.geometry;
  23939. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  23940. var morph = geometry.morphTargets[ i ];
  23941. var chunks = morph.name.match( pattern );
  23942. if ( chunks && chunks.length > 1 ) {
  23943. var name = chunks[ 1 ];
  23944. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: - Infinity };
  23945. var range = frameRanges[ name ];
  23946. if ( i < range.start ) range.start = i;
  23947. if ( i > range.end ) range.end = i;
  23948. if ( ! firstAnimation ) firstAnimation = name;
  23949. }
  23950. }
  23951. for ( var name in frameRanges ) {
  23952. var range = frameRanges[ name ];
  23953. this.createAnimation( name, range.start, range.end, fps );
  23954. }
  23955. this.firstAnimation = firstAnimation;
  23956. };
  23957. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  23958. var animation = this.animationsMap[ name ];
  23959. if ( animation ) {
  23960. animation.direction = 1;
  23961. animation.directionBackwards = false;
  23962. }
  23963. };
  23964. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  23965. var animation = this.animationsMap[ name ];
  23966. if ( animation ) {
  23967. animation.direction = - 1;
  23968. animation.directionBackwards = true;
  23969. }
  23970. };
  23971. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  23972. var animation = this.animationsMap[ name ];
  23973. if ( animation ) {
  23974. animation.fps = fps;
  23975. animation.duration = ( animation.end - animation.start ) / animation.fps;
  23976. }
  23977. };
  23978. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  23979. var animation = this.animationsMap[ name ];
  23980. if ( animation ) {
  23981. animation.duration = duration;
  23982. animation.fps = ( animation.end - animation.start ) / animation.duration;
  23983. }
  23984. };
  23985. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  23986. var animation = this.animationsMap[ name ];
  23987. if ( animation ) {
  23988. animation.weight = weight;
  23989. }
  23990. };
  23991. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  23992. var animation = this.animationsMap[ name ];
  23993. if ( animation ) {
  23994. animation.time = time;
  23995. }
  23996. };
  23997. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  23998. var time = 0;
  23999. var animation = this.animationsMap[ name ];
  24000. if ( animation ) {
  24001. time = animation.time;
  24002. }
  24003. return time;
  24004. };
  24005. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  24006. var duration = - 1;
  24007. var animation = this.animationsMap[ name ];
  24008. if ( animation ) {
  24009. duration = animation.duration;
  24010. }
  24011. return duration;
  24012. };
  24013. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  24014. var animation = this.animationsMap[ name ];
  24015. if ( animation ) {
  24016. animation.time = 0;
  24017. animation.active = true;
  24018. } else {
  24019. console.warn( "THREE.MorphBlendMesh: animation[" + name + "] undefined in .playAnimation()" );
  24020. }
  24021. };
  24022. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  24023. var animation = this.animationsMap[ name ];
  24024. if ( animation ) {
  24025. animation.active = false;
  24026. }
  24027. };
  24028. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  24029. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  24030. var animation = this.animationsList[ i ];
  24031. if ( ! animation.active ) continue;
  24032. var frameTime = animation.duration / animation.length;
  24033. animation.time += animation.direction * delta;
  24034. if ( animation.mirroredLoop ) {
  24035. if ( animation.time > animation.duration || animation.time < 0 ) {
  24036. animation.direction *= - 1;
  24037. if ( animation.time > animation.duration ) {
  24038. animation.time = animation.duration;
  24039. animation.directionBackwards = true;
  24040. }
  24041. if ( animation.time < 0 ) {
  24042. animation.time = 0;
  24043. animation.directionBackwards = false;
  24044. }
  24045. }
  24046. } else {
  24047. animation.time = animation.time % animation.duration;
  24048. if ( animation.time < 0 ) animation.time += animation.duration;
  24049. }
  24050. var keyframe = animation.start + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  24051. var weight = animation.weight;
  24052. if ( keyframe !== animation.currentFrame ) {
  24053. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  24054. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  24055. this.morphTargetInfluences[ keyframe ] = 0;
  24056. animation.lastFrame = animation.currentFrame;
  24057. animation.currentFrame = keyframe;
  24058. }
  24059. var mix = ( animation.time % frameTime ) / frameTime;
  24060. if ( animation.directionBackwards ) mix = 1 - mix;
  24061. if ( animation.currentFrame !== animation.lastFrame ) {
  24062. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  24063. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  24064. } else {
  24065. this.morphTargetInfluences[ animation.currentFrame ] = weight;
  24066. }
  24067. }
  24068. };
粤ICP备19079148号