three.js 967 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  3. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4. (factory((global.THREE = global.THREE || {})));
  5. }(this, function (exports) { 'use strict';
  6. // Polyfills
  7. if ( Number.EPSILON === undefined ) {
  8. Number.EPSILON = Math.pow( 2, - 52 );
  9. }
  10. //
  11. if ( Math.sign === undefined ) {
  12. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
  13. Math.sign = function ( x ) {
  14. return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : + x;
  15. };
  16. }
  17. if ( Function.prototype.name === undefined ) {
  18. // Missing in IE9-11.
  19. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
  20. Object.defineProperty( Function.prototype, 'name', {
  21. get: function () {
  22. return this.toString().match( /^\s*function\s*(\S*)\s*\(/ )[ 1 ];
  23. }
  24. } );
  25. }
  26. if ( Object.assign === undefined ) {
  27. // Missing in IE.
  28. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
  29. ( function () {
  30. Object.assign = function ( target ) {
  31. 'use strict';
  32. if ( target === undefined || target === null ) {
  33. throw new TypeError( 'Cannot convert undefined or null to object' );
  34. }
  35. var output = Object( target );
  36. for ( var index = 1; index < arguments.length; index ++ ) {
  37. var source = arguments[ index ];
  38. if ( source !== undefined && source !== null ) {
  39. for ( var nextKey in source ) {
  40. if ( Object.prototype.hasOwnProperty.call( source, nextKey ) ) {
  41. output[ nextKey ] = source[ nextKey ];
  42. }
  43. }
  44. }
  45. }
  46. return output;
  47. };
  48. } )();
  49. }
  50. /**
  51. * https://github.com/mrdoob/eventdispatcher.js/
  52. */
  53. function EventDispatcher() {}
  54. Object.assign( EventDispatcher.prototype, {
  55. addEventListener: function ( type, listener ) {
  56. if ( this._listeners === undefined ) this._listeners = {};
  57. var listeners = this._listeners;
  58. if ( listeners[ type ] === undefined ) {
  59. listeners[ type ] = [];
  60. }
  61. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  62. listeners[ type ].push( listener );
  63. }
  64. },
  65. hasEventListener: function ( type, listener ) {
  66. if ( this._listeners === undefined ) return false;
  67. var listeners = this._listeners;
  68. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  69. return true;
  70. }
  71. return false;
  72. },
  73. removeEventListener: function ( type, listener ) {
  74. if ( this._listeners === undefined ) return;
  75. var listeners = this._listeners;
  76. var listenerArray = listeners[ type ];
  77. if ( listenerArray !== undefined ) {
  78. var index = listenerArray.indexOf( listener );
  79. if ( index !== - 1 ) {
  80. listenerArray.splice( index, 1 );
  81. }
  82. }
  83. },
  84. dispatchEvent: function ( event ) {
  85. if ( this._listeners === undefined ) return;
  86. var listeners = this._listeners;
  87. var listenerArray = listeners[ event.type ];
  88. if ( listenerArray !== undefined ) {
  89. event.target = this;
  90. var array = [], i = 0;
  91. var length = listenerArray.length;
  92. for ( i = 0; i < length; i ++ ) {
  93. array[ i ] = listenerArray[ i ];
  94. }
  95. for ( i = 0; i < length; i ++ ) {
  96. array[ i ].call( this, event );
  97. }
  98. }
  99. }
  100. } );
  101. var REVISION = '80dev';
  102. var MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2 };
  103. var CullFaceNone = 0;
  104. var CullFaceBack = 1;
  105. var CullFaceFront = 2;
  106. var CullFaceFrontBack = 3;
  107. var FrontFaceDirectionCW = 0;
  108. var FrontFaceDirectionCCW = 1;
  109. var BasicShadowMap = 0;
  110. var PCFShadowMap = 1;
  111. var PCFSoftShadowMap = 2;
  112. var FrontSide = 0;
  113. var BackSide = 1;
  114. var DoubleSide = 2;
  115. var FlatShading = 1;
  116. var SmoothShading = 2;
  117. var NoColors = 0;
  118. var FaceColors = 1;
  119. var VertexColors = 2;
  120. var NoBlending = 0;
  121. var NormalBlending = 1;
  122. var AdditiveBlending = 2;
  123. var SubtractiveBlending = 3;
  124. var MultiplyBlending = 4;
  125. var CustomBlending = 5;
  126. var AddEquation = 100;
  127. var SubtractEquation = 101;
  128. var ReverseSubtractEquation = 102;
  129. var MinEquation = 103;
  130. var MaxEquation = 104;
  131. var ZeroFactor = 200;
  132. var OneFactor = 201;
  133. var SrcColorFactor = 202;
  134. var OneMinusSrcColorFactor = 203;
  135. var SrcAlphaFactor = 204;
  136. var OneMinusSrcAlphaFactor = 205;
  137. var DstAlphaFactor = 206;
  138. var OneMinusDstAlphaFactor = 207;
  139. var DstColorFactor = 208;
  140. var OneMinusDstColorFactor = 209;
  141. var SrcAlphaSaturateFactor = 210;
  142. var NeverDepth = 0;
  143. var AlwaysDepth = 1;
  144. var LessDepth = 2;
  145. var LessEqualDepth = 3;
  146. var EqualDepth = 4;
  147. var GreaterEqualDepth = 5;
  148. var GreaterDepth = 6;
  149. var NotEqualDepth = 7;
  150. var MultiplyOperation = 0;
  151. var MixOperation = 1;
  152. var AddOperation = 2;
  153. var NoToneMapping = 0;
  154. var LinearToneMapping = 1;
  155. var ReinhardToneMapping = 2;
  156. var Uncharted2ToneMapping = 3;
  157. var CineonToneMapping = 4;
  158. var UVMapping = 300;
  159. var CubeReflectionMapping = 301;
  160. var CubeRefractionMapping = 302;
  161. var EquirectangularReflectionMapping = 303;
  162. var EquirectangularRefractionMapping = 304;
  163. var SphericalReflectionMapping = 305;
  164. var CubeUVReflectionMapping = 306;
  165. var CubeUVRefractionMapping = 307;
  166. var RepeatWrapping = 1000;
  167. var ClampToEdgeWrapping = 1001;
  168. var MirroredRepeatWrapping = 1002;
  169. var NearestFilter = 1003;
  170. var NearestMipMapNearestFilter = 1004;
  171. var NearestMipMapLinearFilter = 1005;
  172. var LinearFilter = 1006;
  173. var LinearMipMapNearestFilter = 1007;
  174. var LinearMipMapLinearFilter = 1008;
  175. var UnsignedByteType = 1009;
  176. var ByteType = 1010;
  177. var ShortType = 1011;
  178. var UnsignedShortType = 1012;
  179. var IntType = 1013;
  180. var UnsignedIntType = 1014;
  181. var FloatType = 1015;
  182. var HalfFloatType = 1016;
  183. var UnsignedShort4444Type = 1017;
  184. var UnsignedShort5551Type = 1018;
  185. var UnsignedShort565Type = 1019;
  186. var UnsignedInt248Type = 1020;
  187. var AlphaFormat = 1021;
  188. var RGBFormat = 1022;
  189. var RGBAFormat = 1023;
  190. var LuminanceFormat = 1024;
  191. var LuminanceAlphaFormat = 1025;
  192. var RGBEFormat = RGBAFormat;
  193. var DepthFormat = 1026;
  194. var DepthStencilFormat = 1027;
  195. var RGB_S3TC_DXT1_Format = 2001;
  196. var RGBA_S3TC_DXT1_Format = 2002;
  197. var RGBA_S3TC_DXT3_Format = 2003;
  198. var RGBA_S3TC_DXT5_Format = 2004;
  199. var RGB_PVRTC_4BPPV1_Format = 2100;
  200. var RGB_PVRTC_2BPPV1_Format = 2101;
  201. var RGBA_PVRTC_4BPPV1_Format = 2102;
  202. var RGBA_PVRTC_2BPPV1_Format = 2103;
  203. var RGB_ETC1_Format = 2151;
  204. var LoopOnce = 2200;
  205. var LoopRepeat = 2201;
  206. var LoopPingPong = 2202;
  207. var InterpolateDiscrete = 2300;
  208. var InterpolateLinear = 2301;
  209. var InterpolateSmooth = 2302;
  210. var ZeroCurvatureEnding = 2400;
  211. var ZeroSlopeEnding = 2401;
  212. var WrapAroundEnding = 2402;
  213. var TrianglesDrawMode = 0;
  214. var TriangleStripDrawMode = 1;
  215. var TriangleFanDrawMode = 2;
  216. var LinearEncoding = 3000;
  217. var sRGBEncoding = 3001;
  218. var GammaEncoding = 3007;
  219. var RGBEEncoding = 3002;
  220. var LogLuvEncoding = 3003;
  221. var RGBM7Encoding = 3004;
  222. var RGBM16Encoding = 3005;
  223. var RGBDEncoding = 3006;
  224. var BasicDepthPacking = 3200;
  225. var RGBADepthPacking = 3201;
  226. /**
  227. * @author alteredq / http://alteredqualia.com/
  228. * @author mrdoob / http://mrdoob.com/
  229. */
  230. exports.Math = {
  231. DEG2RAD: Math.PI / 180,
  232. RAD2DEG: 180 / Math.PI,
  233. generateUUID: function () {
  234. // http://www.broofa.com/Tools/Math.uuid.htm
  235. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split( '' );
  236. var uuid = new Array( 36 );
  237. var rnd = 0, r;
  238. return function generateUUID() {
  239. for ( var i = 0; i < 36; i ++ ) {
  240. if ( i === 8 || i === 13 || i === 18 || i === 23 ) {
  241. uuid[ i ] = '-';
  242. } else if ( i === 14 ) {
  243. uuid[ i ] = '4';
  244. } else {
  245. if ( rnd <= 0x02 ) rnd = 0x2000000 + ( Math.random() * 0x1000000 ) | 0;
  246. r = rnd & 0xf;
  247. rnd = rnd >> 4;
  248. uuid[ i ] = chars[ ( i === 19 ) ? ( r & 0x3 ) | 0x8 : r ];
  249. }
  250. }
  251. return uuid.join( '' );
  252. };
  253. }(),
  254. clamp: function ( value, min, max ) {
  255. return Math.max( min, Math.min( max, value ) );
  256. },
  257. // compute euclidian modulo of m % n
  258. // https://en.wikipedia.org/wiki/Modulo_operation
  259. euclideanModulo: function ( n, m ) {
  260. return ( ( n % m ) + m ) % m;
  261. },
  262. // Linear mapping from range <a1, a2> to range <b1, b2>
  263. mapLinear: function ( x, a1, a2, b1, b2 ) {
  264. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  265. },
  266. // http://en.wikipedia.org/wiki/Smoothstep
  267. smoothstep: function ( x, min, max ) {
  268. if ( x <= min ) return 0;
  269. if ( x >= max ) return 1;
  270. x = ( x - min ) / ( max - min );
  271. return x * x * ( 3 - 2 * x );
  272. },
  273. smootherstep: function ( x, min, max ) {
  274. if ( x <= min ) return 0;
  275. if ( x >= max ) return 1;
  276. x = ( x - min ) / ( max - min );
  277. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  278. },
  279. random16: function () {
  280. console.warn( 'THREE.Math.random16() has been deprecated. Use Math.random() instead.' );
  281. return Math.random();
  282. },
  283. // Random integer from <low, high> interval
  284. randInt: function ( low, high ) {
  285. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  286. },
  287. // Random float from <low, high> interval
  288. randFloat: function ( low, high ) {
  289. return low + Math.random() * ( high - low );
  290. },
  291. // Random float from <-range/2, range/2> interval
  292. randFloatSpread: function ( range ) {
  293. return range * ( 0.5 - Math.random() );
  294. },
  295. degToRad: function ( degrees ) {
  296. return degrees * exports.Math.DEG2RAD;
  297. },
  298. radToDeg: function ( radians ) {
  299. return radians * exports.Math.RAD2DEG;
  300. },
  301. isPowerOfTwo: function ( value ) {
  302. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  303. },
  304. nearestPowerOfTwo: function ( value ) {
  305. return Math.pow( 2, Math.round( Math.log( value ) / Math.LN2 ) );
  306. },
  307. nextPowerOfTwo: function ( value ) {
  308. value --;
  309. value |= value >> 1;
  310. value |= value >> 2;
  311. value |= value >> 4;
  312. value |= value >> 8;
  313. value |= value >> 16;
  314. value ++;
  315. return value;
  316. }
  317. };
  318. /**
  319. * @author mrdoob / http://mrdoob.com/
  320. * @author philogb / http://blog.thejit.org/
  321. * @author egraether / http://egraether.com/
  322. * @author zz85 / http://www.lab4games.net/zz85/blog
  323. */
  324. function Vector2( x, y ) {
  325. this.x = x || 0;
  326. this.y = y || 0;
  327. }
  328. Vector2.prototype = {
  329. constructor: Vector2,
  330. isVector2: true,
  331. get width() {
  332. return this.x;
  333. },
  334. set width( value ) {
  335. this.x = value;
  336. },
  337. get height() {
  338. return this.y;
  339. },
  340. set height( value ) {
  341. this.y = value;
  342. },
  343. //
  344. set: function ( x, y ) {
  345. this.x = x;
  346. this.y = y;
  347. return this;
  348. },
  349. setScalar: function ( scalar ) {
  350. this.x = scalar;
  351. this.y = scalar;
  352. return this;
  353. },
  354. setX: function ( x ) {
  355. this.x = x;
  356. return this;
  357. },
  358. setY: function ( y ) {
  359. this.y = y;
  360. return this;
  361. },
  362. setComponent: function ( index, value ) {
  363. switch ( index ) {
  364. case 0: this.x = value; break;
  365. case 1: this.y = value; break;
  366. default: throw new Error( 'index is out of range: ' + index );
  367. }
  368. },
  369. getComponent: function ( index ) {
  370. switch ( index ) {
  371. case 0: return this.x;
  372. case 1: return this.y;
  373. default: throw new Error( 'index is out of range: ' + index );
  374. }
  375. },
  376. clone: function () {
  377. return new this.constructor( this.x, this.y );
  378. },
  379. copy: function ( v ) {
  380. this.x = v.x;
  381. this.y = v.y;
  382. return this;
  383. },
  384. add: function ( v, w ) {
  385. if ( w !== undefined ) {
  386. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  387. return this.addVectors( v, w );
  388. }
  389. this.x += v.x;
  390. this.y += v.y;
  391. return this;
  392. },
  393. addScalar: function ( s ) {
  394. this.x += s;
  395. this.y += s;
  396. return this;
  397. },
  398. addVectors: function ( a, b ) {
  399. this.x = a.x + b.x;
  400. this.y = a.y + b.y;
  401. return this;
  402. },
  403. addScaledVector: function ( v, s ) {
  404. this.x += v.x * s;
  405. this.y += v.y * s;
  406. return this;
  407. },
  408. sub: function ( v, w ) {
  409. if ( w !== undefined ) {
  410. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  411. return this.subVectors( v, w );
  412. }
  413. this.x -= v.x;
  414. this.y -= v.y;
  415. return this;
  416. },
  417. subScalar: function ( s ) {
  418. this.x -= s;
  419. this.y -= s;
  420. return this;
  421. },
  422. subVectors: function ( a, b ) {
  423. this.x = a.x - b.x;
  424. this.y = a.y - b.y;
  425. return this;
  426. },
  427. multiply: function ( v ) {
  428. this.x *= v.x;
  429. this.y *= v.y;
  430. return this;
  431. },
  432. multiplyScalar: function ( scalar ) {
  433. if ( isFinite( scalar ) ) {
  434. this.x *= scalar;
  435. this.y *= scalar;
  436. } else {
  437. this.x = 0;
  438. this.y = 0;
  439. }
  440. return this;
  441. },
  442. divide: function ( v ) {
  443. this.x /= v.x;
  444. this.y /= v.y;
  445. return this;
  446. },
  447. divideScalar: function ( scalar ) {
  448. return this.multiplyScalar( 1 / scalar );
  449. },
  450. min: function ( v ) {
  451. this.x = Math.min( this.x, v.x );
  452. this.y = Math.min( this.y, v.y );
  453. return this;
  454. },
  455. max: function ( v ) {
  456. this.x = Math.max( this.x, v.x );
  457. this.y = Math.max( this.y, v.y );
  458. return this;
  459. },
  460. clamp: function ( min, max ) {
  461. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  462. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  463. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  464. return this;
  465. },
  466. clampScalar: function () {
  467. var min, max;
  468. return function clampScalar( minVal, maxVal ) {
  469. if ( min === undefined ) {
  470. min = new Vector2();
  471. max = new Vector2();
  472. }
  473. min.set( minVal, minVal );
  474. max.set( maxVal, maxVal );
  475. return this.clamp( min, max );
  476. };
  477. }(),
  478. clampLength: function ( min, max ) {
  479. var length = this.length();
  480. return this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length );
  481. },
  482. floor: function () {
  483. this.x = Math.floor( this.x );
  484. this.y = Math.floor( this.y );
  485. return this;
  486. },
  487. ceil: function () {
  488. this.x = Math.ceil( this.x );
  489. this.y = Math.ceil( this.y );
  490. return this;
  491. },
  492. round: function () {
  493. this.x = Math.round( this.x );
  494. this.y = Math.round( this.y );
  495. return this;
  496. },
  497. roundToZero: function () {
  498. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  499. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  500. return this;
  501. },
  502. negate: function () {
  503. this.x = - this.x;
  504. this.y = - this.y;
  505. return this;
  506. },
  507. dot: function ( v ) {
  508. return this.x * v.x + this.y * v.y;
  509. },
  510. lengthSq: function () {
  511. return this.x * this.x + this.y * this.y;
  512. },
  513. length: function () {
  514. return Math.sqrt( this.x * this.x + this.y * this.y );
  515. },
  516. lengthManhattan: function() {
  517. return Math.abs( this.x ) + Math.abs( this.y );
  518. },
  519. normalize: function () {
  520. return this.divideScalar( this.length() );
  521. },
  522. angle: function () {
  523. // computes the angle in radians with respect to the positive x-axis
  524. var angle = Math.atan2( this.y, this.x );
  525. if ( angle < 0 ) angle += 2 * Math.PI;
  526. return angle;
  527. },
  528. distanceTo: function ( v ) {
  529. return Math.sqrt( this.distanceToSquared( v ) );
  530. },
  531. distanceToSquared: function ( v ) {
  532. var dx = this.x - v.x, dy = this.y - v.y;
  533. return dx * dx + dy * dy;
  534. },
  535. distanceToManhattan: function ( v ) {
  536. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  537. },
  538. setLength: function ( length ) {
  539. return this.multiplyScalar( length / this.length() );
  540. },
  541. lerp: function ( v, alpha ) {
  542. this.x += ( v.x - this.x ) * alpha;
  543. this.y += ( v.y - this.y ) * alpha;
  544. return this;
  545. },
  546. lerpVectors: function ( v1, v2, alpha ) {
  547. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  548. },
  549. equals: function ( v ) {
  550. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  551. },
  552. fromArray: function ( array, offset ) {
  553. if ( offset === undefined ) offset = 0;
  554. this.x = array[ offset ];
  555. this.y = array[ offset + 1 ];
  556. return this;
  557. },
  558. toArray: function ( array, offset ) {
  559. if ( array === undefined ) array = [];
  560. if ( offset === undefined ) offset = 0;
  561. array[ offset ] = this.x;
  562. array[ offset + 1 ] = this.y;
  563. return array;
  564. },
  565. fromAttribute: function ( attribute, index, offset ) {
  566. if ( offset === undefined ) offset = 0;
  567. index = index * attribute.itemSize + offset;
  568. this.x = attribute.array[ index ];
  569. this.y = attribute.array[ index + 1 ];
  570. return this;
  571. },
  572. rotateAround: function ( center, angle ) {
  573. var c = Math.cos( angle ), s = Math.sin( angle );
  574. var x = this.x - center.x;
  575. var y = this.y - center.y;
  576. this.x = x * c - y * s + center.x;
  577. this.y = x * s + y * c + center.y;
  578. return this;
  579. }
  580. };
  581. /**
  582. * @author mrdoob / http://mrdoob.com/
  583. * @author alteredq / http://alteredqualia.com/
  584. * @author szimek / https://github.com/szimek/
  585. */
  586. function Texture( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  587. Object.defineProperty( this, 'id', { value: TextureIdCount() } );
  588. this.uuid = exports.Math.generateUUID();
  589. this.name = '';
  590. this.sourceFile = '';
  591. this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE;
  592. this.mipmaps = [];
  593. this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING;
  594. this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping;
  595. this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping;
  596. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  597. this.minFilter = minFilter !== undefined ? minFilter : LinearMipMapLinearFilter;
  598. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  599. this.format = format !== undefined ? format : RGBAFormat;
  600. this.type = type !== undefined ? type : UnsignedByteType;
  601. this.offset = new Vector2( 0, 0 );
  602. this.repeat = new Vector2( 1, 1 );
  603. this.generateMipmaps = true;
  604. this.premultiplyAlpha = false;
  605. this.flipY = true;
  606. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  607. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  608. //
  609. // Also changing the encoding after already used by a Material will not automatically make the Material
  610. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  611. this.encoding = encoding !== undefined ? encoding : LinearEncoding;
  612. this.version = 0;
  613. this.onUpdate = null;
  614. }
  615. Texture.DEFAULT_IMAGE = undefined;
  616. Texture.DEFAULT_MAPPING = UVMapping;
  617. Texture.prototype = {
  618. constructor: Texture,
  619. isTexture: true,
  620. set needsUpdate( value ) {
  621. if ( value === true ) this.version ++;
  622. },
  623. clone: function () {
  624. return new this.constructor().copy( this );
  625. },
  626. copy: function ( source ) {
  627. this.image = source.image;
  628. this.mipmaps = source.mipmaps.slice( 0 );
  629. this.mapping = source.mapping;
  630. this.wrapS = source.wrapS;
  631. this.wrapT = source.wrapT;
  632. this.magFilter = source.magFilter;
  633. this.minFilter = source.minFilter;
  634. this.anisotropy = source.anisotropy;
  635. this.format = source.format;
  636. this.type = source.type;
  637. this.offset.copy( source.offset );
  638. this.repeat.copy( source.repeat );
  639. this.generateMipmaps = source.generateMipmaps;
  640. this.premultiplyAlpha = source.premultiplyAlpha;
  641. this.flipY = source.flipY;
  642. this.unpackAlignment = source.unpackAlignment;
  643. this.encoding = source.encoding;
  644. return this;
  645. },
  646. toJSON: function ( meta ) {
  647. if ( meta.textures[ this.uuid ] !== undefined ) {
  648. return meta.textures[ this.uuid ];
  649. }
  650. function getDataURL( image ) {
  651. var canvas;
  652. if ( image.toDataURL !== undefined ) {
  653. canvas = image;
  654. } else {
  655. canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  656. canvas.width = image.width;
  657. canvas.height = image.height;
  658. canvas.getContext( '2d' ).drawImage( image, 0, 0, image.width, image.height );
  659. }
  660. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  661. return canvas.toDataURL( 'image/jpeg', 0.6 );
  662. } else {
  663. return canvas.toDataURL( 'image/png' );
  664. }
  665. }
  666. var output = {
  667. metadata: {
  668. version: 4.4,
  669. type: 'Texture',
  670. generator: 'Texture.toJSON'
  671. },
  672. uuid: this.uuid,
  673. name: this.name,
  674. mapping: this.mapping,
  675. repeat: [ this.repeat.x, this.repeat.y ],
  676. offset: [ this.offset.x, this.offset.y ],
  677. wrap: [ this.wrapS, this.wrapT ],
  678. minFilter: this.minFilter,
  679. magFilter: this.magFilter,
  680. anisotropy: this.anisotropy,
  681. flipY: this.flipY
  682. };
  683. if ( this.image !== undefined ) {
  684. // TODO: Move to THREE.Image
  685. var image = this.image;
  686. if ( image.uuid === undefined ) {
  687. image.uuid = exports.Math.generateUUID(); // UGH
  688. }
  689. if ( meta.images[ image.uuid ] === undefined ) {
  690. meta.images[ image.uuid ] = {
  691. uuid: image.uuid,
  692. url: getDataURL( image )
  693. };
  694. }
  695. output.image = image.uuid;
  696. }
  697. meta.textures[ this.uuid ] = output;
  698. return output;
  699. },
  700. dispose: function () {
  701. this.dispatchEvent( { type: 'dispose' } );
  702. },
  703. transformUv: function ( uv ) {
  704. if ( this.mapping !== UVMapping ) return;
  705. uv.multiply( this.repeat );
  706. uv.add( this.offset );
  707. if ( uv.x < 0 || uv.x > 1 ) {
  708. switch ( this.wrapS ) {
  709. case RepeatWrapping:
  710. uv.x = uv.x - Math.floor( uv.x );
  711. break;
  712. case ClampToEdgeWrapping:
  713. uv.x = uv.x < 0 ? 0 : 1;
  714. break;
  715. case MirroredRepeatWrapping:
  716. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  717. uv.x = Math.ceil( uv.x ) - uv.x;
  718. } else {
  719. uv.x = uv.x - Math.floor( uv.x );
  720. }
  721. break;
  722. }
  723. }
  724. if ( uv.y < 0 || uv.y > 1 ) {
  725. switch ( this.wrapT ) {
  726. case RepeatWrapping:
  727. uv.y = uv.y - Math.floor( uv.y );
  728. break;
  729. case ClampToEdgeWrapping:
  730. uv.y = uv.y < 0 ? 0 : 1;
  731. break;
  732. case MirroredRepeatWrapping:
  733. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  734. uv.y = Math.ceil( uv.y ) - uv.y;
  735. } else {
  736. uv.y = uv.y - Math.floor( uv.y );
  737. }
  738. break;
  739. }
  740. }
  741. if ( this.flipY ) {
  742. uv.y = 1 - uv.y;
  743. }
  744. }
  745. };
  746. Object.assign( Texture.prototype, EventDispatcher.prototype );
  747. var count = 0;
  748. function TextureIdCount() { return count++; };
  749. /**
  750. * @author mrdoob / http://mrdoob.com/
  751. * @author supereggbert / http://www.paulbrunt.co.uk/
  752. * @author philogb / http://blog.thejit.org/
  753. * @author jordi_ros / http://plattsoft.com
  754. * @author D1plo1d / http://github.com/D1plo1d
  755. * @author alteredq / http://alteredqualia.com/
  756. * @author mikael emtinger / http://gomo.se/
  757. * @author timknip / http://www.floorplanner.com/
  758. * @author bhouston / http://clara.io
  759. * @author WestLangley / http://github.com/WestLangley
  760. */
  761. function Matrix4() {
  762. this.elements = new Float32Array( [
  763. 1, 0, 0, 0,
  764. 0, 1, 0, 0,
  765. 0, 0, 1, 0,
  766. 0, 0, 0, 1
  767. ] );
  768. if ( arguments.length > 0 ) {
  769. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  770. }
  771. }
  772. Matrix4.prototype = {
  773. constructor: Matrix4,
  774. isMatrix4: true,
  775. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  776. var te = this.elements;
  777. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  778. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  779. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  780. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  781. return this;
  782. },
  783. identity: function () {
  784. this.set(
  785. 1, 0, 0, 0,
  786. 0, 1, 0, 0,
  787. 0, 0, 1, 0,
  788. 0, 0, 0, 1
  789. );
  790. return this;
  791. },
  792. clone: function () {
  793. return new Matrix4().fromArray( this.elements );
  794. },
  795. copy: function ( m ) {
  796. this.elements.set( m.elements );
  797. return this;
  798. },
  799. copyPosition: function ( m ) {
  800. var te = this.elements;
  801. var me = m.elements;
  802. te[ 12 ] = me[ 12 ];
  803. te[ 13 ] = me[ 13 ];
  804. te[ 14 ] = me[ 14 ];
  805. return this;
  806. },
  807. extractBasis: function ( xAxis, yAxis, zAxis ) {
  808. xAxis.setFromMatrixColumn( this, 0 );
  809. yAxis.setFromMatrixColumn( this, 1 );
  810. zAxis.setFromMatrixColumn( this, 2 );
  811. return this;
  812. },
  813. makeBasis: function ( xAxis, yAxis, zAxis ) {
  814. this.set(
  815. xAxis.x, yAxis.x, zAxis.x, 0,
  816. xAxis.y, yAxis.y, zAxis.y, 0,
  817. xAxis.z, yAxis.z, zAxis.z, 0,
  818. 0, 0, 0, 1
  819. );
  820. return this;
  821. },
  822. extractRotation: function () {
  823. var v1;
  824. return function extractRotation( m ) {
  825. if ( v1 === undefined ) v1 = new Vector3();
  826. var te = this.elements;
  827. var me = m.elements;
  828. var scaleX = 1 / v1.setFromMatrixColumn( m, 0 ).length();
  829. var scaleY = 1 / v1.setFromMatrixColumn( m, 1 ).length();
  830. var scaleZ = 1 / v1.setFromMatrixColumn( m, 2 ).length();
  831. te[ 0 ] = me[ 0 ] * scaleX;
  832. te[ 1 ] = me[ 1 ] * scaleX;
  833. te[ 2 ] = me[ 2 ] * scaleX;
  834. te[ 4 ] = me[ 4 ] * scaleY;
  835. te[ 5 ] = me[ 5 ] * scaleY;
  836. te[ 6 ] = me[ 6 ] * scaleY;
  837. te[ 8 ] = me[ 8 ] * scaleZ;
  838. te[ 9 ] = me[ 9 ] * scaleZ;
  839. te[ 10 ] = me[ 10 ] * scaleZ;
  840. return this;
  841. };
  842. }(),
  843. makeRotationFromEuler: function ( euler ) {
  844. if ( (euler && euler.isEuler) === false ) {
  845. console.error( 'THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  846. }
  847. var te = this.elements;
  848. var x = euler.x, y = euler.y, z = euler.z;
  849. var a = Math.cos( x ), b = Math.sin( x );
  850. var c = Math.cos( y ), d = Math.sin( y );
  851. var e = Math.cos( z ), f = Math.sin( z );
  852. if ( euler.order === 'XYZ' ) {
  853. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  854. te[ 0 ] = c * e;
  855. te[ 4 ] = - c * f;
  856. te[ 8 ] = d;
  857. te[ 1 ] = af + be * d;
  858. te[ 5 ] = ae - bf * d;
  859. te[ 9 ] = - b * c;
  860. te[ 2 ] = bf - ae * d;
  861. te[ 6 ] = be + af * d;
  862. te[ 10 ] = a * c;
  863. } else if ( euler.order === 'YXZ' ) {
  864. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  865. te[ 0 ] = ce + df * b;
  866. te[ 4 ] = de * b - cf;
  867. te[ 8 ] = a * d;
  868. te[ 1 ] = a * f;
  869. te[ 5 ] = a * e;
  870. te[ 9 ] = - b;
  871. te[ 2 ] = cf * b - de;
  872. te[ 6 ] = df + ce * b;
  873. te[ 10 ] = a * c;
  874. } else if ( euler.order === 'ZXY' ) {
  875. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  876. te[ 0 ] = ce - df * b;
  877. te[ 4 ] = - a * f;
  878. te[ 8 ] = de + cf * b;
  879. te[ 1 ] = cf + de * b;
  880. te[ 5 ] = a * e;
  881. te[ 9 ] = df - ce * b;
  882. te[ 2 ] = - a * d;
  883. te[ 6 ] = b;
  884. te[ 10 ] = a * c;
  885. } else if ( euler.order === 'ZYX' ) {
  886. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  887. te[ 0 ] = c * e;
  888. te[ 4 ] = be * d - af;
  889. te[ 8 ] = ae * d + bf;
  890. te[ 1 ] = c * f;
  891. te[ 5 ] = bf * d + ae;
  892. te[ 9 ] = af * d - be;
  893. te[ 2 ] = - d;
  894. te[ 6 ] = b * c;
  895. te[ 10 ] = a * c;
  896. } else if ( euler.order === 'YZX' ) {
  897. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  898. te[ 0 ] = c * e;
  899. te[ 4 ] = bd - ac * f;
  900. te[ 8 ] = bc * f + ad;
  901. te[ 1 ] = f;
  902. te[ 5 ] = a * e;
  903. te[ 9 ] = - b * e;
  904. te[ 2 ] = - d * e;
  905. te[ 6 ] = ad * f + bc;
  906. te[ 10 ] = ac - bd * f;
  907. } else if ( euler.order === 'XZY' ) {
  908. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  909. te[ 0 ] = c * e;
  910. te[ 4 ] = - f;
  911. te[ 8 ] = d * e;
  912. te[ 1 ] = ac * f + bd;
  913. te[ 5 ] = a * e;
  914. te[ 9 ] = ad * f - bc;
  915. te[ 2 ] = bc * f - ad;
  916. te[ 6 ] = b * e;
  917. te[ 10 ] = bd * f + ac;
  918. }
  919. // last column
  920. te[ 3 ] = 0;
  921. te[ 7 ] = 0;
  922. te[ 11 ] = 0;
  923. // bottom row
  924. te[ 12 ] = 0;
  925. te[ 13 ] = 0;
  926. te[ 14 ] = 0;
  927. te[ 15 ] = 1;
  928. return this;
  929. },
  930. makeRotationFromQuaternion: function ( q ) {
  931. var te = this.elements;
  932. var x = q.x, y = q.y, z = q.z, w = q.w;
  933. var x2 = x + x, y2 = y + y, z2 = z + z;
  934. var xx = x * x2, xy = x * y2, xz = x * z2;
  935. var yy = y * y2, yz = y * z2, zz = z * z2;
  936. var wx = w * x2, wy = w * y2, wz = w * z2;
  937. te[ 0 ] = 1 - ( yy + zz );
  938. te[ 4 ] = xy - wz;
  939. te[ 8 ] = xz + wy;
  940. te[ 1 ] = xy + wz;
  941. te[ 5 ] = 1 - ( xx + zz );
  942. te[ 9 ] = yz - wx;
  943. te[ 2 ] = xz - wy;
  944. te[ 6 ] = yz + wx;
  945. te[ 10 ] = 1 - ( xx + yy );
  946. // last column
  947. te[ 3 ] = 0;
  948. te[ 7 ] = 0;
  949. te[ 11 ] = 0;
  950. // bottom row
  951. te[ 12 ] = 0;
  952. te[ 13 ] = 0;
  953. te[ 14 ] = 0;
  954. te[ 15 ] = 1;
  955. return this;
  956. },
  957. lookAt: function () {
  958. var x, y, z;
  959. return function lookAt( eye, target, up ) {
  960. if ( x === undefined ) {
  961. x = new Vector3();
  962. y = new Vector3();
  963. z = new Vector3();
  964. }
  965. var te = this.elements;
  966. z.subVectors( eye, target ).normalize();
  967. if ( z.lengthSq() === 0 ) {
  968. z.z = 1;
  969. }
  970. x.crossVectors( up, z ).normalize();
  971. if ( x.lengthSq() === 0 ) {
  972. z.z += 0.0001;
  973. x.crossVectors( up, z ).normalize();
  974. }
  975. y.crossVectors( z, x );
  976. te[ 0 ] = x.x; te[ 4 ] = y.x; te[ 8 ] = z.x;
  977. te[ 1 ] = x.y; te[ 5 ] = y.y; te[ 9 ] = z.y;
  978. te[ 2 ] = x.z; te[ 6 ] = y.z; te[ 10 ] = z.z;
  979. return this;
  980. };
  981. }(),
  982. multiply: function ( m, n ) {
  983. if ( n !== undefined ) {
  984. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  985. return this.multiplyMatrices( m, n );
  986. }
  987. return this.multiplyMatrices( this, m );
  988. },
  989. premultiply: function ( m ) {
  990. return this.multiplyMatrices( m, this );
  991. },
  992. multiplyMatrices: function ( a, b ) {
  993. var ae = a.elements;
  994. var be = b.elements;
  995. var te = this.elements;
  996. var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  997. var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  998. var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  999. var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  1000. var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  1001. var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  1002. var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  1003. var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  1004. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  1005. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  1006. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  1007. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  1008. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  1009. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  1010. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  1011. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  1012. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  1013. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  1014. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  1015. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  1016. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  1017. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  1018. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  1019. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  1020. return this;
  1021. },
  1022. multiplyToArray: function ( a, b, r ) {
  1023. var te = this.elements;
  1024. this.multiplyMatrices( a, b );
  1025. r[ 0 ] = te[ 0 ]; r[ 1 ] = te[ 1 ]; r[ 2 ] = te[ 2 ]; r[ 3 ] = te[ 3 ];
  1026. r[ 4 ] = te[ 4 ]; r[ 5 ] = te[ 5 ]; r[ 6 ] = te[ 6 ]; r[ 7 ] = te[ 7 ];
  1027. r[ 8 ] = te[ 8 ]; r[ 9 ] = te[ 9 ]; r[ 10 ] = te[ 10 ]; r[ 11 ] = te[ 11 ];
  1028. r[ 12 ] = te[ 12 ]; r[ 13 ] = te[ 13 ]; r[ 14 ] = te[ 14 ]; r[ 15 ] = te[ 15 ];
  1029. return this;
  1030. },
  1031. multiplyScalar: function ( s ) {
  1032. var te = this.elements;
  1033. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  1034. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  1035. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  1036. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  1037. return this;
  1038. },
  1039. applyToVector3Array: function () {
  1040. var v1;
  1041. return function applyToVector3Array( array, offset, length ) {
  1042. if ( v1 === undefined ) v1 = new Vector3();
  1043. if ( offset === undefined ) offset = 0;
  1044. if ( length === undefined ) length = array.length;
  1045. for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) {
  1046. v1.fromArray( array, j );
  1047. v1.applyMatrix4( this );
  1048. v1.toArray( array, j );
  1049. }
  1050. return array;
  1051. };
  1052. }(),
  1053. applyToBuffer: function () {
  1054. var v1;
  1055. return function applyToBuffer( buffer, offset, length ) {
  1056. if ( v1 === undefined ) v1 = new Vector3();
  1057. if ( offset === undefined ) offset = 0;
  1058. if ( length === undefined ) length = buffer.length / buffer.itemSize;
  1059. for ( var i = 0, j = offset; i < length; i ++, j ++ ) {
  1060. v1.x = buffer.getX( j );
  1061. v1.y = buffer.getY( j );
  1062. v1.z = buffer.getZ( j );
  1063. v1.applyMatrix4( this );
  1064. buffer.setXYZ( v1.x, v1.y, v1.z );
  1065. }
  1066. return buffer;
  1067. };
  1068. }(),
  1069. determinant: function () {
  1070. var te = this.elements;
  1071. var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  1072. var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  1073. var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  1074. var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  1075. //TODO: make this more efficient
  1076. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  1077. return (
  1078. n41 * (
  1079. + n14 * n23 * n32
  1080. - n13 * n24 * n32
  1081. - n14 * n22 * n33
  1082. + n12 * n24 * n33
  1083. + n13 * n22 * n34
  1084. - n12 * n23 * n34
  1085. ) +
  1086. n42 * (
  1087. + n11 * n23 * n34
  1088. - n11 * n24 * n33
  1089. + n14 * n21 * n33
  1090. - n13 * n21 * n34
  1091. + n13 * n24 * n31
  1092. - n14 * n23 * n31
  1093. ) +
  1094. n43 * (
  1095. + n11 * n24 * n32
  1096. - n11 * n22 * n34
  1097. - n14 * n21 * n32
  1098. + n12 * n21 * n34
  1099. + n14 * n22 * n31
  1100. - n12 * n24 * n31
  1101. ) +
  1102. n44 * (
  1103. - n13 * n22 * n31
  1104. - n11 * n23 * n32
  1105. + n11 * n22 * n33
  1106. + n13 * n21 * n32
  1107. - n12 * n21 * n33
  1108. + n12 * n23 * n31
  1109. )
  1110. );
  1111. },
  1112. transpose: function () {
  1113. var te = this.elements;
  1114. var tmp;
  1115. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  1116. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  1117. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  1118. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  1119. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  1120. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  1121. return this;
  1122. },
  1123. flattenToArrayOffset: function ( array, offset ) {
  1124. console.warn( "THREE.Matrix3: .flattenToArrayOffset is deprecated " +
  1125. "- just use .toArray instead." );
  1126. return this.toArray( array, offset );
  1127. },
  1128. getPosition: function () {
  1129. var v1;
  1130. return function getPosition() {
  1131. if ( v1 === undefined ) v1 = new Vector3();
  1132. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  1133. return v1.setFromMatrixColumn( this, 3 );
  1134. };
  1135. }(),
  1136. setPosition: function ( v ) {
  1137. var te = this.elements;
  1138. te[ 12 ] = v.x;
  1139. te[ 13 ] = v.y;
  1140. te[ 14 ] = v.z;
  1141. return this;
  1142. },
  1143. getInverse: function ( m, throwOnDegenerate ) {
  1144. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  1145. var te = this.elements,
  1146. me = m.elements,
  1147. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], n41 = me[ 3 ],
  1148. n12 = me[ 4 ], n22 = me[ 5 ], n32 = me[ 6 ], n42 = me[ 7 ],
  1149. n13 = me[ 8 ], n23 = me[ 9 ], n33 = me[ 10 ], n43 = me[ 11 ],
  1150. n14 = me[ 12 ], n24 = me[ 13 ], n34 = me[ 14 ], n44 = me[ 15 ],
  1151. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  1152. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  1153. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  1154. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  1155. var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  1156. if ( det === 0 ) {
  1157. var msg = "THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0";
  1158. if ( throwOnDegenerate === true ) {
  1159. throw new Error( msg );
  1160. } else {
  1161. console.warn( msg );
  1162. }
  1163. return this.identity();
  1164. }
  1165. var detInv = 1 / det;
  1166. te[ 0 ] = t11 * detInv;
  1167. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  1168. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  1169. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  1170. te[ 4 ] = t12 * detInv;
  1171. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  1172. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  1173. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  1174. te[ 8 ] = t13 * detInv;
  1175. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  1176. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  1177. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  1178. te[ 12 ] = t14 * detInv;
  1179. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  1180. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  1181. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  1182. return this;
  1183. },
  1184. scale: function ( v ) {
  1185. var te = this.elements;
  1186. var x = v.x, y = v.y, z = v.z;
  1187. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  1188. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  1189. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  1190. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  1191. return this;
  1192. },
  1193. getMaxScaleOnAxis: function () {
  1194. var te = this.elements;
  1195. var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  1196. var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  1197. var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  1198. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  1199. },
  1200. makeTranslation: function ( x, y, z ) {
  1201. this.set(
  1202. 1, 0, 0, x,
  1203. 0, 1, 0, y,
  1204. 0, 0, 1, z,
  1205. 0, 0, 0, 1
  1206. );
  1207. return this;
  1208. },
  1209. makeRotationX: function ( theta ) {
  1210. var c = Math.cos( theta ), s = Math.sin( theta );
  1211. this.set(
  1212. 1, 0, 0, 0,
  1213. 0, c, - s, 0,
  1214. 0, s, c, 0,
  1215. 0, 0, 0, 1
  1216. );
  1217. return this;
  1218. },
  1219. makeRotationY: function ( theta ) {
  1220. var c = Math.cos( theta ), s = Math.sin( theta );
  1221. this.set(
  1222. c, 0, s, 0,
  1223. 0, 1, 0, 0,
  1224. - s, 0, c, 0,
  1225. 0, 0, 0, 1
  1226. );
  1227. return this;
  1228. },
  1229. makeRotationZ: function ( theta ) {
  1230. var c = Math.cos( theta ), s = Math.sin( theta );
  1231. this.set(
  1232. c, - s, 0, 0,
  1233. s, c, 0, 0,
  1234. 0, 0, 1, 0,
  1235. 0, 0, 0, 1
  1236. );
  1237. return this;
  1238. },
  1239. makeRotationAxis: function ( axis, angle ) {
  1240. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  1241. var c = Math.cos( angle );
  1242. var s = Math.sin( angle );
  1243. var t = 1 - c;
  1244. var x = axis.x, y = axis.y, z = axis.z;
  1245. var tx = t * x, ty = t * y;
  1246. this.set(
  1247. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  1248. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  1249. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  1250. 0, 0, 0, 1
  1251. );
  1252. return this;
  1253. },
  1254. makeScale: function ( x, y, z ) {
  1255. this.set(
  1256. x, 0, 0, 0,
  1257. 0, y, 0, 0,
  1258. 0, 0, z, 0,
  1259. 0, 0, 0, 1
  1260. );
  1261. return this;
  1262. },
  1263. compose: function ( position, quaternion, scale ) {
  1264. this.makeRotationFromQuaternion( quaternion );
  1265. this.scale( scale );
  1266. this.setPosition( position );
  1267. return this;
  1268. },
  1269. decompose: function () {
  1270. var vector, matrix;
  1271. return function decompose( position, quaternion, scale ) {
  1272. if ( vector === undefined ) {
  1273. vector = new Vector3();
  1274. matrix = new Matrix4();
  1275. }
  1276. var te = this.elements;
  1277. var sx = vector.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  1278. var sy = vector.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  1279. var sz = vector.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  1280. // if determine is negative, we need to invert one scale
  1281. var det = this.determinant();
  1282. if ( det < 0 ) {
  1283. sx = - sx;
  1284. }
  1285. position.x = te[ 12 ];
  1286. position.y = te[ 13 ];
  1287. position.z = te[ 14 ];
  1288. // scale the rotation part
  1289. matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy()
  1290. var invSX = 1 / sx;
  1291. var invSY = 1 / sy;
  1292. var invSZ = 1 / sz;
  1293. matrix.elements[ 0 ] *= invSX;
  1294. matrix.elements[ 1 ] *= invSX;
  1295. matrix.elements[ 2 ] *= invSX;
  1296. matrix.elements[ 4 ] *= invSY;
  1297. matrix.elements[ 5 ] *= invSY;
  1298. matrix.elements[ 6 ] *= invSY;
  1299. matrix.elements[ 8 ] *= invSZ;
  1300. matrix.elements[ 9 ] *= invSZ;
  1301. matrix.elements[ 10 ] *= invSZ;
  1302. quaternion.setFromRotationMatrix( matrix );
  1303. scale.x = sx;
  1304. scale.y = sy;
  1305. scale.z = sz;
  1306. return this;
  1307. };
  1308. }(),
  1309. makeFrustum: function ( left, right, bottom, top, near, far ) {
  1310. var te = this.elements;
  1311. var x = 2 * near / ( right - left );
  1312. var y = 2 * near / ( top - bottom );
  1313. var a = ( right + left ) / ( right - left );
  1314. var b = ( top + bottom ) / ( top - bottom );
  1315. var c = - ( far + near ) / ( far - near );
  1316. var d = - 2 * far * near / ( far - near );
  1317. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  1318. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  1319. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  1320. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  1321. return this;
  1322. },
  1323. makePerspective: function ( fov, aspect, near, far ) {
  1324. var ymax = near * Math.tan( exports.Math.DEG2RAD * fov * 0.5 );
  1325. var ymin = - ymax;
  1326. var xmin = ymin * aspect;
  1327. var xmax = ymax * aspect;
  1328. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  1329. },
  1330. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  1331. var te = this.elements;
  1332. var w = 1.0 / ( right - left );
  1333. var h = 1.0 / ( top - bottom );
  1334. var p = 1.0 / ( far - near );
  1335. var x = ( right + left ) * w;
  1336. var y = ( top + bottom ) * h;
  1337. var z = ( far + near ) * p;
  1338. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  1339. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  1340. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  1341. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  1342. return this;
  1343. },
  1344. equals: function ( matrix ) {
  1345. var te = this.elements;
  1346. var me = matrix.elements;
  1347. for ( var i = 0; i < 16; i ++ ) {
  1348. if ( te[ i ] !== me[ i ] ) return false;
  1349. }
  1350. return true;
  1351. },
  1352. fromArray: function ( array ) {
  1353. this.elements.set( array );
  1354. return this;
  1355. },
  1356. toArray: function ( array, offset ) {
  1357. if ( array === undefined ) array = [];
  1358. if ( offset === undefined ) offset = 0;
  1359. var te = this.elements;
  1360. array[ offset ] = te[ 0 ];
  1361. array[ offset + 1 ] = te[ 1 ];
  1362. array[ offset + 2 ] = te[ 2 ];
  1363. array[ offset + 3 ] = te[ 3 ];
  1364. array[ offset + 4 ] = te[ 4 ];
  1365. array[ offset + 5 ] = te[ 5 ];
  1366. array[ offset + 6 ] = te[ 6 ];
  1367. array[ offset + 7 ] = te[ 7 ];
  1368. array[ offset + 8 ] = te[ 8 ];
  1369. array[ offset + 9 ] = te[ 9 ];
  1370. array[ offset + 10 ] = te[ 10 ];
  1371. array[ offset + 11 ] = te[ 11 ];
  1372. array[ offset + 12 ] = te[ 12 ];
  1373. array[ offset + 13 ] = te[ 13 ];
  1374. array[ offset + 14 ] = te[ 14 ];
  1375. array[ offset + 15 ] = te[ 15 ];
  1376. return array;
  1377. }
  1378. };
  1379. /**
  1380. * @author mikael emtinger / http://gomo.se/
  1381. * @author alteredq / http://alteredqualia.com/
  1382. * @author WestLangley / http://github.com/WestLangley
  1383. * @author bhouston / http://clara.io
  1384. */
  1385. function Quaternion( x, y, z, w ) {
  1386. this._x = x || 0;
  1387. this._y = y || 0;
  1388. this._z = z || 0;
  1389. this._w = ( w !== undefined ) ? w : 1;
  1390. }
  1391. Quaternion.prototype = {
  1392. constructor: Quaternion,
  1393. get x () {
  1394. return this._x;
  1395. },
  1396. set x ( value ) {
  1397. this._x = value;
  1398. this.onChangeCallback();
  1399. },
  1400. get y () {
  1401. return this._y;
  1402. },
  1403. set y ( value ) {
  1404. this._y = value;
  1405. this.onChangeCallback();
  1406. },
  1407. get z () {
  1408. return this._z;
  1409. },
  1410. set z ( value ) {
  1411. this._z = value;
  1412. this.onChangeCallback();
  1413. },
  1414. get w () {
  1415. return this._w;
  1416. },
  1417. set w ( value ) {
  1418. this._w = value;
  1419. this.onChangeCallback();
  1420. },
  1421. set: function ( x, y, z, w ) {
  1422. this._x = x;
  1423. this._y = y;
  1424. this._z = z;
  1425. this._w = w;
  1426. this.onChangeCallback();
  1427. return this;
  1428. },
  1429. clone: function () {
  1430. return new this.constructor( this._x, this._y, this._z, this._w );
  1431. },
  1432. copy: function ( quaternion ) {
  1433. this._x = quaternion.x;
  1434. this._y = quaternion.y;
  1435. this._z = quaternion.z;
  1436. this._w = quaternion.w;
  1437. this.onChangeCallback();
  1438. return this;
  1439. },
  1440. setFromEuler: function ( euler, update ) {
  1441. if ( (euler && euler.isEuler) === false ) {
  1442. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  1443. }
  1444. // http://www.mathworks.com/matlabcentral/fileexchange/
  1445. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  1446. // content/SpinCalc.m
  1447. var c1 = Math.cos( euler._x / 2 );
  1448. var c2 = Math.cos( euler._y / 2 );
  1449. var c3 = Math.cos( euler._z / 2 );
  1450. var s1 = Math.sin( euler._x / 2 );
  1451. var s2 = Math.sin( euler._y / 2 );
  1452. var s3 = Math.sin( euler._z / 2 );
  1453. var order = euler.order;
  1454. if ( order === 'XYZ' ) {
  1455. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1456. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1457. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1458. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1459. } else if ( order === 'YXZ' ) {
  1460. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1461. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1462. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1463. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1464. } else if ( order === 'ZXY' ) {
  1465. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1466. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1467. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1468. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1469. } else if ( order === 'ZYX' ) {
  1470. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1471. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1472. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1473. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1474. } else if ( order === 'YZX' ) {
  1475. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1476. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1477. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1478. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1479. } else if ( order === 'XZY' ) {
  1480. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1481. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1482. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1483. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1484. }
  1485. if ( update !== false ) this.onChangeCallback();
  1486. return this;
  1487. },
  1488. setFromAxisAngle: function ( axis, angle ) {
  1489. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  1490. // assumes axis is normalized
  1491. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  1492. this._x = axis.x * s;
  1493. this._y = axis.y * s;
  1494. this._z = axis.z * s;
  1495. this._w = Math.cos( halfAngle );
  1496. this.onChangeCallback();
  1497. return this;
  1498. },
  1499. setFromRotationMatrix: function ( m ) {
  1500. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  1501. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1502. var te = m.elements,
  1503. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1504. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1505. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  1506. trace = m11 + m22 + m33,
  1507. s;
  1508. if ( trace > 0 ) {
  1509. s = 0.5 / Math.sqrt( trace + 1.0 );
  1510. this._w = 0.25 / s;
  1511. this._x = ( m32 - m23 ) * s;
  1512. this._y = ( m13 - m31 ) * s;
  1513. this._z = ( m21 - m12 ) * s;
  1514. } else if ( m11 > m22 && m11 > m33 ) {
  1515. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  1516. this._w = ( m32 - m23 ) / s;
  1517. this._x = 0.25 * s;
  1518. this._y = ( m12 + m21 ) / s;
  1519. this._z = ( m13 + m31 ) / s;
  1520. } else if ( m22 > m33 ) {
  1521. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  1522. this._w = ( m13 - m31 ) / s;
  1523. this._x = ( m12 + m21 ) / s;
  1524. this._y = 0.25 * s;
  1525. this._z = ( m23 + m32 ) / s;
  1526. } else {
  1527. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  1528. this._w = ( m21 - m12 ) / s;
  1529. this._x = ( m13 + m31 ) / s;
  1530. this._y = ( m23 + m32 ) / s;
  1531. this._z = 0.25 * s;
  1532. }
  1533. this.onChangeCallback();
  1534. return this;
  1535. },
  1536. setFromUnitVectors: function () {
  1537. // http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final
  1538. // assumes direction vectors vFrom and vTo are normalized
  1539. var v1, r;
  1540. var EPS = 0.000001;
  1541. return function setFromUnitVectors( vFrom, vTo ) {
  1542. if ( v1 === undefined ) v1 = new Vector3();
  1543. r = vFrom.dot( vTo ) + 1;
  1544. if ( r < EPS ) {
  1545. r = 0;
  1546. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  1547. v1.set( - vFrom.y, vFrom.x, 0 );
  1548. } else {
  1549. v1.set( 0, - vFrom.z, vFrom.y );
  1550. }
  1551. } else {
  1552. v1.crossVectors( vFrom, vTo );
  1553. }
  1554. this._x = v1.x;
  1555. this._y = v1.y;
  1556. this._z = v1.z;
  1557. this._w = r;
  1558. return this.normalize();
  1559. };
  1560. }(),
  1561. inverse: function () {
  1562. return this.conjugate().normalize();
  1563. },
  1564. conjugate: function () {
  1565. this._x *= - 1;
  1566. this._y *= - 1;
  1567. this._z *= - 1;
  1568. this.onChangeCallback();
  1569. return this;
  1570. },
  1571. dot: function ( v ) {
  1572. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  1573. },
  1574. lengthSq: function () {
  1575. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  1576. },
  1577. length: function () {
  1578. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  1579. },
  1580. normalize: function () {
  1581. var l = this.length();
  1582. if ( l === 0 ) {
  1583. this._x = 0;
  1584. this._y = 0;
  1585. this._z = 0;
  1586. this._w = 1;
  1587. } else {
  1588. l = 1 / l;
  1589. this._x = this._x * l;
  1590. this._y = this._y * l;
  1591. this._z = this._z * l;
  1592. this._w = this._w * l;
  1593. }
  1594. this.onChangeCallback();
  1595. return this;
  1596. },
  1597. multiply: function ( q, p ) {
  1598. if ( p !== undefined ) {
  1599. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  1600. return this.multiplyQuaternions( q, p );
  1601. }
  1602. return this.multiplyQuaternions( this, q );
  1603. },
  1604. premultiply: function ( q ) {
  1605. return this.multiplyQuaternions( q, this );
  1606. },
  1607. multiplyQuaternions: function ( a, b ) {
  1608. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  1609. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  1610. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  1611. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  1612. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  1613. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  1614. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  1615. this.onChangeCallback();
  1616. return this;
  1617. },
  1618. slerp: function ( qb, t ) {
  1619. if ( t === 0 ) return this;
  1620. if ( t === 1 ) return this.copy( qb );
  1621. var x = this._x, y = this._y, z = this._z, w = this._w;
  1622. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  1623. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  1624. if ( cosHalfTheta < 0 ) {
  1625. this._w = - qb._w;
  1626. this._x = - qb._x;
  1627. this._y = - qb._y;
  1628. this._z = - qb._z;
  1629. cosHalfTheta = - cosHalfTheta;
  1630. } else {
  1631. this.copy( qb );
  1632. }
  1633. if ( cosHalfTheta >= 1.0 ) {
  1634. this._w = w;
  1635. this._x = x;
  1636. this._y = y;
  1637. this._z = z;
  1638. return this;
  1639. }
  1640. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  1641. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  1642. this._w = 0.5 * ( w + this._w );
  1643. this._x = 0.5 * ( x + this._x );
  1644. this._y = 0.5 * ( y + this._y );
  1645. this._z = 0.5 * ( z + this._z );
  1646. return this;
  1647. }
  1648. var halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  1649. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  1650. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  1651. this._w = ( w * ratioA + this._w * ratioB );
  1652. this._x = ( x * ratioA + this._x * ratioB );
  1653. this._y = ( y * ratioA + this._y * ratioB );
  1654. this._z = ( z * ratioA + this._z * ratioB );
  1655. this.onChangeCallback();
  1656. return this;
  1657. },
  1658. equals: function ( quaternion ) {
  1659. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  1660. },
  1661. fromArray: function ( array, offset ) {
  1662. if ( offset === undefined ) offset = 0;
  1663. this._x = array[ offset ];
  1664. this._y = array[ offset + 1 ];
  1665. this._z = array[ offset + 2 ];
  1666. this._w = array[ offset + 3 ];
  1667. this.onChangeCallback();
  1668. return this;
  1669. },
  1670. toArray: function ( array, offset ) {
  1671. if ( array === undefined ) array = [];
  1672. if ( offset === undefined ) offset = 0;
  1673. array[ offset ] = this._x;
  1674. array[ offset + 1 ] = this._y;
  1675. array[ offset + 2 ] = this._z;
  1676. array[ offset + 3 ] = this._w;
  1677. return array;
  1678. },
  1679. onChange: function ( callback ) {
  1680. this.onChangeCallback = callback;
  1681. return this;
  1682. },
  1683. onChangeCallback: function () {}
  1684. };
  1685. Object.assign( Quaternion, {
  1686. slerp: function( qa, qb, qm, t ) {
  1687. return qm.copy( qa ).slerp( qb, t );
  1688. },
  1689. slerpFlat: function(
  1690. dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  1691. // fuzz-free, array-based Quaternion SLERP operation
  1692. var x0 = src0[ srcOffset0 + 0 ],
  1693. y0 = src0[ srcOffset0 + 1 ],
  1694. z0 = src0[ srcOffset0 + 2 ],
  1695. w0 = src0[ srcOffset0 + 3 ],
  1696. x1 = src1[ srcOffset1 + 0 ],
  1697. y1 = src1[ srcOffset1 + 1 ],
  1698. z1 = src1[ srcOffset1 + 2 ],
  1699. w1 = src1[ srcOffset1 + 3 ];
  1700. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  1701. var s = 1 - t,
  1702. cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1703. dir = ( cos >= 0 ? 1 : - 1 ),
  1704. sqrSin = 1 - cos * cos;
  1705. // Skip the Slerp for tiny steps to avoid numeric problems:
  1706. if ( sqrSin > Number.EPSILON ) {
  1707. var sin = Math.sqrt( sqrSin ),
  1708. len = Math.atan2( sin, cos * dir );
  1709. s = Math.sin( s * len ) / sin;
  1710. t = Math.sin( t * len ) / sin;
  1711. }
  1712. var tDir = t * dir;
  1713. x0 = x0 * s + x1 * tDir;
  1714. y0 = y0 * s + y1 * tDir;
  1715. z0 = z0 * s + z1 * tDir;
  1716. w0 = w0 * s + w1 * tDir;
  1717. // Normalize in case we just did a lerp:
  1718. if ( s === 1 - t ) {
  1719. var f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  1720. x0 *= f;
  1721. y0 *= f;
  1722. z0 *= f;
  1723. w0 *= f;
  1724. }
  1725. }
  1726. dst[ dstOffset ] = x0;
  1727. dst[ dstOffset + 1 ] = y0;
  1728. dst[ dstOffset + 2 ] = z0;
  1729. dst[ dstOffset + 3 ] = w0;
  1730. }
  1731. } );
  1732. /**
  1733. * @author mrdoob / http://mrdoob.com/
  1734. * @author *kile / http://kile.stravaganza.org/
  1735. * @author philogb / http://blog.thejit.org/
  1736. * @author mikael emtinger / http://gomo.se/
  1737. * @author egraether / http://egraether.com/
  1738. * @author WestLangley / http://github.com/WestLangley
  1739. */
  1740. function Vector3( x, y, z ) {
  1741. this.x = x || 0;
  1742. this.y = y || 0;
  1743. this.z = z || 0;
  1744. }
  1745. Vector3.prototype = {
  1746. constructor: Vector3,
  1747. isVector3: true,
  1748. set: function ( x, y, z ) {
  1749. this.x = x;
  1750. this.y = y;
  1751. this.z = z;
  1752. return this;
  1753. },
  1754. setScalar: function ( scalar ) {
  1755. this.x = scalar;
  1756. this.y = scalar;
  1757. this.z = scalar;
  1758. return this;
  1759. },
  1760. setX: function ( x ) {
  1761. this.x = x;
  1762. return this;
  1763. },
  1764. setY: function ( y ) {
  1765. this.y = y;
  1766. return this;
  1767. },
  1768. setZ: function ( z ) {
  1769. this.z = z;
  1770. return this;
  1771. },
  1772. setComponent: function ( index, value ) {
  1773. switch ( index ) {
  1774. case 0: this.x = value; break;
  1775. case 1: this.y = value; break;
  1776. case 2: this.z = value; break;
  1777. default: throw new Error( 'index is out of range: ' + index );
  1778. }
  1779. },
  1780. getComponent: function ( index ) {
  1781. switch ( index ) {
  1782. case 0: return this.x;
  1783. case 1: return this.y;
  1784. case 2: return this.z;
  1785. default: throw new Error( 'index is out of range: ' + index );
  1786. }
  1787. },
  1788. clone: function () {
  1789. return new this.constructor( this.x, this.y, this.z );
  1790. },
  1791. copy: function ( v ) {
  1792. this.x = v.x;
  1793. this.y = v.y;
  1794. this.z = v.z;
  1795. return this;
  1796. },
  1797. add: function ( v, w ) {
  1798. if ( w !== undefined ) {
  1799. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1800. return this.addVectors( v, w );
  1801. }
  1802. this.x += v.x;
  1803. this.y += v.y;
  1804. this.z += v.z;
  1805. return this;
  1806. },
  1807. addScalar: function ( s ) {
  1808. this.x += s;
  1809. this.y += s;
  1810. this.z += s;
  1811. return this;
  1812. },
  1813. addVectors: function ( a, b ) {
  1814. this.x = a.x + b.x;
  1815. this.y = a.y + b.y;
  1816. this.z = a.z + b.z;
  1817. return this;
  1818. },
  1819. addScaledVector: function ( v, s ) {
  1820. this.x += v.x * s;
  1821. this.y += v.y * s;
  1822. this.z += v.z * s;
  1823. return this;
  1824. },
  1825. sub: function ( v, w ) {
  1826. if ( w !== undefined ) {
  1827. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1828. return this.subVectors( v, w );
  1829. }
  1830. this.x -= v.x;
  1831. this.y -= v.y;
  1832. this.z -= v.z;
  1833. return this;
  1834. },
  1835. subScalar: function ( s ) {
  1836. this.x -= s;
  1837. this.y -= s;
  1838. this.z -= s;
  1839. return this;
  1840. },
  1841. subVectors: function ( a, b ) {
  1842. this.x = a.x - b.x;
  1843. this.y = a.y - b.y;
  1844. this.z = a.z - b.z;
  1845. return this;
  1846. },
  1847. multiply: function ( v, w ) {
  1848. if ( w !== undefined ) {
  1849. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  1850. return this.multiplyVectors( v, w );
  1851. }
  1852. this.x *= v.x;
  1853. this.y *= v.y;
  1854. this.z *= v.z;
  1855. return this;
  1856. },
  1857. multiplyScalar: function ( scalar ) {
  1858. if ( isFinite( scalar ) ) {
  1859. this.x *= scalar;
  1860. this.y *= scalar;
  1861. this.z *= scalar;
  1862. } else {
  1863. this.x = 0;
  1864. this.y = 0;
  1865. this.z = 0;
  1866. }
  1867. return this;
  1868. },
  1869. multiplyVectors: function ( a, b ) {
  1870. this.x = a.x * b.x;
  1871. this.y = a.y * b.y;
  1872. this.z = a.z * b.z;
  1873. return this;
  1874. },
  1875. applyEuler: function () {
  1876. var quaternion;
  1877. return function applyEuler( euler ) {
  1878. if ( (euler && euler.isEuler) === false ) {
  1879. console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  1880. }
  1881. if ( quaternion === undefined ) quaternion = new Quaternion();
  1882. return this.applyQuaternion( quaternion.setFromEuler( euler ) );
  1883. };
  1884. }(),
  1885. applyAxisAngle: function () {
  1886. var quaternion;
  1887. return function applyAxisAngle( axis, angle ) {
  1888. if ( quaternion === undefined ) quaternion = new Quaternion();
  1889. return this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  1890. };
  1891. }(),
  1892. applyMatrix3: function ( m ) {
  1893. var x = this.x, y = this.y, z = this.z;
  1894. var e = m.elements;
  1895. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  1896. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  1897. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  1898. return this;
  1899. },
  1900. applyMatrix4: function ( m ) {
  1901. // input: THREE.Matrix4 affine matrix
  1902. var x = this.x, y = this.y, z = this.z;
  1903. var e = m.elements;
  1904. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ];
  1905. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ];
  1906. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ];
  1907. return this;
  1908. },
  1909. applyProjection: function ( m ) {
  1910. // input: THREE.Matrix4 projection matrix
  1911. var x = this.x, y = this.y, z = this.z;
  1912. var e = m.elements;
  1913. var d = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] ); // perspective divide
  1914. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * d;
  1915. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * d;
  1916. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * d;
  1917. return this;
  1918. },
  1919. applyQuaternion: function ( q ) {
  1920. var x = this.x, y = this.y, z = this.z;
  1921. var qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  1922. // calculate quat * vector
  1923. var ix = qw * x + qy * z - qz * y;
  1924. var iy = qw * y + qz * x - qx * z;
  1925. var iz = qw * z + qx * y - qy * x;
  1926. var iw = - qx * x - qy * y - qz * z;
  1927. // calculate result * inverse quat
  1928. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  1929. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  1930. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  1931. return this;
  1932. },
  1933. project: function () {
  1934. var matrix;
  1935. return function project( camera ) {
  1936. if ( matrix === undefined ) matrix = new Matrix4();
  1937. matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) );
  1938. return this.applyProjection( matrix );
  1939. };
  1940. }(),
  1941. unproject: function () {
  1942. var matrix;
  1943. return function unproject( camera ) {
  1944. if ( matrix === undefined ) matrix = new Matrix4();
  1945. matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) );
  1946. return this.applyProjection( matrix );
  1947. };
  1948. }(),
  1949. transformDirection: function ( m ) {
  1950. // input: THREE.Matrix4 affine matrix
  1951. // vector interpreted as a direction
  1952. var x = this.x, y = this.y, z = this.z;
  1953. var e = m.elements;
  1954. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  1955. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  1956. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  1957. return this.normalize();
  1958. },
  1959. divide: function ( v ) {
  1960. this.x /= v.x;
  1961. this.y /= v.y;
  1962. this.z /= v.z;
  1963. return this;
  1964. },
  1965. divideScalar: function ( scalar ) {
  1966. return this.multiplyScalar( 1 / scalar );
  1967. },
  1968. min: function ( v ) {
  1969. this.x = Math.min( this.x, v.x );
  1970. this.y = Math.min( this.y, v.y );
  1971. this.z = Math.min( this.z, v.z );
  1972. return this;
  1973. },
  1974. max: function ( v ) {
  1975. this.x = Math.max( this.x, v.x );
  1976. this.y = Math.max( this.y, v.y );
  1977. this.z = Math.max( this.z, v.z );
  1978. return this;
  1979. },
  1980. clamp: function ( min, max ) {
  1981. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1982. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1983. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1984. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1985. return this;
  1986. },
  1987. clampScalar: function () {
  1988. var min, max;
  1989. return function clampScalar( minVal, maxVal ) {
  1990. if ( min === undefined ) {
  1991. min = new Vector3();
  1992. max = new Vector3();
  1993. }
  1994. min.set( minVal, minVal, minVal );
  1995. max.set( maxVal, maxVal, maxVal );
  1996. return this.clamp( min, max );
  1997. };
  1998. }(),
  1999. clampLength: function ( min, max ) {
  2000. var length = this.length();
  2001. return this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length );
  2002. },
  2003. floor: function () {
  2004. this.x = Math.floor( this.x );
  2005. this.y = Math.floor( this.y );
  2006. this.z = Math.floor( this.z );
  2007. return this;
  2008. },
  2009. ceil: function () {
  2010. this.x = Math.ceil( this.x );
  2011. this.y = Math.ceil( this.y );
  2012. this.z = Math.ceil( this.z );
  2013. return this;
  2014. },
  2015. round: function () {
  2016. this.x = Math.round( this.x );
  2017. this.y = Math.round( this.y );
  2018. this.z = Math.round( this.z );
  2019. return this;
  2020. },
  2021. roundToZero: function () {
  2022. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  2023. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  2024. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  2025. return this;
  2026. },
  2027. negate: function () {
  2028. this.x = - this.x;
  2029. this.y = - this.y;
  2030. this.z = - this.z;
  2031. return this;
  2032. },
  2033. dot: function ( v ) {
  2034. return this.x * v.x + this.y * v.y + this.z * v.z;
  2035. },
  2036. lengthSq: function () {
  2037. return this.x * this.x + this.y * this.y + this.z * this.z;
  2038. },
  2039. length: function () {
  2040. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  2041. },
  2042. lengthManhattan: function () {
  2043. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  2044. },
  2045. normalize: function () {
  2046. return this.divideScalar( this.length() );
  2047. },
  2048. setLength: function ( length ) {
  2049. return this.multiplyScalar( length / this.length() );
  2050. },
  2051. lerp: function ( v, alpha ) {
  2052. this.x += ( v.x - this.x ) * alpha;
  2053. this.y += ( v.y - this.y ) * alpha;
  2054. this.z += ( v.z - this.z ) * alpha;
  2055. return this;
  2056. },
  2057. lerpVectors: function ( v1, v2, alpha ) {
  2058. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  2059. },
  2060. cross: function ( v, w ) {
  2061. if ( w !== undefined ) {
  2062. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  2063. return this.crossVectors( v, w );
  2064. }
  2065. var x = this.x, y = this.y, z = this.z;
  2066. this.x = y * v.z - z * v.y;
  2067. this.y = z * v.x - x * v.z;
  2068. this.z = x * v.y - y * v.x;
  2069. return this;
  2070. },
  2071. crossVectors: function ( a, b ) {
  2072. var ax = a.x, ay = a.y, az = a.z;
  2073. var bx = b.x, by = b.y, bz = b.z;
  2074. this.x = ay * bz - az * by;
  2075. this.y = az * bx - ax * bz;
  2076. this.z = ax * by - ay * bx;
  2077. return this;
  2078. },
  2079. projectOnVector: function ( vector ) {
  2080. var scalar = vector.dot( this ) / vector.lengthSq();
  2081. return this.copy( vector ).multiplyScalar( scalar );
  2082. },
  2083. projectOnPlane: function () {
  2084. var v1;
  2085. return function projectOnPlane( planeNormal ) {
  2086. if ( v1 === undefined ) v1 = new Vector3();
  2087. v1.copy( this ).projectOnVector( planeNormal );
  2088. return this.sub( v1 );
  2089. };
  2090. }(),
  2091. reflect: function () {
  2092. // reflect incident vector off plane orthogonal to normal
  2093. // normal is assumed to have unit length
  2094. var v1;
  2095. return function reflect( normal ) {
  2096. if ( v1 === undefined ) v1 = new Vector3();
  2097. return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  2098. };
  2099. }(),
  2100. angleTo: function ( v ) {
  2101. var theta = this.dot( v ) / ( Math.sqrt( this.lengthSq() * v.lengthSq() ) );
  2102. // clamp, to handle numerical problems
  2103. return Math.acos( exports.Math.clamp( theta, - 1, 1 ) );
  2104. },
  2105. distanceTo: function ( v ) {
  2106. return Math.sqrt( this.distanceToSquared( v ) );
  2107. },
  2108. distanceToSquared: function ( v ) {
  2109. var dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  2110. return dx * dx + dy * dy + dz * dz;
  2111. },
  2112. distanceToManhattan: function ( v ) {
  2113. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  2114. },
  2115. setFromSpherical: function( s ) {
  2116. var sinPhiRadius = Math.sin( s.phi ) * s.radius;
  2117. this.x = sinPhiRadius * Math.sin( s.theta );
  2118. this.y = Math.cos( s.phi ) * s.radius;
  2119. this.z = sinPhiRadius * Math.cos( s.theta );
  2120. return this;
  2121. },
  2122. setFromMatrixPosition: function ( m ) {
  2123. return this.setFromMatrixColumn( m, 3 );
  2124. },
  2125. setFromMatrixScale: function ( m ) {
  2126. var sx = this.setFromMatrixColumn( m, 0 ).length();
  2127. var sy = this.setFromMatrixColumn( m, 1 ).length();
  2128. var sz = this.setFromMatrixColumn( m, 2 ).length();
  2129. this.x = sx;
  2130. this.y = sy;
  2131. this.z = sz;
  2132. return this;
  2133. },
  2134. setFromMatrixColumn: function ( m, index ) {
  2135. if ( typeof m === 'number' ) {
  2136. console.warn( 'THREE.Vector3: setFromMatrixColumn now expects ( matrix, index ).' );
  2137. var temp = m
  2138. m = index;
  2139. index = temp;
  2140. }
  2141. return this.fromArray( m.elements, index * 4 );
  2142. },
  2143. equals: function ( v ) {
  2144. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  2145. },
  2146. fromArray: function ( array, offset ) {
  2147. if ( offset === undefined ) offset = 0;
  2148. this.x = array[ offset ];
  2149. this.y = array[ offset + 1 ];
  2150. this.z = array[ offset + 2 ];
  2151. return this;
  2152. },
  2153. toArray: function ( array, offset ) {
  2154. if ( array === undefined ) array = [];
  2155. if ( offset === undefined ) offset = 0;
  2156. array[ offset ] = this.x;
  2157. array[ offset + 1 ] = this.y;
  2158. array[ offset + 2 ] = this.z;
  2159. return array;
  2160. },
  2161. fromAttribute: function ( attribute, index, offset ) {
  2162. if ( offset === undefined ) offset = 0;
  2163. index = index * attribute.itemSize + offset;
  2164. this.x = attribute.array[ index ];
  2165. this.y = attribute.array[ index + 1 ];
  2166. this.z = attribute.array[ index + 2 ];
  2167. return this;
  2168. }
  2169. };
  2170. /**
  2171. * @author mikael emtinger / http://gomo.se/
  2172. * @author alteredq / http://alteredqualia.com/
  2173. */
  2174. function SpritePlugin( renderer, sprites ) {
  2175. var gl = renderer.context;
  2176. var state = renderer.state;
  2177. var vertexBuffer, elementBuffer;
  2178. var program, attributes, uniforms;
  2179. var texture;
  2180. // decompose matrixWorld
  2181. var spritePosition = new Vector3();
  2182. var spriteRotation = new Quaternion();
  2183. var spriteScale = new Vector3();
  2184. function init() {
  2185. var vertices = new Float32Array( [
  2186. - 0.5, - 0.5, 0, 0,
  2187. 0.5, - 0.5, 1, 0,
  2188. 0.5, 0.5, 1, 1,
  2189. - 0.5, 0.5, 0, 1
  2190. ] );
  2191. var faces = new Uint16Array( [
  2192. 0, 1, 2,
  2193. 0, 2, 3
  2194. ] );
  2195. vertexBuffer = gl.createBuffer();
  2196. elementBuffer = gl.createBuffer();
  2197. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  2198. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  2199. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  2200. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  2201. program = createProgram();
  2202. attributes = {
  2203. position: gl.getAttribLocation ( program, 'position' ),
  2204. uv: gl.getAttribLocation ( program, 'uv' )
  2205. };
  2206. uniforms = {
  2207. uvOffset: gl.getUniformLocation( program, 'uvOffset' ),
  2208. uvScale: gl.getUniformLocation( program, 'uvScale' ),
  2209. rotation: gl.getUniformLocation( program, 'rotation' ),
  2210. scale: gl.getUniformLocation( program, 'scale' ),
  2211. color: gl.getUniformLocation( program, 'color' ),
  2212. map: gl.getUniformLocation( program, 'map' ),
  2213. opacity: gl.getUniformLocation( program, 'opacity' ),
  2214. modelViewMatrix: gl.getUniformLocation( program, 'modelViewMatrix' ),
  2215. projectionMatrix: gl.getUniformLocation( program, 'projectionMatrix' ),
  2216. fogType: gl.getUniformLocation( program, 'fogType' ),
  2217. fogDensity: gl.getUniformLocation( program, 'fogDensity' ),
  2218. fogNear: gl.getUniformLocation( program, 'fogNear' ),
  2219. fogFar: gl.getUniformLocation( program, 'fogFar' ),
  2220. fogColor: gl.getUniformLocation( program, 'fogColor' ),
  2221. alphaTest: gl.getUniformLocation( program, 'alphaTest' )
  2222. };
  2223. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  2224. canvas.width = 8;
  2225. canvas.height = 8;
  2226. var context = canvas.getContext( '2d' );
  2227. context.fillStyle = 'white';
  2228. context.fillRect( 0, 0, 8, 8 );
  2229. texture = new Texture( canvas );
  2230. texture.needsUpdate = true;
  2231. }
  2232. this.render = function ( scene, camera ) {
  2233. if ( sprites.length === 0 ) return;
  2234. // setup gl
  2235. if ( program === undefined ) {
  2236. init();
  2237. }
  2238. gl.useProgram( program );
  2239. state.initAttributes();
  2240. state.enableAttribute( attributes.position );
  2241. state.enableAttribute( attributes.uv );
  2242. state.disableUnusedAttributes();
  2243. state.disable( gl.CULL_FACE );
  2244. state.enable( gl.BLEND );
  2245. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  2246. gl.vertexAttribPointer( attributes.position, 2, gl.FLOAT, false, 2 * 8, 0 );
  2247. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  2248. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  2249. gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  2250. state.activeTexture( gl.TEXTURE0 );
  2251. gl.uniform1i( uniforms.map, 0 );
  2252. var oldFogType = 0;
  2253. var sceneFogType = 0;
  2254. var fog = scene.fog;
  2255. if ( fog ) {
  2256. gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  2257. if ( (fog && fog.isFog) ) {
  2258. gl.uniform1f( uniforms.fogNear, fog.near );
  2259. gl.uniform1f( uniforms.fogFar, fog.far );
  2260. gl.uniform1i( uniforms.fogType, 1 );
  2261. oldFogType = 1;
  2262. sceneFogType = 1;
  2263. } else if ( (fog && fog.isFogExp2) ) {
  2264. gl.uniform1f( uniforms.fogDensity, fog.density );
  2265. gl.uniform1i( uniforms.fogType, 2 );
  2266. oldFogType = 2;
  2267. sceneFogType = 2;
  2268. }
  2269. } else {
  2270. gl.uniform1i( uniforms.fogType, 0 );
  2271. oldFogType = 0;
  2272. sceneFogType = 0;
  2273. }
  2274. // update positions and sort
  2275. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  2276. var sprite = sprites[ i ];
  2277. sprite.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  2278. sprite.z = - sprite.modelViewMatrix.elements[ 14 ];
  2279. }
  2280. sprites.sort( painterSortStable );
  2281. // render all sprites
  2282. var scale = [];
  2283. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  2284. var sprite = sprites[ i ];
  2285. var material = sprite.material;
  2286. if ( material.visible === false ) continue;
  2287. gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  2288. gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite.modelViewMatrix.elements );
  2289. sprite.matrixWorld.decompose( spritePosition, spriteRotation, spriteScale );
  2290. scale[ 0 ] = spriteScale.x;
  2291. scale[ 1 ] = spriteScale.y;
  2292. var fogType = 0;
  2293. if ( scene.fog && material.fog ) {
  2294. fogType = sceneFogType;
  2295. }
  2296. if ( oldFogType !== fogType ) {
  2297. gl.uniform1i( uniforms.fogType, fogType );
  2298. oldFogType = fogType;
  2299. }
  2300. if ( material.map !== null ) {
  2301. gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y );
  2302. gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y );
  2303. } else {
  2304. gl.uniform2f( uniforms.uvOffset, 0, 0 );
  2305. gl.uniform2f( uniforms.uvScale, 1, 1 );
  2306. }
  2307. gl.uniform1f( uniforms.opacity, material.opacity );
  2308. gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  2309. gl.uniform1f( uniforms.rotation, material.rotation );
  2310. gl.uniform2fv( uniforms.scale, scale );
  2311. state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  2312. state.setDepthTest( material.depthTest );
  2313. state.setDepthWrite( material.depthWrite );
  2314. if ( material.map ) {
  2315. renderer.setTexture2D( material.map, 0 );
  2316. } else {
  2317. renderer.setTexture2D( texture, 0 );
  2318. }
  2319. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  2320. }
  2321. // restore gl
  2322. state.enable( gl.CULL_FACE );
  2323. renderer.resetGLState();
  2324. };
  2325. function createProgram() {
  2326. var program = gl.createProgram();
  2327. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  2328. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  2329. gl.shaderSource( vertexShader, [
  2330. 'precision ' + renderer.getPrecision() + ' float;',
  2331. 'uniform mat4 modelViewMatrix;',
  2332. 'uniform mat4 projectionMatrix;',
  2333. 'uniform float rotation;',
  2334. 'uniform vec2 scale;',
  2335. 'uniform vec2 uvOffset;',
  2336. 'uniform vec2 uvScale;',
  2337. 'attribute vec2 position;',
  2338. 'attribute vec2 uv;',
  2339. 'varying vec2 vUV;',
  2340. 'void main() {',
  2341. 'vUV = uvOffset + uv * uvScale;',
  2342. 'vec2 alignedPosition = position * scale;',
  2343. 'vec2 rotatedPosition;',
  2344. 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  2345. 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  2346. 'vec4 finalPosition;',
  2347. 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  2348. 'finalPosition.xy += rotatedPosition;',
  2349. 'finalPosition = projectionMatrix * finalPosition;',
  2350. 'gl_Position = finalPosition;',
  2351. '}'
  2352. ].join( '\n' ) );
  2353. gl.shaderSource( fragmentShader, [
  2354. 'precision ' + renderer.getPrecision() + ' float;',
  2355. 'uniform vec3 color;',
  2356. 'uniform sampler2D map;',
  2357. 'uniform float opacity;',
  2358. 'uniform int fogType;',
  2359. 'uniform vec3 fogColor;',
  2360. 'uniform float fogDensity;',
  2361. 'uniform float fogNear;',
  2362. 'uniform float fogFar;',
  2363. 'uniform float alphaTest;',
  2364. 'varying vec2 vUV;',
  2365. 'void main() {',
  2366. 'vec4 texture = texture2D( map, vUV );',
  2367. 'if ( texture.a < alphaTest ) discard;',
  2368. 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  2369. 'if ( fogType > 0 ) {',
  2370. 'float depth = gl_FragCoord.z / gl_FragCoord.w;',
  2371. 'float fogFactor = 0.0;',
  2372. 'if ( fogType == 1 ) {',
  2373. 'fogFactor = smoothstep( fogNear, fogFar, depth );',
  2374. '} else {',
  2375. 'const float LOG2 = 1.442695;',
  2376. 'fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );',
  2377. 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  2378. '}',
  2379. 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );',
  2380. '}',
  2381. '}'
  2382. ].join( '\n' ) );
  2383. gl.compileShader( vertexShader );
  2384. gl.compileShader( fragmentShader );
  2385. gl.attachShader( program, vertexShader );
  2386. gl.attachShader( program, fragmentShader );
  2387. gl.linkProgram( program );
  2388. return program;
  2389. }
  2390. function painterSortStable( a, b ) {
  2391. if ( a.renderOrder !== b.renderOrder ) {
  2392. return a.renderOrder - b.renderOrder;
  2393. } else if ( a.z !== b.z ) {
  2394. return b.z - a.z;
  2395. } else {
  2396. return b.id - a.id;
  2397. }
  2398. }
  2399. }
  2400. /**
  2401. * @author bhouston / http://clara.io
  2402. */
  2403. function Box2( min, max ) {
  2404. this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity );
  2405. this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity );
  2406. }
  2407. Box2.prototype = {
  2408. constructor: Box2,
  2409. set: function ( min, max ) {
  2410. this.min.copy( min );
  2411. this.max.copy( max );
  2412. return this;
  2413. },
  2414. setFromPoints: function ( points ) {
  2415. this.makeEmpty();
  2416. for ( var i = 0, il = points.length; i < il; i ++ ) {
  2417. this.expandByPoint( points[ i ] );
  2418. }
  2419. return this;
  2420. },
  2421. setFromCenterAndSize: function () {
  2422. var v1 = new Vector2();
  2423. return function setFromCenterAndSize( center, size ) {
  2424. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2425. this.min.copy( center ).sub( halfSize );
  2426. this.max.copy( center ).add( halfSize );
  2427. return this;
  2428. };
  2429. }(),
  2430. clone: function () {
  2431. return new this.constructor().copy( this );
  2432. },
  2433. copy: function ( box ) {
  2434. this.min.copy( box.min );
  2435. this.max.copy( box.max );
  2436. return this;
  2437. },
  2438. makeEmpty: function () {
  2439. this.min.x = this.min.y = + Infinity;
  2440. this.max.x = this.max.y = - Infinity;
  2441. return this;
  2442. },
  2443. isEmpty: function () {
  2444. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2445. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  2446. },
  2447. center: function ( optionalTarget ) {
  2448. var result = optionalTarget || new Vector2();
  2449. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2450. },
  2451. size: function ( optionalTarget ) {
  2452. var result = optionalTarget || new Vector2();
  2453. return result.subVectors( this.max, this.min );
  2454. },
  2455. expandByPoint: function ( point ) {
  2456. this.min.min( point );
  2457. this.max.max( point );
  2458. return this;
  2459. },
  2460. expandByVector: function ( vector ) {
  2461. this.min.sub( vector );
  2462. this.max.add( vector );
  2463. return this;
  2464. },
  2465. expandByScalar: function ( scalar ) {
  2466. this.min.addScalar( - scalar );
  2467. this.max.addScalar( scalar );
  2468. return this;
  2469. },
  2470. containsPoint: function ( point ) {
  2471. if ( point.x < this.min.x || point.x > this.max.x ||
  2472. point.y < this.min.y || point.y > this.max.y ) {
  2473. return false;
  2474. }
  2475. return true;
  2476. },
  2477. containsBox: function ( box ) {
  2478. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2479. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  2480. return true;
  2481. }
  2482. return false;
  2483. },
  2484. getParameter: function ( point, optionalTarget ) {
  2485. // This can potentially have a divide by zero if the box
  2486. // has a size dimension of 0.
  2487. var result = optionalTarget || new Vector2();
  2488. return result.set(
  2489. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2490. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  2491. );
  2492. },
  2493. intersectsBox: function ( box ) {
  2494. // using 6 splitting planes to rule out intersections.
  2495. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2496. box.max.y < this.min.y || box.min.y > this.max.y ) {
  2497. return false;
  2498. }
  2499. return true;
  2500. },
  2501. clampPoint: function ( point, optionalTarget ) {
  2502. var result = optionalTarget || new Vector2();
  2503. return result.copy( point ).clamp( this.min, this.max );
  2504. },
  2505. distanceToPoint: function () {
  2506. var v1 = new Vector2();
  2507. return function distanceToPoint( point ) {
  2508. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2509. return clampedPoint.sub( point ).length();
  2510. };
  2511. }(),
  2512. intersect: function ( box ) {
  2513. this.min.max( box.min );
  2514. this.max.min( box.max );
  2515. return this;
  2516. },
  2517. union: function ( box ) {
  2518. this.min.min( box.min );
  2519. this.max.max( box.max );
  2520. return this;
  2521. },
  2522. translate: function ( offset ) {
  2523. this.min.add( offset );
  2524. this.max.add( offset );
  2525. return this;
  2526. },
  2527. equals: function ( box ) {
  2528. return box.min.equals( this.min ) && box.max.equals( this.max );
  2529. }
  2530. };
  2531. /**
  2532. * @author mikael emtinger / http://gomo.se/
  2533. * @author alteredq / http://alteredqualia.com/
  2534. */
  2535. function LensFlarePlugin( renderer, flares ) {
  2536. var gl = renderer.context;
  2537. var state = renderer.state;
  2538. var vertexBuffer, elementBuffer;
  2539. var shader, program, attributes, uniforms;
  2540. var tempTexture, occlusionTexture;
  2541. function init() {
  2542. var vertices = new Float32Array( [
  2543. - 1, - 1, 0, 0,
  2544. 1, - 1, 1, 0,
  2545. 1, 1, 1, 1,
  2546. - 1, 1, 0, 1
  2547. ] );
  2548. var faces = new Uint16Array( [
  2549. 0, 1, 2,
  2550. 0, 2, 3
  2551. ] );
  2552. // buffers
  2553. vertexBuffer = gl.createBuffer();
  2554. elementBuffer = gl.createBuffer();
  2555. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  2556. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  2557. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  2558. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  2559. // textures
  2560. tempTexture = gl.createTexture();
  2561. occlusionTexture = gl.createTexture();
  2562. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  2563. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB, 16, 16, 0, gl.RGB, gl.UNSIGNED_BYTE, null );
  2564. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  2565. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  2566. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  2567. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  2568. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  2569. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, 16, 16, 0, gl.RGBA, gl.UNSIGNED_BYTE, null );
  2570. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  2571. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  2572. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  2573. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  2574. shader = {
  2575. vertexShader: [
  2576. "uniform lowp int renderType;",
  2577. "uniform vec3 screenPosition;",
  2578. "uniform vec2 scale;",
  2579. "uniform float rotation;",
  2580. "uniform sampler2D occlusionMap;",
  2581. "attribute vec2 position;",
  2582. "attribute vec2 uv;",
  2583. "varying vec2 vUV;",
  2584. "varying float vVisibility;",
  2585. "void main() {",
  2586. "vUV = uv;",
  2587. "vec2 pos = position;",
  2588. "if ( renderType == 2 ) {",
  2589. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  2590. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  2591. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  2592. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  2593. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  2594. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  2595. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  2596. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  2597. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  2598. "vVisibility = visibility.r / 9.0;",
  2599. "vVisibility *= 1.0 - visibility.g / 9.0;",
  2600. "vVisibility *= visibility.b / 9.0;",
  2601. "vVisibility *= 1.0 - visibility.a / 9.0;",
  2602. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  2603. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  2604. "}",
  2605. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  2606. "}"
  2607. ].join( "\n" ),
  2608. fragmentShader: [
  2609. "uniform lowp int renderType;",
  2610. "uniform sampler2D map;",
  2611. "uniform float opacity;",
  2612. "uniform vec3 color;",
  2613. "varying vec2 vUV;",
  2614. "varying float vVisibility;",
  2615. "void main() {",
  2616. // pink square
  2617. "if ( renderType == 0 ) {",
  2618. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  2619. // restore
  2620. "} else if ( renderType == 1 ) {",
  2621. "gl_FragColor = texture2D( map, vUV );",
  2622. // flare
  2623. "} else {",
  2624. "vec4 texture = texture2D( map, vUV );",
  2625. "texture.a *= opacity * vVisibility;",
  2626. "gl_FragColor = texture;",
  2627. "gl_FragColor.rgb *= color;",
  2628. "}",
  2629. "}"
  2630. ].join( "\n" )
  2631. };
  2632. program = createProgram( shader );
  2633. attributes = {
  2634. vertex: gl.getAttribLocation ( program, "position" ),
  2635. uv: gl.getAttribLocation ( program, "uv" )
  2636. };
  2637. uniforms = {
  2638. renderType: gl.getUniformLocation( program, "renderType" ),
  2639. map: gl.getUniformLocation( program, "map" ),
  2640. occlusionMap: gl.getUniformLocation( program, "occlusionMap" ),
  2641. opacity: gl.getUniformLocation( program, "opacity" ),
  2642. color: gl.getUniformLocation( program, "color" ),
  2643. scale: gl.getUniformLocation( program, "scale" ),
  2644. rotation: gl.getUniformLocation( program, "rotation" ),
  2645. screenPosition: gl.getUniformLocation( program, "screenPosition" )
  2646. };
  2647. }
  2648. /*
  2649. * Render lens flares
  2650. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  2651. * reads these back and calculates occlusion.
  2652. */
  2653. this.render = function ( scene, camera, viewport ) {
  2654. if ( flares.length === 0 ) return;
  2655. var tempPosition = new Vector3();
  2656. var invAspect = viewport.w / viewport.z,
  2657. halfViewportWidth = viewport.z * 0.5,
  2658. halfViewportHeight = viewport.w * 0.5;
  2659. var size = 16 / viewport.w,
  2660. scale = new Vector2( size * invAspect, size );
  2661. var screenPosition = new Vector3( 1, 1, 0 ),
  2662. screenPositionPixels = new Vector2( 1, 1 );
  2663. var validArea = new Box2();
  2664. validArea.min.set( 0, 0 );
  2665. validArea.max.set( viewport.z - 16, viewport.w - 16 );
  2666. if ( program === undefined ) {
  2667. init();
  2668. }
  2669. gl.useProgram( program );
  2670. state.initAttributes();
  2671. state.enableAttribute( attributes.vertex );
  2672. state.enableAttribute( attributes.uv );
  2673. state.disableUnusedAttributes();
  2674. // loop through all lens flares to update their occlusion and positions
  2675. // setup gl and common used attribs/uniforms
  2676. gl.uniform1i( uniforms.occlusionMap, 0 );
  2677. gl.uniform1i( uniforms.map, 1 );
  2678. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  2679. gl.vertexAttribPointer( attributes.vertex, 2, gl.FLOAT, false, 2 * 8, 0 );
  2680. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  2681. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  2682. state.disable( gl.CULL_FACE );
  2683. state.setDepthWrite( false );
  2684. for ( var i = 0, l = flares.length; i < l; i ++ ) {
  2685. size = 16 / viewport.w;
  2686. scale.set( size * invAspect, size );
  2687. // calc object screen position
  2688. var flare = flares[ i ];
  2689. tempPosition.set( flare.matrixWorld.elements[ 12 ], flare.matrixWorld.elements[ 13 ], flare.matrixWorld.elements[ 14 ] );
  2690. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  2691. tempPosition.applyProjection( camera.projectionMatrix );
  2692. // setup arrays for gl programs
  2693. screenPosition.copy( tempPosition );
  2694. // horizontal and vertical coordinate of the lower left corner of the pixels to copy
  2695. screenPositionPixels.x = viewport.x + ( screenPosition.x * halfViewportWidth ) + halfViewportWidth - 8;
  2696. screenPositionPixels.y = viewport.y + ( screenPosition.y * halfViewportHeight ) + halfViewportHeight - 8;
  2697. // screen cull
  2698. if ( validArea.containsPoint( screenPositionPixels ) === true ) {
  2699. // save current RGB to temp texture
  2700. state.activeTexture( gl.TEXTURE0 );
  2701. state.bindTexture( gl.TEXTURE_2D, null );
  2702. state.activeTexture( gl.TEXTURE1 );
  2703. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  2704. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGB, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 );
  2705. // render pink quad
  2706. gl.uniform1i( uniforms.renderType, 0 );
  2707. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  2708. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  2709. state.disable( gl.BLEND );
  2710. state.enable( gl.DEPTH_TEST );
  2711. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  2712. // copy result to occlusionMap
  2713. state.activeTexture( gl.TEXTURE0 );
  2714. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  2715. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGBA, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 );
  2716. // restore graphics
  2717. gl.uniform1i( uniforms.renderType, 1 );
  2718. state.disable( gl.DEPTH_TEST );
  2719. state.activeTexture( gl.TEXTURE1 );
  2720. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  2721. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  2722. // update object positions
  2723. flare.positionScreen.copy( screenPosition );
  2724. if ( flare.customUpdateCallback ) {
  2725. flare.customUpdateCallback( flare );
  2726. } else {
  2727. flare.updateLensFlares();
  2728. }
  2729. // render flares
  2730. gl.uniform1i( uniforms.renderType, 2 );
  2731. state.enable( gl.BLEND );
  2732. for ( var j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  2733. var sprite = flare.lensFlares[ j ];
  2734. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  2735. screenPosition.x = sprite.x;
  2736. screenPosition.y = sprite.y;
  2737. screenPosition.z = sprite.z;
  2738. size = sprite.size * sprite.scale / viewport.w;
  2739. scale.x = size * invAspect;
  2740. scale.y = size;
  2741. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  2742. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  2743. gl.uniform1f( uniforms.rotation, sprite.rotation );
  2744. gl.uniform1f( uniforms.opacity, sprite.opacity );
  2745. gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  2746. state.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  2747. renderer.setTexture2D( sprite.texture, 1 );
  2748. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  2749. }
  2750. }
  2751. }
  2752. }
  2753. // restore gl
  2754. state.enable( gl.CULL_FACE );
  2755. state.enable( gl.DEPTH_TEST );
  2756. state.setDepthWrite( true );
  2757. renderer.resetGLState();
  2758. };
  2759. function createProgram( shader ) {
  2760. var program = gl.createProgram();
  2761. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  2762. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  2763. var prefix = "precision " + renderer.getPrecision() + " float;\n";
  2764. gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  2765. gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  2766. gl.compileShader( fragmentShader );
  2767. gl.compileShader( vertexShader );
  2768. gl.attachShader( program, fragmentShader );
  2769. gl.attachShader( program, vertexShader );
  2770. gl.linkProgram( program );
  2771. return program;
  2772. }
  2773. }
  2774. /**
  2775. * @author mrdoob / http://mrdoob.com/
  2776. */
  2777. function CubeTexture( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  2778. images = images !== undefined ? images : [];
  2779. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  2780. Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  2781. this.flipY = false;
  2782. }
  2783. CubeTexture.prototype = Object.create( Texture.prototype );
  2784. CubeTexture.prototype.constructor = CubeTexture;
  2785. CubeTexture.prototype.isCubeTexture = true;
  2786. Object.defineProperty( CubeTexture.prototype, 'images', {
  2787. get: function () {
  2788. return this.image;
  2789. },
  2790. set: function ( value ) {
  2791. this.image = value;
  2792. }
  2793. } );
  2794. /**
  2795. *
  2796. * Uniforms of a program.
  2797. * Those form a tree structure with a special top-level container for the root,
  2798. * which you get by calling 'new WebGLUniforms( gl, program, renderer )'.
  2799. *
  2800. *
  2801. * Properties of inner nodes including the top-level container:
  2802. *
  2803. * .seq - array of nested uniforms
  2804. * .map - nested uniforms by name
  2805. *
  2806. *
  2807. * Methods of all nodes except the top-level container:
  2808. *
  2809. * .setValue( gl, value, [renderer] )
  2810. *
  2811. * uploads a uniform value(s)
  2812. * the 'renderer' parameter is needed for sampler uniforms
  2813. *
  2814. *
  2815. * Static methods of the top-level container (renderer factorizations):
  2816. *
  2817. * .upload( gl, seq, values, renderer )
  2818. *
  2819. * sets uniforms in 'seq' to 'values[id].value'
  2820. *
  2821. * .seqWithValue( seq, values ) : filteredSeq
  2822. *
  2823. * filters 'seq' entries with corresponding entry in values
  2824. *
  2825. * .splitDynamic( seq, values ) : filteredSeq
  2826. *
  2827. * filters 'seq' entries with dynamic entry and removes them from 'seq'
  2828. *
  2829. *
  2830. * Methods of the top-level container (renderer factorizations):
  2831. *
  2832. * .setValue( gl, name, value )
  2833. *
  2834. * sets uniform with name 'name' to 'value'
  2835. *
  2836. * .set( gl, obj, prop )
  2837. *
  2838. * sets uniform from object and property with same name than uniform
  2839. *
  2840. * .setOptional( gl, obj, prop )
  2841. *
  2842. * like .set for an optional property of the object
  2843. *
  2844. *
  2845. * @author tschw
  2846. *
  2847. */
  2848. exports.WebGLUniforms = ( function() { // scope
  2849. var emptyTexture = new Texture();
  2850. var emptyCubeTexture = new CubeTexture();
  2851. // --- Base for inner nodes (including the root) ---
  2852. var UniformContainer = function() {
  2853. this.seq = [];
  2854. this.map = {};
  2855. },
  2856. // --- Utilities ---
  2857. // Array Caches (provide typed arrays for temporary by size)
  2858. arrayCacheF32 = [],
  2859. arrayCacheI32 = [],
  2860. // Flattening for arrays of vectors and matrices
  2861. flatten = function( array, nBlocks, blockSize ) {
  2862. var firstElem = array[ 0 ];
  2863. if ( firstElem <= 0 || firstElem > 0 ) return array;
  2864. // unoptimized: ! isNaN( firstElem )
  2865. // see http://jacksondunstan.com/articles/983
  2866. var n = nBlocks * blockSize,
  2867. r = arrayCacheF32[ n ];
  2868. if ( r === undefined ) {
  2869. r = new Float32Array( n );
  2870. arrayCacheF32[ n ] = r;
  2871. }
  2872. if ( nBlocks !== 0 ) {
  2873. firstElem.toArray( r, 0 );
  2874. for ( var i = 1, offset = 0; i !== nBlocks; ++ i ) {
  2875. offset += blockSize;
  2876. array[ i ].toArray( r, offset );
  2877. }
  2878. }
  2879. return r;
  2880. },
  2881. // Texture unit allocation
  2882. allocTexUnits = function( renderer, n ) {
  2883. var r = arrayCacheI32[ n ];
  2884. if ( r === undefined ) {
  2885. r = new Int32Array( n );
  2886. arrayCacheI32[ n ] = r;
  2887. }
  2888. for ( var i = 0; i !== n; ++ i )
  2889. r[ i ] = renderer.allocTextureUnit();
  2890. return r;
  2891. },
  2892. // --- Setters ---
  2893. // Note: Defining these methods externally, because they come in a bunch
  2894. // and this way their names minify.
  2895. // Single scalar
  2896. setValue1f = function( gl, v ) { gl.uniform1f( this.addr, v ); },
  2897. setValue1i = function( gl, v ) { gl.uniform1i( this.addr, v ); },
  2898. // Single float vector (from flat array or THREE.VectorN)
  2899. setValue2fv = function( gl, v ) {
  2900. if ( v.x === undefined ) gl.uniform2fv( this.addr, v );
  2901. else gl.uniform2f( this.addr, v.x, v.y );
  2902. },
  2903. setValue3fv = function( gl, v ) {
  2904. if ( v.x !== undefined )
  2905. gl.uniform3f( this.addr, v.x, v.y, v.z );
  2906. else if ( v.r !== undefined )
  2907. gl.uniform3f( this.addr, v.r, v.g, v.b );
  2908. else
  2909. gl.uniform3fv( this.addr, v );
  2910. },
  2911. setValue4fv = function( gl, v ) {
  2912. if ( v.x === undefined ) gl.uniform4fv( this.addr, v );
  2913. else gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  2914. },
  2915. // Single matrix (from flat array or MatrixN)
  2916. setValue2fm = function( gl, v ) {
  2917. gl.uniformMatrix2fv( this.addr, false, v.elements || v );
  2918. },
  2919. setValue3fm = function( gl, v ) {
  2920. gl.uniformMatrix3fv( this.addr, false, v.elements || v );
  2921. },
  2922. setValue4fm = function( gl, v ) {
  2923. gl.uniformMatrix4fv( this.addr, false, v.elements || v );
  2924. },
  2925. // Single texture (2D / Cube)
  2926. setValueT1 = function( gl, v, renderer ) {
  2927. var unit = renderer.allocTextureUnit();
  2928. gl.uniform1i( this.addr, unit );
  2929. renderer.setTexture2D( v || emptyTexture, unit );
  2930. },
  2931. setValueT6 = function( gl, v, renderer ) {
  2932. var unit = renderer.allocTextureUnit();
  2933. gl.uniform1i( this.addr, unit );
  2934. renderer.setTextureCube( v || emptyCubeTexture, unit );
  2935. },
  2936. // Integer / Boolean vectors or arrays thereof (always flat arrays)
  2937. setValue2iv = function( gl, v ) { gl.uniform2iv( this.addr, v ); },
  2938. setValue3iv = function( gl, v ) { gl.uniform3iv( this.addr, v ); },
  2939. setValue4iv = function( gl, v ) { gl.uniform4iv( this.addr, v ); },
  2940. // Helper to pick the right setter for the singular case
  2941. getSingularSetter = function( type ) {
  2942. switch ( type ) {
  2943. case 0x1406: return setValue1f; // FLOAT
  2944. case 0x8b50: return setValue2fv; // _VEC2
  2945. case 0x8b51: return setValue3fv; // _VEC3
  2946. case 0x8b52: return setValue4fv; // _VEC4
  2947. case 0x8b5a: return setValue2fm; // _MAT2
  2948. case 0x8b5b: return setValue3fm; // _MAT3
  2949. case 0x8b5c: return setValue4fm; // _MAT4
  2950. case 0x8b5e: return setValueT1; // SAMPLER_2D
  2951. case 0x8b60: return setValueT6; // SAMPLER_CUBE
  2952. case 0x1404: case 0x8b56: return setValue1i; // INT, BOOL
  2953. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  2954. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  2955. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  2956. }
  2957. },
  2958. // Array of scalars
  2959. setValue1fv = function( gl, v ) { gl.uniform1fv( this.addr, v ); },
  2960. setValue1iv = function( gl, v ) { gl.uniform1iv( this.addr, v ); },
  2961. // Array of vectors (flat or from THREE classes)
  2962. setValueV2a = function( gl, v ) {
  2963. gl.uniform2fv( this.addr, flatten( v, this.size, 2 ) );
  2964. },
  2965. setValueV3a = function( gl, v ) {
  2966. gl.uniform3fv( this.addr, flatten( v, this.size, 3 ) );
  2967. },
  2968. setValueV4a = function( gl, v ) {
  2969. gl.uniform4fv( this.addr, flatten( v, this.size, 4 ) );
  2970. },
  2971. // Array of matrices (flat or from THREE clases)
  2972. setValueM2a = function( gl, v ) {
  2973. gl.uniformMatrix2fv( this.addr, false, flatten( v, this.size, 4 ) );
  2974. },
  2975. setValueM3a = function( gl, v ) {
  2976. gl.uniformMatrix3fv( this.addr, false, flatten( v, this.size, 9 ) );
  2977. },
  2978. setValueM4a = function( gl, v ) {
  2979. gl.uniformMatrix4fv( this.addr, false, flatten( v, this.size, 16 ) );
  2980. },
  2981. // Array of textures (2D / Cube)
  2982. setValueT1a = function( gl, v, renderer ) {
  2983. var n = v.length,
  2984. units = allocTexUnits( renderer, n );
  2985. gl.uniform1iv( this.addr, units );
  2986. for ( var i = 0; i !== n; ++ i ) {
  2987. renderer.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  2988. }
  2989. },
  2990. setValueT6a = function( gl, v, renderer ) {
  2991. var n = v.length,
  2992. units = allocTexUnits( renderer, n );
  2993. gl.uniform1iv( this.addr, units );
  2994. for ( var i = 0; i !== n; ++ i ) {
  2995. renderer.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  2996. }
  2997. },
  2998. // Helper to pick the right setter for a pure (bottom-level) array
  2999. getPureArraySetter = function( type ) {
  3000. switch ( type ) {
  3001. case 0x1406: return setValue1fv; // FLOAT
  3002. case 0x8b50: return setValueV2a; // _VEC2
  3003. case 0x8b51: return setValueV3a; // _VEC3
  3004. case 0x8b52: return setValueV4a; // _VEC4
  3005. case 0x8b5a: return setValueM2a; // _MAT2
  3006. case 0x8b5b: return setValueM3a; // _MAT3
  3007. case 0x8b5c: return setValueM4a; // _MAT4
  3008. case 0x8b5e: return setValueT1a; // SAMPLER_2D
  3009. case 0x8b60: return setValueT6a; // SAMPLER_CUBE
  3010. case 0x1404: case 0x8b56: return setValue1iv; // INT, BOOL
  3011. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  3012. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  3013. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  3014. }
  3015. },
  3016. // --- Uniform Classes ---
  3017. SingleUniform = function SingleUniform( id, activeInfo, addr ) {
  3018. this.id = id;
  3019. this.addr = addr;
  3020. this.setValue = getSingularSetter( activeInfo.type );
  3021. // this.path = activeInfo.name; // DEBUG
  3022. },
  3023. PureArrayUniform = function( id, activeInfo, addr ) {
  3024. this.id = id;
  3025. this.addr = addr;
  3026. this.size = activeInfo.size;
  3027. this.setValue = getPureArraySetter( activeInfo.type );
  3028. // this.path = activeInfo.name; // DEBUG
  3029. },
  3030. StructuredUniform = function( id ) {
  3031. this.id = id;
  3032. UniformContainer.call( this ); // mix-in
  3033. };
  3034. StructuredUniform.prototype.setValue = function( gl, value ) {
  3035. // Note: Don't need an extra 'renderer' parameter, since samplers
  3036. // are not allowed in structured uniforms.
  3037. var seq = this.seq;
  3038. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  3039. var u = seq[ i ];
  3040. u.setValue( gl, value[ u.id ] );
  3041. }
  3042. };
  3043. // --- Top-level ---
  3044. // Parser - builds up the property tree from the path strings
  3045. var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g,
  3046. // extracts
  3047. // - the identifier (member name or array index)
  3048. // - followed by an optional right bracket (found when array index)
  3049. // - followed by an optional left bracket or dot (type of subscript)
  3050. //
  3051. // Note: These portions can be read in a non-overlapping fashion and
  3052. // allow straightforward parsing of the hierarchy that WebGL encodes
  3053. // in the uniform names.
  3054. addUniform = function( container, uniformObject ) {
  3055. container.seq.push( uniformObject );
  3056. container.map[ uniformObject.id ] = uniformObject;
  3057. },
  3058. parseUniform = function( activeInfo, addr, container ) {
  3059. var path = activeInfo.name,
  3060. pathLength = path.length;
  3061. // reset RegExp object, because of the early exit of a previous run
  3062. RePathPart.lastIndex = 0;
  3063. for (; ;) {
  3064. var match = RePathPart.exec( path ),
  3065. matchEnd = RePathPart.lastIndex,
  3066. id = match[ 1 ],
  3067. idIsIndex = match[ 2 ] === ']',
  3068. subscript = match[ 3 ];
  3069. if ( idIsIndex ) id = id | 0; // convert to integer
  3070. if ( subscript === undefined ||
  3071. subscript === '[' && matchEnd + 2 === pathLength ) {
  3072. // bare name or "pure" bottom-level array "[0]" suffix
  3073. addUniform( container, subscript === undefined ?
  3074. new SingleUniform( id, activeInfo, addr ) :
  3075. new PureArrayUniform( id, activeInfo, addr ) );
  3076. break;
  3077. } else {
  3078. // step into inner node / create it in case it doesn't exist
  3079. var map = container.map,
  3080. next = map[ id ];
  3081. if ( next === undefined ) {
  3082. next = new StructuredUniform( id );
  3083. addUniform( container, next );
  3084. }
  3085. container = next;
  3086. }
  3087. }
  3088. },
  3089. // Root Container
  3090. WebGLUniforms = function WebGLUniforms( gl, program, renderer ) {
  3091. UniformContainer.call( this );
  3092. this.renderer = renderer;
  3093. var n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  3094. for ( var i = 0; i !== n; ++ i ) {
  3095. var info = gl.getActiveUniform( program, i ),
  3096. path = info.name,
  3097. addr = gl.getUniformLocation( program, path );
  3098. parseUniform( info, addr, this );
  3099. }
  3100. };
  3101. WebGLUniforms.prototype.setValue = function( gl, name, value ) {
  3102. var u = this.map[ name ];
  3103. if ( u !== undefined ) u.setValue( gl, value, this.renderer );
  3104. };
  3105. WebGLUniforms.prototype.set = function( gl, object, name ) {
  3106. var u = this.map[ name ];
  3107. if ( u !== undefined ) u.setValue( gl, object[ name ], this.renderer );
  3108. };
  3109. WebGLUniforms.prototype.setOptional = function( gl, object, name ) {
  3110. var v = object[ name ];
  3111. if ( v !== undefined ) this.setValue( gl, name, v );
  3112. };
  3113. // Static interface
  3114. WebGLUniforms.upload = function( gl, seq, values, renderer ) {
  3115. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  3116. var u = seq[ i ],
  3117. v = values[ u.id ];
  3118. if ( v.needsUpdate !== false ) {
  3119. // note: always updating when .needsUpdate is undefined
  3120. u.setValue( gl, v.value, renderer );
  3121. }
  3122. }
  3123. };
  3124. WebGLUniforms.seqWithValue = function( seq, values ) {
  3125. var r = [];
  3126. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  3127. var u = seq[ i ];
  3128. if ( u.id in values ) r.push( u );
  3129. }
  3130. return r;
  3131. };
  3132. WebGLUniforms.splitDynamic = function( seq, values ) {
  3133. var r = null,
  3134. n = seq.length,
  3135. w = 0;
  3136. for ( var i = 0; i !== n; ++ i ) {
  3137. var u = seq[ i ],
  3138. v = values[ u.id ];
  3139. if ( v && v.dynamic === true ) {
  3140. if ( r === null ) r = [];
  3141. r.push( u );
  3142. } else {
  3143. // in-place compact 'seq', removing the matches
  3144. if ( w < i ) seq[ w ] = u;
  3145. ++ w;
  3146. }
  3147. }
  3148. if ( w < n ) seq.length = w;
  3149. return r;
  3150. };
  3151. WebGLUniforms.evalDynamic = function( seq, values, object, camera ) {
  3152. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  3153. var v = values[ seq[ i ].id ],
  3154. f = v.onUpdateCallback;
  3155. if ( f !== undefined ) f.call( v, object, camera );
  3156. }
  3157. };
  3158. return WebGLUniforms;
  3159. } )();
  3160. /**
  3161. * @author mrdoob / http://mrdoob.com/
  3162. */
  3163. function WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, info ) {
  3164. var _infoMemory = info.memory;
  3165. var _isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && _gl instanceof WebGL2RenderingContext );
  3166. //
  3167. function clampToMaxSize( image, maxSize ) {
  3168. if ( image.width > maxSize || image.height > maxSize ) {
  3169. // Warning: Scaling through the canvas will only work with images that use
  3170. // premultiplied alpha.
  3171. var scale = maxSize / Math.max( image.width, image.height );
  3172. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  3173. canvas.width = Math.floor( image.width * scale );
  3174. canvas.height = Math.floor( image.height * scale );
  3175. var context = canvas.getContext( '2d' );
  3176. context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
  3177. console.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  3178. return canvas;
  3179. }
  3180. return image;
  3181. }
  3182. function isPowerOfTwo( image ) {
  3183. return exports.Math.isPowerOfTwo( image.width ) && exports.Math.isPowerOfTwo( image.height );
  3184. }
  3185. function makePowerOfTwo( image ) {
  3186. if ( image instanceof HTMLImageElement || image instanceof HTMLCanvasElement ) {
  3187. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  3188. canvas.width = exports.Math.nearestPowerOfTwo( image.width );
  3189. canvas.height = exports.Math.nearestPowerOfTwo( image.height );
  3190. var context = canvas.getContext( '2d' );
  3191. context.drawImage( image, 0, 0, canvas.width, canvas.height );
  3192. console.warn( 'THREE.WebGLRenderer: image is not power of two (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  3193. return canvas;
  3194. }
  3195. return image;
  3196. }
  3197. function textureNeedsPowerOfTwo( texture ) {
  3198. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) return true;
  3199. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) return true;
  3200. return false;
  3201. }
  3202. // Fallback filters for non-power-of-2 textures
  3203. function filterFallback( f ) {
  3204. if ( f === NearestFilter || f === NearestMipMapNearestFilter || f === NearestMipMapLinearFilter ) {
  3205. return _gl.NEAREST;
  3206. }
  3207. return _gl.LINEAR;
  3208. }
  3209. //
  3210. function onTextureDispose( event ) {
  3211. var texture = event.target;
  3212. texture.removeEventListener( 'dispose', onTextureDispose );
  3213. deallocateTexture( texture );
  3214. _infoMemory.textures --;
  3215. }
  3216. function onRenderTargetDispose( event ) {
  3217. var renderTarget = event.target;
  3218. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  3219. deallocateRenderTarget( renderTarget );
  3220. _infoMemory.textures --;
  3221. }
  3222. //
  3223. function deallocateTexture( texture ) {
  3224. var textureProperties = properties.get( texture );
  3225. if ( texture.image && textureProperties.__image__webglTextureCube ) {
  3226. // cube texture
  3227. _gl.deleteTexture( textureProperties.__image__webglTextureCube );
  3228. } else {
  3229. // 2D texture
  3230. if ( textureProperties.__webglInit === undefined ) return;
  3231. _gl.deleteTexture( textureProperties.__webglTexture );
  3232. }
  3233. // remove all webgl properties
  3234. properties.delete( texture );
  3235. }
  3236. function deallocateRenderTarget( renderTarget ) {
  3237. var renderTargetProperties = properties.get( renderTarget );
  3238. var textureProperties = properties.get( renderTarget.texture );
  3239. if ( ! renderTarget ) return;
  3240. if ( textureProperties.__webglTexture !== undefined ) {
  3241. _gl.deleteTexture( textureProperties.__webglTexture );
  3242. }
  3243. if ( renderTarget.depthTexture ) {
  3244. renderTarget.depthTexture.dispose();
  3245. }
  3246. if ( (renderTarget && renderTarget.isWebGLRenderTargetCube) ) {
  3247. for ( var i = 0; i < 6; i ++ ) {
  3248. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  3249. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  3250. }
  3251. } else {
  3252. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  3253. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  3254. }
  3255. properties.delete( renderTarget.texture );
  3256. properties.delete( renderTarget );
  3257. }
  3258. //
  3259. function setTexture2D( texture, slot ) {
  3260. var textureProperties = properties.get( texture );
  3261. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  3262. var image = texture.image;
  3263. if ( image === undefined ) {
  3264. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined', texture );
  3265. } else if ( image.complete === false ) {
  3266. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture );
  3267. } else {
  3268. uploadTexture( textureProperties, texture, slot );
  3269. return;
  3270. }
  3271. }
  3272. state.activeTexture( _gl.TEXTURE0 + slot );
  3273. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  3274. }
  3275. function setTextureCube( texture, slot ) {
  3276. var textureProperties = properties.get( texture );
  3277. if ( texture.image.length === 6 ) {
  3278. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  3279. if ( ! textureProperties.__image__webglTextureCube ) {
  3280. texture.addEventListener( 'dispose', onTextureDispose );
  3281. textureProperties.__image__webglTextureCube = _gl.createTexture();
  3282. _infoMemory.textures ++;
  3283. }
  3284. state.activeTexture( _gl.TEXTURE0 + slot );
  3285. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  3286. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  3287. var isCompressed = (texture && texture.isCompressedTexture);
  3288. var isDataTexture = (texture.image[ 0 ] && texture.image[ 0 ].isDataTexture);
  3289. var cubeImage = [];
  3290. for ( var i = 0; i < 6; i ++ ) {
  3291. if ( ! isCompressed && ! isDataTexture ) {
  3292. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], capabilities.maxCubemapSize );
  3293. } else {
  3294. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  3295. }
  3296. }
  3297. var image = cubeImage[ 0 ],
  3298. isPowerOfTwoImage = isPowerOfTwo( image ),
  3299. glFormat = paramThreeToGL( texture.format ),
  3300. glType = paramThreeToGL( texture.type );
  3301. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isPowerOfTwoImage );
  3302. for ( var i = 0; i < 6; i ++ ) {
  3303. if ( ! isCompressed ) {
  3304. if ( isDataTexture ) {
  3305. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  3306. } else {
  3307. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  3308. }
  3309. } else {
  3310. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  3311. for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  3312. mipmap = mipmaps[ j ];
  3313. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  3314. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  3315. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  3316. } else {
  3317. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()" );
  3318. }
  3319. } else {
  3320. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  3321. }
  3322. }
  3323. }
  3324. }
  3325. if ( texture.generateMipmaps && isPowerOfTwoImage ) {
  3326. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  3327. }
  3328. textureProperties.__version = texture.version;
  3329. if ( texture.onUpdate ) texture.onUpdate( texture );
  3330. } else {
  3331. state.activeTexture( _gl.TEXTURE0 + slot );
  3332. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  3333. }
  3334. }
  3335. }
  3336. function setTextureCubeDynamic( texture, slot ) {
  3337. state.activeTexture( _gl.TEXTURE0 + slot );
  3338. state.bindTexture( _gl.TEXTURE_CUBE_MAP, properties.get( texture ).__webglTexture );
  3339. }
  3340. function setTextureParameters( textureType, texture, isPowerOfTwoImage ) {
  3341. var extension;
  3342. if ( isPowerOfTwoImage ) {
  3343. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  3344. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  3345. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  3346. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  3347. } else {
  3348. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  3349. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  3350. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  3351. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.', texture );
  3352. }
  3353. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  3354. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  3355. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  3356. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.', texture );
  3357. }
  3358. }
  3359. extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  3360. if ( extension ) {
  3361. if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return;
  3362. if ( texture.type === HalfFloatType && extensions.get( 'OES_texture_half_float_linear' ) === null ) return;
  3363. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  3364. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  3365. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  3366. }
  3367. }
  3368. }
  3369. function uploadTexture( textureProperties, texture, slot ) {
  3370. if ( textureProperties.__webglInit === undefined ) {
  3371. textureProperties.__webglInit = true;
  3372. texture.addEventListener( 'dispose', onTextureDispose );
  3373. textureProperties.__webglTexture = _gl.createTexture();
  3374. _infoMemory.textures ++;
  3375. }
  3376. state.activeTexture( _gl.TEXTURE0 + slot );
  3377. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  3378. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  3379. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  3380. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  3381. var image = clampToMaxSize( texture.image, capabilities.maxTextureSize );
  3382. if ( textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( image ) === false ) {
  3383. image = makePowerOfTwo( image );
  3384. }
  3385. var isPowerOfTwoImage = isPowerOfTwo( image ),
  3386. glFormat = paramThreeToGL( texture.format ),
  3387. glType = paramThreeToGL( texture.type );
  3388. setTextureParameters( _gl.TEXTURE_2D, texture, isPowerOfTwoImage );
  3389. var mipmap, mipmaps = texture.mipmaps;
  3390. if ( (texture && texture.isDepthTexture) ) {
  3391. // populate depth texture with dummy data
  3392. var internalFormat = _gl.DEPTH_COMPONENT;
  3393. if ( texture.type === FloatType ) {
  3394. if ( !_isWebGL2 ) throw new Error('Float Depth Texture only supported in WebGL2.0');
  3395. internalFormat = _gl.DEPTH_COMPONENT32F;
  3396. } else if ( _isWebGL2 ) {
  3397. // WebGL 2.0 requires signed internalformat for glTexImage2D
  3398. internalFormat = _gl.DEPTH_COMPONENT16;
  3399. }
  3400. // Depth stencil textures need the DEPTH_STENCIL internal format
  3401. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  3402. if ( texture.format === DepthStencilFormat ) {
  3403. internalFormat = _gl.DEPTH_STENCIL;
  3404. }
  3405. state.texImage2D( _gl.TEXTURE_2D, 0, internalFormat, image.width, image.height, 0, glFormat, glType, null );
  3406. } else if ( (texture && texture.isDataTexture) ) {
  3407. // use manually created mipmaps if available
  3408. // if there are no manual mipmaps
  3409. // set 0 level mipmap and then use GL to generate other mipmap levels
  3410. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  3411. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  3412. mipmap = mipmaps[ i ];
  3413. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  3414. }
  3415. texture.generateMipmaps = false;
  3416. } else {
  3417. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  3418. }
  3419. } else if ( (texture && texture.isCompressedTexture) ) {
  3420. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  3421. mipmap = mipmaps[ i ];
  3422. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  3423. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  3424. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  3425. } else {
  3426. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()" );
  3427. }
  3428. } else {
  3429. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  3430. }
  3431. }
  3432. } else {
  3433. // regular Texture (image, video, canvas)
  3434. // use manually created mipmaps if available
  3435. // if there are no manual mipmaps
  3436. // set 0 level mipmap and then use GL to generate other mipmap levels
  3437. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  3438. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  3439. mipmap = mipmaps[ i ];
  3440. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  3441. }
  3442. texture.generateMipmaps = false;
  3443. } else {
  3444. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, image );
  3445. }
  3446. }
  3447. if ( texture.generateMipmaps && isPowerOfTwoImage ) _gl.generateMipmap( _gl.TEXTURE_2D );
  3448. textureProperties.__version = texture.version;
  3449. if ( texture.onUpdate ) texture.onUpdate( texture );
  3450. }
  3451. // Render targets
  3452. // Setup storage for target texture and bind it to correct framebuffer
  3453. function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) {
  3454. var glFormat = paramThreeToGL( renderTarget.texture.format );
  3455. var glType = paramThreeToGL( renderTarget.texture.type );
  3456. state.texImage2D( textureTarget, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  3457. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  3458. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
  3459. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  3460. }
  3461. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  3462. function setupRenderBufferStorage( renderbuffer, renderTarget ) {
  3463. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  3464. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  3465. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  3466. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  3467. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  3468. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  3469. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  3470. } else {
  3471. // FIXME: We don't support !depth !stencil
  3472. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  3473. }
  3474. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  3475. }
  3476. // Setup resources for a Depth Texture for a FBO (needs an extension)
  3477. function setupDepthTexture( framebuffer, renderTarget ) {
  3478. var isCube = ( (renderTarget && renderTarget.isWebGLRenderTargetCube) );
  3479. if ( isCube ) throw new Error('Depth Texture with cube render targets is not supported!');
  3480. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  3481. if ( !( (renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture) ) ) {
  3482. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  3483. }
  3484. // upload an empty depth texture with framebuffer size
  3485. if ( !properties.get( renderTarget.depthTexture ).__webglTexture ||
  3486. renderTarget.depthTexture.image.width !== renderTarget.width ||
  3487. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  3488. renderTarget.depthTexture.image.width = renderTarget.width;
  3489. renderTarget.depthTexture.image.height = renderTarget.height;
  3490. renderTarget.depthTexture.needsUpdate = true;
  3491. }
  3492. setTexture2D( renderTarget.depthTexture, 0 );
  3493. var webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  3494. if ( renderTarget.depthTexture.format === DepthFormat ) {
  3495. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  3496. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  3497. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  3498. } else {
  3499. throw new Error('Unknown depthTexture format')
  3500. }
  3501. }
  3502. // Setup GL resources for a non-texture depth buffer
  3503. function setupDepthRenderbuffer( renderTarget ) {
  3504. var renderTargetProperties = properties.get( renderTarget );
  3505. var isCube = ( (renderTarget && renderTarget.isWebGLRenderTargetCube) );
  3506. if ( renderTarget.depthTexture ) {
  3507. if ( isCube ) throw new Error('target.depthTexture not supported in Cube render targets');
  3508. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  3509. } else {
  3510. if ( isCube ) {
  3511. renderTargetProperties.__webglDepthbuffer = [];
  3512. for ( var i = 0; i < 6; i ++ ) {
  3513. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  3514. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  3515. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget );
  3516. }
  3517. } else {
  3518. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  3519. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  3520. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget );
  3521. }
  3522. }
  3523. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  3524. }
  3525. // Set up GL resources for the render target
  3526. function setupRenderTarget( renderTarget ) {
  3527. var renderTargetProperties = properties.get( renderTarget );
  3528. var textureProperties = properties.get( renderTarget.texture );
  3529. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  3530. textureProperties.__webglTexture = _gl.createTexture();
  3531. _infoMemory.textures ++;
  3532. var isCube = ( (renderTarget && renderTarget.isWebGLRenderTargetCube) );
  3533. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget );
  3534. // Setup framebuffer
  3535. if ( isCube ) {
  3536. renderTargetProperties.__webglFramebuffer = [];
  3537. for ( var i = 0; i < 6; i ++ ) {
  3538. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  3539. }
  3540. } else {
  3541. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  3542. }
  3543. // Setup color buffer
  3544. if ( isCube ) {
  3545. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  3546. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, isTargetPowerOfTwo );
  3547. for ( var i = 0; i < 6; i ++ ) {
  3548. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  3549. }
  3550. if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  3551. state.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  3552. } else {
  3553. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  3554. setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, isTargetPowerOfTwo );
  3555. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D );
  3556. if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  3557. state.bindTexture( _gl.TEXTURE_2D, null );
  3558. }
  3559. // Setup depth and stencil buffers
  3560. if ( renderTarget.depthBuffer ) {
  3561. setupDepthRenderbuffer( renderTarget );
  3562. }
  3563. }
  3564. function updateRenderTargetMipmap( renderTarget ) {
  3565. var texture = renderTarget.texture;
  3566. if ( texture.generateMipmaps && isPowerOfTwo( renderTarget ) &&
  3567. texture.minFilter !== NearestFilter &&
  3568. texture.minFilter !== LinearFilter ) {
  3569. var target = (renderTarget && renderTarget.isWebGLRenderTargetCube) ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  3570. var webglTexture = properties.get( texture ).__webglTexture;
  3571. state.bindTexture( target, webglTexture );
  3572. _gl.generateMipmap( target );
  3573. state.bindTexture( target, null );
  3574. }
  3575. }
  3576. this.setTexture2D = setTexture2D;
  3577. this.setTextureCube = setTextureCube;
  3578. this.setTextureCubeDynamic = setTextureCubeDynamic;
  3579. this.setupRenderTarget = setupRenderTarget;
  3580. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  3581. }
  3582. /**
  3583. * @author supereggbert / http://www.paulbrunt.co.uk/
  3584. * @author philogb / http://blog.thejit.org/
  3585. * @author mikael emtinger / http://gomo.se/
  3586. * @author egraether / http://egraether.com/
  3587. * @author WestLangley / http://github.com/WestLangley
  3588. */
  3589. function Vector4( x, y, z, w ) {
  3590. this.x = x || 0;
  3591. this.y = y || 0;
  3592. this.z = z || 0;
  3593. this.w = ( w !== undefined ) ? w : 1;
  3594. }
  3595. Vector4.prototype = {
  3596. constructor: Vector4,
  3597. isVector4: true,
  3598. set: function ( x, y, z, w ) {
  3599. this.x = x;
  3600. this.y = y;
  3601. this.z = z;
  3602. this.w = w;
  3603. return this;
  3604. },
  3605. setScalar: function ( scalar ) {
  3606. this.x = scalar;
  3607. this.y = scalar;
  3608. this.z = scalar;
  3609. this.w = scalar;
  3610. return this;
  3611. },
  3612. setX: function ( x ) {
  3613. this.x = x;
  3614. return this;
  3615. },
  3616. setY: function ( y ) {
  3617. this.y = y;
  3618. return this;
  3619. },
  3620. setZ: function ( z ) {
  3621. this.z = z;
  3622. return this;
  3623. },
  3624. setW: function ( w ) {
  3625. this.w = w;
  3626. return this;
  3627. },
  3628. setComponent: function ( index, value ) {
  3629. switch ( index ) {
  3630. case 0: this.x = value; break;
  3631. case 1: this.y = value; break;
  3632. case 2: this.z = value; break;
  3633. case 3: this.w = value; break;
  3634. default: throw new Error( 'index is out of range: ' + index );
  3635. }
  3636. },
  3637. getComponent: function ( index ) {
  3638. switch ( index ) {
  3639. case 0: return this.x;
  3640. case 1: return this.y;
  3641. case 2: return this.z;
  3642. case 3: return this.w;
  3643. default: throw new Error( 'index is out of range: ' + index );
  3644. }
  3645. },
  3646. clone: function () {
  3647. return new this.constructor( this.x, this.y, this.z, this.w );
  3648. },
  3649. copy: function ( v ) {
  3650. this.x = v.x;
  3651. this.y = v.y;
  3652. this.z = v.z;
  3653. this.w = ( v.w !== undefined ) ? v.w : 1;
  3654. return this;
  3655. },
  3656. add: function ( v, w ) {
  3657. if ( w !== undefined ) {
  3658. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  3659. return this.addVectors( v, w );
  3660. }
  3661. this.x += v.x;
  3662. this.y += v.y;
  3663. this.z += v.z;
  3664. this.w += v.w;
  3665. return this;
  3666. },
  3667. addScalar: function ( s ) {
  3668. this.x += s;
  3669. this.y += s;
  3670. this.z += s;
  3671. this.w += s;
  3672. return this;
  3673. },
  3674. addVectors: function ( a, b ) {
  3675. this.x = a.x + b.x;
  3676. this.y = a.y + b.y;
  3677. this.z = a.z + b.z;
  3678. this.w = a.w + b.w;
  3679. return this;
  3680. },
  3681. addScaledVector: function ( v, s ) {
  3682. this.x += v.x * s;
  3683. this.y += v.y * s;
  3684. this.z += v.z * s;
  3685. this.w += v.w * s;
  3686. return this;
  3687. },
  3688. sub: function ( v, w ) {
  3689. if ( w !== undefined ) {
  3690. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  3691. return this.subVectors( v, w );
  3692. }
  3693. this.x -= v.x;
  3694. this.y -= v.y;
  3695. this.z -= v.z;
  3696. this.w -= v.w;
  3697. return this;
  3698. },
  3699. subScalar: function ( s ) {
  3700. this.x -= s;
  3701. this.y -= s;
  3702. this.z -= s;
  3703. this.w -= s;
  3704. return this;
  3705. },
  3706. subVectors: function ( a, b ) {
  3707. this.x = a.x - b.x;
  3708. this.y = a.y - b.y;
  3709. this.z = a.z - b.z;
  3710. this.w = a.w - b.w;
  3711. return this;
  3712. },
  3713. multiplyScalar: function ( scalar ) {
  3714. if ( isFinite( scalar ) ) {
  3715. this.x *= scalar;
  3716. this.y *= scalar;
  3717. this.z *= scalar;
  3718. this.w *= scalar;
  3719. } else {
  3720. this.x = 0;
  3721. this.y = 0;
  3722. this.z = 0;
  3723. this.w = 0;
  3724. }
  3725. return this;
  3726. },
  3727. applyMatrix4: function ( m ) {
  3728. var x = this.x, y = this.y, z = this.z, w = this.w;
  3729. var e = m.elements;
  3730. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  3731. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  3732. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  3733. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  3734. return this;
  3735. },
  3736. divideScalar: function ( scalar ) {
  3737. return this.multiplyScalar( 1 / scalar );
  3738. },
  3739. setAxisAngleFromQuaternion: function ( q ) {
  3740. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  3741. // q is assumed to be normalized
  3742. this.w = 2 * Math.acos( q.w );
  3743. var s = Math.sqrt( 1 - q.w * q.w );
  3744. if ( s < 0.0001 ) {
  3745. this.x = 1;
  3746. this.y = 0;
  3747. this.z = 0;
  3748. } else {
  3749. this.x = q.x / s;
  3750. this.y = q.y / s;
  3751. this.z = q.z / s;
  3752. }
  3753. return this;
  3754. },
  3755. setAxisAngleFromRotationMatrix: function ( m ) {
  3756. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  3757. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3758. var angle, x, y, z, // variables for result
  3759. epsilon = 0.01, // margin to allow for rounding errors
  3760. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  3761. te = m.elements,
  3762. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  3763. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  3764. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  3765. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  3766. ( Math.abs( m13 - m31 ) < epsilon ) &&
  3767. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  3768. // singularity found
  3769. // first check for identity matrix which must have +1 for all terms
  3770. // in leading diagonal and zero in other terms
  3771. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  3772. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  3773. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  3774. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  3775. // this singularity is identity matrix so angle = 0
  3776. this.set( 1, 0, 0, 0 );
  3777. return this; // zero angle, arbitrary axis
  3778. }
  3779. // otherwise this singularity is angle = 180
  3780. angle = Math.PI;
  3781. var xx = ( m11 + 1 ) / 2;
  3782. var yy = ( m22 + 1 ) / 2;
  3783. var zz = ( m33 + 1 ) / 2;
  3784. var xy = ( m12 + m21 ) / 4;
  3785. var xz = ( m13 + m31 ) / 4;
  3786. var yz = ( m23 + m32 ) / 4;
  3787. if ( ( xx > yy ) && ( xx > zz ) ) {
  3788. // m11 is the largest diagonal term
  3789. if ( xx < epsilon ) {
  3790. x = 0;
  3791. y = 0.707106781;
  3792. z = 0.707106781;
  3793. } else {
  3794. x = Math.sqrt( xx );
  3795. y = xy / x;
  3796. z = xz / x;
  3797. }
  3798. } else if ( yy > zz ) {
  3799. // m22 is the largest diagonal term
  3800. if ( yy < epsilon ) {
  3801. x = 0.707106781;
  3802. y = 0;
  3803. z = 0.707106781;
  3804. } else {
  3805. y = Math.sqrt( yy );
  3806. x = xy / y;
  3807. z = yz / y;
  3808. }
  3809. } else {
  3810. // m33 is the largest diagonal term so base result on this
  3811. if ( zz < epsilon ) {
  3812. x = 0.707106781;
  3813. y = 0.707106781;
  3814. z = 0;
  3815. } else {
  3816. z = Math.sqrt( zz );
  3817. x = xz / z;
  3818. y = yz / z;
  3819. }
  3820. }
  3821. this.set( x, y, z, angle );
  3822. return this; // return 180 deg rotation
  3823. }
  3824. // as we have reached here there are no singularities so we can handle normally
  3825. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  3826. ( m13 - m31 ) * ( m13 - m31 ) +
  3827. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  3828. if ( Math.abs( s ) < 0.001 ) s = 1;
  3829. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  3830. // caught by singularity test above, but I've left it in just in case
  3831. this.x = ( m32 - m23 ) / s;
  3832. this.y = ( m13 - m31 ) / s;
  3833. this.z = ( m21 - m12 ) / s;
  3834. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  3835. return this;
  3836. },
  3837. min: function ( v ) {
  3838. this.x = Math.min( this.x, v.x );
  3839. this.y = Math.min( this.y, v.y );
  3840. this.z = Math.min( this.z, v.z );
  3841. this.w = Math.min( this.w, v.w );
  3842. return this;
  3843. },
  3844. max: function ( v ) {
  3845. this.x = Math.max( this.x, v.x );
  3846. this.y = Math.max( this.y, v.y );
  3847. this.z = Math.max( this.z, v.z );
  3848. this.w = Math.max( this.w, v.w );
  3849. return this;
  3850. },
  3851. clamp: function ( min, max ) {
  3852. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  3853. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  3854. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  3855. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  3856. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  3857. return this;
  3858. },
  3859. clampScalar: function () {
  3860. var min, max;
  3861. return function clampScalar( minVal, maxVal ) {
  3862. if ( min === undefined ) {
  3863. min = new Vector4();
  3864. max = new Vector4();
  3865. }
  3866. min.set( minVal, minVal, minVal, minVal );
  3867. max.set( maxVal, maxVal, maxVal, maxVal );
  3868. return this.clamp( min, max );
  3869. };
  3870. }(),
  3871. floor: function () {
  3872. this.x = Math.floor( this.x );
  3873. this.y = Math.floor( this.y );
  3874. this.z = Math.floor( this.z );
  3875. this.w = Math.floor( this.w );
  3876. return this;
  3877. },
  3878. ceil: function () {
  3879. this.x = Math.ceil( this.x );
  3880. this.y = Math.ceil( this.y );
  3881. this.z = Math.ceil( this.z );
  3882. this.w = Math.ceil( this.w );
  3883. return this;
  3884. },
  3885. round: function () {
  3886. this.x = Math.round( this.x );
  3887. this.y = Math.round( this.y );
  3888. this.z = Math.round( this.z );
  3889. this.w = Math.round( this.w );
  3890. return this;
  3891. },
  3892. roundToZero: function () {
  3893. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  3894. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  3895. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  3896. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  3897. return this;
  3898. },
  3899. negate: function () {
  3900. this.x = - this.x;
  3901. this.y = - this.y;
  3902. this.z = - this.z;
  3903. this.w = - this.w;
  3904. return this;
  3905. },
  3906. dot: function ( v ) {
  3907. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  3908. },
  3909. lengthSq: function () {
  3910. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  3911. },
  3912. length: function () {
  3913. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  3914. },
  3915. lengthManhattan: function () {
  3916. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  3917. },
  3918. normalize: function () {
  3919. return this.divideScalar( this.length() );
  3920. },
  3921. setLength: function ( length ) {
  3922. return this.multiplyScalar( length / this.length() );
  3923. },
  3924. lerp: function ( v, alpha ) {
  3925. this.x += ( v.x - this.x ) * alpha;
  3926. this.y += ( v.y - this.y ) * alpha;
  3927. this.z += ( v.z - this.z ) * alpha;
  3928. this.w += ( v.w - this.w ) * alpha;
  3929. return this;
  3930. },
  3931. lerpVectors: function ( v1, v2, alpha ) {
  3932. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  3933. },
  3934. equals: function ( v ) {
  3935. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  3936. },
  3937. fromArray: function ( array, offset ) {
  3938. if ( offset === undefined ) offset = 0;
  3939. this.x = array[ offset ];
  3940. this.y = array[ offset + 1 ];
  3941. this.z = array[ offset + 2 ];
  3942. this.w = array[ offset + 3 ];
  3943. return this;
  3944. },
  3945. toArray: function ( array, offset ) {
  3946. if ( array === undefined ) array = [];
  3947. if ( offset === undefined ) offset = 0;
  3948. array[ offset ] = this.x;
  3949. array[ offset + 1 ] = this.y;
  3950. array[ offset + 2 ] = this.z;
  3951. array[ offset + 3 ] = this.w;
  3952. return array;
  3953. },
  3954. fromAttribute: function ( attribute, index, offset ) {
  3955. if ( offset === undefined ) offset = 0;
  3956. index = index * attribute.itemSize + offset;
  3957. this.x = attribute.array[ index ];
  3958. this.y = attribute.array[ index + 1 ];
  3959. this.z = attribute.array[ index + 2 ];
  3960. this.w = attribute.array[ index + 3 ];
  3961. return this;
  3962. }
  3963. };
  3964. /**
  3965. * @author mrdoob / http://mrdoob.com/
  3966. */
  3967. function WebGLState( gl, extensions, paramThreeToGL ) {
  3968. var _this = this;
  3969. this.buffers = {
  3970. color: new WebGLColorBuffer( gl, this ),
  3971. depth: new WebGLDepthBuffer( gl, this ),
  3972. stencil: new WebGLStencilBuffer( gl, this )
  3973. };
  3974. var maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  3975. var newAttributes = new Uint8Array( maxVertexAttributes );
  3976. var enabledAttributes = new Uint8Array( maxVertexAttributes );
  3977. var attributeDivisors = new Uint8Array( maxVertexAttributes );
  3978. var capabilities = {};
  3979. var compressedTextureFormats = null;
  3980. var currentBlending = null;
  3981. var currentBlendEquation = null;
  3982. var currentBlendSrc = null;
  3983. var currentBlendDst = null;
  3984. var currentBlendEquationAlpha = null;
  3985. var currentBlendSrcAlpha = null;
  3986. var currentBlendDstAlpha = null;
  3987. var currentPremultipledAlpha = false;
  3988. var currentFlipSided = null;
  3989. var currentCullFace = null;
  3990. var currentLineWidth = null;
  3991. var currentPolygonOffsetFactor = null;
  3992. var currentPolygonOffsetUnits = null;
  3993. var currentScissorTest = null;
  3994. var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  3995. var currentTextureSlot = null;
  3996. var currentBoundTextures = {};
  3997. var currentScissor = new Vector4();
  3998. var currentViewport = new Vector4();
  3999. function createTexture( type, target, count ) {
  4000. var data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  4001. var texture = gl.createTexture();
  4002. gl.bindTexture( type, texture );
  4003. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  4004. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  4005. for ( var i = 0; i < count; i ++ ) {
  4006. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  4007. }
  4008. return texture;
  4009. }
  4010. var emptyTextures = {};
  4011. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  4012. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  4013. //
  4014. this.init = function () {
  4015. this.clearColor( 0, 0, 0, 1 );
  4016. this.clearDepth( 1 );
  4017. this.clearStencil( 0 );
  4018. this.enable( gl.DEPTH_TEST );
  4019. this.setDepthFunc( LessEqualDepth );
  4020. this.setFlipSided( false );
  4021. this.setCullFace( CullFaceBack );
  4022. this.enable( gl.CULL_FACE );
  4023. this.enable( gl.BLEND );
  4024. this.setBlending( NormalBlending );
  4025. };
  4026. this.initAttributes = function () {
  4027. for ( var i = 0, l = newAttributes.length; i < l; i ++ ) {
  4028. newAttributes[ i ] = 0;
  4029. }
  4030. };
  4031. this.enableAttribute = function ( attribute ) {
  4032. newAttributes[ attribute ] = 1;
  4033. if ( enabledAttributes[ attribute ] === 0 ) {
  4034. gl.enableVertexAttribArray( attribute );
  4035. enabledAttributes[ attribute ] = 1;
  4036. }
  4037. if ( attributeDivisors[ attribute ] !== 0 ) {
  4038. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  4039. extension.vertexAttribDivisorANGLE( attribute, 0 );
  4040. attributeDivisors[ attribute ] = 0;
  4041. }
  4042. };
  4043. this.enableAttributeAndDivisor = function ( attribute, meshPerAttribute, extension ) {
  4044. newAttributes[ attribute ] = 1;
  4045. if ( enabledAttributes[ attribute ] === 0 ) {
  4046. gl.enableVertexAttribArray( attribute );
  4047. enabledAttributes[ attribute ] = 1;
  4048. }
  4049. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  4050. extension.vertexAttribDivisorANGLE( attribute, meshPerAttribute );
  4051. attributeDivisors[ attribute ] = meshPerAttribute;
  4052. }
  4053. };
  4054. this.disableUnusedAttributes = function () {
  4055. for ( var i = 0, l = enabledAttributes.length; i !== l; ++ i ) {
  4056. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  4057. gl.disableVertexAttribArray( i );
  4058. enabledAttributes[ i ] = 0;
  4059. }
  4060. }
  4061. };
  4062. this.enable = function ( id ) {
  4063. if ( capabilities[ id ] !== true ) {
  4064. gl.enable( id );
  4065. capabilities[ id ] = true;
  4066. }
  4067. };
  4068. this.disable = function ( id ) {
  4069. if ( capabilities[ id ] !== false ) {
  4070. gl.disable( id );
  4071. capabilities[ id ] = false;
  4072. }
  4073. };
  4074. this.getCompressedTextureFormats = function () {
  4075. if ( compressedTextureFormats === null ) {
  4076. compressedTextureFormats = [];
  4077. if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) ||
  4078. extensions.get( 'WEBGL_compressed_texture_s3tc' ) ||
  4079. extensions.get( 'WEBGL_compressed_texture_etc1' ) ) {
  4080. var formats = gl.getParameter( gl.COMPRESSED_TEXTURE_FORMATS );
  4081. for ( var i = 0; i < formats.length; i ++ ) {
  4082. compressedTextureFormats.push( formats[ i ] );
  4083. }
  4084. }
  4085. }
  4086. return compressedTextureFormats;
  4087. };
  4088. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  4089. if ( blending !== NoBlending ) {
  4090. this.enable( gl.BLEND );
  4091. } else {
  4092. this.disable( gl.BLEND );
  4093. currentBlending = blending; // no blending, that is
  4094. return;
  4095. }
  4096. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  4097. if ( blending === AdditiveBlending ) {
  4098. if ( premultipliedAlpha ) {
  4099. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  4100. gl.blendFuncSeparate( gl.ONE, gl.ONE, gl.ONE, gl.ONE );
  4101. } else {
  4102. gl.blendEquation( gl.FUNC_ADD );
  4103. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  4104. }
  4105. } else if ( blending === SubtractiveBlending ) {
  4106. if ( premultipliedAlpha ) {
  4107. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  4108. gl.blendFuncSeparate( gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA );
  4109. } else {
  4110. gl.blendEquation( gl.FUNC_ADD );
  4111. gl.blendFunc( gl.ZERO, gl.ONE_MINUS_SRC_COLOR );
  4112. }
  4113. } else if ( blending === MultiplyBlending ) {
  4114. if ( premultipliedAlpha ) {
  4115. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  4116. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  4117. } else {
  4118. gl.blendEquation( gl.FUNC_ADD );
  4119. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  4120. }
  4121. } else {
  4122. if ( premultipliedAlpha ) {
  4123. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  4124. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  4125. } else {
  4126. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  4127. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  4128. }
  4129. }
  4130. currentBlending = blending;
  4131. currentPremultipledAlpha = premultipliedAlpha;
  4132. }
  4133. if ( blending === CustomBlending ) {
  4134. blendEquationAlpha = blendEquationAlpha || blendEquation;
  4135. blendSrcAlpha = blendSrcAlpha || blendSrc;
  4136. blendDstAlpha = blendDstAlpha || blendDst;
  4137. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  4138. gl.blendEquationSeparate( paramThreeToGL( blendEquation ), paramThreeToGL( blendEquationAlpha ) );
  4139. currentBlendEquation = blendEquation;
  4140. currentBlendEquationAlpha = blendEquationAlpha;
  4141. }
  4142. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  4143. gl.blendFuncSeparate( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ), paramThreeToGL( blendSrcAlpha ), paramThreeToGL( blendDstAlpha ) );
  4144. currentBlendSrc = blendSrc;
  4145. currentBlendDst = blendDst;
  4146. currentBlendSrcAlpha = blendSrcAlpha;
  4147. currentBlendDstAlpha = blendDstAlpha;
  4148. }
  4149. } else {
  4150. currentBlendEquation = null;
  4151. currentBlendSrc = null;
  4152. currentBlendDst = null;
  4153. currentBlendEquationAlpha = null;
  4154. currentBlendSrcAlpha = null;
  4155. currentBlendDstAlpha = null;
  4156. }
  4157. };
  4158. // TODO Deprecate
  4159. this.setColorWrite = function ( colorWrite ) {
  4160. this.buffers.color.setMask( colorWrite );
  4161. };
  4162. this.setDepthTest = function ( depthTest ) {
  4163. this.buffers.depth.setTest( depthTest );
  4164. };
  4165. this.setDepthWrite = function ( depthWrite ) {
  4166. this.buffers.depth.setMask( depthWrite );
  4167. };
  4168. this.setDepthFunc = function ( depthFunc ) {
  4169. this.buffers.depth.setFunc( depthFunc );
  4170. };
  4171. this.setStencilTest = function ( stencilTest ) {
  4172. this.buffers.stencil.setTest( stencilTest );
  4173. };
  4174. this.setStencilWrite = function ( stencilWrite ) {
  4175. this.buffers.stencil.setMask( stencilWrite );
  4176. };
  4177. this.setStencilFunc = function ( stencilFunc, stencilRef, stencilMask ) {
  4178. this.buffers.stencil.setFunc( stencilFunc, stencilRef, stencilMask );
  4179. };
  4180. this.setStencilOp = function ( stencilFail, stencilZFail, stencilZPass ) {
  4181. this.buffers.stencil.setOp( stencilFail, stencilZFail, stencilZPass );
  4182. };
  4183. //
  4184. this.setFlipSided = function ( flipSided ) {
  4185. if ( currentFlipSided !== flipSided ) {
  4186. if ( flipSided ) {
  4187. gl.frontFace( gl.CW );
  4188. } else {
  4189. gl.frontFace( gl.CCW );
  4190. }
  4191. currentFlipSided = flipSided;
  4192. }
  4193. };
  4194. this.setCullFace = function ( cullFace ) {
  4195. if ( cullFace !== CullFaceNone ) {
  4196. this.enable( gl.CULL_FACE );
  4197. if ( cullFace !== currentCullFace ) {
  4198. if ( cullFace === CullFaceBack ) {
  4199. gl.cullFace( gl.BACK );
  4200. } else if ( cullFace === CullFaceFront ) {
  4201. gl.cullFace( gl.FRONT );
  4202. } else {
  4203. gl.cullFace( gl.FRONT_AND_BACK );
  4204. }
  4205. }
  4206. } else {
  4207. this.disable( gl.CULL_FACE );
  4208. }
  4209. currentCullFace = cullFace;
  4210. };
  4211. this.setLineWidth = function ( width ) {
  4212. if ( width !== currentLineWidth ) {
  4213. gl.lineWidth( width );
  4214. currentLineWidth = width;
  4215. }
  4216. };
  4217. this.setPolygonOffset = function ( polygonOffset, factor, units ) {
  4218. if ( polygonOffset ) {
  4219. this.enable( gl.POLYGON_OFFSET_FILL );
  4220. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  4221. gl.polygonOffset( factor, units );
  4222. currentPolygonOffsetFactor = factor;
  4223. currentPolygonOffsetUnits = units;
  4224. }
  4225. } else {
  4226. this.disable( gl.POLYGON_OFFSET_FILL );
  4227. }
  4228. };
  4229. this.getScissorTest = function () {
  4230. return currentScissorTest;
  4231. };
  4232. this.setScissorTest = function ( scissorTest ) {
  4233. currentScissorTest = scissorTest;
  4234. if ( scissorTest ) {
  4235. this.enable( gl.SCISSOR_TEST );
  4236. } else {
  4237. this.disable( gl.SCISSOR_TEST );
  4238. }
  4239. };
  4240. // texture
  4241. this.activeTexture = function ( webglSlot ) {
  4242. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  4243. if ( currentTextureSlot !== webglSlot ) {
  4244. gl.activeTexture( webglSlot );
  4245. currentTextureSlot = webglSlot;
  4246. }
  4247. };
  4248. this.bindTexture = function ( webglType, webglTexture ) {
  4249. if ( currentTextureSlot === null ) {
  4250. _this.activeTexture();
  4251. }
  4252. var boundTexture = currentBoundTextures[ currentTextureSlot ];
  4253. if ( boundTexture === undefined ) {
  4254. boundTexture = { type: undefined, texture: undefined };
  4255. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  4256. }
  4257. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  4258. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  4259. boundTexture.type = webglType;
  4260. boundTexture.texture = webglTexture;
  4261. }
  4262. };
  4263. this.compressedTexImage2D = function () {
  4264. try {
  4265. gl.compressedTexImage2D.apply( gl, arguments );
  4266. } catch ( error ) {
  4267. console.error( error );
  4268. }
  4269. };
  4270. this.texImage2D = function () {
  4271. try {
  4272. gl.texImage2D.apply( gl, arguments );
  4273. } catch ( error ) {
  4274. console.error( error );
  4275. }
  4276. };
  4277. // TODO Deprecate
  4278. this.clearColor = function ( r, g, b, a ) {
  4279. this.buffers.color.setClear( r, g, b, a );
  4280. };
  4281. this.clearDepth = function ( depth ) {
  4282. this.buffers.depth.setClear( depth );
  4283. };
  4284. this.clearStencil = function ( stencil ) {
  4285. this.buffers.stencil.setClear( stencil );
  4286. };
  4287. //
  4288. this.scissor = function ( scissor ) {
  4289. if ( currentScissor.equals( scissor ) === false ) {
  4290. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  4291. currentScissor.copy( scissor );
  4292. }
  4293. };
  4294. this.viewport = function ( viewport ) {
  4295. if ( currentViewport.equals( viewport ) === false ) {
  4296. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  4297. currentViewport.copy( viewport );
  4298. }
  4299. };
  4300. //
  4301. this.reset = function () {
  4302. for ( var i = 0; i < enabledAttributes.length; i ++ ) {
  4303. if ( enabledAttributes[ i ] === 1 ) {
  4304. gl.disableVertexAttribArray( i );
  4305. enabledAttributes[ i ] = 0;
  4306. }
  4307. }
  4308. capabilities = {};
  4309. compressedTextureFormats = null;
  4310. currentTextureSlot = null;
  4311. currentBoundTextures = {};
  4312. currentBlending = null;
  4313. currentFlipSided = null;
  4314. currentCullFace = null;
  4315. this.buffers.color.reset();
  4316. this.buffers.depth.reset();
  4317. this.buffers.stencil.reset();
  4318. };
  4319. };
  4320. function WebGLColorBuffer( gl, state ) {
  4321. var locked = false;
  4322. var color = new Vector4();
  4323. var currentColorMask = null;
  4324. var currentColorClear = new Vector4();
  4325. this.setMask = function ( colorMask ) {
  4326. if ( currentColorMask !== colorMask && ! locked ) {
  4327. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  4328. currentColorMask = colorMask;
  4329. }
  4330. };
  4331. this.setLocked = function ( lock ) {
  4332. locked = lock;
  4333. };
  4334. this.setClear = function ( r, g, b, a ) {
  4335. color.set( r, g, b, a );
  4336. if ( currentColorClear.equals( color ) === false ) {
  4337. gl.clearColor( r, g, b, a );
  4338. currentColorClear.copy( color );
  4339. }
  4340. };
  4341. this.reset = function () {
  4342. locked = false;
  4343. currentColorMask = null;
  4344. currentColorClear = new Vector4();
  4345. };
  4346. };
  4347. function WebGLDepthBuffer( gl, state ) {
  4348. var locked = false;
  4349. var currentDepthMask = null;
  4350. var currentDepthFunc = null;
  4351. var currentDepthClear = null;
  4352. this.setTest = function ( depthTest ) {
  4353. if ( depthTest ) {
  4354. state.enable( gl.DEPTH_TEST );
  4355. } else {
  4356. state.disable( gl.DEPTH_TEST );
  4357. }
  4358. };
  4359. this.setMask = function( depthMask ){
  4360. if ( currentDepthMask !== depthMask && ! locked ) {
  4361. gl.depthMask( depthMask );
  4362. currentDepthMask = depthMask;
  4363. }
  4364. };
  4365. this.setFunc = function ( depthFunc ) {
  4366. if ( currentDepthFunc !== depthFunc ) {
  4367. if ( depthFunc ) {
  4368. switch ( depthFunc ) {
  4369. case NeverDepth:
  4370. gl.depthFunc( gl.NEVER );
  4371. break;
  4372. case AlwaysDepth:
  4373. gl.depthFunc( gl.ALWAYS );
  4374. break;
  4375. case LessDepth:
  4376. gl.depthFunc( gl.LESS );
  4377. break;
  4378. case LessEqualDepth:
  4379. gl.depthFunc( gl.LEQUAL );
  4380. break;
  4381. case EqualDepth:
  4382. gl.depthFunc( gl.EQUAL );
  4383. break;
  4384. case GreaterEqualDepth:
  4385. gl.depthFunc( gl.GEQUAL );
  4386. break;
  4387. case GreaterDepth:
  4388. gl.depthFunc( gl.GREATER );
  4389. break;
  4390. case NotEqualDepth:
  4391. gl.depthFunc( gl.NOTEQUAL );
  4392. break;
  4393. default:
  4394. gl.depthFunc( gl.LEQUAL );
  4395. }
  4396. } else {
  4397. gl.depthFunc( gl.LEQUAL );
  4398. }
  4399. currentDepthFunc = depthFunc;
  4400. }
  4401. };
  4402. this.setLocked = function ( lock ) {
  4403. locked = lock;
  4404. };
  4405. this.setClear = function ( depth ) {
  4406. if ( currentDepthClear !== depth ) {
  4407. gl.clearDepth( depth );
  4408. currentDepthClear = depth;
  4409. }
  4410. };
  4411. this.reset = function () {
  4412. locked = false;
  4413. currentDepthMask = null;
  4414. currentDepthFunc = null;
  4415. currentDepthClear = null;
  4416. };
  4417. };
  4418. function WebGLStencilBuffer( gl, state ) {
  4419. var locked = false;
  4420. var currentStencilMask = null;
  4421. var currentStencilFunc = null;
  4422. var currentStencilRef = null;
  4423. var currentStencilFuncMask = null;
  4424. var currentStencilFail = null;
  4425. var currentStencilZFail = null;
  4426. var currentStencilZPass = null;
  4427. var currentStencilClear = null;
  4428. this.setTest = function ( stencilTest ) {
  4429. if ( stencilTest ) {
  4430. state.enable( gl.STENCIL_TEST );
  4431. } else {
  4432. state.disable( gl.STENCIL_TEST );
  4433. }
  4434. };
  4435. this.setMask = function ( stencilMask ) {
  4436. if ( currentStencilMask !== stencilMask && ! locked ) {
  4437. gl.stencilMask( stencilMask );
  4438. currentStencilMask = stencilMask;
  4439. }
  4440. };
  4441. this.setFunc = function ( stencilFunc, stencilRef, stencilMask ) {
  4442. if ( currentStencilFunc !== stencilFunc ||
  4443. currentStencilRef !== stencilRef ||
  4444. currentStencilFuncMask !== stencilMask ) {
  4445. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  4446. currentStencilFunc = stencilFunc;
  4447. currentStencilRef = stencilRef;
  4448. currentStencilFuncMask = stencilMask;
  4449. }
  4450. };
  4451. this.setOp = function ( stencilFail, stencilZFail, stencilZPass ) {
  4452. if ( currentStencilFail !== stencilFail ||
  4453. currentStencilZFail !== stencilZFail ||
  4454. currentStencilZPass !== stencilZPass ) {
  4455. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  4456. currentStencilFail = stencilFail;
  4457. currentStencilZFail = stencilZFail;
  4458. currentStencilZPass = stencilZPass;
  4459. }
  4460. };
  4461. this.setLocked = function ( lock ) {
  4462. locked = lock;
  4463. };
  4464. this.setClear = function ( stencil ) {
  4465. if ( currentStencilClear !== stencil ) {
  4466. gl.clearStencil( stencil );
  4467. currentStencilClear = stencil;
  4468. }
  4469. };
  4470. this.reset = function () {
  4471. locked = false;
  4472. currentStencilMask = null;
  4473. currentStencilFunc = null;
  4474. currentStencilRef = null;
  4475. currentStencilFuncMask = null;
  4476. currentStencilFail = null;
  4477. currentStencilZFail = null;
  4478. currentStencilZPass = null;
  4479. currentStencilClear = null;
  4480. };
  4481. }
  4482. /**
  4483. * @author szimek / https://github.com/szimek/
  4484. * @author alteredq / http://alteredqualia.com/
  4485. * @author Marius Kintel / https://github.com/kintel
  4486. */
  4487. /*
  4488. In options, we can specify:
  4489. * Texture parameters for an auto-generated target texture
  4490. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  4491. */
  4492. function WebGLRenderTarget( width, height, options ) {
  4493. this.uuid = exports.Math.generateUUID();
  4494. this.width = width;
  4495. this.height = height;
  4496. this.scissor = new Vector4( 0, 0, width, height );
  4497. this.scissorTest = false;
  4498. this.viewport = new Vector4( 0, 0, width, height );
  4499. options = options || {};
  4500. if ( options.minFilter === undefined ) options.minFilter = LinearFilter;
  4501. this.texture = new Texture( undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  4502. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  4503. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  4504. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  4505. }
  4506. Object.assign( WebGLRenderTarget.prototype, EventDispatcher.prototype, {
  4507. isWebGLRenderTarget: true,
  4508. setSize: function ( width, height ) {
  4509. if ( this.width !== width || this.height !== height ) {
  4510. this.width = width;
  4511. this.height = height;
  4512. this.dispose();
  4513. }
  4514. this.viewport.set( 0, 0, width, height );
  4515. this.scissor.set( 0, 0, width, height );
  4516. },
  4517. clone: function () {
  4518. return new this.constructor().copy( this );
  4519. },
  4520. copy: function ( source ) {
  4521. this.width = source.width;
  4522. this.height = source.height;
  4523. this.viewport.copy( source.viewport );
  4524. this.texture = source.texture.clone();
  4525. this.depthBuffer = source.depthBuffer;
  4526. this.stencilBuffer = source.stencilBuffer;
  4527. this.depthTexture = source.depthTexture;
  4528. return this;
  4529. },
  4530. dispose: function () {
  4531. this.dispatchEvent( { type: 'dispose' } );
  4532. }
  4533. } );
  4534. /**
  4535. * @author mrdoob / http://mrdoob.com/
  4536. * @author alteredq / http://alteredqualia.com/
  4537. */
  4538. function Material() {
  4539. Object.defineProperty( this, 'id', { value: MaterialIdCount() } );
  4540. this.uuid = exports.Math.generateUUID();
  4541. this.name = '';
  4542. this.type = 'Material';
  4543. this.fog = true;
  4544. this.lights = true;
  4545. this.blending = NormalBlending;
  4546. this.side = FrontSide;
  4547. this.shading = SmoothShading; // THREE.FlatShading, THREE.SmoothShading
  4548. this.vertexColors = NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors
  4549. this.opacity = 1;
  4550. this.transparent = false;
  4551. this.blendSrc = SrcAlphaFactor;
  4552. this.blendDst = OneMinusSrcAlphaFactor;
  4553. this.blendEquation = AddEquation;
  4554. this.blendSrcAlpha = null;
  4555. this.blendDstAlpha = null;
  4556. this.blendEquationAlpha = null;
  4557. this.depthFunc = LessEqualDepth;
  4558. this.depthTest = true;
  4559. this.depthWrite = true;
  4560. this.clippingPlanes = null;
  4561. this.clipShadows = false;
  4562. this.colorWrite = true;
  4563. this.precision = null; // override the renderer's default precision for this material
  4564. this.polygonOffset = false;
  4565. this.polygonOffsetFactor = 0;
  4566. this.polygonOffsetUnits = 0;
  4567. this.alphaTest = 0;
  4568. this.premultipliedAlpha = false;
  4569. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  4570. this.visible = true;
  4571. this._needsUpdate = true;
  4572. }
  4573. Material.prototype = {
  4574. constructor: Material,
  4575. isMaterial: true,
  4576. get needsUpdate() {
  4577. return this._needsUpdate;
  4578. },
  4579. set needsUpdate( value ) {
  4580. if ( value === true ) this.update();
  4581. this._needsUpdate = value;
  4582. },
  4583. setValues: function ( values ) {
  4584. if ( values === undefined ) return;
  4585. for ( var key in values ) {
  4586. var newValue = values[ key ];
  4587. if ( newValue === undefined ) {
  4588. console.warn( "THREE.Material: '" + key + "' parameter is undefined." );
  4589. continue;
  4590. }
  4591. var currentValue = this[ key ];
  4592. if ( currentValue === undefined ) {
  4593. console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." );
  4594. continue;
  4595. }
  4596. if ( (currentValue && currentValue.isColor) ) {
  4597. currentValue.set( newValue );
  4598. } else if ( (currentValue && currentValue.isVector3) && (newValue && newValue.isVector3) ) {
  4599. currentValue.copy( newValue );
  4600. } else if ( key === 'overdraw' ) {
  4601. // ensure overdraw is backwards-compatible with legacy boolean type
  4602. this[ key ] = Number( newValue );
  4603. } else {
  4604. this[ key ] = newValue;
  4605. }
  4606. }
  4607. },
  4608. toJSON: function ( meta ) {
  4609. var isRoot = meta === undefined;
  4610. if ( isRoot ) {
  4611. meta = {
  4612. textures: {},
  4613. images: {}
  4614. };
  4615. }
  4616. var data = {
  4617. metadata: {
  4618. version: 4.4,
  4619. type: 'Material',
  4620. generator: 'Material.toJSON'
  4621. }
  4622. };
  4623. // standard Material serialization
  4624. data.uuid = this.uuid;
  4625. data.type = this.type;
  4626. if ( this.name !== '' ) data.name = this.name;
  4627. if ( (this.color && this.color.isColor) ) data.color = this.color.getHex();
  4628. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  4629. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  4630. if ( (this.emissive && this.emissive.isColor) ) data.emissive = this.emissive.getHex();
  4631. if ( (this.specular && this.specular.isColor) ) data.specular = this.specular.getHex();
  4632. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  4633. if ( (this.map && this.map.isTexture) ) data.map = this.map.toJSON( meta ).uuid;
  4634. if ( (this.alphaMap && this.alphaMap.isTexture) ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  4635. if ( (this.lightMap && this.lightMap.isTexture) ) data.lightMap = this.lightMap.toJSON( meta ).uuid;
  4636. if ( (this.bumpMap && this.bumpMap.isTexture) ) {
  4637. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  4638. data.bumpScale = this.bumpScale;
  4639. }
  4640. if ( (this.normalMap && this.normalMap.isTexture) ) {
  4641. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  4642. data.normalScale = this.normalScale.toArray();
  4643. }
  4644. if ( (this.displacementMap && this.displacementMap.isTexture) ) {
  4645. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  4646. data.displacementScale = this.displacementScale;
  4647. data.displacementBias = this.displacementBias;
  4648. }
  4649. if ( (this.roughnessMap && this.roughnessMap.isTexture) ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  4650. if ( (this.metalnessMap && this.metalnessMap.isTexture) ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  4651. if ( (this.emissiveMap && this.emissiveMap.isTexture) ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  4652. if ( (this.specularMap && this.specularMap.isTexture) ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  4653. if ( (this.envMap && this.envMap.isTexture) ) {
  4654. data.envMap = this.envMap.toJSON( meta ).uuid;
  4655. data.reflectivity = this.reflectivity; // Scale behind envMap
  4656. }
  4657. if ( this.size !== undefined ) data.size = this.size;
  4658. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  4659. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  4660. if ( this.shading !== SmoothShading ) data.shading = this.shading;
  4661. if ( this.side !== FrontSide ) data.side = this.side;
  4662. if ( this.vertexColors !== NoColors ) data.vertexColors = this.vertexColors;
  4663. if ( this.opacity < 1 ) data.opacity = this.opacity;
  4664. if ( this.transparent === true ) data.transparent = this.transparent;
  4665. data.depthFunc = this.depthFunc;
  4666. data.depthTest = this.depthTest;
  4667. data.depthWrite = this.depthWrite;
  4668. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  4669. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  4670. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  4671. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  4672. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  4673. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  4674. data.skinning = this.skinning;
  4675. data.morphTargets = this.morphTargets;
  4676. // TODO: Copied from Object3D.toJSON
  4677. function extractFromCache( cache ) {
  4678. var values = [];
  4679. for ( var key in cache ) {
  4680. var data = cache[ key ];
  4681. delete data.metadata;
  4682. values.push( data );
  4683. }
  4684. return values;
  4685. }
  4686. if ( isRoot ) {
  4687. var textures = extractFromCache( meta.textures );
  4688. var images = extractFromCache( meta.images );
  4689. if ( textures.length > 0 ) data.textures = textures;
  4690. if ( images.length > 0 ) data.images = images;
  4691. }
  4692. return data;
  4693. },
  4694. clone: function () {
  4695. return new this.constructor().copy( this );
  4696. },
  4697. copy: function ( source ) {
  4698. this.name = source.name;
  4699. this.fog = source.fog;
  4700. this.lights = source.lights;
  4701. this.blending = source.blending;
  4702. this.side = source.side;
  4703. this.shading = source.shading;
  4704. this.vertexColors = source.vertexColors;
  4705. this.opacity = source.opacity;
  4706. this.transparent = source.transparent;
  4707. this.blendSrc = source.blendSrc;
  4708. this.blendDst = source.blendDst;
  4709. this.blendEquation = source.blendEquation;
  4710. this.blendSrcAlpha = source.blendSrcAlpha;
  4711. this.blendDstAlpha = source.blendDstAlpha;
  4712. this.blendEquationAlpha = source.blendEquationAlpha;
  4713. this.depthFunc = source.depthFunc;
  4714. this.depthTest = source.depthTest;
  4715. this.depthWrite = source.depthWrite;
  4716. this.colorWrite = source.colorWrite;
  4717. this.precision = source.precision;
  4718. this.polygonOffset = source.polygonOffset;
  4719. this.polygonOffsetFactor = source.polygonOffsetFactor;
  4720. this.polygonOffsetUnits = source.polygonOffsetUnits;
  4721. this.alphaTest = source.alphaTest;
  4722. this.premultipliedAlpha = source.premultipliedAlpha;
  4723. this.overdraw = source.overdraw;
  4724. this.visible = source.visible;
  4725. this.clipShadows = source.clipShadows;
  4726. var srcPlanes = source.clippingPlanes,
  4727. dstPlanes = null;
  4728. if ( srcPlanes !== null ) {
  4729. var n = srcPlanes.length;
  4730. dstPlanes = new Array( n );
  4731. for ( var i = 0; i !== n; ++ i )
  4732. dstPlanes[ i ] = srcPlanes[ i ].clone();
  4733. }
  4734. this.clippingPlanes = dstPlanes;
  4735. return this;
  4736. },
  4737. update: function () {
  4738. this.dispatchEvent( { type: 'update' } );
  4739. },
  4740. dispose: function () {
  4741. this.dispatchEvent( { type: 'dispose' } );
  4742. }
  4743. };
  4744. Object.assign( Material.prototype, EventDispatcher.prototype );
  4745. var count$1 = 0;
  4746. function MaterialIdCount() { return count$1++; };
  4747. /**
  4748. * Uniform Utilities
  4749. */
  4750. exports.UniformsUtils = {
  4751. merge: function ( uniforms ) {
  4752. var merged = {};
  4753. for ( var u = 0; u < uniforms.length; u ++ ) {
  4754. var tmp = this.clone( uniforms[ u ] );
  4755. for ( var p in tmp ) {
  4756. merged[ p ] = tmp[ p ];
  4757. }
  4758. }
  4759. return merged;
  4760. },
  4761. clone: function ( uniforms_src ) {
  4762. var uniforms_dst = {};
  4763. for ( var u in uniforms_src ) {
  4764. uniforms_dst[ u ] = {};
  4765. for ( var p in uniforms_src[ u ] ) {
  4766. var parameter_src = uniforms_src[ u ][ p ];
  4767. if ( (parameter_src && parameter_src.isColor) ||
  4768. (parameter_src && parameter_src.isVector2) ||
  4769. (parameter_src && parameter_src.isVector3) ||
  4770. (parameter_src && parameter_src.isVector4) ||
  4771. (parameter_src && parameter_src.isMatrix3) ||
  4772. (parameter_src && parameter_src.isMatrix4) ||
  4773. (parameter_src && parameter_src.isTexture) ) {
  4774. uniforms_dst[ u ][ p ] = parameter_src.clone();
  4775. } else if ( Array.isArray( parameter_src ) ) {
  4776. uniforms_dst[ u ][ p ] = parameter_src.slice();
  4777. } else {
  4778. uniforms_dst[ u ][ p ] = parameter_src;
  4779. }
  4780. }
  4781. }
  4782. return uniforms_dst;
  4783. }
  4784. };
  4785. /**
  4786. * @author alteredq / http://alteredqualia.com/
  4787. *
  4788. * parameters = {
  4789. * defines: { "label" : "value" },
  4790. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  4791. *
  4792. * fragmentShader: <string>,
  4793. * vertexShader: <string>,
  4794. *
  4795. * wireframe: <boolean>,
  4796. * wireframeLinewidth: <float>,
  4797. *
  4798. * lights: <bool>,
  4799. *
  4800. * skinning: <bool>,
  4801. * morphTargets: <bool>,
  4802. * morphNormals: <bool>
  4803. * }
  4804. */
  4805. function ShaderMaterial( parameters ) {
  4806. Material.call( this );
  4807. this.type = 'ShaderMaterial';
  4808. this.defines = {};
  4809. this.uniforms = {};
  4810. this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}';
  4811. this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}';
  4812. this.linewidth = 1;
  4813. this.wireframe = false;
  4814. this.wireframeLinewidth = 1;
  4815. this.fog = false; // set to use scene fog
  4816. this.lights = false; // set to use scene lights
  4817. this.clipping = false; // set to use user-defined clipping planes
  4818. this.skinning = false; // set to use skinning attribute streams
  4819. this.morphTargets = false; // set to use morph targets
  4820. this.morphNormals = false; // set to use morph normals
  4821. this.extensions = {
  4822. derivatives: false, // set to use derivatives
  4823. fragDepth: false, // set to use fragment depth values
  4824. drawBuffers: false, // set to use draw buffers
  4825. shaderTextureLOD: false // set to use shader texture LOD
  4826. };
  4827. // When rendered geometry doesn't include these attributes but the material does,
  4828. // use these default values in WebGL. This avoids errors when buffer data is missing.
  4829. this.defaultAttributeValues = {
  4830. 'color': [ 1, 1, 1 ],
  4831. 'uv': [ 0, 0 ],
  4832. 'uv2': [ 0, 0 ]
  4833. };
  4834. this.index0AttributeName = undefined;
  4835. if ( parameters !== undefined ) {
  4836. if ( parameters.attributes !== undefined ) {
  4837. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  4838. }
  4839. this.setValues( parameters );
  4840. }
  4841. }
  4842. ShaderMaterial.prototype = Object.create( Material.prototype );
  4843. ShaderMaterial.prototype.constructor = ShaderMaterial;
  4844. ShaderMaterial.prototype.isShaderMaterial = true;
  4845. ShaderMaterial.prototype.copy = function ( source ) {
  4846. Material.prototype.copy.call( this, source );
  4847. this.fragmentShader = source.fragmentShader;
  4848. this.vertexShader = source.vertexShader;
  4849. this.uniforms = exports.UniformsUtils.clone( source.uniforms );
  4850. this.defines = source.defines;
  4851. this.wireframe = source.wireframe;
  4852. this.wireframeLinewidth = source.wireframeLinewidth;
  4853. this.lights = source.lights;
  4854. this.clipping = source.clipping;
  4855. this.skinning = source.skinning;
  4856. this.morphTargets = source.morphTargets;
  4857. this.morphNormals = source.morphNormals;
  4858. this.extensions = source.extensions;
  4859. return this;
  4860. };
  4861. ShaderMaterial.prototype.toJSON = function ( meta ) {
  4862. var data = Material.prototype.toJSON.call( this, meta );
  4863. data.uniforms = this.uniforms;
  4864. data.vertexShader = this.vertexShader;
  4865. data.fragmentShader = this.fragmentShader;
  4866. return data;
  4867. };
  4868. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif\n";
  4869. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif\n";
  4870. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif\n";
  4871. var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\t#endif\n#endif\n";
  4872. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  4873. var begin_vertex = "\nvec3 transformed = vec3( position );\n";
  4874. var beginnormal_vertex = "\nvec3 objectNormal = vec3( normal );\n";
  4875. var bsdfs = "bool testLightInRange( const in float lightDistance, const in float cutoffDistance ) {\n\treturn any( bvec2( cutoffDistance == 0.0, lightDistance < cutoffDistance ) );\n}\nfloat punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\t\tif( decayExponent > 0.0 ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\t\tfloat maxDistanceCutoffFactor = pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t\treturn distanceFalloff * maxDistanceCutoffFactor;\n#else\n\t\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n#endif\n\t\t}\n\t\treturn 1.0;\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec3 BRDF_Specular_GGX_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n\treturn specularColor * AB.x + AB.y;\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn 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\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n";
  4876. var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n\t\tvec3 vSigmaX = dFdx( surf_pos );\n\t\tvec3 vSigmaY = dFdy( surf_pos );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 );\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif\n";
  4877. var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tfor ( int i = 0; i < NUM_CLIPPING_PLANES; ++ i ) {\n\t\tvec4 plane = clippingPlanes[ i ];\n\t\tif ( dot( vViewPosition, plane.xyz ) > plane.w ) discard;\n\t}\n#endif\n";
  4878. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\t#if ! defined( PHYSICAL ) && ! defined( PHONG )\n\t\tvarying vec3 vViewPosition;\n\t#endif\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif\n";
  4879. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvarying vec3 vViewPosition;\n#endif\n";
  4880. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n";
  4881. var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";
  4882. var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif\n";
  4883. var color_pars_vertex = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  4884. var color_vertex = "#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif";
  4885. var common = "#define PI 3.14159265359\n#define PI2 6.28318530718\n#define RECIPROCAL_PI 0.31830988618\n#define RECIPROCAL_PI2 0.15915494\n#define LOG2 1.442695\n#define EPSILON 1e-6\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define whiteCompliment(a) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract(sin(sn) * c);\n}\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\treturn - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n}\n";
  4886. var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n#define cubeUV_textureSize (1024.0)\nint getFaceFromDirection(vec3 direction) {\n\tvec3 absDirection = abs(direction);\n\tint face = -1;\n\tif( absDirection.x > absDirection.z ) {\n\t\tif(absDirection.x > absDirection.y )\n\t\t\tface = direction.x > 0.0 ? 0 : 3;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\telse {\n\t\tif(absDirection.z > absDirection.y )\n\t\t\tface = direction.z > 0.0 ? 2 : 5;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\treturn face;\n}\n#define cubeUV_maxLods1 (log2(cubeUV_textureSize*0.25) - 1.0)\n#define cubeUV_rangeClamp (exp2((6.0 - 1.0) * 2.0))\nvec2 MipLevelInfo( vec3 vec, float roughnessLevel, float roughness ) {\n\tfloat scale = exp2(cubeUV_maxLods1 - roughnessLevel);\n\tfloat dxRoughness = dFdx(roughness);\n\tfloat dyRoughness = dFdy(roughness);\n\tvec3 dx = dFdx( vec * scale * dxRoughness );\n\tvec3 dy = dFdy( vec * scale * dyRoughness );\n\tfloat d = max( dot( dx, dx ), dot( dy, dy ) );\n\td = clamp(d, 1.0, cubeUV_rangeClamp);\n\tfloat mipLevel = 0.5 * log2(d);\n\treturn vec2(floor(mipLevel), fract(mipLevel));\n}\n#define cubeUV_maxLods2 (log2(cubeUV_textureSize*0.25) - 2.0)\n#define cubeUV_rcpTextureSize (1.0 / cubeUV_textureSize)\nvec2 getCubeUV(vec3 direction, float roughnessLevel, float mipLevel) {\n\tmipLevel = roughnessLevel > cubeUV_maxLods2 - 3.0 ? 0.0 : mipLevel;\n\tfloat a = 16.0 * cubeUV_rcpTextureSize;\n\tvec2 exp2_packed = exp2( vec2( roughnessLevel, mipLevel ) );\n\tvec2 rcp_exp2_packed = vec2( 1.0 ) / exp2_packed;\n\tfloat powScale = exp2_packed.x * exp2_packed.y;\n\tfloat scale = rcp_exp2_packed.x * rcp_exp2_packed.y * 0.25;\n\tfloat mipOffset = 0.75*(1.0 - rcp_exp2_packed.y) * rcp_exp2_packed.x;\n\tbool bRes = mipLevel == 0.0;\n\tscale = bRes && (scale < a) ? a : scale;\n\tvec3 r;\n\tvec2 offset;\n\tint face = getFaceFromDirection(direction);\n\tfloat rcpPowScale = 1.0 / powScale;\n\tif( face == 0) {\n\t\tr = vec3(direction.x, -direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 1) {\n\t\tr = vec3(direction.y, direction.x, direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 2) {\n\t\tr = vec3(direction.z, direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 3) {\n\t\tr = vec3(direction.x, direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse if( face == 4) {\n\t\tr = vec3(direction.y, direction.x, -direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse {\n\t\tr = vec3(direction.z, -direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\tr = normalize(r);\n\tfloat texelOffset = 0.5 * cubeUV_rcpTextureSize;\n\tvec2 s = ( r.yz / abs( r.x ) + vec2( 1.0 ) ) * 0.5;\n\tvec2 base = offset + vec2( texelOffset );\n\treturn base + s * ( scale - 2.0 * texelOffset );\n}\n#define cubeUV_maxLods3 (log2(cubeUV_textureSize*0.25) - 3.0)\nvec4 textureCubeUV(vec3 reflectedDirection, float roughness ) {\n\tfloat roughnessVal = roughness* cubeUV_maxLods3;\n\tfloat r1 = floor(roughnessVal);\n\tfloat r2 = r1 + 1.0;\n\tfloat t = fract(roughnessVal);\n\tvec2 mipInfo = MipLevelInfo(reflectedDirection, r1, roughness);\n\tfloat s = mipInfo.y;\n\tfloat level0 = mipInfo.x;\n\tfloat level1 = level0 + 1.0;\n\tlevel1 = level1 > 5.0 ? 5.0 : level1;\n\tlevel0 += min( floor( s + 0.5 ), 5.0 );\n\tvec2 uv_10 = getCubeUV(reflectedDirection, r1, level0);\n\tvec4 color10 = envMapTexelToLinear(texture2D(envMap, uv_10));\n\tvec2 uv_20 = getCubeUV(reflectedDirection, r2, level0);\n\tvec4 color20 = envMapTexelToLinear(texture2D(envMap, uv_20));\n\tvec4 result = mix(color10, color20, t);\n\treturn vec4(result.rgb, 1.0);\n}\n#endif\n";
  4887. var defaultnormal_vertex = "#ifdef FLIP_SIDED\n\tobjectNormal = -objectNormal;\n#endif\nvec3 transformedNormal = normalMatrix * objectNormal;\n";
  4888. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif\n";
  4889. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normal * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n#endif\n";
  4890. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif\n";
  4891. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif\n";
  4892. var encodings_fragment = " gl_FragColor = linearToOutputTexel( gl_FragColor );\n";
  4893. var encodings_pars_fragment = "\nvec4 LinearToLinear( in vec4 value ) {\n return value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.w );\n}\nvec4 RGBEToLinear( in vec4 value ) {\n return vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n float maxComponent = max( max( value.r, value.g ), value.b );\n float fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n return vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n return vec4( value.xyz * value.w * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n float maxRGB = max( value.x, max( value.g, value.b ) );\n float M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n M = ceil( M * 255.0 ) / 255.0;\n return vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n return vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n float maxRGB = max( value.x, max( value.g, value.b ) );\n float D = max( maxRange / maxRGB, 1.0 );\n D = min( floor( D ) / 255.0, 1.0 );\n return vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n vec3 Xp_Y_XYZp = value.rgb * cLogLuvM;\n Xp_Y_XYZp = max(Xp_Y_XYZp, vec3(1e-6, 1e-6, 1e-6));\n vec4 vResult;\n vResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n float Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n vResult.w = fract(Le);\n vResult.z = (Le - (floor(vResult.w*255.0))/255.0)/255.0;\n return vResult;\n}\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n float Le = value.z * 255.0 + value.w;\n vec3 Xp_Y_XYZp;\n Xp_Y_XYZp.y = exp2((Le - 127.0) / 2.0);\n Xp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n Xp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n vec3 vRGB = Xp_Y_XYZp.rgb * cLogLuvInverseM;\n return vec4( max(vRGB, 0.0), 1.0 );\n}\n";
  4894. var envmap_fragment = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\tvec2 sampleUV;\n\t\tsampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 );\n\t\tsampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\tvec3 reflectView = flipNormal * normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0, 0.0, 1.0 ) );\n\t\tvec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n\t#endif\n\tenvColor = envMapTexelToLinear( envColor );\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif\n";
  4895. var envmap_pars_fragment = "#if defined( USE_ENVMAP ) || defined( PHYSICAL )\n\tuniform float reflectivity;\n\tuniform float envMapIntenstiy;\n#endif\n#ifdef USE_ENVMAP\n\t#if ! defined( PHYSICAL ) && ( defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) )\n\t\tvarying vec3 vWorldPosition;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\tuniform float flipEnvMap;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( PHYSICAL )\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif\n";
  4896. var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif\n";
  4897. var envmap_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif\n";
  4898. var fog_fragment = "#ifdef USE_FOG\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tfloat depth = gl_FragDepthEXT / gl_FragCoord.w;\n\t#else\n\t\tfloat depth = gl_FragCoord.z / gl_FragCoord.w;\n\t#endif\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = whiteCompliment( exp2( - fogDensity * fogDensity * depth * depth * LOG2 ) );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, depth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif\n";
  4899. var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif";
  4900. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif\n";
  4901. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  4902. var 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\tvLightBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\n#if NUM_POINT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_DIR_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvLightFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n#endif\n";
  4903. var lights_pars = "uniform vec3 ambientLightColor;\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treturn irradiance;\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tif ( testLightInRange( lightDistance, pointLight.distance ) ) {\n\t\t\tdirectLight.color = pointLight.color;\n\t\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( all( bvec2( angleCos > spotLight.coneCos, testLightInRange( lightDistance, spotLight.distance ) ) ) ) {\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tirradiance *= PI;\n\t\t#endif\n\t\treturn irradiance;\n\t}\n#endif\n#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\tvec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\t#include <normal_flip>\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = flipNormal * vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryVec = flipNormal * vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\tvec4 envMapColor = textureCubeUV( queryVec, 1.0 );\n\t\t#else\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\t\t#endif\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t}\n\tfloat getSpecularMIPLevel( const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( pow2( blinnShininessExponent ) + 1.0 );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in GeometricContext geometry, const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( -geometry.viewDir, geometry.normal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( -geometry.viewDir, geometry.normal, refractionRatio );\n\t\t#endif\n\t\t#include <normal_flip>\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( blinnShininessExponent, maxMIPLevel );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryReflectVec = flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryReflectVec = flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\tvec4 envMapColor = textureCubeUV(queryReflectVec, BlinnExponentToGGXRoughness(blinnShininessExponent));\n\t\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\t\tvec2 sampleUV;\n\t\t\tsampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 );\n\t\t\tsampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\t\tvec3 reflectView = flipNormal * normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0,0.0,1.0 ) );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif\n";
  4904. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n";
  4905. var lights_phong_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n\tvec3\tdiffuseColor;\n\tvec3\tspecularColor;\n\tfloat\tspecularShininess;\n\tfloat\tspecularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.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\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)\n";
  4906. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.specularRoughness = clamp( roughnessFactor, 0.04, 1.0 );\n#ifdef STANDARD\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.clearCoat = saturate( clearCoat );\tmaterial.clearCoatRoughness = clamp( clearCoatRoughness, 0.04, 1.0 );\n#endif\n";
  4907. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3\tdiffuseColor;\n\tfloat\tspecularRoughness;\n\tvec3\tspecularColor;\n\t#ifndef STANDARD\n\t\tfloat clearCoat;\n\t\tfloat clearCoatRoughness;\n\t#endif\n};\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\nfloat clearCoatDHRApprox( const in float roughness, const in float dotNL ) {\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n}\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\t#ifndef STANDARD\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\treflectedLight.directSpecular += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry, material.specularColor, material.specularRoughness );\n\treflectedLight.directDiffuse += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\t#ifndef STANDARD\n\t\treflectedLight.directSpecular += irradiance * material.clearCoat * BRDF_Specular_GGX( directLight, geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\t#endif\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 clearCoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t#ifndef STANDARD\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\tfloat dotNL = dotNV;\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\treflectedLight.indirectSpecular += ( 1.0 - clearCoatDHR ) * radiance * BRDF_Specular_GGX_Environment( geometry, material.specularColor, material.specularRoughness );\n\t#ifndef STANDARD\n\t\treflectedLight.indirectSpecular += clearCoatRadiance * material.clearCoat * BRDF_Specular_GGX_Environment( geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\t#endif\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\n#define Material_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.specularRoughness )\n#define Material_ClearCoat_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.clearCoatRoughness )\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}\n";
  4908. var lights_template = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = normalize( vViewPosition );\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( pointLight.shadow, directLight.visible ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( spotLight.shadow, directLight.visible ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( directionalLight.shadow, directLight.visible ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#ifdef USE_LIGHTMAP\n\t\tvec3 lightMapIrradiance = texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t \tirradiance += getLightProbeIndirectIrradiance( geometry, 8 );\n\t#endif\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tvec3 radiance = getLightProbeIndirectRadiance( geometry, Material_BlinnShininessExponent( material ), 8 );\n\t#ifndef STANDARD\n\t\tvec3 clearCoatRadiance = getLightProbeIndirectRadiance( geometry, Material_ClearCoat_BlinnShininessExponent( material ), 8 );\n\t#else\n\t\tvec3 clearCoatRadiance = vec3( 0.0 );\n\t#endif\n\t\t\n\tRE_IndirectSpecular( radiance, clearCoatRadiance, geometry, material, reflectedLight );\n#endif\n";
  4909. var logdepthbuf_fragment = "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n\tgl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n#endif";
  4910. var logdepthbuf_pars_fragment = "#ifdef USE_LOGDEPTHBUF\n\tuniform float logDepthBufFC;\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n#endif\n";
  4911. var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n\tuniform float logDepthBufFC;\n#endif";
  4912. var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\tgl_Position.z = log2(max( EPSILON, gl_Position.w + 1.0 )) * logDepthBufFC;\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t#else\n\t\tgl_Position.z = (gl_Position.z - 1.0) * gl_Position.w;\n\t#endif\n#endif\n";
  4913. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif\n";
  4914. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n";
  4915. var map_particle_fragment = "#ifdef USE_MAP\n\tvec4 mapTexel = texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) * offsetRepeat.zw + offsetRepeat.xy );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n";
  4916. var map_particle_pars_fragment = "#ifdef USE_MAP\n\tuniform vec4 offsetRepeat;\n\tuniform sampler2D map;\n#endif\n";
  4917. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.r;\n#endif\n";
  4918. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  4919. var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];\n\tobjectNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];\n\tobjectNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];\n\tobjectNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];\n#endif\n";
  4920. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\t#ifndef USE_MORPHNORMALS\n\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif";
  4921. var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];\n\ttransformed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];\n\ttransformed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];\n\ttransformed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\ttransformed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];\n\ttransformed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];\n\ttransformed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];\n\ttransformed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];\n\t#endif\n#endif\n";
  4922. var normal_flip = "#ifdef DOUBLE_SIDED\n\tfloat flipNormal = ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n#else\n\tfloat flipNormal = 1.0;\n#endif\n";
  4923. var normal_fragment = "#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal ) * flipNormal;\n#endif\n#ifdef USE_NORMALMAP\n\tnormal = perturbNormal2Arb( -vViewPosition, normal );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif\n";
  4924. var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tvec3 S = normalize( q0 * st1.t - q1 * st0.t );\n\t\tvec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n\t\tvec3 N = normalize( surf_norm );\n\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\tmapN.xy = normalScale * mapN.xy;\n\t\tmat3 tsn = mat3( S, T, N );\n\t\treturn normalize( tsn * mapN );\n\t}\n#endif\n";
  4925. var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n return normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n return 1.0 - 2.0 * rgb.xyz;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n return ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n return linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n return (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n return ( near * far ) / ( ( far - near ) * invClipZ - far );\n}\n";
  4926. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif\n";
  4927. var project_vertex = "#ifdef USE_SKINNING\n\tvec4 mvPosition = modelViewMatrix * skinned;\n#else\n\tvec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );\n#endif\ngl_Position = projectionMatrix * mvPosition;\n";
  4928. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.r;\n#endif\n";
  4929. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  4930. var shadowmap_pars_fragment = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tfloat texture2DShadowLerp( sampler2D depths, vec2 size, vec2 uv, float compare ) {\n\t\tconst vec2 offset = vec2( 0.0, 1.0 );\n\t\tvec2 texelSize = vec2( 1.0 ) / size;\n\t\tvec2 centroidUV = floor( uv * size + 0.5 ) / size;\n\t\tfloat lb = texture2DCompare( depths, centroidUV + texelSize * offset.xx, compare );\n\t\tfloat lt = texture2DCompare( depths, centroidUV + texelSize * offset.xy, compare );\n\t\tfloat rb = texture2DCompare( depths, centroidUV + texelSize * offset.yx, compare );\n\t\tfloat rt = texture2DCompare( depths, centroidUV + texelSize * offset.yy, compare );\n\t\tvec2 f = fract( uv * size + 0.5 );\n\t\tfloat a = mix( lb, lt, f.y );\n\t\tfloat b = mix( rb, rt, f.y );\n\t\tfloat c = mix( a, b, f.x );\n\t\treturn c;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\treturn (\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn 1.0;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\tfloat dp = ( length( lightToPosition ) - shadowBias ) / 1000.0;\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif\n";
  4931. var shadowmap_pars_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n#endif\n";
  4932. var shadowmap_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n#endif\n";
  4933. var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\tDirectionalLight directionalLight;\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tshadow *= bool( directionalLight.shadow ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\tSpotLight spotLight;\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tshadow *= bool( spotLight.shadow ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\tPointLight pointLight;\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tshadow *= bool( pointLight.shadow ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#endif\n\treturn shadow;\n}\n";
  4934. var skinbase_vertex = "#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif";
  4935. var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform sampler2D boneTexture;\n\t\tuniform int boneTextureWidth;\n\t\tuniform int boneTextureHeight;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureWidth ) );\n\t\t\tfloat y = floor( j / float( boneTextureWidth ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureWidth );\n\t\t\tfloat dy = 1.0 / float( boneTextureHeight );\n\t\t\ty = dy * ( y + 0.5 );\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\t\treturn bone;\n\t\t}\n\t#else\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\t\t}\n\t#endif\n#endif\n";
  4936. var skinning_vertex = "#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\tskinned = bindMatrixInverse * skinned;\n#endif\n";
  4937. var skinnormal_vertex = "#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n#endif\n";
  4938. var specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif";
  4939. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  4940. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif\n";
  4941. var tonemapping_pars_fragment = "#define saturate(a) clamp( a, 0.0, 1.0 )\nuniform float toneMappingExposure;\nuniform float toneMappingWhitePoint;\nvec3 LinearToneMapping( vec3 color ) {\n return toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n color *= toneMappingExposure;\n return saturate( color / ( vec3( 1.0 ) + color ) );\n}\n#define Uncharted2Helper( x ) max( ( ( x * ( 0.15 * x + 0.10 * 0.50 ) + 0.20 * 0.02 ) / ( x * ( 0.15 * x + 0.50 ) + 0.20 * 0.30 ) ) - 0.02 / 0.30, vec3( 0.0 ) )\nvec3 Uncharted2ToneMapping( vec3 color ) {\n color *= toneMappingExposure;\n return saturate( Uncharted2Helper( color ) / Uncharted2Helper( vec3( toneMappingWhitePoint ) ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n color *= toneMappingExposure;\n color = max( vec3( 0.0 ), color - 0.004 );\n return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\n";
  4942. var 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\tvarying vec2 vUv;\n#endif";
  4943. var 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\tvarying vec2 vUv;\n\tuniform vec4 offsetRepeat;\n#endif\n";
  4944. var 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\tvUv = uv * offsetRepeat.zw + offsetRepeat.xy;\n#endif";
  4945. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  4946. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif";
  4947. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif";
  4948. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( PHYSICAL ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )\n\t#ifdef USE_SKINNING\n\t\tvec4 worldPosition = modelMatrix * skinned;\n\t#else\n\t\tvec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n\t#endif\n#endif\n";
  4949. var cube_frag = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tgl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );\n\tgl_FragColor.a *= opacity;\n}\n";
  4950. var cube_vert = "varying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}\n";
  4951. var depth_frag = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <logdepthbuf_fragment>\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( gl_FragCoord.z ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( gl_FragCoord.z );\n\t#endif\n}\n";
  4952. var depth_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#include <begin_vertex>\n\t#include <displacementmap_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n}\n";
  4953. var distanceRGBA_frag = "uniform vec3 lightPos;\nvarying vec4 vWorldPosition;\n#include <common>\n#include <packing>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tgl_FragColor = packDepthToRGBA( length( vWorldPosition.xyz - lightPos.xyz ) / 1000.0 );\n}\n";
  4954. var distanceRGBA_vert = "varying vec4 vWorldPosition;\n#include <common>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <skinbase_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition;\n}\n";
  4955. var equirect_frag = "uniform sampler2D tEquirect;\nuniform float tFlip;\nvarying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldPosition );\n\tvec2 sampleUV;\n\tsampleUV.y = saturate( tFlip * direction.y * -0.5 + 0.5 );\n\tsampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n}\n";
  4956. var equirect_vert = "varying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}\n";
  4957. var linedashed_frag = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n";
  4958. var linedashed_vert = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\tvLineDistance = scale * lineDistance;\n\tvec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n}\n";
  4959. var meshbasic_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight;\n\treflectedLight.directDiffuse = vec3( 0.0 );\n\treflectedLight.directSpecular = vec3( 0.0 );\n\treflectedLight.indirectDiffuse = diffuseColor.rgb;\n\treflectedLight.indirectSpecular = vec3( 0.0 );\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <normal_flip>\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n";
  4960. var meshbasic_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_ENVMAP\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <envmap_vertex>\n}\n";
  4961. var meshlambert_frag = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n#endif\n#include <common>\n#include <packing>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <bsdfs>\n#include <lights_pars>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <emissivemap_fragment>\n\treflectedLight.indirectDiffuse = getAmbientLightIrradiance( ambientLightColor );\n\t#include <lightmap_fragment>\n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <normal_flip>\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n";
  4962. var meshlambert_vert = "#define LAMBERT\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <bsdfs>\n#include <lights_pars>\n#include <color_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <lights_lambert_vertex>\n\t#include <shadowmap_vertex>\n}\n";
  4963. var meshphong_frag = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_flip>\n\t#include <normal_fragment>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_template>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n";
  4964. var meshphong_vert = "#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <displacementmap_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n}\n";
  4965. var meshphysical_frag = "#define PHYSICAL\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifndef STANDARD\n\tuniform float clearCoat;\n\tuniform float clearCoatRoughness;\n#endif\nuniform float envMapIntensity;\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <packing>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <cube_uv_reflection_fragment>\n#include <lights_pars>\n#include <lights_physical_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_flip>\n\t#include <normal_fragment>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_template>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n";
  4966. var meshphysical_vert = "#define PHYSICAL\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <displacementmap_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n}\n";
  4967. var normal_frag = "uniform float opacity;\nvarying vec3 vNormal;\n#include <common>\n#include <packing>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tgl_FragColor = vec4( packNormalToRGB( vNormal ), opacity );\n\t#include <logdepthbuf_fragment>\n}\n";
  4968. var normal_vert = "varying vec3 vNormal;\n#include <common>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\tvNormal = normalize( normalMatrix * normal );\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n}\n";
  4969. var points_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n";
  4970. var points_vert = "uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#ifdef USE_SIZEATTENUATION\n\t\tgl_PointSize = size * ( scale / - mvPosition.z );\n\t#else\n\t\tgl_PointSize = size;\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n}\n";
  4971. var shadow_frag = "uniform float opacity;\n#include <common>\n#include <packing>\n#include <bsdfs>\n#include <lights_pars>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( 0.0, 0.0, 0.0, opacity * ( 1.0 - getShadowMask() ) );\n}\n";
  4972. var shadow_vert = "#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n}\n";
  4973. var ShaderChunk = {
  4974. alphamap_fragment: alphamap_fragment,
  4975. alphamap_pars_fragment: alphamap_pars_fragment,
  4976. alphatest_fragment: alphatest_fragment,
  4977. aomap_fragment: aomap_fragment,
  4978. aomap_pars_fragment: aomap_pars_fragment,
  4979. begin_vertex: begin_vertex,
  4980. beginnormal_vertex: beginnormal_vertex,
  4981. bsdfs: bsdfs,
  4982. bumpmap_pars_fragment: bumpmap_pars_fragment,
  4983. clipping_planes_fragment: clipping_planes_fragment,
  4984. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  4985. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  4986. clipping_planes_vertex: clipping_planes_vertex,
  4987. color_fragment: color_fragment,
  4988. color_pars_fragment: color_pars_fragment,
  4989. color_pars_vertex: color_pars_vertex,
  4990. color_vertex: color_vertex,
  4991. common: common,
  4992. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  4993. defaultnormal_vertex: defaultnormal_vertex,
  4994. displacementmap_pars_vertex: displacementmap_pars_vertex,
  4995. displacementmap_vertex: displacementmap_vertex,
  4996. emissivemap_fragment: emissivemap_fragment,
  4997. emissivemap_pars_fragment: emissivemap_pars_fragment,
  4998. encodings_fragment: encodings_fragment,
  4999. encodings_pars_fragment: encodings_pars_fragment,
  5000. envmap_fragment: envmap_fragment,
  5001. envmap_pars_fragment: envmap_pars_fragment,
  5002. envmap_pars_vertex: envmap_pars_vertex,
  5003. envmap_vertex: envmap_vertex,
  5004. fog_fragment: fog_fragment,
  5005. fog_pars_fragment: fog_pars_fragment,
  5006. lightmap_fragment: lightmap_fragment,
  5007. lightmap_pars_fragment: lightmap_pars_fragment,
  5008. lights_lambert_vertex: lights_lambert_vertex,
  5009. lights_pars: lights_pars,
  5010. lights_phong_fragment: lights_phong_fragment,
  5011. lights_phong_pars_fragment: lights_phong_pars_fragment,
  5012. lights_physical_fragment: lights_physical_fragment,
  5013. lights_physical_pars_fragment: lights_physical_pars_fragment,
  5014. lights_template: lights_template,
  5015. logdepthbuf_fragment: logdepthbuf_fragment,
  5016. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  5017. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  5018. logdepthbuf_vertex: logdepthbuf_vertex,
  5019. map_fragment: map_fragment,
  5020. map_pars_fragment: map_pars_fragment,
  5021. map_particle_fragment: map_particle_fragment,
  5022. map_particle_pars_fragment: map_particle_pars_fragment,
  5023. metalnessmap_fragment: metalnessmap_fragment,
  5024. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  5025. morphnormal_vertex: morphnormal_vertex,
  5026. morphtarget_pars_vertex: morphtarget_pars_vertex,
  5027. morphtarget_vertex: morphtarget_vertex,
  5028. normal_flip: normal_flip,
  5029. normal_fragment: normal_fragment,
  5030. normalmap_pars_fragment: normalmap_pars_fragment,
  5031. packing: packing,
  5032. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  5033. project_vertex: project_vertex,
  5034. roughnessmap_fragment: roughnessmap_fragment,
  5035. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  5036. shadowmap_pars_fragment: shadowmap_pars_fragment,
  5037. shadowmap_pars_vertex: shadowmap_pars_vertex,
  5038. shadowmap_vertex: shadowmap_vertex,
  5039. shadowmask_pars_fragment: shadowmask_pars_fragment,
  5040. skinbase_vertex: skinbase_vertex,
  5041. skinning_pars_vertex: skinning_pars_vertex,
  5042. skinning_vertex: skinning_vertex,
  5043. skinnormal_vertex: skinnormal_vertex,
  5044. specularmap_fragment: specularmap_fragment,
  5045. specularmap_pars_fragment: specularmap_pars_fragment,
  5046. tonemapping_fragment: tonemapping_fragment,
  5047. tonemapping_pars_fragment: tonemapping_pars_fragment,
  5048. uv_pars_fragment: uv_pars_fragment,
  5049. uv_pars_vertex: uv_pars_vertex,
  5050. uv_vertex: uv_vertex,
  5051. uv2_pars_fragment: uv2_pars_fragment,
  5052. uv2_pars_vertex: uv2_pars_vertex,
  5053. uv2_vertex: uv2_vertex,
  5054. worldpos_vertex: worldpos_vertex,
  5055. cube_frag: cube_frag,
  5056. cube_vert: cube_vert,
  5057. depth_frag: depth_frag,
  5058. depth_vert: depth_vert,
  5059. distanceRGBA_frag: distanceRGBA_frag,
  5060. distanceRGBA_vert: distanceRGBA_vert,
  5061. equirect_frag: equirect_frag,
  5062. equirect_vert: equirect_vert,
  5063. linedashed_frag: linedashed_frag,
  5064. linedashed_vert: linedashed_vert,
  5065. meshbasic_frag: meshbasic_frag,
  5066. meshbasic_vert: meshbasic_vert,
  5067. meshlambert_frag: meshlambert_frag,
  5068. meshlambert_vert: meshlambert_vert,
  5069. meshphong_frag: meshphong_frag,
  5070. meshphong_vert: meshphong_vert,
  5071. meshphysical_frag: meshphysical_frag,
  5072. meshphysical_vert: meshphysical_vert,
  5073. normal_frag: normal_frag,
  5074. normal_vert: normal_vert,
  5075. points_frag: points_frag,
  5076. points_vert: points_vert,
  5077. shadow_frag: shadow_frag,
  5078. shadow_vert: shadow_vert
  5079. };
  5080. /**
  5081. * @author mrdoob / http://mrdoob.com/
  5082. */
  5083. function Color( r, g, b ) {
  5084. if ( g === undefined && b === undefined ) {
  5085. // r is THREE.Color, hex or string
  5086. return this.set( r );
  5087. }
  5088. return this.setRGB( r, g, b );
  5089. }
  5090. Color.prototype = {
  5091. constructor: Color,
  5092. isColor: true,
  5093. r: 1, g: 1, b: 1,
  5094. set: function ( value ) {
  5095. if ( (value && value.isColor) ) {
  5096. this.copy( value );
  5097. } else if ( typeof value === 'number' ) {
  5098. this.setHex( value );
  5099. } else if ( typeof value === 'string' ) {
  5100. this.setStyle( value );
  5101. }
  5102. return this;
  5103. },
  5104. setScalar: function ( scalar ) {
  5105. this.r = scalar;
  5106. this.g = scalar;
  5107. this.b = scalar;
  5108. },
  5109. setHex: function ( hex ) {
  5110. hex = Math.floor( hex );
  5111. this.r = ( hex >> 16 & 255 ) / 255;
  5112. this.g = ( hex >> 8 & 255 ) / 255;
  5113. this.b = ( hex & 255 ) / 255;
  5114. return this;
  5115. },
  5116. setRGB: function ( r, g, b ) {
  5117. this.r = r;
  5118. this.g = g;
  5119. this.b = b;
  5120. return this;
  5121. },
  5122. setHSL: function () {
  5123. function hue2rgb( p, q, t ) {
  5124. if ( t < 0 ) t += 1;
  5125. if ( t > 1 ) t -= 1;
  5126. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  5127. if ( t < 1 / 2 ) return q;
  5128. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  5129. return p;
  5130. }
  5131. return function setHSL( h, s, l ) {
  5132. // h,s,l ranges are in 0.0 - 1.0
  5133. h = exports.Math.euclideanModulo( h, 1 );
  5134. s = exports.Math.clamp( s, 0, 1 );
  5135. l = exports.Math.clamp( l, 0, 1 );
  5136. if ( s === 0 ) {
  5137. this.r = this.g = this.b = l;
  5138. } else {
  5139. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  5140. var q = ( 2 * l ) - p;
  5141. this.r = hue2rgb( q, p, h + 1 / 3 );
  5142. this.g = hue2rgb( q, p, h );
  5143. this.b = hue2rgb( q, p, h - 1 / 3 );
  5144. }
  5145. return this;
  5146. };
  5147. }(),
  5148. setStyle: function ( style ) {
  5149. function handleAlpha( string ) {
  5150. if ( string === undefined ) return;
  5151. if ( parseFloat( string ) < 1 ) {
  5152. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  5153. }
  5154. }
  5155. var m;
  5156. if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) {
  5157. // rgb / hsl
  5158. var color;
  5159. var name = m[ 1 ];
  5160. var components = m[ 2 ];
  5161. switch ( name ) {
  5162. case 'rgb':
  5163. case 'rgba':
  5164. if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  5165. // rgb(255,0,0) rgba(255,0,0,0.5)
  5166. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  5167. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  5168. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  5169. handleAlpha( color[ 5 ] );
  5170. return this;
  5171. }
  5172. if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  5173. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5174. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  5175. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  5176. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  5177. handleAlpha( color[ 5 ] );
  5178. return this;
  5179. }
  5180. break;
  5181. case 'hsl':
  5182. case 'hsla':
  5183. if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  5184. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5185. var h = parseFloat( color[ 1 ] ) / 360;
  5186. var s = parseInt( color[ 2 ], 10 ) / 100;
  5187. var l = parseInt( color[ 3 ], 10 ) / 100;
  5188. handleAlpha( color[ 5 ] );
  5189. return this.setHSL( h, s, l );
  5190. }
  5191. break;
  5192. }
  5193. } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) {
  5194. // hex color
  5195. var hex = m[ 1 ];
  5196. var size = hex.length;
  5197. if ( size === 3 ) {
  5198. // #ff0
  5199. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  5200. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  5201. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  5202. return this;
  5203. } else if ( size === 6 ) {
  5204. // #ff0000
  5205. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  5206. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  5207. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  5208. return this;
  5209. }
  5210. }
  5211. if ( style && style.length > 0 ) {
  5212. // color keywords
  5213. var hex = exports.ColorKeywords[ style ];
  5214. if ( hex !== undefined ) {
  5215. // red
  5216. this.setHex( hex );
  5217. } else {
  5218. // unknown color
  5219. console.warn( 'THREE.Color: Unknown color ' + style );
  5220. }
  5221. }
  5222. return this;
  5223. },
  5224. clone: function () {
  5225. return new this.constructor( this.r, this.g, this.b );
  5226. },
  5227. copy: function ( color ) {
  5228. this.r = color.r;
  5229. this.g = color.g;
  5230. this.b = color.b;
  5231. return this;
  5232. },
  5233. copyGammaToLinear: function ( color, gammaFactor ) {
  5234. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  5235. this.r = Math.pow( color.r, gammaFactor );
  5236. this.g = Math.pow( color.g, gammaFactor );
  5237. this.b = Math.pow( color.b, gammaFactor );
  5238. return this;
  5239. },
  5240. copyLinearToGamma: function ( color, gammaFactor ) {
  5241. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  5242. var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  5243. this.r = Math.pow( color.r, safeInverse );
  5244. this.g = Math.pow( color.g, safeInverse );
  5245. this.b = Math.pow( color.b, safeInverse );
  5246. return this;
  5247. },
  5248. convertGammaToLinear: function () {
  5249. var r = this.r, g = this.g, b = this.b;
  5250. this.r = r * r;
  5251. this.g = g * g;
  5252. this.b = b * b;
  5253. return this;
  5254. },
  5255. convertLinearToGamma: function () {
  5256. this.r = Math.sqrt( this.r );
  5257. this.g = Math.sqrt( this.g );
  5258. this.b = Math.sqrt( this.b );
  5259. return this;
  5260. },
  5261. getHex: function () {
  5262. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  5263. },
  5264. getHexString: function () {
  5265. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  5266. },
  5267. getHSL: function ( optionalTarget ) {
  5268. // h,s,l ranges are in 0.0 - 1.0
  5269. var hsl = optionalTarget || { h: 0, s: 0, l: 0 };
  5270. var r = this.r, g = this.g, b = this.b;
  5271. var max = Math.max( r, g, b );
  5272. var min = Math.min( r, g, b );
  5273. var hue, saturation;
  5274. var lightness = ( min + max ) / 2.0;
  5275. if ( min === max ) {
  5276. hue = 0;
  5277. saturation = 0;
  5278. } else {
  5279. var delta = max - min;
  5280. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  5281. switch ( max ) {
  5282. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  5283. case g: hue = ( b - r ) / delta + 2; break;
  5284. case b: hue = ( r - g ) / delta + 4; break;
  5285. }
  5286. hue /= 6;
  5287. }
  5288. hsl.h = hue;
  5289. hsl.s = saturation;
  5290. hsl.l = lightness;
  5291. return hsl;
  5292. },
  5293. getStyle: function () {
  5294. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  5295. },
  5296. offsetHSL: function ( h, s, l ) {
  5297. var hsl = this.getHSL();
  5298. hsl.h += h; hsl.s += s; hsl.l += l;
  5299. this.setHSL( hsl.h, hsl.s, hsl.l );
  5300. return this;
  5301. },
  5302. add: function ( color ) {
  5303. this.r += color.r;
  5304. this.g += color.g;
  5305. this.b += color.b;
  5306. return this;
  5307. },
  5308. addColors: function ( color1, color2 ) {
  5309. this.r = color1.r + color2.r;
  5310. this.g = color1.g + color2.g;
  5311. this.b = color1.b + color2.b;
  5312. return this;
  5313. },
  5314. addScalar: function ( s ) {
  5315. this.r += s;
  5316. this.g += s;
  5317. this.b += s;
  5318. return this;
  5319. },
  5320. sub: function( color ) {
  5321. this.r = Math.max( 0, this.r - color.r );
  5322. this.g = Math.max( 0, this.g - color.g );
  5323. this.b = Math.max( 0, this.b - color.b );
  5324. return this;
  5325. },
  5326. multiply: function ( color ) {
  5327. this.r *= color.r;
  5328. this.g *= color.g;
  5329. this.b *= color.b;
  5330. return this;
  5331. },
  5332. multiplyScalar: function ( s ) {
  5333. this.r *= s;
  5334. this.g *= s;
  5335. this.b *= s;
  5336. return this;
  5337. },
  5338. lerp: function ( color, alpha ) {
  5339. this.r += ( color.r - this.r ) * alpha;
  5340. this.g += ( color.g - this.g ) * alpha;
  5341. this.b += ( color.b - this.b ) * alpha;
  5342. return this;
  5343. },
  5344. equals: function ( c ) {
  5345. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  5346. },
  5347. fromArray: function ( array, offset ) {
  5348. if ( offset === undefined ) offset = 0;
  5349. this.r = array[ offset ];
  5350. this.g = array[ offset + 1 ];
  5351. this.b = array[ offset + 2 ];
  5352. return this;
  5353. },
  5354. toArray: function ( array, offset ) {
  5355. if ( array === undefined ) array = [];
  5356. if ( offset === undefined ) offset = 0;
  5357. array[ offset ] = this.r;
  5358. array[ offset + 1 ] = this.g;
  5359. array[ offset + 2 ] = this.b;
  5360. return array;
  5361. }
  5362. };
  5363. exports.ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  5364. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  5365. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  5366. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  5367. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  5368. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  5369. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  5370. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  5371. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  5372. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  5373. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  5374. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  5375. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  5376. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  5377. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  5378. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  5379. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  5380. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  5381. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  5382. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  5383. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  5384. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  5385. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  5386. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  5387. /**
  5388. * Uniforms library for shared webgl shaders
  5389. */
  5390. exports.UniformsLib = {
  5391. common: {
  5392. "diffuse": { value: new Color( 0xeeeeee ) },
  5393. "opacity": { value: 1.0 },
  5394. "map": { value: null },
  5395. "offsetRepeat": { value: new Vector4( 0, 0, 1, 1 ) },
  5396. "specularMap": { value: null },
  5397. "alphaMap": { value: null },
  5398. "envMap": { value: null },
  5399. "flipEnvMap": { value: - 1 },
  5400. "reflectivity": { value: 1.0 },
  5401. "refractionRatio": { value: 0.98 }
  5402. },
  5403. aomap: {
  5404. "aoMap": { value: null },
  5405. "aoMapIntensity": { value: 1 }
  5406. },
  5407. lightmap: {
  5408. "lightMap": { value: null },
  5409. "lightMapIntensity": { value: 1 }
  5410. },
  5411. emissivemap: {
  5412. "emissiveMap": { value: null }
  5413. },
  5414. bumpmap: {
  5415. "bumpMap": { value: null },
  5416. "bumpScale": { value: 1 }
  5417. },
  5418. normalmap: {
  5419. "normalMap": { value: null },
  5420. "normalScale": { value: new Vector2( 1, 1 ) }
  5421. },
  5422. displacementmap: {
  5423. "displacementMap": { value: null },
  5424. "displacementScale": { value: 1 },
  5425. "displacementBias": { value: 0 }
  5426. },
  5427. roughnessmap: {
  5428. "roughnessMap": { value: null }
  5429. },
  5430. metalnessmap: {
  5431. "metalnessMap": { value: null }
  5432. },
  5433. fog: {
  5434. "fogDensity": { value: 0.00025 },
  5435. "fogNear": { value: 1 },
  5436. "fogFar": { value: 2000 },
  5437. "fogColor": { value: new Color( 0xffffff ) }
  5438. },
  5439. lights: {
  5440. "ambientLightColor": { value: [] },
  5441. "directionalLights": { value: [], properties: {
  5442. "direction": {},
  5443. "color": {},
  5444. "shadow": {},
  5445. "shadowBias": {},
  5446. "shadowRadius": {},
  5447. "shadowMapSize": {}
  5448. } },
  5449. "directionalShadowMap": { value: [] },
  5450. "directionalShadowMatrix": { value: [] },
  5451. "spotLights": { value: [], properties: {
  5452. "color": {},
  5453. "position": {},
  5454. "direction": {},
  5455. "distance": {},
  5456. "coneCos": {},
  5457. "penumbraCos": {},
  5458. "decay": {},
  5459. "shadow": {},
  5460. "shadowBias": {},
  5461. "shadowRadius": {},
  5462. "shadowMapSize": {}
  5463. } },
  5464. "spotShadowMap": { value: [] },
  5465. "spotShadowMatrix": { value: [] },
  5466. "pointLights": { value: [], properties: {
  5467. "color": {},
  5468. "position": {},
  5469. "decay": {},
  5470. "distance": {},
  5471. "shadow": {},
  5472. "shadowBias": {},
  5473. "shadowRadius": {},
  5474. "shadowMapSize": {}
  5475. } },
  5476. "pointShadowMap": { value: [] },
  5477. "pointShadowMatrix": { value: [] },
  5478. "hemisphereLights": { value: [], properties: {
  5479. "direction": {},
  5480. "skyColor": {},
  5481. "groundColor": {}
  5482. } }
  5483. },
  5484. points: {
  5485. "diffuse": { value: new Color( 0xeeeeee ) },
  5486. "opacity": { value: 1.0 },
  5487. "size": { value: 1.0 },
  5488. "scale": { value: 1.0 },
  5489. "map": { value: null },
  5490. "offsetRepeat": { value: new Vector4( 0, 0, 1, 1 ) }
  5491. }
  5492. };
  5493. /**
  5494. * Webgl Shader Library for three.js
  5495. *
  5496. * @author alteredq / http://alteredqualia.com/
  5497. * @author mrdoob / http://mrdoob.com/
  5498. * @author mikael emtinger / http://gomo.se/
  5499. */
  5500. exports.ShaderLib = {
  5501. 'basic': {
  5502. uniforms: exports.UniformsUtils.merge( [
  5503. exports.UniformsLib[ 'common' ],
  5504. exports.UniformsLib[ 'aomap' ],
  5505. exports.UniformsLib[ 'fog' ]
  5506. ] ),
  5507. vertexShader: ShaderChunk[ 'meshbasic_vert' ],
  5508. fragmentShader: ShaderChunk[ 'meshbasic_frag' ]
  5509. },
  5510. 'lambert': {
  5511. uniforms: exports.UniformsUtils.merge( [
  5512. exports.UniformsLib[ 'common' ],
  5513. exports.UniformsLib[ 'aomap' ],
  5514. exports.UniformsLib[ 'lightmap' ],
  5515. exports.UniformsLib[ 'emissivemap' ],
  5516. exports.UniformsLib[ 'fog' ],
  5517. exports.UniformsLib[ 'lights' ],
  5518. {
  5519. "emissive" : { value: new Color( 0x000000 ) }
  5520. }
  5521. ] ),
  5522. vertexShader: ShaderChunk[ 'meshlambert_vert' ],
  5523. fragmentShader: ShaderChunk[ 'meshlambert_frag' ]
  5524. },
  5525. 'phong': {
  5526. uniforms: exports.UniformsUtils.merge( [
  5527. exports.UniformsLib[ 'common' ],
  5528. exports.UniformsLib[ 'aomap' ],
  5529. exports.UniformsLib[ 'lightmap' ],
  5530. exports.UniformsLib[ 'emissivemap' ],
  5531. exports.UniformsLib[ 'bumpmap' ],
  5532. exports.UniformsLib[ 'normalmap' ],
  5533. exports.UniformsLib[ 'displacementmap' ],
  5534. exports.UniformsLib[ 'fog' ],
  5535. exports.UniformsLib[ 'lights' ],
  5536. {
  5537. "emissive" : { value: new Color( 0x000000 ) },
  5538. "specular" : { value: new Color( 0x111111 ) },
  5539. "shininess": { value: 30 }
  5540. }
  5541. ] ),
  5542. vertexShader: ShaderChunk[ 'meshphong_vert' ],
  5543. fragmentShader: ShaderChunk[ 'meshphong_frag' ]
  5544. },
  5545. 'standard': {
  5546. uniforms: exports.UniformsUtils.merge( [
  5547. exports.UniformsLib[ 'common' ],
  5548. exports.UniformsLib[ 'aomap' ],
  5549. exports.UniformsLib[ 'lightmap' ],
  5550. exports.UniformsLib[ 'emissivemap' ],
  5551. exports.UniformsLib[ 'bumpmap' ],
  5552. exports.UniformsLib[ 'normalmap' ],
  5553. exports.UniformsLib[ 'displacementmap' ],
  5554. exports.UniformsLib[ 'roughnessmap' ],
  5555. exports.UniformsLib[ 'metalnessmap' ],
  5556. exports.UniformsLib[ 'fog' ],
  5557. exports.UniformsLib[ 'lights' ],
  5558. {
  5559. "emissive" : { value: new Color( 0x000000 ) },
  5560. "roughness": { value: 0.5 },
  5561. "metalness": { value: 0 },
  5562. "envMapIntensity" : { value: 1 }, // temporary
  5563. }
  5564. ] ),
  5565. vertexShader: ShaderChunk[ 'meshphysical_vert' ],
  5566. fragmentShader: ShaderChunk[ 'meshphysical_frag' ]
  5567. },
  5568. 'points': {
  5569. uniforms: exports.UniformsUtils.merge( [
  5570. exports.UniformsLib[ 'points' ],
  5571. exports.UniformsLib[ 'fog' ]
  5572. ] ),
  5573. vertexShader: ShaderChunk[ 'points_vert' ],
  5574. fragmentShader: ShaderChunk[ 'points_frag' ]
  5575. },
  5576. 'dashed': {
  5577. uniforms: exports.UniformsUtils.merge( [
  5578. exports.UniformsLib[ 'common' ],
  5579. exports.UniformsLib[ 'fog' ],
  5580. {
  5581. "scale" : { value: 1 },
  5582. "dashSize" : { value: 1 },
  5583. "totalSize": { value: 2 }
  5584. }
  5585. ] ),
  5586. vertexShader: ShaderChunk[ 'linedashed_vert' ],
  5587. fragmentShader: ShaderChunk[ 'linedashed_frag' ]
  5588. },
  5589. 'depth': {
  5590. uniforms: exports.UniformsUtils.merge( [
  5591. exports.UniformsLib[ 'common' ],
  5592. exports.UniformsLib[ 'displacementmap' ]
  5593. ] ),
  5594. vertexShader: ShaderChunk[ 'depth_vert' ],
  5595. fragmentShader: ShaderChunk[ 'depth_frag' ]
  5596. },
  5597. 'normal': {
  5598. uniforms: {
  5599. "opacity" : { value: 1.0 }
  5600. },
  5601. vertexShader: ShaderChunk[ 'normal_vert' ],
  5602. fragmentShader: ShaderChunk[ 'normal_frag' ]
  5603. },
  5604. /* -------------------------------------------------------------------------
  5605. // Cube map shader
  5606. ------------------------------------------------------------------------- */
  5607. 'cube': {
  5608. uniforms: {
  5609. "tCube": { value: null },
  5610. "tFlip": { value: - 1 },
  5611. "opacity": { value: 1.0 }
  5612. },
  5613. vertexShader: ShaderChunk[ 'cube_vert' ],
  5614. fragmentShader: ShaderChunk[ 'cube_frag' ]
  5615. },
  5616. /* -------------------------------------------------------------------------
  5617. // Cube map shader
  5618. ------------------------------------------------------------------------- */
  5619. 'equirect': {
  5620. uniforms: {
  5621. "tEquirect": { value: null },
  5622. "tFlip": { value: - 1 }
  5623. },
  5624. vertexShader: ShaderChunk[ 'equirect_vert' ],
  5625. fragmentShader: ShaderChunk[ 'equirect_frag' ]
  5626. },
  5627. 'distanceRGBA': {
  5628. uniforms: {
  5629. "lightPos": { value: new Vector3() }
  5630. },
  5631. vertexShader: ShaderChunk[ 'distanceRGBA_vert' ],
  5632. fragmentShader: ShaderChunk[ 'distanceRGBA_frag' ]
  5633. }
  5634. };
  5635. exports.ShaderLib[ 'physical' ] = {
  5636. uniforms: exports.UniformsUtils.merge( [
  5637. exports.ShaderLib[ 'standard' ].uniforms,
  5638. {
  5639. "clearCoat": { value: 0 },
  5640. "clearCoatRoughness": { value: 0 }
  5641. }
  5642. ] ),
  5643. vertexShader: ShaderChunk[ 'meshphysical_vert' ],
  5644. fragmentShader: ShaderChunk[ 'meshphysical_frag' ]
  5645. };
  5646. /**
  5647. * @author mrdoob / http://mrdoob.com/
  5648. * @author alteredq / http://alteredqualia.com/
  5649. * @author bhouston / https://clara.io
  5650. * @author WestLangley / http://github.com/WestLangley
  5651. *
  5652. * parameters = {
  5653. *
  5654. * opacity: <float>,
  5655. *
  5656. * map: new THREE.Texture( <Image> ),
  5657. *
  5658. * alphaMap: new THREE.Texture( <Image> ),
  5659. *
  5660. * displacementMap: new THREE.Texture( <Image> ),
  5661. * displacementScale: <float>,
  5662. * displacementBias: <float>,
  5663. *
  5664. * wireframe: <boolean>,
  5665. * wireframeLinewidth: <float>
  5666. * }
  5667. */
  5668. function MeshDepthMaterial( parameters ) {
  5669. Material.call( this );
  5670. this.type = 'MeshDepthMaterial';
  5671. this.depthPacking = BasicDepthPacking;
  5672. this.skinning = false;
  5673. this.morphTargets = false;
  5674. this.map = null;
  5675. this.alphaMap = null;
  5676. this.displacementMap = null;
  5677. this.displacementScale = 1;
  5678. this.displacementBias = 0;
  5679. this.wireframe = false;
  5680. this.wireframeLinewidth = 1;
  5681. this.fog = false;
  5682. this.lights = false;
  5683. this.setValues( parameters );
  5684. }
  5685. MeshDepthMaterial.prototype = Object.create( Material.prototype );
  5686. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  5687. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  5688. MeshDepthMaterial.prototype.copy = function ( source ) {
  5689. Material.prototype.copy.call( this, source );
  5690. this.depthPacking = source.depthPacking;
  5691. this.skinning = source.skinning;
  5692. this.morphTargets = source.morphTargets;
  5693. this.map = source.map;
  5694. this.alphaMap = source.alphaMap;
  5695. this.displacementMap = source.displacementMap;
  5696. this.displacementScale = source.displacementScale;
  5697. this.displacementBias = source.displacementBias;
  5698. this.wireframe = source.wireframe;
  5699. this.wireframeLinewidth = source.wireframeLinewidth;
  5700. return this;
  5701. };
  5702. /**
  5703. * @author bhouston / http://clara.io
  5704. * @author WestLangley / http://github.com/WestLangley
  5705. */
  5706. function Box3( min, max ) {
  5707. this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity );
  5708. this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity );
  5709. }
  5710. Box3.prototype = {
  5711. constructor: Box3,
  5712. isBox3: true,
  5713. set: function ( min, max ) {
  5714. this.min.copy( min );
  5715. this.max.copy( max );
  5716. return this;
  5717. },
  5718. setFromArray: function ( array ) {
  5719. var minX = + Infinity;
  5720. var minY = + Infinity;
  5721. var minZ = + Infinity;
  5722. var maxX = - Infinity;
  5723. var maxY = - Infinity;
  5724. var maxZ = - Infinity;
  5725. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  5726. var x = array[ i ];
  5727. var y = array[ i + 1 ];
  5728. var z = array[ i + 2 ];
  5729. if ( x < minX ) minX = x;
  5730. if ( y < minY ) minY = y;
  5731. if ( z < minZ ) minZ = z;
  5732. if ( x > maxX ) maxX = x;
  5733. if ( y > maxY ) maxY = y;
  5734. if ( z > maxZ ) maxZ = z;
  5735. }
  5736. this.min.set( minX, minY, minZ );
  5737. this.max.set( maxX, maxY, maxZ );
  5738. },
  5739. setFromPoints: function ( points ) {
  5740. this.makeEmpty();
  5741. for ( var i = 0, il = points.length; i < il; i ++ ) {
  5742. this.expandByPoint( points[ i ] );
  5743. }
  5744. return this;
  5745. },
  5746. setFromCenterAndSize: function () {
  5747. var v1 = new Vector3();
  5748. return function setFromCenterAndSize( center, size ) {
  5749. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  5750. this.min.copy( center ).sub( halfSize );
  5751. this.max.copy( center ).add( halfSize );
  5752. return this;
  5753. };
  5754. }(),
  5755. setFromObject: function () {
  5756. // Computes the world-axis-aligned bounding box of an object (including its children),
  5757. // accounting for both the object's, and children's, world transforms
  5758. var v1 = new Vector3();
  5759. return function setFromObject( object ) {
  5760. var scope = this;
  5761. object.updateMatrixWorld( true );
  5762. this.makeEmpty();
  5763. object.traverse( function ( node ) {
  5764. var geometry = node.geometry;
  5765. if ( geometry !== undefined ) {
  5766. if ( (geometry && geometry.isGeometry) ) {
  5767. var vertices = geometry.vertices;
  5768. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  5769. v1.copy( vertices[ i ] );
  5770. v1.applyMatrix4( node.matrixWorld );
  5771. scope.expandByPoint( v1 );
  5772. }
  5773. } else if ( (geometry && geometry.isBufferGeometry) ) {
  5774. var attribute = geometry.attributes.position;
  5775. if ( attribute !== undefined ) {
  5776. var array, offset, stride;
  5777. if ( (attribute && attribute.isInterleavedBufferAttribute) ) {
  5778. array = attribute.data.array;
  5779. offset = attribute.offset;
  5780. stride = attribute.data.stride;
  5781. } else {
  5782. array = attribute.array;
  5783. offset = 0;
  5784. stride = 3;
  5785. }
  5786. for ( var i = offset, il = array.length; i < il; i += stride ) {
  5787. v1.fromArray( array, i );
  5788. v1.applyMatrix4( node.matrixWorld );
  5789. scope.expandByPoint( v1 );
  5790. }
  5791. }
  5792. }
  5793. }
  5794. } );
  5795. return this;
  5796. };
  5797. }(),
  5798. clone: function () {
  5799. return new this.constructor().copy( this );
  5800. },
  5801. copy: function ( box ) {
  5802. this.min.copy( box.min );
  5803. this.max.copy( box.max );
  5804. return this;
  5805. },
  5806. makeEmpty: function () {
  5807. this.min.x = this.min.y = this.min.z = + Infinity;
  5808. this.max.x = this.max.y = this.max.z = - Infinity;
  5809. return this;
  5810. },
  5811. isEmpty: function () {
  5812. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  5813. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  5814. },
  5815. center: function ( optionalTarget ) {
  5816. var result = optionalTarget || new Vector3();
  5817. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  5818. },
  5819. size: function ( optionalTarget ) {
  5820. var result = optionalTarget || new Vector3();
  5821. return result.subVectors( this.max, this.min );
  5822. },
  5823. expandByPoint: function ( point ) {
  5824. this.min.min( point );
  5825. this.max.max( point );
  5826. return this;
  5827. },
  5828. expandByVector: function ( vector ) {
  5829. this.min.sub( vector );
  5830. this.max.add( vector );
  5831. return this;
  5832. },
  5833. expandByScalar: function ( scalar ) {
  5834. this.min.addScalar( - scalar );
  5835. this.max.addScalar( scalar );
  5836. return this;
  5837. },
  5838. containsPoint: function ( point ) {
  5839. if ( point.x < this.min.x || point.x > this.max.x ||
  5840. point.y < this.min.y || point.y > this.max.y ||
  5841. point.z < this.min.z || point.z > this.max.z ) {
  5842. return false;
  5843. }
  5844. return true;
  5845. },
  5846. containsBox: function ( box ) {
  5847. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  5848. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  5849. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  5850. return true;
  5851. }
  5852. return false;
  5853. },
  5854. getParameter: function ( point, optionalTarget ) {
  5855. // This can potentially have a divide by zero if the box
  5856. // has a size dimension of 0.
  5857. var result = optionalTarget || new Vector3();
  5858. return result.set(
  5859. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  5860. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  5861. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  5862. );
  5863. },
  5864. intersectsBox: function ( box ) {
  5865. // using 6 splitting planes to rule out intersections.
  5866. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  5867. box.max.y < this.min.y || box.min.y > this.max.y ||
  5868. box.max.z < this.min.z || box.min.z > this.max.z ) {
  5869. return false;
  5870. }
  5871. return true;
  5872. },
  5873. intersectsSphere: ( function () {
  5874. var closestPoint;
  5875. return function intersectsSphere( sphere ) {
  5876. if ( closestPoint === undefined ) closestPoint = new Vector3();
  5877. // Find the point on the AABB closest to the sphere center.
  5878. this.clampPoint( sphere.center, closestPoint );
  5879. // If that point is inside the sphere, the AABB and sphere intersect.
  5880. return closestPoint.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  5881. };
  5882. } )(),
  5883. intersectsPlane: function ( plane ) {
  5884. // We compute the minimum and maximum dot product values. If those values
  5885. // are on the same side (back or front) of the plane, then there is no intersection.
  5886. var min, max;
  5887. if ( plane.normal.x > 0 ) {
  5888. min = plane.normal.x * this.min.x;
  5889. max = plane.normal.x * this.max.x;
  5890. } else {
  5891. min = plane.normal.x * this.max.x;
  5892. max = plane.normal.x * this.min.x;
  5893. }
  5894. if ( plane.normal.y > 0 ) {
  5895. min += plane.normal.y * this.min.y;
  5896. max += plane.normal.y * this.max.y;
  5897. } else {
  5898. min += plane.normal.y * this.max.y;
  5899. max += plane.normal.y * this.min.y;
  5900. }
  5901. if ( plane.normal.z > 0 ) {
  5902. min += plane.normal.z * this.min.z;
  5903. max += plane.normal.z * this.max.z;
  5904. } else {
  5905. min += plane.normal.z * this.max.z;
  5906. max += plane.normal.z * this.min.z;
  5907. }
  5908. return ( min <= plane.constant && max >= plane.constant );
  5909. },
  5910. clampPoint: function ( point, optionalTarget ) {
  5911. var result = optionalTarget || new Vector3();
  5912. return result.copy( point ).clamp( this.min, this.max );
  5913. },
  5914. distanceToPoint: function () {
  5915. var v1 = new Vector3();
  5916. return function distanceToPoint( point ) {
  5917. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  5918. return clampedPoint.sub( point ).length();
  5919. };
  5920. }(),
  5921. getBoundingSphere: function () {
  5922. var v1 = new Vector3();
  5923. return function getBoundingSphere( optionalTarget ) {
  5924. var result = optionalTarget || new Sphere();
  5925. result.center = this.center();
  5926. result.radius = this.size( v1 ).length() * 0.5;
  5927. return result;
  5928. };
  5929. }(),
  5930. intersect: function ( box ) {
  5931. this.min.max( box.min );
  5932. this.max.min( box.max );
  5933. // ensure that if there is no overlap, the result is fully empty, not slightly empty with non-inf/+inf values that will cause subsequence intersects to erroneously return valid values.
  5934. if( this.isEmpty() ) this.makeEmpty();
  5935. return this;
  5936. },
  5937. union: function ( box ) {
  5938. this.min.min( box.min );
  5939. this.max.max( box.max );
  5940. return this;
  5941. },
  5942. applyMatrix4: function () {
  5943. var points = [
  5944. new Vector3(),
  5945. new Vector3(),
  5946. new Vector3(),
  5947. new Vector3(),
  5948. new Vector3(),
  5949. new Vector3(),
  5950. new Vector3(),
  5951. new Vector3()
  5952. ];
  5953. return function applyMatrix4( matrix ) {
  5954. // transform of empty box is an empty box.
  5955. if( this.isEmpty() ) return this;
  5956. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  5957. points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  5958. points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  5959. points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  5960. points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  5961. points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  5962. points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  5963. points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  5964. points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  5965. this.setFromPoints( points );
  5966. return this;
  5967. };
  5968. }(),
  5969. translate: function ( offset ) {
  5970. this.min.add( offset );
  5971. this.max.add( offset );
  5972. return this;
  5973. },
  5974. equals: function ( box ) {
  5975. return box.min.equals( this.min ) && box.max.equals( this.max );
  5976. }
  5977. };
  5978. /**
  5979. * @author bhouston / http://clara.io
  5980. * @author mrdoob / http://mrdoob.com/
  5981. */
  5982. function Sphere( center, radius ) {
  5983. this.center = ( center !== undefined ) ? center : new Vector3();
  5984. this.radius = ( radius !== undefined ) ? radius : 0;
  5985. }
  5986. Sphere.prototype = {
  5987. constructor: Sphere,
  5988. set: function ( center, radius ) {
  5989. this.center.copy( center );
  5990. this.radius = radius;
  5991. return this;
  5992. },
  5993. setFromPoints: function () {
  5994. var box = new Box3();
  5995. return function setFromPoints( points, optionalCenter ) {
  5996. var center = this.center;
  5997. if ( optionalCenter !== undefined ) {
  5998. center.copy( optionalCenter );
  5999. } else {
  6000. box.setFromPoints( points ).center( center );
  6001. }
  6002. var maxRadiusSq = 0;
  6003. for ( var i = 0, il = points.length; i < il; i ++ ) {
  6004. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  6005. }
  6006. this.radius = Math.sqrt( maxRadiusSq );
  6007. return this;
  6008. };
  6009. }(),
  6010. clone: function () {
  6011. return new this.constructor().copy( this );
  6012. },
  6013. copy: function ( sphere ) {
  6014. this.center.copy( sphere.center );
  6015. this.radius = sphere.radius;
  6016. return this;
  6017. },
  6018. empty: function () {
  6019. return ( this.radius <= 0 );
  6020. },
  6021. containsPoint: function ( point ) {
  6022. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  6023. },
  6024. distanceToPoint: function ( point ) {
  6025. return ( point.distanceTo( this.center ) - this.radius );
  6026. },
  6027. intersectsSphere: function ( sphere ) {
  6028. var radiusSum = this.radius + sphere.radius;
  6029. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  6030. },
  6031. intersectsBox: function ( box ) {
  6032. return box.intersectsSphere( this );
  6033. },
  6034. intersectsPlane: function ( plane ) {
  6035. // We use the following equation to compute the signed distance from
  6036. // the center of the sphere to the plane.
  6037. //
  6038. // distance = q * n - d
  6039. //
  6040. // If this distance is greater than the radius of the sphere,
  6041. // then there is no intersection.
  6042. return Math.abs( this.center.dot( plane.normal ) - plane.constant ) <= this.radius;
  6043. },
  6044. clampPoint: function ( point, optionalTarget ) {
  6045. var deltaLengthSq = this.center.distanceToSquared( point );
  6046. var result = optionalTarget || new Vector3();
  6047. result.copy( point );
  6048. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  6049. result.sub( this.center ).normalize();
  6050. result.multiplyScalar( this.radius ).add( this.center );
  6051. }
  6052. return result;
  6053. },
  6054. getBoundingBox: function ( optionalTarget ) {
  6055. var box = optionalTarget || new Box3();
  6056. box.set( this.center, this.center );
  6057. box.expandByScalar( this.radius );
  6058. return box;
  6059. },
  6060. applyMatrix4: function ( matrix ) {
  6061. this.center.applyMatrix4( matrix );
  6062. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  6063. return this;
  6064. },
  6065. translate: function ( offset ) {
  6066. this.center.add( offset );
  6067. return this;
  6068. },
  6069. equals: function ( sphere ) {
  6070. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  6071. }
  6072. };
  6073. /**
  6074. * @author alteredq / http://alteredqualia.com/
  6075. * @author WestLangley / http://github.com/WestLangley
  6076. * @author bhouston / http://clara.io
  6077. * @author tschw
  6078. */
  6079. function Matrix3() {
  6080. this.elements = new Float32Array( [
  6081. 1, 0, 0,
  6082. 0, 1, 0,
  6083. 0, 0, 1
  6084. ] );
  6085. if ( arguments.length > 0 ) {
  6086. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  6087. }
  6088. }
  6089. Matrix3.prototype = {
  6090. constructor: Matrix3,
  6091. isMatrix3: true,
  6092. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  6093. var te = this.elements;
  6094. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  6095. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  6096. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  6097. return this;
  6098. },
  6099. identity: function () {
  6100. this.set(
  6101. 1, 0, 0,
  6102. 0, 1, 0,
  6103. 0, 0, 1
  6104. );
  6105. return this;
  6106. },
  6107. clone: function () {
  6108. return new this.constructor().fromArray( this.elements );
  6109. },
  6110. copy: function ( m ) {
  6111. var me = m.elements;
  6112. this.set(
  6113. me[ 0 ], me[ 3 ], me[ 6 ],
  6114. me[ 1 ], me[ 4 ], me[ 7 ],
  6115. me[ 2 ], me[ 5 ], me[ 8 ]
  6116. );
  6117. return this;
  6118. },
  6119. setFromMatrix4: function( m ) {
  6120. var me = m.elements;
  6121. this.set(
  6122. me[ 0 ], me[ 4 ], me[ 8 ],
  6123. me[ 1 ], me[ 5 ], me[ 9 ],
  6124. me[ 2 ], me[ 6 ], me[ 10 ]
  6125. );
  6126. return this;
  6127. },
  6128. applyToVector3Array: function () {
  6129. var v1;
  6130. return function applyToVector3Array( array, offset, length ) {
  6131. if ( v1 === undefined ) v1 = new Vector3();
  6132. if ( offset === undefined ) offset = 0;
  6133. if ( length === undefined ) length = array.length;
  6134. for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) {
  6135. v1.fromArray( array, j );
  6136. v1.applyMatrix3( this );
  6137. v1.toArray( array, j );
  6138. }
  6139. return array;
  6140. };
  6141. }(),
  6142. applyToBuffer: function () {
  6143. var v1;
  6144. return function applyToBuffer( buffer, offset, length ) {
  6145. if ( v1 === undefined ) v1 = new Vector3();
  6146. if ( offset === undefined ) offset = 0;
  6147. if ( length === undefined ) length = buffer.length / buffer.itemSize;
  6148. for ( var i = 0, j = offset; i < length; i ++, j ++ ) {
  6149. v1.x = buffer.getX( j );
  6150. v1.y = buffer.getY( j );
  6151. v1.z = buffer.getZ( j );
  6152. v1.applyMatrix3( this );
  6153. buffer.setXYZ( v1.x, v1.y, v1.z );
  6154. }
  6155. return buffer;
  6156. };
  6157. }(),
  6158. multiplyScalar: function ( s ) {
  6159. var te = this.elements;
  6160. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  6161. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  6162. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  6163. return this;
  6164. },
  6165. determinant: function () {
  6166. var te = this.elements;
  6167. var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  6168. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  6169. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  6170. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  6171. },
  6172. getInverse: function ( matrix, throwOnDegenerate ) {
  6173. if ( (matrix && matrix.isMatrix4) ) {
  6174. console.error( "THREE.Matrix3.getInverse no longer takes a Matrix4 argument." );
  6175. }
  6176. var me = matrix.elements,
  6177. te = this.elements,
  6178. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ],
  6179. n12 = me[ 3 ], n22 = me[ 4 ], n32 = me[ 5 ],
  6180. n13 = me[ 6 ], n23 = me[ 7 ], n33 = me[ 8 ],
  6181. t11 = n33 * n22 - n32 * n23,
  6182. t12 = n32 * n13 - n33 * n12,
  6183. t13 = n23 * n12 - n22 * n13,
  6184. det = n11 * t11 + n21 * t12 + n31 * t13;
  6185. if ( det === 0 ) {
  6186. var msg = "THREE.Matrix3.getInverse(): can't invert matrix, determinant is 0";
  6187. if ( throwOnDegenerate === true ) {
  6188. throw new Error( msg );
  6189. } else {
  6190. console.warn( msg );
  6191. }
  6192. return this.identity();
  6193. }
  6194. var detInv = 1 / det;
  6195. te[ 0 ] = t11 * detInv;
  6196. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  6197. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  6198. te[ 3 ] = t12 * detInv;
  6199. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  6200. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  6201. te[ 6 ] = t13 * detInv;
  6202. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  6203. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  6204. return this;
  6205. },
  6206. transpose: function () {
  6207. var tmp, m = this.elements;
  6208. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  6209. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  6210. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  6211. return this;
  6212. },
  6213. flattenToArrayOffset: function ( array, offset ) {
  6214. console.warn( "THREE.Matrix3: .flattenToArrayOffset is deprecated " +
  6215. "- just use .toArray instead." );
  6216. return this.toArray( array, offset );
  6217. },
  6218. getNormalMatrix: function ( matrix4 ) {
  6219. return this.setFromMatrix4( matrix4 ).getInverse( this ).transpose();
  6220. },
  6221. transposeIntoArray: function ( r ) {
  6222. var m = this.elements;
  6223. r[ 0 ] = m[ 0 ];
  6224. r[ 1 ] = m[ 3 ];
  6225. r[ 2 ] = m[ 6 ];
  6226. r[ 3 ] = m[ 1 ];
  6227. r[ 4 ] = m[ 4 ];
  6228. r[ 5 ] = m[ 7 ];
  6229. r[ 6 ] = m[ 2 ];
  6230. r[ 7 ] = m[ 5 ];
  6231. r[ 8 ] = m[ 8 ];
  6232. return this;
  6233. },
  6234. fromArray: function ( array ) {
  6235. this.elements.set( array );
  6236. return this;
  6237. },
  6238. toArray: function ( array, offset ) {
  6239. if ( array === undefined ) array = [];
  6240. if ( offset === undefined ) offset = 0;
  6241. var te = this.elements;
  6242. array[ offset ] = te[ 0 ];
  6243. array[ offset + 1 ] = te[ 1 ];
  6244. array[ offset + 2 ] = te[ 2 ];
  6245. array[ offset + 3 ] = te[ 3 ];
  6246. array[ offset + 4 ] = te[ 4 ];
  6247. array[ offset + 5 ] = te[ 5 ];
  6248. array[ offset + 6 ] = te[ 6 ];
  6249. array[ offset + 7 ] = te[ 7 ];
  6250. array[ offset + 8 ] = te[ 8 ];
  6251. return array;
  6252. }
  6253. };
  6254. /**
  6255. * @author bhouston / http://clara.io
  6256. */
  6257. function Plane( normal, constant ) {
  6258. this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 );
  6259. this.constant = ( constant !== undefined ) ? constant : 0;
  6260. }
  6261. Plane.prototype = {
  6262. constructor: Plane,
  6263. set: function ( normal, constant ) {
  6264. this.normal.copy( normal );
  6265. this.constant = constant;
  6266. return this;
  6267. },
  6268. setComponents: function ( x, y, z, w ) {
  6269. this.normal.set( x, y, z );
  6270. this.constant = w;
  6271. return this;
  6272. },
  6273. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  6274. this.normal.copy( normal );
  6275. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  6276. return this;
  6277. },
  6278. setFromCoplanarPoints: function () {
  6279. var v1 = new Vector3();
  6280. var v2 = new Vector3();
  6281. return function setFromCoplanarPoints( a, b, c ) {
  6282. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  6283. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  6284. this.setFromNormalAndCoplanarPoint( normal, a );
  6285. return this;
  6286. };
  6287. }(),
  6288. clone: function () {
  6289. return new this.constructor().copy( this );
  6290. },
  6291. copy: function ( plane ) {
  6292. this.normal.copy( plane.normal );
  6293. this.constant = plane.constant;
  6294. return this;
  6295. },
  6296. normalize: function () {
  6297. // Note: will lead to a divide by zero if the plane is invalid.
  6298. var inverseNormalLength = 1.0 / this.normal.length();
  6299. this.normal.multiplyScalar( inverseNormalLength );
  6300. this.constant *= inverseNormalLength;
  6301. return this;
  6302. },
  6303. negate: function () {
  6304. this.constant *= - 1;
  6305. this.normal.negate();
  6306. return this;
  6307. },
  6308. distanceToPoint: function ( point ) {
  6309. return this.normal.dot( point ) + this.constant;
  6310. },
  6311. distanceToSphere: function ( sphere ) {
  6312. return this.distanceToPoint( sphere.center ) - sphere.radius;
  6313. },
  6314. projectPoint: function ( point, optionalTarget ) {
  6315. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  6316. },
  6317. orthoPoint: function ( point, optionalTarget ) {
  6318. var perpendicularMagnitude = this.distanceToPoint( point );
  6319. var result = optionalTarget || new Vector3();
  6320. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  6321. },
  6322. intersectLine: function () {
  6323. var v1 = new Vector3();
  6324. return function intersectLine( line, optionalTarget ) {
  6325. var result = optionalTarget || new Vector3();
  6326. var direction = line.delta( v1 );
  6327. var denominator = this.normal.dot( direction );
  6328. if ( denominator === 0 ) {
  6329. // line is coplanar, return origin
  6330. if ( this.distanceToPoint( line.start ) === 0 ) {
  6331. return result.copy( line.start );
  6332. }
  6333. // Unsure if this is the correct method to handle this case.
  6334. return undefined;
  6335. }
  6336. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  6337. if ( t < 0 || t > 1 ) {
  6338. return undefined;
  6339. }
  6340. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  6341. };
  6342. }(),
  6343. intersectsLine: function ( line ) {
  6344. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  6345. var startSign = this.distanceToPoint( line.start );
  6346. var endSign = this.distanceToPoint( line.end );
  6347. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  6348. },
  6349. intersectsBox: function ( box ) {
  6350. return box.intersectsPlane( this );
  6351. },
  6352. intersectsSphere: function ( sphere ) {
  6353. return sphere.intersectsPlane( this );
  6354. },
  6355. coplanarPoint: function ( optionalTarget ) {
  6356. var result = optionalTarget || new Vector3();
  6357. return result.copy( this.normal ).multiplyScalar( - this.constant );
  6358. },
  6359. applyMatrix4: function () {
  6360. var v1 = new Vector3();
  6361. var m1 = new Matrix3();
  6362. return function applyMatrix4( matrix, optionalNormalMatrix ) {
  6363. var referencePoint = this.coplanarPoint( v1 ).applyMatrix4( matrix );
  6364. // transform normal based on theory here:
  6365. // http://www.songho.ca/opengl/gl_normaltransform.html
  6366. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  6367. var normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  6368. // recalculate constant (like in setFromNormalAndCoplanarPoint)
  6369. this.constant = - referencePoint.dot( normal );
  6370. return this;
  6371. };
  6372. }(),
  6373. translate: function ( offset ) {
  6374. this.constant = this.constant - offset.dot( this.normal );
  6375. return this;
  6376. },
  6377. equals: function ( plane ) {
  6378. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  6379. }
  6380. };
  6381. /**
  6382. * @author mrdoob / http://mrdoob.com/
  6383. * @author alteredq / http://alteredqualia.com/
  6384. * @author bhouston / http://clara.io
  6385. */
  6386. function Frustum( p0, p1, p2, p3, p4, p5 ) {
  6387. this.planes = [
  6388. ( p0 !== undefined ) ? p0 : new Plane(),
  6389. ( p1 !== undefined ) ? p1 : new Plane(),
  6390. ( p2 !== undefined ) ? p2 : new Plane(),
  6391. ( p3 !== undefined ) ? p3 : new Plane(),
  6392. ( p4 !== undefined ) ? p4 : new Plane(),
  6393. ( p5 !== undefined ) ? p5 : new Plane()
  6394. ];
  6395. }
  6396. Frustum.prototype = {
  6397. constructor: Frustum,
  6398. set: function ( p0, p1, p2, p3, p4, p5 ) {
  6399. var planes = this.planes;
  6400. planes[ 0 ].copy( p0 );
  6401. planes[ 1 ].copy( p1 );
  6402. planes[ 2 ].copy( p2 );
  6403. planes[ 3 ].copy( p3 );
  6404. planes[ 4 ].copy( p4 );
  6405. planes[ 5 ].copy( p5 );
  6406. return this;
  6407. },
  6408. clone: function () {
  6409. return new this.constructor().copy( this );
  6410. },
  6411. copy: function ( frustum ) {
  6412. var planes = this.planes;
  6413. for ( var i = 0; i < 6; i ++ ) {
  6414. planes[ i ].copy( frustum.planes[ i ] );
  6415. }
  6416. return this;
  6417. },
  6418. setFromMatrix: function ( m ) {
  6419. var planes = this.planes;
  6420. var me = m.elements;
  6421. var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  6422. var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  6423. var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  6424. var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  6425. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  6426. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  6427. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  6428. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  6429. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  6430. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  6431. return this;
  6432. },
  6433. intersectsObject: function () {
  6434. var sphere = new Sphere();
  6435. return function intersectsObject( object ) {
  6436. var geometry = object.geometry;
  6437. if ( geometry.boundingSphere === null )
  6438. geometry.computeBoundingSphere();
  6439. sphere.copy( geometry.boundingSphere )
  6440. .applyMatrix4( object.matrixWorld );
  6441. return this.intersectsSphere( sphere );
  6442. };
  6443. }(),
  6444. intersectsSprite: function () {
  6445. var sphere = new Sphere();
  6446. return function intersectsSprite( sprite ) {
  6447. sphere.center.set( 0, 0, 0 );
  6448. sphere.radius = 0.7071067811865476;
  6449. sphere.applyMatrix4( sprite.matrixWorld );
  6450. return this.intersectsSphere( sphere );
  6451. };
  6452. }(),
  6453. intersectsSphere: function ( sphere ) {
  6454. var planes = this.planes;
  6455. var center = sphere.center;
  6456. var negRadius = - sphere.radius;
  6457. for ( var i = 0; i < 6; i ++ ) {
  6458. var distance = planes[ i ].distanceToPoint( center );
  6459. if ( distance < negRadius ) {
  6460. return false;
  6461. }
  6462. }
  6463. return true;
  6464. },
  6465. intersectsBox: function () {
  6466. var p1 = new Vector3(),
  6467. p2 = new Vector3();
  6468. return function intersectsBox( box ) {
  6469. var planes = this.planes;
  6470. for ( var i = 0; i < 6 ; i ++ ) {
  6471. var plane = planes[ i ];
  6472. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  6473. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  6474. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  6475. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  6476. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  6477. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  6478. var d1 = plane.distanceToPoint( p1 );
  6479. var d2 = plane.distanceToPoint( p2 );
  6480. // if both outside plane, no intersection
  6481. if ( d1 < 0 && d2 < 0 ) {
  6482. return false;
  6483. }
  6484. }
  6485. return true;
  6486. };
  6487. }(),
  6488. containsPoint: function ( point ) {
  6489. var planes = this.planes;
  6490. for ( var i = 0; i < 6; i ++ ) {
  6491. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  6492. return false;
  6493. }
  6494. }
  6495. return true;
  6496. }
  6497. };
  6498. /**
  6499. * @author alteredq / http://alteredqualia.com/
  6500. * @author mrdoob / http://mrdoob.com/
  6501. */
  6502. function WebGLShadowMap( _renderer, _lights, _objects, capabilities ) {
  6503. var _gl = _renderer.context,
  6504. _state = _renderer.state,
  6505. _frustum = new Frustum(),
  6506. _projScreenMatrix = new Matrix4(),
  6507. _lightShadows = _lights.shadows,
  6508. _shadowMapSize = new Vector2(),
  6509. _maxShadowMapSize = new Vector2( capabilities.maxTextureSize, capabilities.maxTextureSize ),
  6510. _lookTarget = new Vector3(),
  6511. _lightPositionWorld = new Vector3(),
  6512. _renderList = [],
  6513. _MorphingFlag = 1,
  6514. _SkinningFlag = 2,
  6515. _NumberOfMaterialVariants = ( _MorphingFlag | _SkinningFlag ) + 1,
  6516. _depthMaterials = new Array( _NumberOfMaterialVariants ),
  6517. _distanceMaterials = new Array( _NumberOfMaterialVariants ),
  6518. _materialCache = {};
  6519. var cubeDirections = [
  6520. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  6521. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  6522. ];
  6523. var cubeUps = [
  6524. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  6525. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  6526. ];
  6527. var cube2DViewPorts = [
  6528. new Vector4(), new Vector4(), new Vector4(),
  6529. new Vector4(), new Vector4(), new Vector4()
  6530. ];
  6531. // init
  6532. var depthMaterialTemplate = new MeshDepthMaterial();
  6533. depthMaterialTemplate.depthPacking = RGBADepthPacking;
  6534. depthMaterialTemplate.clipping = true;
  6535. var distanceShader = exports.ShaderLib[ "distanceRGBA" ];
  6536. var distanceUniforms = exports.UniformsUtils.clone( distanceShader.uniforms );
  6537. for ( var i = 0; i !== _NumberOfMaterialVariants; ++ i ) {
  6538. var useMorphing = ( i & _MorphingFlag ) !== 0;
  6539. var useSkinning = ( i & _SkinningFlag ) !== 0;
  6540. var depthMaterial = depthMaterialTemplate.clone();
  6541. depthMaterial.morphTargets = useMorphing;
  6542. depthMaterial.skinning = useSkinning;
  6543. _depthMaterials[ i ] = depthMaterial;
  6544. var distanceMaterial = new ShaderMaterial( {
  6545. defines: {
  6546. 'USE_SHADOWMAP': ''
  6547. },
  6548. uniforms: distanceUniforms,
  6549. vertexShader: distanceShader.vertexShader,
  6550. fragmentShader: distanceShader.fragmentShader,
  6551. morphTargets: useMorphing,
  6552. skinning: useSkinning,
  6553. clipping: true
  6554. } );
  6555. _distanceMaterials[ i ] = distanceMaterial;
  6556. }
  6557. //
  6558. var scope = this;
  6559. this.enabled = false;
  6560. this.autoUpdate = true;
  6561. this.needsUpdate = false;
  6562. this.type = PCFShadowMap;
  6563. this.renderReverseSided = true;
  6564. this.renderSingleSided = true;
  6565. this.render = function ( scene, camera ) {
  6566. if ( scope.enabled === false ) return;
  6567. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  6568. if ( _lightShadows.length === 0 ) return;
  6569. // Set GL state for depth map.
  6570. _state.clearColor( 1, 1, 1, 1 );
  6571. _state.disable( _gl.BLEND );
  6572. _state.setDepthTest( true );
  6573. _state.setScissorTest( false );
  6574. // render depth map
  6575. var faceCount, isPointLight;
  6576. for ( var i = 0, il = _lightShadows.length; i < il; i ++ ) {
  6577. var light = _lightShadows[ i ];
  6578. var shadow = light.shadow;
  6579. if ( shadow === undefined ) {
  6580. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  6581. continue;
  6582. }
  6583. var shadowCamera = shadow.camera;
  6584. _shadowMapSize.copy( shadow.mapSize );
  6585. _shadowMapSize.min( _maxShadowMapSize );
  6586. if ( (light && light.isPointLight) ) {
  6587. faceCount = 6;
  6588. isPointLight = true;
  6589. var vpWidth = _shadowMapSize.x;
  6590. var vpHeight = _shadowMapSize.y;
  6591. // These viewports map a cube-map onto a 2D texture with the
  6592. // following orientation:
  6593. //
  6594. // xzXZ
  6595. // y Y
  6596. //
  6597. // X - Positive x direction
  6598. // x - Negative x direction
  6599. // Y - Positive y direction
  6600. // y - Negative y direction
  6601. // Z - Positive z direction
  6602. // z - Negative z direction
  6603. // positive X
  6604. cube2DViewPorts[ 0 ].set( vpWidth * 2, vpHeight, vpWidth, vpHeight );
  6605. // negative X
  6606. cube2DViewPorts[ 1 ].set( 0, vpHeight, vpWidth, vpHeight );
  6607. // positive Z
  6608. cube2DViewPorts[ 2 ].set( vpWidth * 3, vpHeight, vpWidth, vpHeight );
  6609. // negative Z
  6610. cube2DViewPorts[ 3 ].set( vpWidth, vpHeight, vpWidth, vpHeight );
  6611. // positive Y
  6612. cube2DViewPorts[ 4 ].set( vpWidth * 3, 0, vpWidth, vpHeight );
  6613. // negative Y
  6614. cube2DViewPorts[ 5 ].set( vpWidth, 0, vpWidth, vpHeight );
  6615. _shadowMapSize.x *= 4.0;
  6616. _shadowMapSize.y *= 2.0;
  6617. } else {
  6618. faceCount = 1;
  6619. isPointLight = false;
  6620. }
  6621. if ( shadow.map === null ) {
  6622. var pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat };
  6623. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  6624. shadowCamera.updateProjectionMatrix();
  6625. }
  6626. if ( (shadow && shadow.isSpotLightShadow) ) {
  6627. shadow.update( light );
  6628. }
  6629. var shadowMap = shadow.map;
  6630. var shadowMatrix = shadow.matrix;
  6631. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  6632. shadowCamera.position.copy( _lightPositionWorld );
  6633. _renderer.setRenderTarget( shadowMap );
  6634. _renderer.clear();
  6635. // render shadow map for each cube face (if omni-directional) or
  6636. // run a single pass if not
  6637. for ( var face = 0; face < faceCount; face ++ ) {
  6638. if ( isPointLight ) {
  6639. _lookTarget.copy( shadowCamera.position );
  6640. _lookTarget.add( cubeDirections[ face ] );
  6641. shadowCamera.up.copy( cubeUps[ face ] );
  6642. shadowCamera.lookAt( _lookTarget );
  6643. var vpDimensions = cube2DViewPorts[ face ];
  6644. _state.viewport( vpDimensions );
  6645. } else {
  6646. _lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  6647. shadowCamera.lookAt( _lookTarget );
  6648. }
  6649. shadowCamera.updateMatrixWorld();
  6650. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  6651. // compute shadow matrix
  6652. shadowMatrix.set(
  6653. 0.5, 0.0, 0.0, 0.5,
  6654. 0.0, 0.5, 0.0, 0.5,
  6655. 0.0, 0.0, 0.5, 0.5,
  6656. 0.0, 0.0, 0.0, 1.0
  6657. );
  6658. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  6659. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  6660. // update camera matrices and frustum
  6661. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  6662. _frustum.setFromMatrix( _projScreenMatrix );
  6663. // set object matrices & frustum culling
  6664. _renderList.length = 0;
  6665. projectObject( scene, camera, shadowCamera );
  6666. // render shadow map
  6667. // render regular objects
  6668. for ( var j = 0, jl = _renderList.length; j < jl; j ++ ) {
  6669. var object = _renderList[ j ];
  6670. var geometry = _objects.update( object );
  6671. var material = object.material;
  6672. if ( (material && material.isMultiMaterial) ) {
  6673. var groups = geometry.groups;
  6674. var materials = material.materials;
  6675. for ( var k = 0, kl = groups.length; k < kl; k ++ ) {
  6676. var group = groups[ k ];
  6677. var groupMaterial = materials[ group.materialIndex ];
  6678. if ( groupMaterial.visible === true ) {
  6679. var depthMaterial = getDepthMaterial( object, groupMaterial, isPointLight, _lightPositionWorld );
  6680. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  6681. }
  6682. }
  6683. } else {
  6684. var depthMaterial = getDepthMaterial( object, material, isPointLight, _lightPositionWorld );
  6685. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  6686. }
  6687. }
  6688. }
  6689. }
  6690. // Restore GL state.
  6691. var clearColor = _renderer.getClearColor(),
  6692. clearAlpha = _renderer.getClearAlpha();
  6693. _renderer.setClearColor( clearColor, clearAlpha );
  6694. scope.needsUpdate = false;
  6695. };
  6696. function getDepthMaterial( object, material, isPointLight, lightPositionWorld ) {
  6697. var geometry = object.geometry;
  6698. var result = null;
  6699. var materialVariants = _depthMaterials;
  6700. var customMaterial = object.customDepthMaterial;
  6701. if ( isPointLight ) {
  6702. materialVariants = _distanceMaterials;
  6703. customMaterial = object.customDistanceMaterial;
  6704. }
  6705. if ( ! customMaterial ) {
  6706. var useMorphing = false;
  6707. if ( material.morphTargets ) {
  6708. if ( (geometry && geometry.isBufferGeometry) ) {
  6709. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  6710. } else if ( (geometry && geometry.isGeometry) ) {
  6711. useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0;
  6712. }
  6713. }
  6714. var useSkinning = (object && object.isSkinnedMesh) && material.skinning;
  6715. var variantIndex = 0;
  6716. if ( useMorphing ) variantIndex |= _MorphingFlag;
  6717. if ( useSkinning ) variantIndex |= _SkinningFlag;
  6718. result = materialVariants[ variantIndex ];
  6719. } else {
  6720. result = customMaterial;
  6721. }
  6722. if ( _renderer.localClippingEnabled &&
  6723. material.clipShadows === true &&
  6724. material.clippingPlanes.length !== 0 ) {
  6725. // in this case we need a unique material instance reflecting the
  6726. // appropriate state
  6727. var keyA = result.uuid, keyB = material.uuid;
  6728. var materialsForVariant = _materialCache[ keyA ];
  6729. if ( materialsForVariant === undefined ) {
  6730. materialsForVariant = {};
  6731. _materialCache[ keyA ] = materialsForVariant;
  6732. }
  6733. var cachedMaterial = materialsForVariant[ keyB ];
  6734. if ( cachedMaterial === undefined ) {
  6735. cachedMaterial = result.clone();
  6736. materialsForVariant[ keyB ] = cachedMaterial;
  6737. }
  6738. result = cachedMaterial;
  6739. }
  6740. result.visible = material.visible;
  6741. result.wireframe = material.wireframe;
  6742. var side = material.side;
  6743. if ( scope.renderSingleSided && side == DoubleSide ) {
  6744. side = FrontSide;
  6745. }
  6746. if ( scope.renderReverseSided ) {
  6747. if ( side === FrontSide ) side = BackSide;
  6748. else if ( side === BackSide ) side = FrontSide;
  6749. }
  6750. result.side = side;
  6751. result.clipShadows = material.clipShadows;
  6752. result.clippingPlanes = material.clippingPlanes;
  6753. result.wireframeLinewidth = material.wireframeLinewidth;
  6754. result.linewidth = material.linewidth;
  6755. if ( isPointLight && result.uniforms.lightPos !== undefined ) {
  6756. result.uniforms.lightPos.value.copy( lightPositionWorld );
  6757. }
  6758. return result;
  6759. }
  6760. function projectObject( object, camera, shadowCamera ) {
  6761. if ( object.visible === false ) return;
  6762. if ( object.layers.test( camera.layers ) && ( (object && object.isMesh) || (object && object.isLine) || (object && object.isPoints) ) ) {
  6763. if ( object.castShadow && ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) ) {
  6764. var material = object.material;
  6765. if ( material.visible === true ) {
  6766. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  6767. _renderList.push( object );
  6768. }
  6769. }
  6770. }
  6771. var children = object.children;
  6772. for ( var i = 0, l = children.length; i < l; i ++ ) {
  6773. projectObject( children[ i ], camera, shadowCamera );
  6774. }
  6775. }
  6776. }
  6777. exports.WebGLShader = ( function () {
  6778. function addLineNumbers( string ) {
  6779. var lines = string.split( '\n' );
  6780. for ( var i = 0; i < lines.length; i ++ ) {
  6781. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  6782. }
  6783. return lines.join( '\n' );
  6784. }
  6785. return function WebGLShader( gl, type, string ) {
  6786. var shader = gl.createShader( type );
  6787. gl.shaderSource( shader, string );
  6788. gl.compileShader( shader );
  6789. if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) {
  6790. console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' );
  6791. }
  6792. if ( gl.getShaderInfoLog( shader ) !== '' ) {
  6793. console.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', type === gl.VERTEX_SHADER ? 'vertex' : 'fragment', gl.getShaderInfoLog( shader ), addLineNumbers( string ) );
  6794. }
  6795. // --enable-privileged-webgl-extension
  6796. // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  6797. return shader;
  6798. };
  6799. } )();
  6800. /**
  6801. * @author fordacious / fordacious.github.io
  6802. */
  6803. function WebGLProperties() {
  6804. var properties = {};
  6805. this.get = function ( object ) {
  6806. var uuid = object.uuid;
  6807. var map = properties[ uuid ];
  6808. if ( map === undefined ) {
  6809. map = {};
  6810. properties[ uuid ] = map;
  6811. }
  6812. return map;
  6813. };
  6814. this.delete = function ( object ) {
  6815. delete properties[ object.uuid ];
  6816. };
  6817. this.clear = function () {
  6818. properties = {};
  6819. };
  6820. }
  6821. exports.WebGLProgram = ( function () {
  6822. var programIdCount = 0;
  6823. function getEncodingComponents( encoding ) {
  6824. switch ( encoding ) {
  6825. case LinearEncoding:
  6826. return [ 'Linear','( value )' ];
  6827. case sRGBEncoding:
  6828. return [ 'sRGB','( value )' ];
  6829. case RGBEEncoding:
  6830. return [ 'RGBE','( value )' ];
  6831. case RGBM7Encoding:
  6832. return [ 'RGBM','( value, 7.0 )' ];
  6833. case RGBM16Encoding:
  6834. return [ 'RGBM','( value, 16.0 )' ];
  6835. case RGBDEncoding:
  6836. return [ 'RGBD','( value, 256.0 )' ];
  6837. case GammaEncoding:
  6838. return [ 'Gamma','( value, float( GAMMA_FACTOR ) )' ];
  6839. default:
  6840. throw new Error( 'unsupported encoding: ' + encoding );
  6841. }
  6842. }
  6843. function getTexelDecodingFunction( functionName, encoding ) {
  6844. var components = getEncodingComponents( encoding );
  6845. return "vec4 " + functionName + "( vec4 value ) { return " + components[ 0 ] + "ToLinear" + components[ 1 ] + "; }";
  6846. }
  6847. function getTexelEncodingFunction( functionName, encoding ) {
  6848. var components = getEncodingComponents( encoding );
  6849. return "vec4 " + functionName + "( vec4 value ) { return LinearTo" + components[ 0 ] + components[ 1 ] + "; }";
  6850. }
  6851. function getToneMappingFunction( functionName, toneMapping ) {
  6852. var toneMappingName;
  6853. switch ( toneMapping ) {
  6854. case LinearToneMapping:
  6855. toneMappingName = "Linear";
  6856. break;
  6857. case ReinhardToneMapping:
  6858. toneMappingName = "Reinhard";
  6859. break;
  6860. case Uncharted2ToneMapping:
  6861. toneMappingName = "Uncharted2";
  6862. break;
  6863. case CineonToneMapping:
  6864. toneMappingName = "OptimizedCineon";
  6865. break;
  6866. default:
  6867. throw new Error( 'unsupported toneMapping: ' + toneMapping );
  6868. }
  6869. return "vec3 " + functionName + "( vec3 color ) { return " + toneMappingName + "ToneMapping( color ); }";
  6870. }
  6871. function generateExtensions( extensions, parameters, rendererExtensions ) {
  6872. extensions = extensions || {};
  6873. var chunks = [
  6874. ( extensions.derivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.normalMap || parameters.flatShading ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  6875. ( extensions.fragDepth || parameters.logarithmicDepthBuffer ) && rendererExtensions.get( 'EXT_frag_depth' ) ? '#extension GL_EXT_frag_depth : enable' : '',
  6876. ( extensions.drawBuffers ) && rendererExtensions.get( 'WEBGL_draw_buffers' ) ? '#extension GL_EXT_draw_buffers : require' : '',
  6877. ( extensions.shaderTextureLOD || parameters.envMap ) && rendererExtensions.get( 'EXT_shader_texture_lod' ) ? '#extension GL_EXT_shader_texture_lod : enable' : '',
  6878. ];
  6879. return chunks.filter( filterEmptyLine ).join( '\n' );
  6880. }
  6881. function generateDefines( defines ) {
  6882. var chunks = [];
  6883. for ( var name in defines ) {
  6884. var value = defines[ name ];
  6885. if ( value === false ) continue;
  6886. chunks.push( '#define ' + name + ' ' + value );
  6887. }
  6888. return chunks.join( '\n' );
  6889. }
  6890. function fetchAttributeLocations( gl, program, identifiers ) {
  6891. var attributes = {};
  6892. var n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  6893. for ( var i = 0; i < n; i ++ ) {
  6894. var info = gl.getActiveAttrib( program, i );
  6895. var name = info.name;
  6896. // console.log("THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:", name, i );
  6897. attributes[ name ] = gl.getAttribLocation( program, name );
  6898. }
  6899. return attributes;
  6900. }
  6901. function filterEmptyLine( string ) {
  6902. return string !== '';
  6903. }
  6904. function replaceLightNums( string, parameters ) {
  6905. return string
  6906. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  6907. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  6908. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  6909. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights );
  6910. }
  6911. function parseIncludes( string ) {
  6912. var pattern = /#include +<([\w\d.]+)>/g;
  6913. function replace( match, include ) {
  6914. var replace = ShaderChunk[ include ];
  6915. if ( replace === undefined ) {
  6916. throw new Error( 'Can not resolve #include <' + include + '>' );
  6917. }
  6918. return parseIncludes( replace );
  6919. }
  6920. return string.replace( pattern, replace );
  6921. }
  6922. function unrollLoops( string ) {
  6923. var pattern = /for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  6924. function replace( match, start, end, snippet ) {
  6925. var unroll = '';
  6926. for ( var i = parseInt( start ); i < parseInt( end ); i ++ ) {
  6927. unroll += snippet.replace( /\[ i \]/g, '[ ' + i + ' ]' );
  6928. }
  6929. return unroll;
  6930. }
  6931. return string.replace( pattern, replace );
  6932. }
  6933. return function WebGLProgram( renderer, code, material, parameters ) {
  6934. var gl = renderer.context;
  6935. var extensions = material.extensions;
  6936. var defines = material.defines;
  6937. var vertexShader = material.__webglShader.vertexShader;
  6938. var fragmentShader = material.__webglShader.fragmentShader;
  6939. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  6940. if ( parameters.shadowMapType === PCFShadowMap ) {
  6941. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  6942. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  6943. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  6944. }
  6945. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  6946. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  6947. var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  6948. if ( parameters.envMap ) {
  6949. switch ( material.envMap.mapping ) {
  6950. case CubeReflectionMapping:
  6951. case CubeRefractionMapping:
  6952. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  6953. break;
  6954. case CubeUVReflectionMapping:
  6955. case CubeUVRefractionMapping:
  6956. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  6957. break;
  6958. case EquirectangularReflectionMapping:
  6959. case EquirectangularRefractionMapping:
  6960. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  6961. break;
  6962. case SphericalReflectionMapping:
  6963. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  6964. break;
  6965. }
  6966. switch ( material.envMap.mapping ) {
  6967. case CubeRefractionMapping:
  6968. case EquirectangularRefractionMapping:
  6969. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  6970. break;
  6971. }
  6972. switch ( material.combine ) {
  6973. case MultiplyOperation:
  6974. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  6975. break;
  6976. case MixOperation:
  6977. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  6978. break;
  6979. case AddOperation:
  6980. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  6981. break;
  6982. }
  6983. }
  6984. var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  6985. // console.log( 'building new program ' );
  6986. //
  6987. var customExtensions = generateExtensions( extensions, parameters, renderer.extensions );
  6988. var customDefines = generateDefines( defines );
  6989. //
  6990. var program = gl.createProgram();
  6991. var prefixVertex, prefixFragment;
  6992. if ( (material && material.isRawShaderMaterial) ) {
  6993. prefixVertex = [
  6994. customDefines
  6995. ].filter( filterEmptyLine ).join( '\n' );
  6996. prefixFragment = [
  6997. customDefines
  6998. ].filter( filterEmptyLine ).join( '\n' );
  6999. } else {
  7000. prefixVertex = [
  7001. 'precision ' + parameters.precision + ' float;',
  7002. 'precision ' + parameters.precision + ' int;',
  7003. '#define SHADER_NAME ' + material.__webglShader.name,
  7004. customDefines,
  7005. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  7006. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  7007. '#define MAX_BONES ' + parameters.maxBones,
  7008. parameters.map ? '#define USE_MAP' : '',
  7009. parameters.envMap ? '#define USE_ENVMAP' : '',
  7010. parameters.envMap ? '#define ' + envMapModeDefine : '',
  7011. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  7012. parameters.aoMap ? '#define USE_AOMAP' : '',
  7013. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  7014. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  7015. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  7016. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  7017. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  7018. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  7019. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  7020. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  7021. parameters.vertexColors ? '#define USE_COLOR' : '',
  7022. parameters.flatShading ? '#define FLAT_SHADED' : '',
  7023. parameters.skinning ? '#define USE_SKINNING' : '',
  7024. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  7025. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  7026. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  7027. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  7028. parameters.flipSided ? '#define FLIP_SIDED' : '',
  7029. '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes,
  7030. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  7031. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  7032. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  7033. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  7034. parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  7035. 'uniform mat4 modelMatrix;',
  7036. 'uniform mat4 modelViewMatrix;',
  7037. 'uniform mat4 projectionMatrix;',
  7038. 'uniform mat4 viewMatrix;',
  7039. 'uniform mat3 normalMatrix;',
  7040. 'uniform vec3 cameraPosition;',
  7041. 'attribute vec3 position;',
  7042. 'attribute vec3 normal;',
  7043. 'attribute vec2 uv;',
  7044. '#ifdef USE_COLOR',
  7045. ' attribute vec3 color;',
  7046. '#endif',
  7047. '#ifdef USE_MORPHTARGETS',
  7048. ' attribute vec3 morphTarget0;',
  7049. ' attribute vec3 morphTarget1;',
  7050. ' attribute vec3 morphTarget2;',
  7051. ' attribute vec3 morphTarget3;',
  7052. ' #ifdef USE_MORPHNORMALS',
  7053. ' attribute vec3 morphNormal0;',
  7054. ' attribute vec3 morphNormal1;',
  7055. ' attribute vec3 morphNormal2;',
  7056. ' attribute vec3 morphNormal3;',
  7057. ' #else',
  7058. ' attribute vec3 morphTarget4;',
  7059. ' attribute vec3 morphTarget5;',
  7060. ' attribute vec3 morphTarget6;',
  7061. ' attribute vec3 morphTarget7;',
  7062. ' #endif',
  7063. '#endif',
  7064. '#ifdef USE_SKINNING',
  7065. ' attribute vec4 skinIndex;',
  7066. ' attribute vec4 skinWeight;',
  7067. '#endif',
  7068. '\n'
  7069. ].filter( filterEmptyLine ).join( '\n' );
  7070. prefixFragment = [
  7071. customExtensions,
  7072. 'precision ' + parameters.precision + ' float;',
  7073. 'precision ' + parameters.precision + ' int;',
  7074. '#define SHADER_NAME ' + material.__webglShader.name,
  7075. customDefines,
  7076. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest : '',
  7077. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  7078. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  7079. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  7080. parameters.map ? '#define USE_MAP' : '',
  7081. parameters.envMap ? '#define USE_ENVMAP' : '',
  7082. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  7083. parameters.envMap ? '#define ' + envMapModeDefine : '',
  7084. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  7085. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  7086. parameters.aoMap ? '#define USE_AOMAP' : '',
  7087. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  7088. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  7089. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  7090. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  7091. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  7092. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  7093. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  7094. parameters.vertexColors ? '#define USE_COLOR' : '',
  7095. parameters.flatShading ? '#define FLAT_SHADED' : '',
  7096. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  7097. parameters.flipSided ? '#define FLIP_SIDED' : '',
  7098. '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes,
  7099. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  7100. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  7101. parameters.premultipliedAlpha ? "#define PREMULTIPLIED_ALPHA" : '',
  7102. parameters.physicallyCorrectLights ? "#define PHYSICALLY_CORRECT_LIGHTS" : '',
  7103. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  7104. parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  7105. parameters.envMap && renderer.extensions.get( 'EXT_shader_texture_lod' ) ? '#define TEXTURE_LOD_EXT' : '',
  7106. 'uniform mat4 viewMatrix;',
  7107. 'uniform vec3 cameraPosition;',
  7108. ( parameters.toneMapping !== NoToneMapping ) ? "#define TONE_MAPPING" : '',
  7109. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  7110. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( "toneMapping", parameters.toneMapping ) : '',
  7111. ( parameters.outputEncoding || parameters.mapEncoding || parameters.envMapEncoding || parameters.emissiveMapEncoding ) ? ShaderChunk[ 'encodings_pars_fragment' ] : '', // this code is required here because it is used by the various encoding/decoding function defined below
  7112. parameters.mapEncoding ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '',
  7113. parameters.envMapEncoding ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '',
  7114. parameters.emissiveMapEncoding ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '',
  7115. parameters.outputEncoding ? getTexelEncodingFunction( "linearToOutputTexel", parameters.outputEncoding ) : '',
  7116. parameters.depthPacking ? "#define DEPTH_PACKING " + material.depthPacking : '',
  7117. '\n'
  7118. ].filter( filterEmptyLine ).join( '\n' );
  7119. }
  7120. vertexShader = parseIncludes( vertexShader, parameters );
  7121. vertexShader = replaceLightNums( vertexShader, parameters );
  7122. fragmentShader = parseIncludes( fragmentShader, parameters );
  7123. fragmentShader = replaceLightNums( fragmentShader, parameters );
  7124. if ( (material && material.isShaderMaterial) === false ) {
  7125. vertexShader = unrollLoops( vertexShader );
  7126. fragmentShader = unrollLoops( fragmentShader );
  7127. }
  7128. var vertexGlsl = prefixVertex + vertexShader;
  7129. var fragmentGlsl = prefixFragment + fragmentShader;
  7130. // console.log( '*VERTEX*', vertexGlsl );
  7131. // console.log( '*FRAGMENT*', fragmentGlsl );
  7132. var glVertexShader = exports.WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  7133. var glFragmentShader = exports.WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  7134. gl.attachShader( program, glVertexShader );
  7135. gl.attachShader( program, glFragmentShader );
  7136. // Force a particular attribute to index 0.
  7137. if ( material.index0AttributeName !== undefined ) {
  7138. gl.bindAttribLocation( program, 0, material.index0AttributeName );
  7139. } else if ( parameters.morphTargets === true ) {
  7140. // programs with morphTargets displace position out of attribute 0
  7141. gl.bindAttribLocation( program, 0, 'position' );
  7142. }
  7143. gl.linkProgram( program );
  7144. var programLog = gl.getProgramInfoLog( program );
  7145. var vertexLog = gl.getShaderInfoLog( glVertexShader );
  7146. var fragmentLog = gl.getShaderInfoLog( glFragmentShader );
  7147. var runnable = true;
  7148. var haveDiagnostics = true;
  7149. // console.log( '**VERTEX**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glVertexShader ) );
  7150. // console.log( '**FRAGMENT**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glFragmentShader ) );
  7151. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  7152. runnable = false;
  7153. console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), 'gl.VALIDATE_STATUS', gl.getProgramParameter( program, gl.VALIDATE_STATUS ), 'gl.getProgramInfoLog', programLog, vertexLog, fragmentLog );
  7154. } else if ( programLog !== '' ) {
  7155. console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog );
  7156. } else if ( vertexLog === '' || fragmentLog === '' ) {
  7157. haveDiagnostics = false;
  7158. }
  7159. if ( haveDiagnostics ) {
  7160. this.diagnostics = {
  7161. runnable: runnable,
  7162. material: material,
  7163. programLog: programLog,
  7164. vertexShader: {
  7165. log: vertexLog,
  7166. prefix: prefixVertex
  7167. },
  7168. fragmentShader: {
  7169. log: fragmentLog,
  7170. prefix: prefixFragment
  7171. }
  7172. };
  7173. }
  7174. // clean up
  7175. gl.deleteShader( glVertexShader );
  7176. gl.deleteShader( glFragmentShader );
  7177. // set up caching for uniform locations
  7178. var cachedUniforms;
  7179. this.getUniforms = function() {
  7180. if ( cachedUniforms === undefined ) {
  7181. cachedUniforms =
  7182. new exports.WebGLUniforms( gl, program, renderer );
  7183. }
  7184. return cachedUniforms;
  7185. };
  7186. // set up caching for attribute locations
  7187. var cachedAttributes;
  7188. this.getAttributes = function() {
  7189. if ( cachedAttributes === undefined ) {
  7190. cachedAttributes = fetchAttributeLocations( gl, program );
  7191. }
  7192. return cachedAttributes;
  7193. };
  7194. // free resource
  7195. this.destroy = function() {
  7196. gl.deleteProgram( program );
  7197. this.program = undefined;
  7198. };
  7199. // DEPRECATED
  7200. Object.defineProperties( this, {
  7201. uniforms: {
  7202. get: function() {
  7203. console.warn( 'THREE.WebGLProgram: .uniforms is now .getUniforms().' );
  7204. return this.getUniforms();
  7205. }
  7206. },
  7207. attributes: {
  7208. get: function() {
  7209. console.warn( 'THREE.WebGLProgram: .attributes is now .getAttributes().' );
  7210. return this.getAttributes();
  7211. }
  7212. }
  7213. } );
  7214. //
  7215. this.id = programIdCount ++;
  7216. this.code = code;
  7217. this.usedTimes = 1;
  7218. this.program = program;
  7219. this.vertexShader = glVertexShader;
  7220. this.fragmentShader = glFragmentShader;
  7221. return this;
  7222. };
  7223. } )();
  7224. function WebGLPrograms( renderer, capabilities ) {
  7225. var programs = [];
  7226. var shaderIDs = {
  7227. MeshDepthMaterial: 'depth',
  7228. MeshNormalMaterial: 'normal',
  7229. MeshBasicMaterial: 'basic',
  7230. MeshLambertMaterial: 'lambert',
  7231. MeshPhongMaterial: 'phong',
  7232. MeshStandardMaterial: 'physical',
  7233. MeshPhysicalMaterial: 'physical',
  7234. LineBasicMaterial: 'basic',
  7235. LineDashedMaterial: 'dashed',
  7236. PointsMaterial: 'points'
  7237. };
  7238. var parameterNames = [
  7239. "precision", "supportsVertexTextures", "map", "mapEncoding", "envMap", "envMapMode", "envMapEncoding",
  7240. "lightMap", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "displacementMap", "specularMap",
  7241. "roughnessMap", "metalnessMap",
  7242. "alphaMap", "combine", "vertexColors", "fog", "useFog", "fogExp",
  7243. "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning",
  7244. "maxBones", "useVertexTexture", "morphTargets", "morphNormals",
  7245. "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha",
  7246. "numDirLights", "numPointLights", "numSpotLights", "numHemiLights",
  7247. "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights',
  7248. "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "depthPacking"
  7249. ];
  7250. function allocateBones( object ) {
  7251. if ( capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture ) {
  7252. return 1024;
  7253. } else {
  7254. // default for when object is not specified
  7255. // ( for example when prebuilding shader to be used with multiple objects )
  7256. //
  7257. // - leave some extra space for other uniforms
  7258. // - limit here is ANGLE's 254 max uniform vectors
  7259. // (up to 54 should be safe)
  7260. var nVertexUniforms = capabilities.maxVertexUniforms;
  7261. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  7262. var maxBones = nVertexMatrices;
  7263. if ( object !== undefined && (object && object.isSkinnedMesh) ) {
  7264. maxBones = Math.min( object.skeleton.bones.length, maxBones );
  7265. if ( maxBones < object.skeleton.bones.length ) {
  7266. console.warn( 'WebGLRenderer: too many bones - ' + object.skeleton.bones.length + ', this GPU supports just ' + maxBones + ' (try OpenGL instead of ANGLE)' );
  7267. }
  7268. }
  7269. return maxBones;
  7270. }
  7271. }
  7272. function getTextureEncodingFromMap( map, gammaOverrideLinear ) {
  7273. var encoding;
  7274. if ( ! map ) {
  7275. encoding = LinearEncoding;
  7276. } else if ( (map && map.isTexture) ) {
  7277. encoding = map.encoding;
  7278. } else if ( (map && map.isWebGLRenderTarget) ) {
  7279. console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." );
  7280. encoding = map.texture.encoding;
  7281. }
  7282. // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point.
  7283. if ( encoding === LinearEncoding && gammaOverrideLinear ) {
  7284. encoding = GammaEncoding;
  7285. }
  7286. return encoding;
  7287. }
  7288. this.getParameters = function ( material, lights, fog, nClipPlanes, object ) {
  7289. var shaderID = shaderIDs[ material.type ];
  7290. // heuristics to create shader parameters according to lights in the scene
  7291. // (not to blow over maxLights budget)
  7292. var maxBones = allocateBones( object );
  7293. var precision = renderer.getPrecision();
  7294. if ( material.precision !== null ) {
  7295. precision = capabilities.getMaxPrecision( material.precision );
  7296. if ( precision !== material.precision ) {
  7297. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  7298. }
  7299. }
  7300. var currentRenderTarget = renderer.getCurrentRenderTarget();
  7301. var parameters = {
  7302. shaderID: shaderID,
  7303. precision: precision,
  7304. supportsVertexTextures: capabilities.vertexTextures,
  7305. outputEncoding: getTextureEncodingFromMap( ( ! currentRenderTarget ) ? null : currentRenderTarget.texture, renderer.gammaOutput ),
  7306. map: !! material.map,
  7307. mapEncoding: getTextureEncodingFromMap( material.map, renderer.gammaInput ),
  7308. envMap: !! material.envMap,
  7309. envMapMode: material.envMap && material.envMap.mapping,
  7310. envMapEncoding: getTextureEncodingFromMap( material.envMap, renderer.gammaInput ),
  7311. envMapCubeUV: ( !! material.envMap ) && ( ( material.envMap.mapping === CubeUVReflectionMapping ) || ( material.envMap.mapping === CubeUVRefractionMapping ) ),
  7312. lightMap: !! material.lightMap,
  7313. aoMap: !! material.aoMap,
  7314. emissiveMap: !! material.emissiveMap,
  7315. emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap, renderer.gammaInput ),
  7316. bumpMap: !! material.bumpMap,
  7317. normalMap: !! material.normalMap,
  7318. displacementMap: !! material.displacementMap,
  7319. roughnessMap: !! material.roughnessMap,
  7320. metalnessMap: !! material.metalnessMap,
  7321. specularMap: !! material.specularMap,
  7322. alphaMap: !! material.alphaMap,
  7323. combine: material.combine,
  7324. vertexColors: material.vertexColors,
  7325. fog: !! fog,
  7326. useFog: material.fog,
  7327. fogExp: (fog && fog.isFogExp2),
  7328. flatShading: material.shading === FlatShading,
  7329. sizeAttenuation: material.sizeAttenuation,
  7330. logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer,
  7331. skinning: material.skinning,
  7332. maxBones: maxBones,
  7333. useVertexTexture: capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture,
  7334. morphTargets: material.morphTargets,
  7335. morphNormals: material.morphNormals,
  7336. maxMorphTargets: renderer.maxMorphTargets,
  7337. maxMorphNormals: renderer.maxMorphNormals,
  7338. numDirLights: lights.directional.length,
  7339. numPointLights: lights.point.length,
  7340. numSpotLights: lights.spot.length,
  7341. numHemiLights: lights.hemi.length,
  7342. numClippingPlanes: nClipPlanes,
  7343. shadowMapEnabled: renderer.shadowMap.enabled && object.receiveShadow && lights.shadows.length > 0,
  7344. shadowMapType: renderer.shadowMap.type,
  7345. toneMapping: renderer.toneMapping,
  7346. physicallyCorrectLights: renderer.physicallyCorrectLights,
  7347. premultipliedAlpha: material.premultipliedAlpha,
  7348. alphaTest: material.alphaTest,
  7349. doubleSided: material.side === DoubleSide,
  7350. flipSided: material.side === BackSide,
  7351. depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false
  7352. };
  7353. return parameters;
  7354. };
  7355. this.getProgramCode = function ( material, parameters ) {
  7356. var array = [];
  7357. if ( parameters.shaderID ) {
  7358. array.push( parameters.shaderID );
  7359. } else {
  7360. array.push( material.fragmentShader );
  7361. array.push( material.vertexShader );
  7362. }
  7363. if ( material.defines !== undefined ) {
  7364. for ( var name in material.defines ) {
  7365. array.push( name );
  7366. array.push( material.defines[ name ] );
  7367. }
  7368. }
  7369. for ( var i = 0; i < parameterNames.length; i ++ ) {
  7370. array.push( parameters[ parameterNames[ i ] ] );
  7371. }
  7372. return array.join();
  7373. };
  7374. this.acquireProgram = function ( material, parameters, code ) {
  7375. var program;
  7376. // Check if code has been already compiled
  7377. for ( var p = 0, pl = programs.length; p < pl; p ++ ) {
  7378. var programInfo = programs[ p ];
  7379. if ( programInfo.code === code ) {
  7380. program = programInfo;
  7381. ++ program.usedTimes;
  7382. break;
  7383. }
  7384. }
  7385. if ( program === undefined ) {
  7386. program = new exports.WebGLProgram( renderer, code, material, parameters );
  7387. programs.push( program );
  7388. }
  7389. return program;
  7390. };
  7391. this.releaseProgram = function( program ) {
  7392. if ( -- program.usedTimes === 0 ) {
  7393. // Remove from unordered set
  7394. var i = programs.indexOf( program );
  7395. programs[ i ] = programs[ programs.length - 1 ];
  7396. programs.pop();
  7397. // Free WebGL resources
  7398. program.destroy();
  7399. }
  7400. };
  7401. // Exposed for resource monitoring & error feedback via renderer.info:
  7402. this.programs = programs;
  7403. }
  7404. /**
  7405. * @author mrdoob / http://mrdoob.com/
  7406. */
  7407. function BufferAttribute( array, itemSize, normalized ) {
  7408. if ( Array.isArray( array ) ) {
  7409. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  7410. }
  7411. this.uuid = exports.Math.generateUUID();
  7412. this.array = array;
  7413. this.itemSize = itemSize;
  7414. this.normalized = normalized === true;
  7415. this.dynamic = false;
  7416. this.updateRange = { offset: 0, count: - 1 };
  7417. this.version = 0;
  7418. }
  7419. BufferAttribute.prototype = {
  7420. constructor: BufferAttribute,
  7421. isBufferAttribute: true,
  7422. get count() {
  7423. return this.array.length / this.itemSize;
  7424. },
  7425. set needsUpdate( value ) {
  7426. if ( value === true ) this.version ++;
  7427. },
  7428. setDynamic: function ( value ) {
  7429. this.dynamic = value;
  7430. return this;
  7431. },
  7432. copy: function ( source ) {
  7433. this.array = new source.array.constructor( source.array );
  7434. this.itemSize = source.itemSize;
  7435. this.normalized = source.normalized;
  7436. this.dynamic = source.dynamic;
  7437. return this;
  7438. },
  7439. copyAt: function ( index1, attribute, index2 ) {
  7440. index1 *= this.itemSize;
  7441. index2 *= attribute.itemSize;
  7442. for ( var i = 0, l = this.itemSize; i < l; i ++ ) {
  7443. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  7444. }
  7445. return this;
  7446. },
  7447. copyArray: function ( array ) {
  7448. this.array.set( array );
  7449. return this;
  7450. },
  7451. copyColorsArray: function ( colors ) {
  7452. var array = this.array, offset = 0;
  7453. for ( var i = 0, l = colors.length; i < l; i ++ ) {
  7454. var color = colors[ i ];
  7455. if ( color === undefined ) {
  7456. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  7457. color = new Color();
  7458. }
  7459. array[ offset ++ ] = color.r;
  7460. array[ offset ++ ] = color.g;
  7461. array[ offset ++ ] = color.b;
  7462. }
  7463. return this;
  7464. },
  7465. copyIndicesArray: function ( indices ) {
  7466. var array = this.array, offset = 0;
  7467. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  7468. var index = indices[ i ];
  7469. array[ offset ++ ] = index.a;
  7470. array[ offset ++ ] = index.b;
  7471. array[ offset ++ ] = index.c;
  7472. }
  7473. return this;
  7474. },
  7475. copyVector2sArray: function ( vectors ) {
  7476. var array = this.array, offset = 0;
  7477. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  7478. var vector = vectors[ i ];
  7479. if ( vector === undefined ) {
  7480. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  7481. vector = new Vector2();
  7482. }
  7483. array[ offset ++ ] = vector.x;
  7484. array[ offset ++ ] = vector.y;
  7485. }
  7486. return this;
  7487. },
  7488. copyVector3sArray: function ( vectors ) {
  7489. var array = this.array, offset = 0;
  7490. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  7491. var vector = vectors[ i ];
  7492. if ( vector === undefined ) {
  7493. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  7494. vector = new Vector3();
  7495. }
  7496. array[ offset ++ ] = vector.x;
  7497. array[ offset ++ ] = vector.y;
  7498. array[ offset ++ ] = vector.z;
  7499. }
  7500. return this;
  7501. },
  7502. copyVector4sArray: function ( vectors ) {
  7503. var array = this.array, offset = 0;
  7504. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  7505. var vector = vectors[ i ];
  7506. if ( vector === undefined ) {
  7507. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  7508. vector = new Vector4();
  7509. }
  7510. array[ offset ++ ] = vector.x;
  7511. array[ offset ++ ] = vector.y;
  7512. array[ offset ++ ] = vector.z;
  7513. array[ offset ++ ] = vector.w;
  7514. }
  7515. return this;
  7516. },
  7517. set: function ( value, offset ) {
  7518. if ( offset === undefined ) offset = 0;
  7519. this.array.set( value, offset );
  7520. return this;
  7521. },
  7522. getX: function ( index ) {
  7523. return this.array[ index * this.itemSize ];
  7524. },
  7525. setX: function ( index, x ) {
  7526. this.array[ index * this.itemSize ] = x;
  7527. return this;
  7528. },
  7529. getY: function ( index ) {
  7530. return this.array[ index * this.itemSize + 1 ];
  7531. },
  7532. setY: function ( index, y ) {
  7533. this.array[ index * this.itemSize + 1 ] = y;
  7534. return this;
  7535. },
  7536. getZ: function ( index ) {
  7537. return this.array[ index * this.itemSize + 2 ];
  7538. },
  7539. setZ: function ( index, z ) {
  7540. this.array[ index * this.itemSize + 2 ] = z;
  7541. return this;
  7542. },
  7543. getW: function ( index ) {
  7544. return this.array[ index * this.itemSize + 3 ];
  7545. },
  7546. setW: function ( index, w ) {
  7547. this.array[ index * this.itemSize + 3 ] = w;
  7548. return this;
  7549. },
  7550. setXY: function ( index, x, y ) {
  7551. index *= this.itemSize;
  7552. this.array[ index + 0 ] = x;
  7553. this.array[ index + 1 ] = y;
  7554. return this;
  7555. },
  7556. setXYZ: function ( index, x, y, z ) {
  7557. index *= this.itemSize;
  7558. this.array[ index + 0 ] = x;
  7559. this.array[ index + 1 ] = y;
  7560. this.array[ index + 2 ] = z;
  7561. return this;
  7562. },
  7563. setXYZW: function ( index, x, y, z, w ) {
  7564. index *= this.itemSize;
  7565. this.array[ index + 0 ] = x;
  7566. this.array[ index + 1 ] = y;
  7567. this.array[ index + 2 ] = z;
  7568. this.array[ index + 3 ] = w;
  7569. return this;
  7570. },
  7571. clone: function () {
  7572. return new this.constructor().copy( this );
  7573. }
  7574. };
  7575. //
  7576. function Int8Attribute( array, itemSize ) {
  7577. return new BufferAttribute( new Int8Array( array ), itemSize );
  7578. }
  7579. function Uint8Attribute( array, itemSize ) {
  7580. return new BufferAttribute( new Uint8Array( array ), itemSize );
  7581. }
  7582. function Uint8ClampedAttribute( array, itemSize ) {
  7583. return new BufferAttribute( new Uint8ClampedArray( array ), itemSize );
  7584. }
  7585. function Int16Attribute( array, itemSize ) {
  7586. return new BufferAttribute( new Int16Array( array ), itemSize );
  7587. }
  7588. function Uint16Attribute( array, itemSize ) {
  7589. return new BufferAttribute( new Uint16Array( array ), itemSize );
  7590. }
  7591. function Int32Attribute( array, itemSize ) {
  7592. return new BufferAttribute( new Int32Array( array ), itemSize );
  7593. }
  7594. function Uint32Attribute( array, itemSize ) {
  7595. return new BufferAttribute( new Uint32Array( array ), itemSize );
  7596. }
  7597. function Float32Attribute( array, itemSize ) {
  7598. return new BufferAttribute( new Float32Array( array ), itemSize );
  7599. }
  7600. function Float64Attribute( array, itemSize ) {
  7601. return new BufferAttribute( new Float64Array( array ), itemSize );
  7602. }
  7603. // Deprecated
  7604. function DynamicBufferAttribute( array, itemSize ) {
  7605. console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.' );
  7606. return new BufferAttribute( array, itemSize ).setDynamic( true );
  7607. }
  7608. /**
  7609. * @author mrdoob / http://mrdoob.com/
  7610. * @author alteredq / http://alteredqualia.com/
  7611. */
  7612. function Face3( a, b, c, normal, color, materialIndex ) {
  7613. this.a = a;
  7614. this.b = b;
  7615. this.c = c;
  7616. this.normal = (normal && normal.isVector3) ? normal : new Vector3();
  7617. this.vertexNormals = Array.isArray( normal ) ? normal : [];
  7618. this.color = (color && color.isColor) ? color : new Color();
  7619. this.vertexColors = Array.isArray( color ) ? color : [];
  7620. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  7621. }
  7622. Face3.prototype = {
  7623. constructor: Face3,
  7624. clone: function () {
  7625. return new this.constructor().copy( this );
  7626. },
  7627. copy: function ( source ) {
  7628. this.a = source.a;
  7629. this.b = source.b;
  7630. this.c = source.c;
  7631. this.normal.copy( source.normal );
  7632. this.color.copy( source.color );
  7633. this.materialIndex = source.materialIndex;
  7634. for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) {
  7635. this.vertexNormals[ i ] = source.vertexNormals[ i ].clone();
  7636. }
  7637. for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) {
  7638. this.vertexColors[ i ] = source.vertexColors[ i ].clone();
  7639. }
  7640. return this;
  7641. }
  7642. };
  7643. /**
  7644. * @author mrdoob / http://mrdoob.com/
  7645. * @author WestLangley / http://github.com/WestLangley
  7646. * @author bhouston / http://clara.io
  7647. */
  7648. function Euler( x, y, z, order ) {
  7649. this._x = x || 0;
  7650. this._y = y || 0;
  7651. this._z = z || 0;
  7652. this._order = order || Euler.DefaultOrder;
  7653. }
  7654. Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  7655. Euler.DefaultOrder = 'XYZ';
  7656. Euler.prototype = {
  7657. constructor: Euler,
  7658. isEuler: true,
  7659. get x () {
  7660. return this._x;
  7661. },
  7662. set x ( value ) {
  7663. this._x = value;
  7664. this.onChangeCallback();
  7665. },
  7666. get y () {
  7667. return this._y;
  7668. },
  7669. set y ( value ) {
  7670. this._y = value;
  7671. this.onChangeCallback();
  7672. },
  7673. get z () {
  7674. return this._z;
  7675. },
  7676. set z ( value ) {
  7677. this._z = value;
  7678. this.onChangeCallback();
  7679. },
  7680. get order () {
  7681. return this._order;
  7682. },
  7683. set order ( value ) {
  7684. this._order = value;
  7685. this.onChangeCallback();
  7686. },
  7687. set: function ( x, y, z, order ) {
  7688. this._x = x;
  7689. this._y = y;
  7690. this._z = z;
  7691. this._order = order || this._order;
  7692. this.onChangeCallback();
  7693. return this;
  7694. },
  7695. clone: function () {
  7696. return new this.constructor( this._x, this._y, this._z, this._order );
  7697. },
  7698. copy: function ( euler ) {
  7699. this._x = euler._x;
  7700. this._y = euler._y;
  7701. this._z = euler._z;
  7702. this._order = euler._order;
  7703. this.onChangeCallback();
  7704. return this;
  7705. },
  7706. setFromRotationMatrix: function ( m, order, update ) {
  7707. var clamp = exports.Math.clamp;
  7708. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  7709. var te = m.elements;
  7710. var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  7711. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  7712. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  7713. order = order || this._order;
  7714. if ( order === 'XYZ' ) {
  7715. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  7716. if ( Math.abs( m13 ) < 0.99999 ) {
  7717. this._x = Math.atan2( - m23, m33 );
  7718. this._z = Math.atan2( - m12, m11 );
  7719. } else {
  7720. this._x = Math.atan2( m32, m22 );
  7721. this._z = 0;
  7722. }
  7723. } else if ( order === 'YXZ' ) {
  7724. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  7725. if ( Math.abs( m23 ) < 0.99999 ) {
  7726. this._y = Math.atan2( m13, m33 );
  7727. this._z = Math.atan2( m21, m22 );
  7728. } else {
  7729. this._y = Math.atan2( - m31, m11 );
  7730. this._z = 0;
  7731. }
  7732. } else if ( order === 'ZXY' ) {
  7733. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  7734. if ( Math.abs( m32 ) < 0.99999 ) {
  7735. this._y = Math.atan2( - m31, m33 );
  7736. this._z = Math.atan2( - m12, m22 );
  7737. } else {
  7738. this._y = 0;
  7739. this._z = Math.atan2( m21, m11 );
  7740. }
  7741. } else if ( order === 'ZYX' ) {
  7742. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  7743. if ( Math.abs( m31 ) < 0.99999 ) {
  7744. this._x = Math.atan2( m32, m33 );
  7745. this._z = Math.atan2( m21, m11 );
  7746. } else {
  7747. this._x = 0;
  7748. this._z = Math.atan2( - m12, m22 );
  7749. }
  7750. } else if ( order === 'YZX' ) {
  7751. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  7752. if ( Math.abs( m21 ) < 0.99999 ) {
  7753. this._x = Math.atan2( - m23, m22 );
  7754. this._y = Math.atan2( - m31, m11 );
  7755. } else {
  7756. this._x = 0;
  7757. this._y = Math.atan2( m13, m33 );
  7758. }
  7759. } else if ( order === 'XZY' ) {
  7760. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  7761. if ( Math.abs( m12 ) < 0.99999 ) {
  7762. this._x = Math.atan2( m32, m22 );
  7763. this._y = Math.atan2( m13, m11 );
  7764. } else {
  7765. this._x = Math.atan2( - m23, m33 );
  7766. this._y = 0;
  7767. }
  7768. } else {
  7769. console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order );
  7770. }
  7771. this._order = order;
  7772. if ( update !== false ) this.onChangeCallback();
  7773. return this;
  7774. },
  7775. setFromQuaternion: function () {
  7776. var matrix;
  7777. return function setFromQuaternion( q, order, update ) {
  7778. if ( matrix === undefined ) matrix = new Matrix4();
  7779. matrix.makeRotationFromQuaternion( q );
  7780. return this.setFromRotationMatrix( matrix, order, update );
  7781. };
  7782. }(),
  7783. setFromVector3: function ( v, order ) {
  7784. return this.set( v.x, v.y, v.z, order || this._order );
  7785. },
  7786. reorder: function () {
  7787. // WARNING: this discards revolution information -bhouston
  7788. var q = new Quaternion();
  7789. return function reorder( newOrder ) {
  7790. q.setFromEuler( this );
  7791. return this.setFromQuaternion( q, newOrder );
  7792. };
  7793. }(),
  7794. equals: function ( euler ) {
  7795. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  7796. },
  7797. fromArray: function ( array ) {
  7798. this._x = array[ 0 ];
  7799. this._y = array[ 1 ];
  7800. this._z = array[ 2 ];
  7801. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  7802. this.onChangeCallback();
  7803. return this;
  7804. },
  7805. toArray: function ( array, offset ) {
  7806. if ( array === undefined ) array = [];
  7807. if ( offset === undefined ) offset = 0;
  7808. array[ offset ] = this._x;
  7809. array[ offset + 1 ] = this._y;
  7810. array[ offset + 2 ] = this._z;
  7811. array[ offset + 3 ] = this._order;
  7812. return array;
  7813. },
  7814. toVector3: function ( optionalResult ) {
  7815. if ( optionalResult ) {
  7816. return optionalResult.set( this._x, this._y, this._z );
  7817. } else {
  7818. return new Vector3( this._x, this._y, this._z );
  7819. }
  7820. },
  7821. onChange: function ( callback ) {
  7822. this.onChangeCallback = callback;
  7823. return this;
  7824. },
  7825. onChangeCallback: function () {}
  7826. };
  7827. /**
  7828. * @author mrdoob / http://mrdoob.com/
  7829. */
  7830. function Layers() {
  7831. this.mask = 1;
  7832. }
  7833. Layers.prototype = {
  7834. constructor: Layers,
  7835. set: function ( channel ) {
  7836. this.mask = 1 << channel;
  7837. },
  7838. enable: function ( channel ) {
  7839. this.mask |= 1 << channel;
  7840. },
  7841. toggle: function ( channel ) {
  7842. this.mask ^= 1 << channel;
  7843. },
  7844. disable: function ( channel ) {
  7845. this.mask &= ~ ( 1 << channel );
  7846. },
  7847. test: function ( layers ) {
  7848. return ( this.mask & layers.mask ) !== 0;
  7849. }
  7850. };
  7851. /**
  7852. * @author mrdoob / http://mrdoob.com/
  7853. * @author mikael emtinger / http://gomo.se/
  7854. * @author alteredq / http://alteredqualia.com/
  7855. * @author WestLangley / http://github.com/WestLangley
  7856. * @author elephantatwork / www.elephantatwork.ch
  7857. */
  7858. function Object3D() {
  7859. Object.defineProperty( this, 'id', { value: Object3DIdCount() } );
  7860. this.uuid = exports.Math.generateUUID();
  7861. this.name = '';
  7862. this.type = 'Object3D';
  7863. this.parent = null;
  7864. this.children = [];
  7865. this.up = Object3D.DefaultUp.clone();
  7866. var position = new Vector3();
  7867. var rotation = new Euler();
  7868. var quaternion = new Quaternion();
  7869. var scale = new Vector3( 1, 1, 1 );
  7870. function onRotationChange() {
  7871. quaternion.setFromEuler( rotation, false );
  7872. }
  7873. function onQuaternionChange() {
  7874. rotation.setFromQuaternion( quaternion, undefined, false );
  7875. }
  7876. rotation.onChange( onRotationChange );
  7877. quaternion.onChange( onQuaternionChange );
  7878. Object.defineProperties( this, {
  7879. position: {
  7880. enumerable: true,
  7881. value: position
  7882. },
  7883. rotation: {
  7884. enumerable: true,
  7885. value: rotation
  7886. },
  7887. quaternion: {
  7888. enumerable: true,
  7889. value: quaternion
  7890. },
  7891. scale: {
  7892. enumerable: true,
  7893. value: scale
  7894. },
  7895. modelViewMatrix: {
  7896. value: new Matrix4()
  7897. },
  7898. normalMatrix: {
  7899. value: new Matrix3()
  7900. }
  7901. } );
  7902. this.matrix = new Matrix4();
  7903. this.matrixWorld = new Matrix4();
  7904. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  7905. this.matrixWorldNeedsUpdate = false;
  7906. this.layers = new Layers();
  7907. this.visible = true;
  7908. this.castShadow = false;
  7909. this.receiveShadow = false;
  7910. this.frustumCulled = true;
  7911. this.renderOrder = 0;
  7912. this.userData = {};
  7913. }
  7914. Object3D.DefaultUp = new Vector3( 0, 1, 0 );
  7915. Object3D.DefaultMatrixAutoUpdate = true;
  7916. Object.assign( Object3D.prototype, EventDispatcher.prototype, {
  7917. isObject3D: true,
  7918. applyMatrix: function ( matrix ) {
  7919. this.matrix.multiplyMatrices( matrix, this.matrix );
  7920. this.matrix.decompose( this.position, this.quaternion, this.scale );
  7921. },
  7922. setRotationFromAxisAngle: function ( axis, angle ) {
  7923. // assumes axis is normalized
  7924. this.quaternion.setFromAxisAngle( axis, angle );
  7925. },
  7926. setRotationFromEuler: function ( euler ) {
  7927. this.quaternion.setFromEuler( euler, true );
  7928. },
  7929. setRotationFromMatrix: function ( m ) {
  7930. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  7931. this.quaternion.setFromRotationMatrix( m );
  7932. },
  7933. setRotationFromQuaternion: function ( q ) {
  7934. // assumes q is normalized
  7935. this.quaternion.copy( q );
  7936. },
  7937. rotateOnAxis: function () {
  7938. // rotate object on axis in object space
  7939. // axis is assumed to be normalized
  7940. var q1 = new Quaternion();
  7941. return function rotateOnAxis( axis, angle ) {
  7942. q1.setFromAxisAngle( axis, angle );
  7943. this.quaternion.multiply( q1 );
  7944. return this;
  7945. };
  7946. }(),
  7947. rotateX: function () {
  7948. var v1 = new Vector3( 1, 0, 0 );
  7949. return function rotateX( angle ) {
  7950. return this.rotateOnAxis( v1, angle );
  7951. };
  7952. }(),
  7953. rotateY: function () {
  7954. var v1 = new Vector3( 0, 1, 0 );
  7955. return function rotateY( angle ) {
  7956. return this.rotateOnAxis( v1, angle );
  7957. };
  7958. }(),
  7959. rotateZ: function () {
  7960. var v1 = new Vector3( 0, 0, 1 );
  7961. return function rotateZ( angle ) {
  7962. return this.rotateOnAxis( v1, angle );
  7963. };
  7964. }(),
  7965. translateOnAxis: function () {
  7966. // translate object by distance along axis in object space
  7967. // axis is assumed to be normalized
  7968. var v1 = new Vector3();
  7969. return function translateOnAxis( axis, distance ) {
  7970. v1.copy( axis ).applyQuaternion( this.quaternion );
  7971. this.position.add( v1.multiplyScalar( distance ) );
  7972. return this;
  7973. };
  7974. }(),
  7975. translateX: function () {
  7976. var v1 = new Vector3( 1, 0, 0 );
  7977. return function translateX( distance ) {
  7978. return this.translateOnAxis( v1, distance );
  7979. };
  7980. }(),
  7981. translateY: function () {
  7982. var v1 = new Vector3( 0, 1, 0 );
  7983. return function translateY( distance ) {
  7984. return this.translateOnAxis( v1, distance );
  7985. };
  7986. }(),
  7987. translateZ: function () {
  7988. var v1 = new Vector3( 0, 0, 1 );
  7989. return function translateZ( distance ) {
  7990. return this.translateOnAxis( v1, distance );
  7991. };
  7992. }(),
  7993. localToWorld: function ( vector ) {
  7994. return vector.applyMatrix4( this.matrixWorld );
  7995. },
  7996. worldToLocal: function () {
  7997. var m1 = new Matrix4();
  7998. return function worldToLocal( vector ) {
  7999. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  8000. };
  8001. }(),
  8002. lookAt: function () {
  8003. // This routine does not support objects with rotated and/or translated parent(s)
  8004. var m1 = new Matrix4();
  8005. return function lookAt( vector ) {
  8006. m1.lookAt( vector, this.position, this.up );
  8007. this.quaternion.setFromRotationMatrix( m1 );
  8008. };
  8009. }(),
  8010. add: function ( object ) {
  8011. if ( arguments.length > 1 ) {
  8012. for ( var i = 0; i < arguments.length; i ++ ) {
  8013. this.add( arguments[ i ] );
  8014. }
  8015. return this;
  8016. }
  8017. if ( object === this ) {
  8018. console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object );
  8019. return this;
  8020. }
  8021. if ( (object && object.isObject3D) ) {
  8022. if ( object.parent !== null ) {
  8023. object.parent.remove( object );
  8024. }
  8025. object.parent = this;
  8026. object.dispatchEvent( { type: 'added' } );
  8027. this.children.push( object );
  8028. } else {
  8029. console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object );
  8030. }
  8031. return this;
  8032. },
  8033. remove: function ( object ) {
  8034. if ( arguments.length > 1 ) {
  8035. for ( var i = 0; i < arguments.length; i ++ ) {
  8036. this.remove( arguments[ i ] );
  8037. }
  8038. }
  8039. var index = this.children.indexOf( object );
  8040. if ( index !== - 1 ) {
  8041. object.parent = null;
  8042. object.dispatchEvent( { type: 'removed' } );
  8043. this.children.splice( index, 1 );
  8044. }
  8045. },
  8046. getObjectById: function ( id ) {
  8047. return this.getObjectByProperty( 'id', id );
  8048. },
  8049. getObjectByName: function ( name ) {
  8050. return this.getObjectByProperty( 'name', name );
  8051. },
  8052. getObjectByProperty: function ( name, value ) {
  8053. if ( this[ name ] === value ) return this;
  8054. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  8055. var child = this.children[ i ];
  8056. var object = child.getObjectByProperty( name, value );
  8057. if ( object !== undefined ) {
  8058. return object;
  8059. }
  8060. }
  8061. return undefined;
  8062. },
  8063. getWorldPosition: function ( optionalTarget ) {
  8064. var result = optionalTarget || new Vector3();
  8065. this.updateMatrixWorld( true );
  8066. return result.setFromMatrixPosition( this.matrixWorld );
  8067. },
  8068. getWorldQuaternion: function () {
  8069. var position = new Vector3();
  8070. var scale = new Vector3();
  8071. return function getWorldQuaternion( optionalTarget ) {
  8072. var result = optionalTarget || new Quaternion();
  8073. this.updateMatrixWorld( true );
  8074. this.matrixWorld.decompose( position, result, scale );
  8075. return result;
  8076. };
  8077. }(),
  8078. getWorldRotation: function () {
  8079. var quaternion = new Quaternion();
  8080. return function getWorldRotation( optionalTarget ) {
  8081. var result = optionalTarget || new Euler();
  8082. this.getWorldQuaternion( quaternion );
  8083. return result.setFromQuaternion( quaternion, this.rotation.order, false );
  8084. };
  8085. }(),
  8086. getWorldScale: function () {
  8087. var position = new Vector3();
  8088. var quaternion = new Quaternion();
  8089. return function getWorldScale( optionalTarget ) {
  8090. var result = optionalTarget || new Vector3();
  8091. this.updateMatrixWorld( true );
  8092. this.matrixWorld.decompose( position, quaternion, result );
  8093. return result;
  8094. };
  8095. }(),
  8096. getWorldDirection: function () {
  8097. var quaternion = new Quaternion();
  8098. return function getWorldDirection( optionalTarget ) {
  8099. var result = optionalTarget || new Vector3();
  8100. this.getWorldQuaternion( quaternion );
  8101. return result.set( 0, 0, 1 ).applyQuaternion( quaternion );
  8102. };
  8103. }(),
  8104. raycast: function () {},
  8105. traverse: function ( callback ) {
  8106. callback( this );
  8107. var children = this.children;
  8108. for ( var i = 0, l = children.length; i < l; i ++ ) {
  8109. children[ i ].traverse( callback );
  8110. }
  8111. },
  8112. traverseVisible: function ( callback ) {
  8113. if ( this.visible === false ) return;
  8114. callback( this );
  8115. var children = this.children;
  8116. for ( var i = 0, l = children.length; i < l; i ++ ) {
  8117. children[ i ].traverseVisible( callback );
  8118. }
  8119. },
  8120. traverseAncestors: function ( callback ) {
  8121. var parent = this.parent;
  8122. if ( parent !== null ) {
  8123. callback( parent );
  8124. parent.traverseAncestors( callback );
  8125. }
  8126. },
  8127. updateMatrix: function () {
  8128. this.matrix.compose( this.position, this.quaternion, this.scale );
  8129. this.matrixWorldNeedsUpdate = true;
  8130. },
  8131. updateMatrixWorld: function ( force ) {
  8132. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  8133. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  8134. if ( this.parent === null ) {
  8135. this.matrixWorld.copy( this.matrix );
  8136. } else {
  8137. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  8138. }
  8139. this.matrixWorldNeedsUpdate = false;
  8140. force = true;
  8141. }
  8142. // update children
  8143. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  8144. this.children[ i ].updateMatrixWorld( force );
  8145. }
  8146. },
  8147. toJSON: function ( meta ) {
  8148. // meta is '' when called from JSON.stringify
  8149. var isRootObject = ( meta === undefined || meta === '' );
  8150. var output = {};
  8151. // meta is a hash used to collect geometries, materials.
  8152. // not providing it implies that this is the root object
  8153. // being serialized.
  8154. if ( isRootObject ) {
  8155. // initialize meta obj
  8156. meta = {
  8157. geometries: {},
  8158. materials: {},
  8159. textures: {},
  8160. images: {}
  8161. };
  8162. output.metadata = {
  8163. version: 4.4,
  8164. type: 'Object',
  8165. generator: 'Object3D.toJSON'
  8166. };
  8167. }
  8168. // standard Object3D serialization
  8169. var object = {};
  8170. object.uuid = this.uuid;
  8171. object.type = this.type;
  8172. if ( this.name !== '' ) object.name = this.name;
  8173. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  8174. if ( this.castShadow === true ) object.castShadow = true;
  8175. if ( this.receiveShadow === true ) object.receiveShadow = true;
  8176. if ( this.visible === false ) object.visible = false;
  8177. object.matrix = this.matrix.toArray();
  8178. //
  8179. if ( this.geometry !== undefined ) {
  8180. if ( meta.geometries[ this.geometry.uuid ] === undefined ) {
  8181. meta.geometries[ this.geometry.uuid ] = this.geometry.toJSON( meta );
  8182. }
  8183. object.geometry = this.geometry.uuid;
  8184. }
  8185. if ( this.material !== undefined ) {
  8186. if ( meta.materials[ this.material.uuid ] === undefined ) {
  8187. meta.materials[ this.material.uuid ] = this.material.toJSON( meta );
  8188. }
  8189. object.material = this.material.uuid;
  8190. }
  8191. //
  8192. if ( this.children.length > 0 ) {
  8193. object.children = [];
  8194. for ( var i = 0; i < this.children.length; i ++ ) {
  8195. object.children.push( this.children[ i ].toJSON( meta ).object );
  8196. }
  8197. }
  8198. if ( isRootObject ) {
  8199. var geometries = extractFromCache( meta.geometries );
  8200. var materials = extractFromCache( meta.materials );
  8201. var textures = extractFromCache( meta.textures );
  8202. var images = extractFromCache( meta.images );
  8203. if ( geometries.length > 0 ) output.geometries = geometries;
  8204. if ( materials.length > 0 ) output.materials = materials;
  8205. if ( textures.length > 0 ) output.textures = textures;
  8206. if ( images.length > 0 ) output.images = images;
  8207. }
  8208. output.object = object;
  8209. return output;
  8210. // extract data from the cache hash
  8211. // remove metadata on each item
  8212. // and return as array
  8213. function extractFromCache( cache ) {
  8214. var values = [];
  8215. for ( var key in cache ) {
  8216. var data = cache[ key ];
  8217. delete data.metadata;
  8218. values.push( data );
  8219. }
  8220. return values;
  8221. }
  8222. },
  8223. clone: function ( recursive ) {
  8224. return new this.constructor().copy( this, recursive );
  8225. },
  8226. copy: function ( source, recursive ) {
  8227. if ( recursive === undefined ) recursive = true;
  8228. this.name = source.name;
  8229. this.up.copy( source.up );
  8230. this.position.copy( source.position );
  8231. this.quaternion.copy( source.quaternion );
  8232. this.scale.copy( source.scale );
  8233. this.matrix.copy( source.matrix );
  8234. this.matrixWorld.copy( source.matrixWorld );
  8235. this.matrixAutoUpdate = source.matrixAutoUpdate;
  8236. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  8237. this.visible = source.visible;
  8238. this.castShadow = source.castShadow;
  8239. this.receiveShadow = source.receiveShadow;
  8240. this.frustumCulled = source.frustumCulled;
  8241. this.renderOrder = source.renderOrder;
  8242. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  8243. if ( recursive === true ) {
  8244. for ( var i = 0; i < source.children.length; i ++ ) {
  8245. var child = source.children[ i ];
  8246. this.add( child.clone() );
  8247. }
  8248. }
  8249. return this;
  8250. }
  8251. } );
  8252. var count$3 = 0;
  8253. function Object3DIdCount() { return count$3++; };
  8254. /**
  8255. * @author mrdoob / http://mrdoob.com/
  8256. * @author kile / http://kile.stravaganza.org/
  8257. * @author alteredq / http://alteredqualia.com/
  8258. * @author mikael emtinger / http://gomo.se/
  8259. * @author zz85 / http://www.lab4games.net/zz85/blog
  8260. * @author bhouston / http://clara.io
  8261. */
  8262. function Geometry() {
  8263. Object.defineProperty( this, 'id', { value: GeometryIdCount() } );
  8264. this.uuid = exports.Math.generateUUID();
  8265. this.name = '';
  8266. this.type = 'Geometry';
  8267. this.vertices = [];
  8268. this.colors = [];
  8269. this.faces = [];
  8270. this.faceVertexUvs = [ [] ];
  8271. this.morphTargets = [];
  8272. this.morphNormals = [];
  8273. this.skinWeights = [];
  8274. this.skinIndices = [];
  8275. this.lineDistances = [];
  8276. this.boundingBox = null;
  8277. this.boundingSphere = null;
  8278. // update flags
  8279. this.elementsNeedUpdate = false;
  8280. this.verticesNeedUpdate = false;
  8281. this.uvsNeedUpdate = false;
  8282. this.normalsNeedUpdate = false;
  8283. this.colorsNeedUpdate = false;
  8284. this.lineDistancesNeedUpdate = false;
  8285. this.groupsNeedUpdate = false;
  8286. }
  8287. Object.assign( Geometry.prototype, EventDispatcher.prototype, {
  8288. isGeometry: true,
  8289. applyMatrix: function ( matrix ) {
  8290. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  8291. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  8292. var vertex = this.vertices[ i ];
  8293. vertex.applyMatrix4( matrix );
  8294. }
  8295. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  8296. var face = this.faces[ i ];
  8297. face.normal.applyMatrix3( normalMatrix ).normalize();
  8298. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  8299. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  8300. }
  8301. }
  8302. if ( this.boundingBox !== null ) {
  8303. this.computeBoundingBox();
  8304. }
  8305. if ( this.boundingSphere !== null ) {
  8306. this.computeBoundingSphere();
  8307. }
  8308. this.verticesNeedUpdate = true;
  8309. this.normalsNeedUpdate = true;
  8310. return this;
  8311. },
  8312. rotateX: function () {
  8313. // rotate geometry around world x-axis
  8314. var m1;
  8315. return function rotateX( angle ) {
  8316. if ( m1 === undefined ) m1 = new Matrix4();
  8317. m1.makeRotationX( angle );
  8318. this.applyMatrix( m1 );
  8319. return this;
  8320. };
  8321. }(),
  8322. rotateY: function () {
  8323. // rotate geometry around world y-axis
  8324. var m1;
  8325. return function rotateY( angle ) {
  8326. if ( m1 === undefined ) m1 = new Matrix4();
  8327. m1.makeRotationY( angle );
  8328. this.applyMatrix( m1 );
  8329. return this;
  8330. };
  8331. }(),
  8332. rotateZ: function () {
  8333. // rotate geometry around world z-axis
  8334. var m1;
  8335. return function rotateZ( angle ) {
  8336. if ( m1 === undefined ) m1 = new Matrix4();
  8337. m1.makeRotationZ( angle );
  8338. this.applyMatrix( m1 );
  8339. return this;
  8340. };
  8341. }(),
  8342. translate: function () {
  8343. // translate geometry
  8344. var m1;
  8345. return function translate( x, y, z ) {
  8346. if ( m1 === undefined ) m1 = new Matrix4();
  8347. m1.makeTranslation( x, y, z );
  8348. this.applyMatrix( m1 );
  8349. return this;
  8350. };
  8351. }(),
  8352. scale: function () {
  8353. // scale geometry
  8354. var m1;
  8355. return function scale( x, y, z ) {
  8356. if ( m1 === undefined ) m1 = new Matrix4();
  8357. m1.makeScale( x, y, z );
  8358. this.applyMatrix( m1 );
  8359. return this;
  8360. };
  8361. }(),
  8362. lookAt: function () {
  8363. var obj;
  8364. return function lookAt( vector ) {
  8365. if ( obj === undefined ) obj = new Object3D();
  8366. obj.lookAt( vector );
  8367. obj.updateMatrix();
  8368. this.applyMatrix( obj.matrix );
  8369. };
  8370. }(),
  8371. fromBufferGeometry: function ( geometry ) {
  8372. var scope = this;
  8373. var indices = geometry.index !== null ? geometry.index.array : undefined;
  8374. var attributes = geometry.attributes;
  8375. var positions = attributes.position.array;
  8376. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  8377. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  8378. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  8379. var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;
  8380. if ( uvs2 !== undefined ) this.faceVertexUvs[ 1 ] = [];
  8381. var tempNormals = [];
  8382. var tempUVs = [];
  8383. var tempUVs2 = [];
  8384. for ( var i = 0, j = 0; i < positions.length; i += 3, j += 2 ) {
  8385. scope.vertices.push( new Vector3( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ) );
  8386. if ( normals !== undefined ) {
  8387. tempNormals.push( new Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) );
  8388. }
  8389. if ( colors !== undefined ) {
  8390. scope.colors.push( new Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) );
  8391. }
  8392. if ( uvs !== undefined ) {
  8393. tempUVs.push( new Vector2( uvs[ j ], uvs[ j + 1 ] ) );
  8394. }
  8395. if ( uvs2 !== undefined ) {
  8396. tempUVs2.push( new Vector2( uvs2[ j ], uvs2[ j + 1 ] ) );
  8397. }
  8398. }
  8399. function addFace( a, b, c, materialIndex ) {
  8400. var vertexNormals = normals !== undefined ? [ tempNormals[ a ].clone(), tempNormals[ b ].clone(), tempNormals[ c ].clone() ] : [];
  8401. var vertexColors = colors !== undefined ? [ scope.colors[ a ].clone(), scope.colors[ b ].clone(), scope.colors[ c ].clone() ] : [];
  8402. var face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex );
  8403. scope.faces.push( face );
  8404. if ( uvs !== undefined ) {
  8405. scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] );
  8406. }
  8407. if ( uvs2 !== undefined ) {
  8408. scope.faceVertexUvs[ 1 ].push( [ tempUVs2[ a ].clone(), tempUVs2[ b ].clone(), tempUVs2[ c ].clone() ] );
  8409. }
  8410. }
  8411. if ( indices !== undefined ) {
  8412. var groups = geometry.groups;
  8413. if ( groups.length > 0 ) {
  8414. for ( var i = 0; i < groups.length; i ++ ) {
  8415. var group = groups[ i ];
  8416. var start = group.start;
  8417. var count = group.count;
  8418. for ( var j = start, jl = start + count; j < jl; j += 3 ) {
  8419. addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ], group.materialIndex );
  8420. }
  8421. }
  8422. } else {
  8423. for ( var i = 0; i < indices.length; i += 3 ) {
  8424. addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  8425. }
  8426. }
  8427. } else {
  8428. for ( var i = 0; i < positions.length / 3; i += 3 ) {
  8429. addFace( i, i + 1, i + 2 );
  8430. }
  8431. }
  8432. this.computeFaceNormals();
  8433. if ( geometry.boundingBox !== null ) {
  8434. this.boundingBox = geometry.boundingBox.clone();
  8435. }
  8436. if ( geometry.boundingSphere !== null ) {
  8437. this.boundingSphere = geometry.boundingSphere.clone();
  8438. }
  8439. return this;
  8440. },
  8441. center: function () {
  8442. this.computeBoundingBox();
  8443. var offset = this.boundingBox.center().negate();
  8444. this.translate( offset.x, offset.y, offset.z );
  8445. return offset;
  8446. },
  8447. normalize: function () {
  8448. this.computeBoundingSphere();
  8449. var center = this.boundingSphere.center;
  8450. var radius = this.boundingSphere.radius;
  8451. var s = radius === 0 ? 1 : 1.0 / radius;
  8452. var matrix = new Matrix4();
  8453. matrix.set(
  8454. s, 0, 0, - s * center.x,
  8455. 0, s, 0, - s * center.y,
  8456. 0, 0, s, - s * center.z,
  8457. 0, 0, 0, 1
  8458. );
  8459. this.applyMatrix( matrix );
  8460. return this;
  8461. },
  8462. computeFaceNormals: function () {
  8463. var cb = new Vector3(), ab = new Vector3();
  8464. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  8465. var face = this.faces[ f ];
  8466. var vA = this.vertices[ face.a ];
  8467. var vB = this.vertices[ face.b ];
  8468. var vC = this.vertices[ face.c ];
  8469. cb.subVectors( vC, vB );
  8470. ab.subVectors( vA, vB );
  8471. cb.cross( ab );
  8472. cb.normalize();
  8473. face.normal.copy( cb );
  8474. }
  8475. },
  8476. computeVertexNormals: function ( areaWeighted ) {
  8477. if ( areaWeighted === undefined ) areaWeighted = true;
  8478. var v, vl, f, fl, face, vertices;
  8479. vertices = new Array( this.vertices.length );
  8480. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  8481. vertices[ v ] = new Vector3();
  8482. }
  8483. if ( areaWeighted ) {
  8484. // vertex normals weighted by triangle areas
  8485. // http://www.iquilezles.org/www/articles/normals/normals.htm
  8486. var vA, vB, vC;
  8487. var cb = new Vector3(), ab = new Vector3();
  8488. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  8489. face = this.faces[ f ];
  8490. vA = this.vertices[ face.a ];
  8491. vB = this.vertices[ face.b ];
  8492. vC = this.vertices[ face.c ];
  8493. cb.subVectors( vC, vB );
  8494. ab.subVectors( vA, vB );
  8495. cb.cross( ab );
  8496. vertices[ face.a ].add( cb );
  8497. vertices[ face.b ].add( cb );
  8498. vertices[ face.c ].add( cb );
  8499. }
  8500. } else {
  8501. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  8502. face = this.faces[ f ];
  8503. vertices[ face.a ].add( face.normal );
  8504. vertices[ face.b ].add( face.normal );
  8505. vertices[ face.c ].add( face.normal );
  8506. }
  8507. }
  8508. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  8509. vertices[ v ].normalize();
  8510. }
  8511. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  8512. face = this.faces[ f ];
  8513. var vertexNormals = face.vertexNormals;
  8514. if ( vertexNormals.length === 3 ) {
  8515. vertexNormals[ 0 ].copy( vertices[ face.a ] );
  8516. vertexNormals[ 1 ].copy( vertices[ face.b ] );
  8517. vertexNormals[ 2 ].copy( vertices[ face.c ] );
  8518. } else {
  8519. vertexNormals[ 0 ] = vertices[ face.a ].clone();
  8520. vertexNormals[ 1 ] = vertices[ face.b ].clone();
  8521. vertexNormals[ 2 ] = vertices[ face.c ].clone();
  8522. }
  8523. }
  8524. if ( this.faces.length > 0 ) {
  8525. this.normalsNeedUpdate = true;
  8526. }
  8527. },
  8528. computeMorphNormals: function () {
  8529. var i, il, f, fl, face;
  8530. // save original normals
  8531. // - create temp variables on first access
  8532. // otherwise just copy (for faster repeated calls)
  8533. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  8534. face = this.faces[ f ];
  8535. if ( ! face.__originalFaceNormal ) {
  8536. face.__originalFaceNormal = face.normal.clone();
  8537. } else {
  8538. face.__originalFaceNormal.copy( face.normal );
  8539. }
  8540. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  8541. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  8542. if ( ! face.__originalVertexNormals[ i ] ) {
  8543. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  8544. } else {
  8545. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  8546. }
  8547. }
  8548. }
  8549. // use temp geometry to compute face and vertex normals for each morph
  8550. var tmpGeo = new Geometry();
  8551. tmpGeo.faces = this.faces;
  8552. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  8553. // create on first access
  8554. if ( ! this.morphNormals[ i ] ) {
  8555. this.morphNormals[ i ] = {};
  8556. this.morphNormals[ i ].faceNormals = [];
  8557. this.morphNormals[ i ].vertexNormals = [];
  8558. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  8559. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  8560. var faceNormal, vertexNormals;
  8561. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  8562. faceNormal = new Vector3();
  8563. vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() };
  8564. dstNormalsFace.push( faceNormal );
  8565. dstNormalsVertex.push( vertexNormals );
  8566. }
  8567. }
  8568. var morphNormals = this.morphNormals[ i ];
  8569. // set vertices to morph target
  8570. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  8571. // compute morph normals
  8572. tmpGeo.computeFaceNormals();
  8573. tmpGeo.computeVertexNormals();
  8574. // store morph normals
  8575. var faceNormal, vertexNormals;
  8576. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  8577. face = this.faces[ f ];
  8578. faceNormal = morphNormals.faceNormals[ f ];
  8579. vertexNormals = morphNormals.vertexNormals[ f ];
  8580. faceNormal.copy( face.normal );
  8581. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  8582. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  8583. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  8584. }
  8585. }
  8586. // restore original normals
  8587. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  8588. face = this.faces[ f ];
  8589. face.normal = face.__originalFaceNormal;
  8590. face.vertexNormals = face.__originalVertexNormals;
  8591. }
  8592. },
  8593. computeTangents: function () {
  8594. console.warn( 'THREE.Geometry: .computeTangents() has been removed.' );
  8595. },
  8596. computeLineDistances: function () {
  8597. var d = 0;
  8598. var vertices = this.vertices;
  8599. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  8600. if ( i > 0 ) {
  8601. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  8602. }
  8603. this.lineDistances[ i ] = d;
  8604. }
  8605. },
  8606. computeBoundingBox: function () {
  8607. if ( this.boundingBox === null ) {
  8608. this.boundingBox = new Box3();
  8609. }
  8610. this.boundingBox.setFromPoints( this.vertices );
  8611. },
  8612. computeBoundingSphere: function () {
  8613. if ( this.boundingSphere === null ) {
  8614. this.boundingSphere = new Sphere();
  8615. }
  8616. this.boundingSphere.setFromPoints( this.vertices );
  8617. },
  8618. merge: function ( geometry, matrix, materialIndexOffset ) {
  8619. if ( (geometry && geometry.isGeometry) === false ) {
  8620. console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  8621. return;
  8622. }
  8623. var normalMatrix,
  8624. vertexOffset = this.vertices.length,
  8625. vertices1 = this.vertices,
  8626. vertices2 = geometry.vertices,
  8627. faces1 = this.faces,
  8628. faces2 = geometry.faces,
  8629. uvs1 = this.faceVertexUvs[ 0 ],
  8630. uvs2 = geometry.faceVertexUvs[ 0 ];
  8631. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  8632. if ( matrix !== undefined ) {
  8633. normalMatrix = new Matrix3().getNormalMatrix( matrix );
  8634. }
  8635. // vertices
  8636. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  8637. var vertex = vertices2[ i ];
  8638. var vertexCopy = vertex.clone();
  8639. if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
  8640. vertices1.push( vertexCopy );
  8641. }
  8642. // faces
  8643. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  8644. var face = faces2[ i ], faceCopy, normal, color,
  8645. faceVertexNormals = face.vertexNormals,
  8646. faceVertexColors = face.vertexColors;
  8647. faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  8648. faceCopy.normal.copy( face.normal );
  8649. if ( normalMatrix !== undefined ) {
  8650. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  8651. }
  8652. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  8653. normal = faceVertexNormals[ j ].clone();
  8654. if ( normalMatrix !== undefined ) {
  8655. normal.applyMatrix3( normalMatrix ).normalize();
  8656. }
  8657. faceCopy.vertexNormals.push( normal );
  8658. }
  8659. faceCopy.color.copy( face.color );
  8660. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  8661. color = faceVertexColors[ j ];
  8662. faceCopy.vertexColors.push( color.clone() );
  8663. }
  8664. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  8665. faces1.push( faceCopy );
  8666. }
  8667. // uvs
  8668. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  8669. var uv = uvs2[ i ], uvCopy = [];
  8670. if ( uv === undefined ) {
  8671. continue;
  8672. }
  8673. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  8674. uvCopy.push( uv[ j ].clone() );
  8675. }
  8676. uvs1.push( uvCopy );
  8677. }
  8678. },
  8679. mergeMesh: function ( mesh ) {
  8680. if ( (mesh && mesh.isMesh) === false ) {
  8681. console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
  8682. return;
  8683. }
  8684. mesh.matrixAutoUpdate && mesh.updateMatrix();
  8685. this.merge( mesh.geometry, mesh.matrix );
  8686. },
  8687. /*
  8688. * Checks for duplicate vertices with hashmap.
  8689. * Duplicated vertices are removed
  8690. * and faces' vertices are updated.
  8691. */
  8692. mergeVertices: function () {
  8693. var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  8694. var unique = [], changes = [];
  8695. var v, key;
  8696. var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
  8697. var precision = Math.pow( 10, precisionPoints );
  8698. var i, il, face;
  8699. var indices, j, jl;
  8700. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  8701. v = this.vertices[ i ];
  8702. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  8703. if ( verticesMap[ key ] === undefined ) {
  8704. verticesMap[ key ] = i;
  8705. unique.push( this.vertices[ i ] );
  8706. changes[ i ] = unique.length - 1;
  8707. } else {
  8708. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  8709. changes[ i ] = changes[ verticesMap[ key ] ];
  8710. }
  8711. }
  8712. // if faces are completely degenerate after merging vertices, we
  8713. // have to remove them from the geometry.
  8714. var faceIndicesToRemove = [];
  8715. for ( i = 0, il = this.faces.length; i < il; i ++ ) {
  8716. face = this.faces[ i ];
  8717. face.a = changes[ face.a ];
  8718. face.b = changes[ face.b ];
  8719. face.c = changes[ face.c ];
  8720. indices = [ face.a, face.b, face.c ];
  8721. var dupIndex = - 1;
  8722. // if any duplicate vertices are found in a Face3
  8723. // we have to remove the face as nothing can be saved
  8724. for ( var n = 0; n < 3; n ++ ) {
  8725. if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) {
  8726. dupIndex = n;
  8727. faceIndicesToRemove.push( i );
  8728. break;
  8729. }
  8730. }
  8731. }
  8732. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  8733. var idx = faceIndicesToRemove[ i ];
  8734. this.faces.splice( idx, 1 );
  8735. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  8736. this.faceVertexUvs[ j ].splice( idx, 1 );
  8737. }
  8738. }
  8739. // Use unique set of vertices
  8740. var diff = this.vertices.length - unique.length;
  8741. this.vertices = unique;
  8742. return diff;
  8743. },
  8744. sortFacesByMaterialIndex: function () {
  8745. var faces = this.faces;
  8746. var length = faces.length;
  8747. // tag faces
  8748. for ( var i = 0; i < length; i ++ ) {
  8749. faces[ i ]._id = i;
  8750. }
  8751. // sort faces
  8752. function materialIndexSort( a, b ) {
  8753. return a.materialIndex - b.materialIndex;
  8754. }
  8755. faces.sort( materialIndexSort );
  8756. // sort uvs
  8757. var uvs1 = this.faceVertexUvs[ 0 ];
  8758. var uvs2 = this.faceVertexUvs[ 1 ];
  8759. var newUvs1, newUvs2;
  8760. if ( uvs1 && uvs1.length === length ) newUvs1 = [];
  8761. if ( uvs2 && uvs2.length === length ) newUvs2 = [];
  8762. for ( var i = 0; i < length; i ++ ) {
  8763. var id = faces[ i ]._id;
  8764. if ( newUvs1 ) newUvs1.push( uvs1[ id ] );
  8765. if ( newUvs2 ) newUvs2.push( uvs2[ id ] );
  8766. }
  8767. if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1;
  8768. if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2;
  8769. },
  8770. toJSON: function () {
  8771. var data = {
  8772. metadata: {
  8773. version: 4.4,
  8774. type: 'Geometry',
  8775. generator: 'Geometry.toJSON'
  8776. }
  8777. };
  8778. // standard Geometry serialization
  8779. data.uuid = this.uuid;
  8780. data.type = this.type;
  8781. if ( this.name !== '' ) data.name = this.name;
  8782. if ( this.parameters !== undefined ) {
  8783. var parameters = this.parameters;
  8784. for ( var key in parameters ) {
  8785. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  8786. }
  8787. return data;
  8788. }
  8789. var vertices = [];
  8790. for ( var i = 0; i < this.vertices.length; i ++ ) {
  8791. var vertex = this.vertices[ i ];
  8792. vertices.push( vertex.x, vertex.y, vertex.z );
  8793. }
  8794. var faces = [];
  8795. var normals = [];
  8796. var normalsHash = {};
  8797. var colors = [];
  8798. var colorsHash = {};
  8799. var uvs = [];
  8800. var uvsHash = {};
  8801. for ( var i = 0; i < this.faces.length; i ++ ) {
  8802. var face = this.faces[ i ];
  8803. var hasMaterial = true;
  8804. var hasFaceUv = false; // deprecated
  8805. var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined;
  8806. var hasFaceNormal = face.normal.length() > 0;
  8807. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  8808. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  8809. var hasFaceVertexColor = face.vertexColors.length > 0;
  8810. var faceType = 0;
  8811. faceType = setBit( faceType, 0, 0 ); // isQuad
  8812. faceType = setBit( faceType, 1, hasMaterial );
  8813. faceType = setBit( faceType, 2, hasFaceUv );
  8814. faceType = setBit( faceType, 3, hasFaceVertexUv );
  8815. faceType = setBit( faceType, 4, hasFaceNormal );
  8816. faceType = setBit( faceType, 5, hasFaceVertexNormal );
  8817. faceType = setBit( faceType, 6, hasFaceColor );
  8818. faceType = setBit( faceType, 7, hasFaceVertexColor );
  8819. faces.push( faceType );
  8820. faces.push( face.a, face.b, face.c );
  8821. faces.push( face.materialIndex );
  8822. if ( hasFaceVertexUv ) {
  8823. var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ];
  8824. faces.push(
  8825. getUvIndex( faceVertexUvs[ 0 ] ),
  8826. getUvIndex( faceVertexUvs[ 1 ] ),
  8827. getUvIndex( faceVertexUvs[ 2 ] )
  8828. );
  8829. }
  8830. if ( hasFaceNormal ) {
  8831. faces.push( getNormalIndex( face.normal ) );
  8832. }
  8833. if ( hasFaceVertexNormal ) {
  8834. var vertexNormals = face.vertexNormals;
  8835. faces.push(
  8836. getNormalIndex( vertexNormals[ 0 ] ),
  8837. getNormalIndex( vertexNormals[ 1 ] ),
  8838. getNormalIndex( vertexNormals[ 2 ] )
  8839. );
  8840. }
  8841. if ( hasFaceColor ) {
  8842. faces.push( getColorIndex( face.color ) );
  8843. }
  8844. if ( hasFaceVertexColor ) {
  8845. var vertexColors = face.vertexColors;
  8846. faces.push(
  8847. getColorIndex( vertexColors[ 0 ] ),
  8848. getColorIndex( vertexColors[ 1 ] ),
  8849. getColorIndex( vertexColors[ 2 ] )
  8850. );
  8851. }
  8852. }
  8853. function setBit( value, position, enabled ) {
  8854. return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) );
  8855. }
  8856. function getNormalIndex( normal ) {
  8857. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  8858. if ( normalsHash[ hash ] !== undefined ) {
  8859. return normalsHash[ hash ];
  8860. }
  8861. normalsHash[ hash ] = normals.length / 3;
  8862. normals.push( normal.x, normal.y, normal.z );
  8863. return normalsHash[ hash ];
  8864. }
  8865. function getColorIndex( color ) {
  8866. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  8867. if ( colorsHash[ hash ] !== undefined ) {
  8868. return colorsHash[ hash ];
  8869. }
  8870. colorsHash[ hash ] = colors.length;
  8871. colors.push( color.getHex() );
  8872. return colorsHash[ hash ];
  8873. }
  8874. function getUvIndex( uv ) {
  8875. var hash = uv.x.toString() + uv.y.toString();
  8876. if ( uvsHash[ hash ] !== undefined ) {
  8877. return uvsHash[ hash ];
  8878. }
  8879. uvsHash[ hash ] = uvs.length / 2;
  8880. uvs.push( uv.x, uv.y );
  8881. return uvsHash[ hash ];
  8882. }
  8883. data.data = {};
  8884. data.data.vertices = vertices;
  8885. data.data.normals = normals;
  8886. if ( colors.length > 0 ) data.data.colors = colors;
  8887. if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility
  8888. data.data.faces = faces;
  8889. return data;
  8890. },
  8891. clone: function () {
  8892. /*
  8893. // Handle primitives
  8894. var parameters = this.parameters;
  8895. if ( parameters !== undefined ) {
  8896. var values = [];
  8897. for ( var key in parameters ) {
  8898. values.push( parameters[ key ] );
  8899. }
  8900. var geometry = Object.create( this.constructor.prototype );
  8901. this.constructor.apply( geometry, values );
  8902. return geometry;
  8903. }
  8904. return new this.constructor().copy( this );
  8905. */
  8906. return new Geometry().copy( this );
  8907. },
  8908. copy: function ( source ) {
  8909. this.vertices = [];
  8910. this.faces = [];
  8911. this.faceVertexUvs = [ [] ];
  8912. var vertices = source.vertices;
  8913. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  8914. this.vertices.push( vertices[ i ].clone() );
  8915. }
  8916. var faces = source.faces;
  8917. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  8918. this.faces.push( faces[ i ].clone() );
  8919. }
  8920. for ( var i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) {
  8921. var faceVertexUvs = source.faceVertexUvs[ i ];
  8922. if ( this.faceVertexUvs[ i ] === undefined ) {
  8923. this.faceVertexUvs[ i ] = [];
  8924. }
  8925. for ( var j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {
  8926. var uvs = faceVertexUvs[ j ], uvsCopy = [];
  8927. for ( var k = 0, kl = uvs.length; k < kl; k ++ ) {
  8928. var uv = uvs[ k ];
  8929. uvsCopy.push( uv.clone() );
  8930. }
  8931. this.faceVertexUvs[ i ].push( uvsCopy );
  8932. }
  8933. }
  8934. return this;
  8935. },
  8936. dispose: function () {
  8937. this.dispatchEvent( { type: 'dispose' } );
  8938. }
  8939. } );
  8940. var count$2 = 0;
  8941. function GeometryIdCount() { return count$2++; };
  8942. /**
  8943. * @author mrdoob / http://mrdoob.com/
  8944. */
  8945. function DirectGeometry() {
  8946. Object.defineProperty( this, 'id', { value: GeometryIdCount() } );
  8947. this.uuid = exports.Math.generateUUID();
  8948. this.name = '';
  8949. this.type = 'DirectGeometry';
  8950. this.indices = [];
  8951. this.vertices = [];
  8952. this.normals = [];
  8953. this.colors = [];
  8954. this.uvs = [];
  8955. this.uvs2 = [];
  8956. this.groups = [];
  8957. this.morphTargets = {};
  8958. this.skinWeights = [];
  8959. this.skinIndices = [];
  8960. // this.lineDistances = [];
  8961. this.boundingBox = null;
  8962. this.boundingSphere = null;
  8963. // update flags
  8964. this.verticesNeedUpdate = false;
  8965. this.normalsNeedUpdate = false;
  8966. this.colorsNeedUpdate = false;
  8967. this.uvsNeedUpdate = false;
  8968. this.groupsNeedUpdate = false;
  8969. }
  8970. Object.assign( DirectGeometry.prototype, EventDispatcher.prototype, {
  8971. computeBoundingBox: Geometry.prototype.computeBoundingBox,
  8972. computeBoundingSphere: Geometry.prototype.computeBoundingSphere,
  8973. computeFaceNormals: function () {
  8974. console.warn( 'THREE.DirectGeometry: computeFaceNormals() is not a method of this type of geometry.' );
  8975. },
  8976. computeVertexNormals: function () {
  8977. console.warn( 'THREE.DirectGeometry: computeVertexNormals() is not a method of this type of geometry.' );
  8978. },
  8979. computeGroups: function ( geometry ) {
  8980. var group;
  8981. var groups = [];
  8982. var materialIndex;
  8983. var faces = geometry.faces;
  8984. for ( var i = 0; i < faces.length; i ++ ) {
  8985. var face = faces[ i ];
  8986. // materials
  8987. if ( face.materialIndex !== materialIndex ) {
  8988. materialIndex = face.materialIndex;
  8989. if ( group !== undefined ) {
  8990. group.count = ( i * 3 ) - group.start;
  8991. groups.push( group );
  8992. }
  8993. group = {
  8994. start: i * 3,
  8995. materialIndex: materialIndex
  8996. };
  8997. }
  8998. }
  8999. if ( group !== undefined ) {
  9000. group.count = ( i * 3 ) - group.start;
  9001. groups.push( group );
  9002. }
  9003. this.groups = groups;
  9004. },
  9005. fromGeometry: function ( geometry ) {
  9006. var faces = geometry.faces;
  9007. var vertices = geometry.vertices;
  9008. var faceVertexUvs = geometry.faceVertexUvs;
  9009. var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0;
  9010. var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0;
  9011. // morphs
  9012. var morphTargets = geometry.morphTargets;
  9013. var morphTargetsLength = morphTargets.length;
  9014. var morphTargetsPosition;
  9015. if ( morphTargetsLength > 0 ) {
  9016. morphTargetsPosition = [];
  9017. for ( var i = 0; i < morphTargetsLength; i ++ ) {
  9018. morphTargetsPosition[ i ] = [];
  9019. }
  9020. this.morphTargets.position = morphTargetsPosition;
  9021. }
  9022. var morphNormals = geometry.morphNormals;
  9023. var morphNormalsLength = morphNormals.length;
  9024. var morphTargetsNormal;
  9025. if ( morphNormalsLength > 0 ) {
  9026. morphTargetsNormal = [];
  9027. for ( var i = 0; i < morphNormalsLength; i ++ ) {
  9028. morphTargetsNormal[ i ] = [];
  9029. }
  9030. this.morphTargets.normal = morphTargetsNormal;
  9031. }
  9032. // skins
  9033. var skinIndices = geometry.skinIndices;
  9034. var skinWeights = geometry.skinWeights;
  9035. var hasSkinIndices = skinIndices.length === vertices.length;
  9036. var hasSkinWeights = skinWeights.length === vertices.length;
  9037. //
  9038. for ( var i = 0; i < faces.length; i ++ ) {
  9039. var face = faces[ i ];
  9040. this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] );
  9041. var vertexNormals = face.vertexNormals;
  9042. if ( vertexNormals.length === 3 ) {
  9043. this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] );
  9044. } else {
  9045. var normal = face.normal;
  9046. this.normals.push( normal, normal, normal );
  9047. }
  9048. var vertexColors = face.vertexColors;
  9049. if ( vertexColors.length === 3 ) {
  9050. this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] );
  9051. } else {
  9052. var color = face.color;
  9053. this.colors.push( color, color, color );
  9054. }
  9055. if ( hasFaceVertexUv === true ) {
  9056. var vertexUvs = faceVertexUvs[ 0 ][ i ];
  9057. if ( vertexUvs !== undefined ) {
  9058. this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  9059. } else {
  9060. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i );
  9061. this.uvs.push( new Vector2(), new Vector2(), new Vector2() );
  9062. }
  9063. }
  9064. if ( hasFaceVertexUv2 === true ) {
  9065. var vertexUvs = faceVertexUvs[ 1 ][ i ];
  9066. if ( vertexUvs !== undefined ) {
  9067. this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  9068. } else {
  9069. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i );
  9070. this.uvs2.push( new Vector2(), new Vector2(), new Vector2() );
  9071. }
  9072. }
  9073. // morphs
  9074. for ( var j = 0; j < morphTargetsLength; j ++ ) {
  9075. var morphTarget = morphTargets[ j ].vertices;
  9076. morphTargetsPosition[ j ].push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] );
  9077. }
  9078. for ( var j = 0; j < morphNormalsLength; j ++ ) {
  9079. var morphNormal = morphNormals[ j ].vertexNormals[ i ];
  9080. morphTargetsNormal[ j ].push( morphNormal.a, morphNormal.b, morphNormal.c );
  9081. }
  9082. // skins
  9083. if ( hasSkinIndices ) {
  9084. this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] );
  9085. }
  9086. if ( hasSkinWeights ) {
  9087. this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] );
  9088. }
  9089. }
  9090. this.computeGroups( geometry );
  9091. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  9092. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  9093. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  9094. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  9095. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  9096. return this;
  9097. },
  9098. dispose: function () {
  9099. this.dispatchEvent( { type: 'dispose' } );
  9100. }
  9101. } );
  9102. /**
  9103. * @author alteredq / http://alteredqualia.com/
  9104. * @author mrdoob / http://mrdoob.com/
  9105. */
  9106. function BufferGeometry() {
  9107. Object.defineProperty( this, 'id', { value: GeometryIdCount() } );
  9108. this.uuid = exports.Math.generateUUID();
  9109. this.name = '';
  9110. this.type = 'BufferGeometry';
  9111. this.index = null;
  9112. this.attributes = {};
  9113. this.morphAttributes = {};
  9114. this.groups = [];
  9115. this.boundingBox = null;
  9116. this.boundingSphere = null;
  9117. this.drawRange = { start: 0, count: Infinity };
  9118. }
  9119. Object.assign( BufferGeometry.prototype, EventDispatcher.prototype, {
  9120. isBufferGeometry: true,
  9121. getIndex: function () {
  9122. return this.index;
  9123. },
  9124. setIndex: function ( index ) {
  9125. this.index = index;
  9126. },
  9127. addAttribute: function ( name, attribute ) {
  9128. if ( (attribute && attribute.isBufferAttribute) === false && (attribute && attribute.isInterleavedBufferAttribute) === false ) {
  9129. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  9130. this.addAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  9131. return;
  9132. }
  9133. if ( name === 'index' ) {
  9134. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  9135. this.setIndex( attribute );
  9136. return;
  9137. }
  9138. this.attributes[ name ] = attribute;
  9139. return this;
  9140. },
  9141. getAttribute: function ( name ) {
  9142. return this.attributes[ name ];
  9143. },
  9144. removeAttribute: function ( name ) {
  9145. delete this.attributes[ name ];
  9146. return this;
  9147. },
  9148. addGroup: function ( start, count, materialIndex ) {
  9149. this.groups.push( {
  9150. start: start,
  9151. count: count,
  9152. materialIndex: materialIndex !== undefined ? materialIndex : 0
  9153. } );
  9154. },
  9155. clearGroups: function () {
  9156. this.groups = [];
  9157. },
  9158. setDrawRange: function ( start, count ) {
  9159. this.drawRange.start = start;
  9160. this.drawRange.count = count;
  9161. },
  9162. applyMatrix: function ( matrix ) {
  9163. var position = this.attributes.position;
  9164. if ( position !== undefined ) {
  9165. matrix.applyToVector3Array( position.array );
  9166. position.needsUpdate = true;
  9167. }
  9168. var normal = this.attributes.normal;
  9169. if ( normal !== undefined ) {
  9170. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  9171. normalMatrix.applyToVector3Array( normal.array );
  9172. normal.needsUpdate = true;
  9173. }
  9174. if ( this.boundingBox !== null ) {
  9175. this.computeBoundingBox();
  9176. }
  9177. if ( this.boundingSphere !== null ) {
  9178. this.computeBoundingSphere();
  9179. }
  9180. return this;
  9181. },
  9182. rotateX: function () {
  9183. // rotate geometry around world x-axis
  9184. var m1;
  9185. return function rotateX( angle ) {
  9186. if ( m1 === undefined ) m1 = new Matrix4();
  9187. m1.makeRotationX( angle );
  9188. this.applyMatrix( m1 );
  9189. return this;
  9190. };
  9191. }(),
  9192. rotateY: function () {
  9193. // rotate geometry around world y-axis
  9194. var m1;
  9195. return function rotateY( angle ) {
  9196. if ( m1 === undefined ) m1 = new Matrix4();
  9197. m1.makeRotationY( angle );
  9198. this.applyMatrix( m1 );
  9199. return this;
  9200. };
  9201. }(),
  9202. rotateZ: function () {
  9203. // rotate geometry around world z-axis
  9204. var m1;
  9205. return function rotateZ( angle ) {
  9206. if ( m1 === undefined ) m1 = new Matrix4();
  9207. m1.makeRotationZ( angle );
  9208. this.applyMatrix( m1 );
  9209. return this;
  9210. };
  9211. }(),
  9212. translate: function () {
  9213. // translate geometry
  9214. var m1;
  9215. return function translate( x, y, z ) {
  9216. if ( m1 === undefined ) m1 = new Matrix4();
  9217. m1.makeTranslation( x, y, z );
  9218. this.applyMatrix( m1 );
  9219. return this;
  9220. };
  9221. }(),
  9222. scale: function () {
  9223. // scale geometry
  9224. var m1;
  9225. return function scale( x, y, z ) {
  9226. if ( m1 === undefined ) m1 = new Matrix4();
  9227. m1.makeScale( x, y, z );
  9228. this.applyMatrix( m1 );
  9229. return this;
  9230. };
  9231. }(),
  9232. lookAt: function () {
  9233. var obj;
  9234. return function lookAt( vector ) {
  9235. if ( obj === undefined ) obj = new Object3D();
  9236. obj.lookAt( vector );
  9237. obj.updateMatrix();
  9238. this.applyMatrix( obj.matrix );
  9239. };
  9240. }(),
  9241. center: function () {
  9242. this.computeBoundingBox();
  9243. var offset = this.boundingBox.center().negate();
  9244. this.translate( offset.x, offset.y, offset.z );
  9245. return offset;
  9246. },
  9247. setFromObject: function ( object ) {
  9248. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  9249. var geometry = object.geometry;
  9250. if ( (object && object.isPoints) || (object && object.isLine) ) {
  9251. var positions = new Float32Attribute( geometry.vertices.length * 3, 3 );
  9252. var colors = new Float32Attribute( geometry.colors.length * 3, 3 );
  9253. this.addAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) );
  9254. this.addAttribute( 'color', colors.copyColorsArray( geometry.colors ) );
  9255. if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) {
  9256. var lineDistances = new Float32Attribute( geometry.lineDistances.length, 1 );
  9257. this.addAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) );
  9258. }
  9259. if ( geometry.boundingSphere !== null ) {
  9260. this.boundingSphere = geometry.boundingSphere.clone();
  9261. }
  9262. if ( geometry.boundingBox !== null ) {
  9263. this.boundingBox = geometry.boundingBox.clone();
  9264. }
  9265. } else if ( (object && object.isMesh) ) {
  9266. if ( (geometry && geometry.isGeometry) ) {
  9267. this.fromGeometry( geometry );
  9268. }
  9269. }
  9270. return this;
  9271. },
  9272. updateFromObject: function ( object ) {
  9273. var geometry = object.geometry;
  9274. if ( (object && object.isMesh) ) {
  9275. var direct = geometry.__directGeometry;
  9276. if ( direct === undefined || geometry.elementsNeedUpdate === true ) {
  9277. return this.fromGeometry( geometry );
  9278. }
  9279. direct.verticesNeedUpdate = geometry.verticesNeedUpdate || geometry.elementsNeedUpdate;
  9280. direct.normalsNeedUpdate = geometry.normalsNeedUpdate || geometry.elementsNeedUpdate;
  9281. direct.colorsNeedUpdate = geometry.colorsNeedUpdate || geometry.elementsNeedUpdate;
  9282. direct.uvsNeedUpdate = geometry.uvsNeedUpdate || geometry.elementsNeedUpdate;
  9283. direct.groupsNeedUpdate = geometry.groupsNeedUpdate || geometry.elementsNeedUpdate;
  9284. geometry.elementsNeedUpdate = false;
  9285. geometry.verticesNeedUpdate = false;
  9286. geometry.normalsNeedUpdate = false;
  9287. geometry.colorsNeedUpdate = false;
  9288. geometry.uvsNeedUpdate = false;
  9289. geometry.groupsNeedUpdate = false;
  9290. geometry = direct;
  9291. }
  9292. var attribute;
  9293. if ( geometry.verticesNeedUpdate === true ) {
  9294. attribute = this.attributes.position;
  9295. if ( attribute !== undefined ) {
  9296. attribute.copyVector3sArray( geometry.vertices );
  9297. attribute.needsUpdate = true;
  9298. }
  9299. geometry.verticesNeedUpdate = false;
  9300. }
  9301. if ( geometry.normalsNeedUpdate === true ) {
  9302. attribute = this.attributes.normal;
  9303. if ( attribute !== undefined ) {
  9304. attribute.copyVector3sArray( geometry.normals );
  9305. attribute.needsUpdate = true;
  9306. }
  9307. geometry.normalsNeedUpdate = false;
  9308. }
  9309. if ( geometry.colorsNeedUpdate === true ) {
  9310. attribute = this.attributes.color;
  9311. if ( attribute !== undefined ) {
  9312. attribute.copyColorsArray( geometry.colors );
  9313. attribute.needsUpdate = true;
  9314. }
  9315. geometry.colorsNeedUpdate = false;
  9316. }
  9317. if ( geometry.uvsNeedUpdate ) {
  9318. attribute = this.attributes.uv;
  9319. if ( attribute !== undefined ) {
  9320. attribute.copyVector2sArray( geometry.uvs );
  9321. attribute.needsUpdate = true;
  9322. }
  9323. geometry.uvsNeedUpdate = false;
  9324. }
  9325. if ( geometry.lineDistancesNeedUpdate ) {
  9326. attribute = this.attributes.lineDistance;
  9327. if ( attribute !== undefined ) {
  9328. attribute.copyArray( geometry.lineDistances );
  9329. attribute.needsUpdate = true;
  9330. }
  9331. geometry.lineDistancesNeedUpdate = false;
  9332. }
  9333. if ( geometry.groupsNeedUpdate ) {
  9334. geometry.computeGroups( object.geometry );
  9335. this.groups = geometry.groups;
  9336. geometry.groupsNeedUpdate = false;
  9337. }
  9338. return this;
  9339. },
  9340. fromGeometry: function ( geometry ) {
  9341. geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry );
  9342. return this.fromDirectGeometry( geometry.__directGeometry );
  9343. },
  9344. fromDirectGeometry: function ( geometry ) {
  9345. var positions = new Float32Array( geometry.vertices.length * 3 );
  9346. this.addAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) );
  9347. if ( geometry.normals.length > 0 ) {
  9348. var normals = new Float32Array( geometry.normals.length * 3 );
  9349. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) );
  9350. }
  9351. if ( geometry.colors.length > 0 ) {
  9352. var colors = new Float32Array( geometry.colors.length * 3 );
  9353. this.addAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) );
  9354. }
  9355. if ( geometry.uvs.length > 0 ) {
  9356. var uvs = new Float32Array( geometry.uvs.length * 2 );
  9357. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) );
  9358. }
  9359. if ( geometry.uvs2.length > 0 ) {
  9360. var uvs2 = new Float32Array( geometry.uvs2.length * 2 );
  9361. this.addAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) );
  9362. }
  9363. if ( geometry.indices.length > 0 ) {
  9364. var TypeArray = geometry.vertices.length > 65535 ? Uint32Array : Uint16Array;
  9365. var indices = new TypeArray( geometry.indices.length * 3 );
  9366. this.setIndex( new BufferAttribute( indices, 1 ).copyIndicesArray( geometry.indices ) );
  9367. }
  9368. // groups
  9369. this.groups = geometry.groups;
  9370. // morphs
  9371. for ( var name in geometry.morphTargets ) {
  9372. var array = [];
  9373. var morphTargets = geometry.morphTargets[ name ];
  9374. for ( var i = 0, l = morphTargets.length; i < l; i ++ ) {
  9375. var morphTarget = morphTargets[ i ];
  9376. var attribute = new Float32Attribute( morphTarget.length * 3, 3 );
  9377. array.push( attribute.copyVector3sArray( morphTarget ) );
  9378. }
  9379. this.morphAttributes[ name ] = array;
  9380. }
  9381. // skinning
  9382. if ( geometry.skinIndices.length > 0 ) {
  9383. var skinIndices = new Float32Attribute( geometry.skinIndices.length * 4, 4 );
  9384. this.addAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) );
  9385. }
  9386. if ( geometry.skinWeights.length > 0 ) {
  9387. var skinWeights = new Float32Attribute( geometry.skinWeights.length * 4, 4 );
  9388. this.addAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) );
  9389. }
  9390. //
  9391. if ( geometry.boundingSphere !== null ) {
  9392. this.boundingSphere = geometry.boundingSphere.clone();
  9393. }
  9394. if ( geometry.boundingBox !== null ) {
  9395. this.boundingBox = geometry.boundingBox.clone();
  9396. }
  9397. return this;
  9398. },
  9399. computeBoundingBox: function () {
  9400. if ( this.boundingBox === null ) {
  9401. this.boundingBox = new Box3();
  9402. }
  9403. var positions = this.attributes.position.array;
  9404. if ( positions !== undefined ) {
  9405. this.boundingBox.setFromArray( positions );
  9406. } else {
  9407. this.boundingBox.makeEmpty();
  9408. }
  9409. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  9410. console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  9411. }
  9412. },
  9413. computeBoundingSphere: function () {
  9414. var box = new Box3();
  9415. var vector = new Vector3();
  9416. return function computeBoundingSphere() {
  9417. if ( this.boundingSphere === null ) {
  9418. this.boundingSphere = new Sphere();
  9419. }
  9420. var positions = this.attributes.position;
  9421. if ( positions ) {
  9422. var array = positions.array;
  9423. var center = this.boundingSphere.center;
  9424. box.setFromArray( array );
  9425. box.center( center );
  9426. // hoping to find a boundingSphere with a radius smaller than the
  9427. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  9428. var maxRadiusSq = 0;
  9429. for ( var i = 0, il = array.length; i < il; i += 3 ) {
  9430. vector.fromArray( array, i );
  9431. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  9432. }
  9433. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  9434. if ( isNaN( this.boundingSphere.radius ) ) {
  9435. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  9436. }
  9437. }
  9438. };
  9439. }(),
  9440. computeFaceNormals: function () {
  9441. // backwards compatibility
  9442. },
  9443. computeVertexNormals: function () {
  9444. var index = this.index;
  9445. var attributes = this.attributes;
  9446. var groups = this.groups;
  9447. if ( attributes.position ) {
  9448. var positions = attributes.position.array;
  9449. if ( attributes.normal === undefined ) {
  9450. this.addAttribute( 'normal', new BufferAttribute( new Float32Array( positions.length ), 3 ) );
  9451. } else {
  9452. // reset existing normals to zero
  9453. var array = attributes.normal.array;
  9454. for ( var i = 0, il = array.length; i < il; i ++ ) {
  9455. array[ i ] = 0;
  9456. }
  9457. }
  9458. var normals = attributes.normal.array;
  9459. var vA, vB, vC,
  9460. pA = new Vector3(),
  9461. pB = new Vector3(),
  9462. pC = new Vector3(),
  9463. cb = new Vector3(),
  9464. ab = new Vector3();
  9465. // indexed elements
  9466. if ( index ) {
  9467. var indices = index.array;
  9468. if ( groups.length === 0 ) {
  9469. this.addGroup( 0, indices.length );
  9470. }
  9471. for ( var j = 0, jl = groups.length; j < jl; ++ j ) {
  9472. var group = groups[ j ];
  9473. var start = group.start;
  9474. var count = group.count;
  9475. for ( var i = start, il = start + count; i < il; i += 3 ) {
  9476. vA = indices[ i + 0 ] * 3;
  9477. vB = indices[ i + 1 ] * 3;
  9478. vC = indices[ i + 2 ] * 3;
  9479. pA.fromArray( positions, vA );
  9480. pB.fromArray( positions, vB );
  9481. pC.fromArray( positions, vC );
  9482. cb.subVectors( pC, pB );
  9483. ab.subVectors( pA, pB );
  9484. cb.cross( ab );
  9485. normals[ vA ] += cb.x;
  9486. normals[ vA + 1 ] += cb.y;
  9487. normals[ vA + 2 ] += cb.z;
  9488. normals[ vB ] += cb.x;
  9489. normals[ vB + 1 ] += cb.y;
  9490. normals[ vB + 2 ] += cb.z;
  9491. normals[ vC ] += cb.x;
  9492. normals[ vC + 1 ] += cb.y;
  9493. normals[ vC + 2 ] += cb.z;
  9494. }
  9495. }
  9496. } else {
  9497. // non-indexed elements (unconnected triangle soup)
  9498. for ( var i = 0, il = positions.length; i < il; i += 9 ) {
  9499. pA.fromArray( positions, i );
  9500. pB.fromArray( positions, i + 3 );
  9501. pC.fromArray( positions, i + 6 );
  9502. cb.subVectors( pC, pB );
  9503. ab.subVectors( pA, pB );
  9504. cb.cross( ab );
  9505. normals[ i ] = cb.x;
  9506. normals[ i + 1 ] = cb.y;
  9507. normals[ i + 2 ] = cb.z;
  9508. normals[ i + 3 ] = cb.x;
  9509. normals[ i + 4 ] = cb.y;
  9510. normals[ i + 5 ] = cb.z;
  9511. normals[ i + 6 ] = cb.x;
  9512. normals[ i + 7 ] = cb.y;
  9513. normals[ i + 8 ] = cb.z;
  9514. }
  9515. }
  9516. this.normalizeNormals();
  9517. attributes.normal.needsUpdate = true;
  9518. }
  9519. },
  9520. merge: function ( geometry, offset ) {
  9521. if ( (geometry && geometry.isBufferGeometry) === false ) {
  9522. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  9523. return;
  9524. }
  9525. if ( offset === undefined ) offset = 0;
  9526. var attributes = this.attributes;
  9527. for ( var key in attributes ) {
  9528. if ( geometry.attributes[ key ] === undefined ) continue;
  9529. var attribute1 = attributes[ key ];
  9530. var attributeArray1 = attribute1.array;
  9531. var attribute2 = geometry.attributes[ key ];
  9532. var attributeArray2 = attribute2.array;
  9533. var attributeSize = attribute2.itemSize;
  9534. for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) {
  9535. attributeArray1[ j ] = attributeArray2[ i ];
  9536. }
  9537. }
  9538. return this;
  9539. },
  9540. normalizeNormals: function () {
  9541. var normals = this.attributes.normal.array;
  9542. var x, y, z, n;
  9543. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  9544. x = normals[ i ];
  9545. y = normals[ i + 1 ];
  9546. z = normals[ i + 2 ];
  9547. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  9548. normals[ i ] *= n;
  9549. normals[ i + 1 ] *= n;
  9550. normals[ i + 2 ] *= n;
  9551. }
  9552. },
  9553. toNonIndexed: function () {
  9554. if ( this.index === null ) {
  9555. console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' );
  9556. return this;
  9557. }
  9558. var geometry2 = new BufferGeometry();
  9559. var indices = this.index.array;
  9560. var attributes = this.attributes;
  9561. for ( var name in attributes ) {
  9562. var attribute = attributes[ name ];
  9563. var array = attribute.array;
  9564. var itemSize = attribute.itemSize;
  9565. var array2 = new array.constructor( indices.length * itemSize );
  9566. var index = 0, index2 = 0;
  9567. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  9568. index = indices[ i ] * itemSize;
  9569. for ( var j = 0; j < itemSize; j ++ ) {
  9570. array2[ index2 ++ ] = array[ index ++ ];
  9571. }
  9572. }
  9573. geometry2.addAttribute( name, new BufferAttribute( array2, itemSize ) );
  9574. }
  9575. return geometry2;
  9576. },
  9577. toJSON: function () {
  9578. var data = {
  9579. metadata: {
  9580. version: 4.4,
  9581. type: 'BufferGeometry',
  9582. generator: 'BufferGeometry.toJSON'
  9583. }
  9584. };
  9585. // standard BufferGeometry serialization
  9586. data.uuid = this.uuid;
  9587. data.type = this.type;
  9588. if ( this.name !== '' ) data.name = this.name;
  9589. if ( this.parameters !== undefined ) {
  9590. var parameters = this.parameters;
  9591. for ( var key in parameters ) {
  9592. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  9593. }
  9594. return data;
  9595. }
  9596. data.data = { attributes: {} };
  9597. var index = this.index;
  9598. if ( index !== null ) {
  9599. var array = Array.prototype.slice.call( index.array );
  9600. data.data.index = {
  9601. type: index.array.constructor.name,
  9602. array: array
  9603. };
  9604. }
  9605. var attributes = this.attributes;
  9606. for ( var key in attributes ) {
  9607. var attribute = attributes[ key ];
  9608. var array = Array.prototype.slice.call( attribute.array );
  9609. data.data.attributes[ key ] = {
  9610. itemSize: attribute.itemSize,
  9611. type: attribute.array.constructor.name,
  9612. array: array,
  9613. normalized: attribute.normalized
  9614. };
  9615. }
  9616. var groups = this.groups;
  9617. if ( groups.length > 0 ) {
  9618. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  9619. }
  9620. var boundingSphere = this.boundingSphere;
  9621. if ( boundingSphere !== null ) {
  9622. data.data.boundingSphere = {
  9623. center: boundingSphere.center.toArray(),
  9624. radius: boundingSphere.radius
  9625. };
  9626. }
  9627. return data;
  9628. },
  9629. clone: function () {
  9630. /*
  9631. // Handle primitives
  9632. var parameters = this.parameters;
  9633. if ( parameters !== undefined ) {
  9634. var values = [];
  9635. for ( var key in parameters ) {
  9636. values.push( parameters[ key ] );
  9637. }
  9638. var geometry = Object.create( this.constructor.prototype );
  9639. this.constructor.apply( geometry, values );
  9640. return geometry;
  9641. }
  9642. return new this.constructor().copy( this );
  9643. */
  9644. return new BufferGeometry().copy( this );
  9645. },
  9646. copy: function ( source ) {
  9647. var index = source.index;
  9648. if ( index !== null ) {
  9649. this.setIndex( index.clone() );
  9650. }
  9651. var attributes = source.attributes;
  9652. for ( var name in attributes ) {
  9653. var attribute = attributes[ name ];
  9654. this.addAttribute( name, attribute.clone() );
  9655. }
  9656. var groups = source.groups;
  9657. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  9658. var group = groups[ i ];
  9659. this.addGroup( group.start, group.count, group.materialIndex );
  9660. }
  9661. return this;
  9662. },
  9663. dispose: function () {
  9664. this.dispatchEvent( { type: 'dispose' } );
  9665. }
  9666. } );
  9667. BufferGeometry.MaxIndex = 65535;
  9668. /**
  9669. * @author mrdoob / http://mrdoob.com/
  9670. */
  9671. function WebGLGeometries( gl, properties, info ) {
  9672. var geometries = {};
  9673. function get( object ) {
  9674. var geometry = object.geometry;
  9675. if ( geometries[ geometry.id ] !== undefined ) {
  9676. return geometries[ geometry.id ];
  9677. }
  9678. geometry.addEventListener( 'dispose', onGeometryDispose );
  9679. var buffergeometry;
  9680. if ( (geometry && geometry.isBufferGeometry) ) {
  9681. buffergeometry = geometry;
  9682. } else if ( (geometry && geometry.isGeometry) ) {
  9683. if ( geometry._bufferGeometry === undefined ) {
  9684. geometry._bufferGeometry = new BufferGeometry().setFromObject( object );
  9685. }
  9686. buffergeometry = geometry._bufferGeometry;
  9687. }
  9688. geometries[ geometry.id ] = buffergeometry;
  9689. info.memory.geometries ++;
  9690. return buffergeometry;
  9691. }
  9692. function onGeometryDispose( event ) {
  9693. var geometry = event.target;
  9694. var buffergeometry = geometries[ geometry.id ];
  9695. if ( buffergeometry.index !== null ) {
  9696. deleteAttribute( buffergeometry.index );
  9697. }
  9698. deleteAttributes( buffergeometry.attributes );
  9699. geometry.removeEventListener( 'dispose', onGeometryDispose );
  9700. delete geometries[ geometry.id ];
  9701. // TODO
  9702. var property = properties.get( geometry );
  9703. if ( property.wireframe ) {
  9704. deleteAttribute( property.wireframe );
  9705. }
  9706. properties.delete( geometry );
  9707. var bufferproperty = properties.get( buffergeometry );
  9708. if ( bufferproperty.wireframe ) {
  9709. deleteAttribute( bufferproperty.wireframe );
  9710. }
  9711. properties.delete( buffergeometry );
  9712. //
  9713. info.memory.geometries --;
  9714. }
  9715. function getAttributeBuffer( attribute ) {
  9716. if ( (attribute && attribute.isInterleavedBufferAttribute) ) {
  9717. return properties.get( attribute.data ).__webglBuffer;
  9718. }
  9719. return properties.get( attribute ).__webglBuffer;
  9720. }
  9721. function deleteAttribute( attribute ) {
  9722. var buffer = getAttributeBuffer( attribute );
  9723. if ( buffer !== undefined ) {
  9724. gl.deleteBuffer( buffer );
  9725. removeAttributeBuffer( attribute );
  9726. }
  9727. }
  9728. function deleteAttributes( attributes ) {
  9729. for ( var name in attributes ) {
  9730. deleteAttribute( attributes[ name ] );
  9731. }
  9732. }
  9733. function removeAttributeBuffer( attribute ) {
  9734. if ( (attribute && attribute.isInterleavedBufferAttribute) ) {
  9735. properties.delete( attribute.data );
  9736. } else {
  9737. properties.delete( attribute );
  9738. }
  9739. }
  9740. this.get = get;
  9741. }
  9742. /**
  9743. * @author mrdoob / http://mrdoob.com/
  9744. */
  9745. function WebGLObjects( gl, properties, info ) {
  9746. var geometries = new WebGLGeometries( gl, properties, info );
  9747. //
  9748. function update( object ) {
  9749. // TODO: Avoid updating twice (when using shadowMap). Maybe add frame counter.
  9750. var geometry = geometries.get( object );
  9751. if ( (object.geometry && object.geometry.isGeometry) ) {
  9752. geometry.updateFromObject( object );
  9753. }
  9754. var index = geometry.index;
  9755. var attributes = geometry.attributes;
  9756. if ( index !== null ) {
  9757. updateAttribute( index, gl.ELEMENT_ARRAY_BUFFER );
  9758. }
  9759. for ( var name in attributes ) {
  9760. updateAttribute( attributes[ name ], gl.ARRAY_BUFFER );
  9761. }
  9762. // morph targets
  9763. var morphAttributes = geometry.morphAttributes;
  9764. for ( var name in morphAttributes ) {
  9765. var array = morphAttributes[ name ];
  9766. for ( var i = 0, l = array.length; i < l; i ++ ) {
  9767. updateAttribute( array[ i ], gl.ARRAY_BUFFER );
  9768. }
  9769. }
  9770. return geometry;
  9771. }
  9772. function updateAttribute( attribute, bufferType ) {
  9773. var data = ( (attribute && attribute.isInterleavedBufferAttribute) ) ? attribute.data : attribute;
  9774. var attributeProperties = properties.get( data );
  9775. if ( attributeProperties.__webglBuffer === undefined ) {
  9776. createBuffer( attributeProperties, data, bufferType );
  9777. } else if ( attributeProperties.version !== data.version ) {
  9778. updateBuffer( attributeProperties, data, bufferType );
  9779. }
  9780. }
  9781. function createBuffer( attributeProperties, data, bufferType ) {
  9782. attributeProperties.__webglBuffer = gl.createBuffer();
  9783. gl.bindBuffer( bufferType, attributeProperties.__webglBuffer );
  9784. var usage = data.dynamic ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW;
  9785. gl.bufferData( bufferType, data.array, usage );
  9786. attributeProperties.version = data.version;
  9787. }
  9788. function updateBuffer( attributeProperties, data, bufferType ) {
  9789. gl.bindBuffer( bufferType, attributeProperties.__webglBuffer );
  9790. if ( data.dynamic === false || data.updateRange.count === - 1 ) {
  9791. // Not using update ranges
  9792. gl.bufferSubData( bufferType, 0, data.array );
  9793. } else if ( data.updateRange.count === 0 ) {
  9794. 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.' );
  9795. } else {
  9796. gl.bufferSubData( bufferType, data.updateRange.offset * data.array.BYTES_PER_ELEMENT,
  9797. data.array.subarray( data.updateRange.offset, data.updateRange.offset + data.updateRange.count ) );
  9798. data.updateRange.count = 0; // reset range
  9799. }
  9800. attributeProperties.version = data.version;
  9801. }
  9802. function getAttributeBuffer( attribute ) {
  9803. if ( (attribute && attribute.isInterleavedBufferAttribute) ) {
  9804. return properties.get( attribute.data ).__webglBuffer;
  9805. }
  9806. return properties.get( attribute ).__webglBuffer;
  9807. }
  9808. function getWireframeAttribute( geometry ) {
  9809. var property = properties.get( geometry );
  9810. if ( property.wireframe !== undefined ) {
  9811. return property.wireframe;
  9812. }
  9813. var indices = [];
  9814. var index = geometry.index;
  9815. var attributes = geometry.attributes;
  9816. var position = attributes.position;
  9817. // console.time( 'wireframe' );
  9818. if ( index !== null ) {
  9819. var edges = {};
  9820. var array = index.array;
  9821. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  9822. var a = array[ i + 0 ];
  9823. var b = array[ i + 1 ];
  9824. var c = array[ i + 2 ];
  9825. if ( checkEdge( edges, a, b ) ) indices.push( a, b );
  9826. if ( checkEdge( edges, b, c ) ) indices.push( b, c );
  9827. if ( checkEdge( edges, c, a ) ) indices.push( c, a );
  9828. }
  9829. } else {
  9830. var array = attributes.position.array;
  9831. for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  9832. var a = i + 0;
  9833. var b = i + 1;
  9834. var c = i + 2;
  9835. indices.push( a, b, b, c, c, a );
  9836. }
  9837. }
  9838. // console.timeEnd( 'wireframe' );
  9839. var TypeArray = position.count > 65535 ? Uint32Array : Uint16Array;
  9840. var attribute = new BufferAttribute( new TypeArray( indices ), 1 );
  9841. updateAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  9842. property.wireframe = attribute;
  9843. return attribute;
  9844. }
  9845. function checkEdge( edges, a, b ) {
  9846. if ( a > b ) {
  9847. var tmp = a;
  9848. a = b;
  9849. b = tmp;
  9850. }
  9851. var list = edges[ a ];
  9852. if ( list === undefined ) {
  9853. edges[ a ] = [ b ];
  9854. return true;
  9855. } else if ( list.indexOf( b ) === -1 ) {
  9856. list.push( b );
  9857. return true;
  9858. }
  9859. return false;
  9860. }
  9861. this.getAttributeBuffer = getAttributeBuffer;
  9862. this.getWireframeAttribute = getWireframeAttribute;
  9863. this.update = update;
  9864. }
  9865. /**
  9866. * @author mrdoob / http://mrdoob.com/
  9867. */
  9868. function WebGLLights() {
  9869. var lights = {};
  9870. this.get = function ( light ) {
  9871. if ( lights[ light.id ] !== undefined ) {
  9872. return lights[ light.id ];
  9873. }
  9874. var uniforms;
  9875. switch ( light.type ) {
  9876. case 'DirectionalLight':
  9877. uniforms = {
  9878. direction: new Vector3(),
  9879. color: new Color(),
  9880. shadow: false,
  9881. shadowBias: 0,
  9882. shadowRadius: 1,
  9883. shadowMapSize: new Vector2()
  9884. };
  9885. break;
  9886. case 'SpotLight':
  9887. uniforms = {
  9888. position: new Vector3(),
  9889. direction: new Vector3(),
  9890. color: new Color(),
  9891. distance: 0,
  9892. coneCos: 0,
  9893. penumbraCos: 0,
  9894. decay: 0,
  9895. shadow: false,
  9896. shadowBias: 0,
  9897. shadowRadius: 1,
  9898. shadowMapSize: new Vector2()
  9899. };
  9900. break;
  9901. case 'PointLight':
  9902. uniforms = {
  9903. position: new Vector3(),
  9904. color: new Color(),
  9905. distance: 0,
  9906. decay: 0,
  9907. shadow: false,
  9908. shadowBias: 0,
  9909. shadowRadius: 1,
  9910. shadowMapSize: new Vector2()
  9911. };
  9912. break;
  9913. case 'HemisphereLight':
  9914. uniforms = {
  9915. direction: new Vector3(),
  9916. skyColor: new Color(),
  9917. groundColor: new Color()
  9918. };
  9919. break;
  9920. }
  9921. lights[ light.id ] = uniforms;
  9922. return uniforms;
  9923. };
  9924. }
  9925. function WebGLCapabilities( gl, extensions, parameters ) {
  9926. var maxAnisotropy;
  9927. function getMaxAnisotropy() {
  9928. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  9929. var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  9930. if ( extension !== null ) {
  9931. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  9932. } else {
  9933. maxAnisotropy = 0;
  9934. }
  9935. return maxAnisotropy;
  9936. }
  9937. function getMaxPrecision( precision ) {
  9938. if ( precision === 'highp' ) {
  9939. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  9940. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  9941. return 'highp';
  9942. }
  9943. precision = 'mediump';
  9944. }
  9945. if ( precision === 'mediump' ) {
  9946. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  9947. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  9948. return 'mediump';
  9949. }
  9950. }
  9951. return 'lowp';
  9952. }
  9953. this.getMaxAnisotropy = getMaxAnisotropy;
  9954. this.getMaxPrecision = getMaxPrecision;
  9955. this.precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  9956. this.logarithmicDepthBuffer = parameters.logarithmicDepthBuffer !== undefined ? parameters.logarithmicDepthBuffer : false;
  9957. this.maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  9958. this.maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  9959. this.maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  9960. this.maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  9961. this.maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  9962. this.maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  9963. this.maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  9964. this.maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  9965. this.vertexTextures = this.maxVertexTextures > 0;
  9966. this.floatFragmentTextures = !! extensions.get( 'OES_texture_float' );
  9967. this.floatVertexTextures = this.vertexTextures && this.floatFragmentTextures;
  9968. var _maxPrecision = getMaxPrecision( this.precision );
  9969. if ( _maxPrecision !== this.precision ) {
  9970. console.warn( 'THREE.WebGLRenderer:', this.precision, 'not supported, using', _maxPrecision, 'instead.' );
  9971. this.precision = _maxPrecision;
  9972. }
  9973. if ( this.logarithmicDepthBuffer ) {
  9974. this.logarithmicDepthBuffer = !! extensions.get( 'EXT_frag_depth' );
  9975. }
  9976. }
  9977. /**
  9978. * @author mrdoob / http://mrdoob.com/
  9979. */
  9980. function WebGLExtensions( gl ) {
  9981. var extensions = {};
  9982. this.get = function ( name ) {
  9983. if ( extensions[ name ] !== undefined ) {
  9984. return extensions[ name ];
  9985. }
  9986. var extension;
  9987. switch ( name ) {
  9988. case 'WEBGL_depth_texture':
  9989. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  9990. break;
  9991. case 'EXT_texture_filter_anisotropic':
  9992. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  9993. break;
  9994. case 'WEBGL_compressed_texture_s3tc':
  9995. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  9996. break;
  9997. case 'WEBGL_compressed_texture_pvrtc':
  9998. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  9999. break;
  10000. case 'WEBGL_compressed_texture_etc1':
  10001. extension = gl.getExtension( 'WEBGL_compressed_texture_etc1' );
  10002. break;
  10003. default:
  10004. extension = gl.getExtension( name );
  10005. }
  10006. if ( extension === null ) {
  10007. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  10008. }
  10009. extensions[ name ] = extension;
  10010. return extension;
  10011. };
  10012. }
  10013. /**
  10014. * @author mrdoob / http://mrdoob.com/
  10015. */
  10016. function WebGLIndexedBufferRenderer( _gl, extensions, _infoRender ) {
  10017. var mode;
  10018. function setMode( value ) {
  10019. mode = value;
  10020. }
  10021. var type, size;
  10022. function setIndex( index ) {
  10023. if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) {
  10024. type = _gl.UNSIGNED_INT;
  10025. size = 4;
  10026. } else {
  10027. type = _gl.UNSIGNED_SHORT;
  10028. size = 2;
  10029. }
  10030. }
  10031. function render( start, count ) {
  10032. _gl.drawElements( mode, count, type, start * size );
  10033. _infoRender.calls ++;
  10034. _infoRender.vertices += count;
  10035. if ( mode === _gl.TRIANGLES ) _infoRender.faces += count / 3;
  10036. }
  10037. function renderInstances( geometry, start, count ) {
  10038. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  10039. if ( extension === null ) {
  10040. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  10041. return;
  10042. }
  10043. extension.drawElementsInstancedANGLE( mode, count, type, start * size, geometry.maxInstancedCount );
  10044. _infoRender.calls ++;
  10045. _infoRender.vertices += count * geometry.maxInstancedCount;
  10046. if ( mode === _gl.TRIANGLES ) _infoRender.faces += geometry.maxInstancedCount * count / 3;
  10047. }
  10048. this.setMode = setMode;
  10049. this.setIndex = setIndex;
  10050. this.render = render;
  10051. this.renderInstances = renderInstances;
  10052. }
  10053. function WebGLClipping() {
  10054. var scope = this,
  10055. globalState = null,
  10056. numGlobalPlanes = 0,
  10057. localClippingEnabled = false,
  10058. renderingShadows = false,
  10059. plane = new Plane(),
  10060. viewNormalMatrix = new Matrix3(),
  10061. uniform = { value: null, needsUpdate: false };
  10062. this.uniform = uniform;
  10063. this.numPlanes = 0;
  10064. this.init = function( planes, enableLocalClipping, camera ) {
  10065. var enabled =
  10066. planes.length !== 0 ||
  10067. enableLocalClipping ||
  10068. // enable state of previous frame - the clipping code has to
  10069. // run another frame in order to reset the state:
  10070. numGlobalPlanes !== 0 ||
  10071. localClippingEnabled;
  10072. localClippingEnabled = enableLocalClipping;
  10073. globalState = projectPlanes( planes, camera, 0 );
  10074. numGlobalPlanes = planes.length;
  10075. return enabled;
  10076. };
  10077. this.beginShadows = function() {
  10078. renderingShadows = true;
  10079. projectPlanes( null );
  10080. };
  10081. this.endShadows = function() {
  10082. renderingShadows = false;
  10083. resetGlobalState();
  10084. };
  10085. this.setState = function( planes, clipShadows, camera, cache, fromCache ) {
  10086. if ( ! localClippingEnabled ||
  10087. planes === null || planes.length === 0 ||
  10088. renderingShadows && ! clipShadows ) {
  10089. // there's no local clipping
  10090. if ( renderingShadows ) {
  10091. // there's no global clipping
  10092. projectPlanes( null );
  10093. } else {
  10094. resetGlobalState();
  10095. }
  10096. } else {
  10097. var nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  10098. lGlobal = nGlobal * 4,
  10099. dstArray = cache.clippingState || null;
  10100. uniform.value = dstArray; // ensure unique state
  10101. dstArray = projectPlanes( planes, camera, lGlobal, fromCache );
  10102. for ( var i = 0; i !== lGlobal; ++ i ) {
  10103. dstArray[ i ] = globalState[ i ];
  10104. }
  10105. cache.clippingState = dstArray;
  10106. this.numPlanes += nGlobal;
  10107. }
  10108. };
  10109. function resetGlobalState() {
  10110. if ( uniform.value !== globalState ) {
  10111. uniform.value = globalState;
  10112. uniform.needsUpdate = numGlobalPlanes > 0;
  10113. }
  10114. scope.numPlanes = numGlobalPlanes;
  10115. }
  10116. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  10117. var nPlanes = planes !== null ? planes.length : 0,
  10118. dstArray = null;
  10119. if ( nPlanes !== 0 ) {
  10120. dstArray = uniform.value;
  10121. if ( skipTransform !== true || dstArray === null ) {
  10122. var flatSize = dstOffset + nPlanes * 4,
  10123. viewMatrix = camera.matrixWorldInverse;
  10124. viewNormalMatrix.getNormalMatrix( viewMatrix );
  10125. if ( dstArray === null || dstArray.length < flatSize ) {
  10126. dstArray = new Float32Array( flatSize );
  10127. }
  10128. for ( var i = 0, i4 = dstOffset;
  10129. i !== nPlanes; ++ i, i4 += 4 ) {
  10130. plane.copy( planes[ i ] ).
  10131. applyMatrix4( viewMatrix, viewNormalMatrix );
  10132. plane.normal.toArray( dstArray, i4 );
  10133. dstArray[ i4 + 3 ] = plane.constant;
  10134. }
  10135. }
  10136. uniform.value = dstArray;
  10137. uniform.needsUpdate = true;
  10138. }
  10139. scope.numPlanes = nPlanes;
  10140. return dstArray;
  10141. }
  10142. }
  10143. /**
  10144. * @author mrdoob / http://mrdoob.com/
  10145. */
  10146. function WebGLBufferRenderer( _gl, extensions, _infoRender ) {
  10147. var mode;
  10148. function setMode( value ) {
  10149. mode = value;
  10150. }
  10151. function render( start, count ) {
  10152. _gl.drawArrays( mode, start, count );
  10153. _infoRender.calls ++;
  10154. _infoRender.vertices += count;
  10155. if ( mode === _gl.TRIANGLES ) _infoRender.faces += count / 3;
  10156. }
  10157. function renderInstances( geometry ) {
  10158. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  10159. if ( extension === null ) {
  10160. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  10161. return;
  10162. }
  10163. var position = geometry.attributes.position;
  10164. var count = 0;
  10165. if ( (position && position.isInterleavedBufferAttribute) ) {
  10166. count = position.data.count;
  10167. extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount );
  10168. } else {
  10169. count = position.count;
  10170. extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount );
  10171. }
  10172. _infoRender.calls ++;
  10173. _infoRender.vertices += count * geometry.maxInstancedCount;
  10174. if ( mode === _gl.TRIANGLES ) _infoRender.faces += geometry.maxInstancedCount * count / 3;
  10175. }
  10176. this.setMode = setMode;
  10177. this.render = render;
  10178. this.renderInstances = renderInstances;
  10179. }
  10180. /**
  10181. * @author alteredq / http://alteredqualia.com
  10182. */
  10183. function WebGLRenderTargetCube( width, height, options ) {
  10184. WebGLRenderTarget.call( this, width, height, options );
  10185. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  10186. this.activeMipMapLevel = 0;
  10187. }
  10188. WebGLRenderTargetCube.prototype = Object.create( WebGLRenderTarget.prototype );
  10189. WebGLRenderTargetCube.prototype.constructor = WebGLRenderTargetCube;
  10190. WebGLRenderTargetCube.prototype.isWebGLRenderTargetCube = true;
  10191. /**
  10192. * @author Mugen87 / https://github.com/Mugen87
  10193. */
  10194. function BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  10195. BufferGeometry.call( this );
  10196. this.type = 'BoxBufferGeometry';
  10197. this.parameters = {
  10198. width: width,
  10199. height: height,
  10200. depth: depth,
  10201. widthSegments: widthSegments,
  10202. heightSegments: heightSegments,
  10203. depthSegments: depthSegments
  10204. };
  10205. var scope = this;
  10206. // segments
  10207. widthSegments = Math.floor( widthSegments ) || 1;
  10208. heightSegments = Math.floor( heightSegments ) || 1;
  10209. depthSegments = Math.floor( depthSegments ) || 1;
  10210. // these are used to calculate buffer length
  10211. var vertexCount = calculateVertexCount( widthSegments, heightSegments, depthSegments );
  10212. var indexCount = calculateIndexCount( widthSegments, heightSegments, depthSegments );
  10213. // buffers
  10214. var indices = new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount );
  10215. var vertices = new Float32Array( vertexCount * 3 );
  10216. var normals = new Float32Array( vertexCount * 3 );
  10217. var uvs = new Float32Array( vertexCount * 2 );
  10218. // offset variables
  10219. var vertexBufferOffset = 0;
  10220. var uvBufferOffset = 0;
  10221. var indexBufferOffset = 0;
  10222. var numberOfVertices = 0;
  10223. // group variables
  10224. var groupStart = 0;
  10225. // build each side of the box geometry
  10226. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  10227. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  10228. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  10229. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  10230. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  10231. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  10232. // build geometry
  10233. this.setIndex( new BufferAttribute( indices, 1 ) );
  10234. this.addAttribute( 'position', new BufferAttribute( vertices, 3 ) );
  10235. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) );
  10236. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) );
  10237. // helper functions
  10238. function calculateVertexCount( w, h, d ) {
  10239. var vertices = 0;
  10240. // calculate the amount of vertices for each side (plane)
  10241. vertices += (w + 1) * (h + 1) * 2; // xy
  10242. vertices += (w + 1) * (d + 1) * 2; // xz
  10243. vertices += (d + 1) * (h + 1) * 2; // zy
  10244. return vertices;
  10245. }
  10246. function calculateIndexCount( w, h, d ) {
  10247. var index = 0;
  10248. // calculate the amount of squares for each side
  10249. index += w * h * 2; // xy
  10250. index += w * d * 2; // xz
  10251. index += d * h * 2; // zy
  10252. return index * 6; // two triangles per square => six vertices per square
  10253. }
  10254. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  10255. var segmentWidth = width / gridX;
  10256. var segmentHeight = height / gridY;
  10257. var widthHalf = width / 2;
  10258. var heightHalf = height / 2;
  10259. var depthHalf = depth / 2;
  10260. var gridX1 = gridX + 1;
  10261. var gridY1 = gridY + 1;
  10262. var vertexCounter = 0;
  10263. var groupCount = 0;
  10264. var vector = new Vector3();
  10265. // generate vertices, normals and uvs
  10266. for ( var iy = 0; iy < gridY1; iy ++ ) {
  10267. var y = iy * segmentHeight - heightHalf;
  10268. for ( var ix = 0; ix < gridX1; ix ++ ) {
  10269. var x = ix * segmentWidth - widthHalf;
  10270. // set values to correct vector component
  10271. vector[ u ] = x * udir;
  10272. vector[ v ] = y * vdir;
  10273. vector[ w ] = depthHalf;
  10274. // now apply vector to vertex buffer
  10275. vertices[ vertexBufferOffset ] = vector.x;
  10276. vertices[ vertexBufferOffset + 1 ] = vector.y;
  10277. vertices[ vertexBufferOffset + 2 ] = vector.z;
  10278. // set values to correct vector component
  10279. vector[ u ] = 0;
  10280. vector[ v ] = 0;
  10281. vector[ w ] = depth > 0 ? 1 : - 1;
  10282. // now apply vector to normal buffer
  10283. normals[ vertexBufferOffset ] = vector.x;
  10284. normals[ vertexBufferOffset + 1 ] = vector.y;
  10285. normals[ vertexBufferOffset + 2 ] = vector.z;
  10286. // uvs
  10287. uvs[ uvBufferOffset ] = ix / gridX;
  10288. uvs[ uvBufferOffset + 1 ] = 1 - ( iy / gridY );
  10289. // update offsets and counters
  10290. vertexBufferOffset += 3;
  10291. uvBufferOffset += 2;
  10292. vertexCounter += 1;
  10293. }
  10294. }
  10295. // 1. you need three indices to draw a single face
  10296. // 2. a single segment consists of two faces
  10297. // 3. so we need to generate six (2*3) indices per segment
  10298. for ( iy = 0; iy < gridY; iy ++ ) {
  10299. for ( ix = 0; ix < gridX; ix ++ ) {
  10300. // indices
  10301. var a = numberOfVertices + ix + gridX1 * iy;
  10302. var b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  10303. var c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  10304. var d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  10305. // face one
  10306. indices[ indexBufferOffset ] = a;
  10307. indices[ indexBufferOffset + 1 ] = b;
  10308. indices[ indexBufferOffset + 2 ] = d;
  10309. // face two
  10310. indices[ indexBufferOffset + 3 ] = b;
  10311. indices[ indexBufferOffset + 4 ] = c;
  10312. indices[ indexBufferOffset + 5 ] = d;
  10313. // update offsets and counters
  10314. indexBufferOffset += 6;
  10315. groupCount += 6;
  10316. }
  10317. }
  10318. // add a group to the geometry. this will ensure multi material support
  10319. scope.addGroup( groupStart, groupCount, materialIndex );
  10320. // calculate new start value for groups
  10321. groupStart += groupCount;
  10322. // update total number of vertices
  10323. numberOfVertices += vertexCounter;
  10324. }
  10325. }
  10326. BoxBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  10327. BoxBufferGeometry.prototype.constructor = BoxBufferGeometry;
  10328. /**
  10329. * @author bhouston / http://clara.io
  10330. */
  10331. function Ray( origin, direction ) {
  10332. this.origin = ( origin !== undefined ) ? origin : new Vector3();
  10333. this.direction = ( direction !== undefined ) ? direction : new Vector3();
  10334. }
  10335. Ray.prototype = {
  10336. constructor: Ray,
  10337. set: function ( origin, direction ) {
  10338. this.origin.copy( origin );
  10339. this.direction.copy( direction );
  10340. return this;
  10341. },
  10342. clone: function () {
  10343. return new this.constructor().copy( this );
  10344. },
  10345. copy: function ( ray ) {
  10346. this.origin.copy( ray.origin );
  10347. this.direction.copy( ray.direction );
  10348. return this;
  10349. },
  10350. at: function ( t, optionalTarget ) {
  10351. var result = optionalTarget || new Vector3();
  10352. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  10353. },
  10354. lookAt: function ( v ) {
  10355. this.direction.copy( v ).sub( this.origin ).normalize();
  10356. return this;
  10357. },
  10358. recast: function () {
  10359. var v1 = new Vector3();
  10360. return function recast( t ) {
  10361. this.origin.copy( this.at( t, v1 ) );
  10362. return this;
  10363. };
  10364. }(),
  10365. closestPointToPoint: function ( point, optionalTarget ) {
  10366. var result = optionalTarget || new Vector3();
  10367. result.subVectors( point, this.origin );
  10368. var directionDistance = result.dot( this.direction );
  10369. if ( directionDistance < 0 ) {
  10370. return result.copy( this.origin );
  10371. }
  10372. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  10373. },
  10374. distanceToPoint: function ( point ) {
  10375. return Math.sqrt( this.distanceSqToPoint( point ) );
  10376. },
  10377. distanceSqToPoint: function () {
  10378. var v1 = new Vector3();
  10379. return function distanceSqToPoint( point ) {
  10380. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  10381. // point behind the ray
  10382. if ( directionDistance < 0 ) {
  10383. return this.origin.distanceToSquared( point );
  10384. }
  10385. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  10386. return v1.distanceToSquared( point );
  10387. };
  10388. }(),
  10389. distanceSqToSegment: function () {
  10390. var segCenter = new Vector3();
  10391. var segDir = new Vector3();
  10392. var diff = new Vector3();
  10393. return function distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  10394. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  10395. // It returns the min distance between the ray and the segment
  10396. // defined by v0 and v1
  10397. // It can also set two optional targets :
  10398. // - The closest point on the ray
  10399. // - The closest point on the segment
  10400. segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  10401. segDir.copy( v1 ).sub( v0 ).normalize();
  10402. diff.copy( this.origin ).sub( segCenter );
  10403. var segExtent = v0.distanceTo( v1 ) * 0.5;
  10404. var a01 = - this.direction.dot( segDir );
  10405. var b0 = diff.dot( this.direction );
  10406. var b1 = - diff.dot( segDir );
  10407. var c = diff.lengthSq();
  10408. var det = Math.abs( 1 - a01 * a01 );
  10409. var s0, s1, sqrDist, extDet;
  10410. if ( det > 0 ) {
  10411. // The ray and segment are not parallel.
  10412. s0 = a01 * b1 - b0;
  10413. s1 = a01 * b0 - b1;
  10414. extDet = segExtent * det;
  10415. if ( s0 >= 0 ) {
  10416. if ( s1 >= - extDet ) {
  10417. if ( s1 <= extDet ) {
  10418. // region 0
  10419. // Minimum at interior points of ray and segment.
  10420. var invDet = 1 / det;
  10421. s0 *= invDet;
  10422. s1 *= invDet;
  10423. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  10424. } else {
  10425. // region 1
  10426. s1 = segExtent;
  10427. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  10428. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  10429. }
  10430. } else {
  10431. // region 5
  10432. s1 = - segExtent;
  10433. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  10434. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  10435. }
  10436. } else {
  10437. if ( s1 <= - extDet ) {
  10438. // region 4
  10439. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  10440. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  10441. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  10442. } else if ( s1 <= extDet ) {
  10443. // region 3
  10444. s0 = 0;
  10445. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  10446. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  10447. } else {
  10448. // region 2
  10449. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  10450. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  10451. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  10452. }
  10453. }
  10454. } else {
  10455. // Ray and segment are parallel.
  10456. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  10457. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  10458. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  10459. }
  10460. if ( optionalPointOnRay ) {
  10461. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  10462. }
  10463. if ( optionalPointOnSegment ) {
  10464. optionalPointOnSegment.copy( segDir ).multiplyScalar( s1 ).add( segCenter );
  10465. }
  10466. return sqrDist;
  10467. };
  10468. }(),
  10469. intersectSphere: function () {
  10470. var v1 = new Vector3();
  10471. return function intersectSphere( sphere, optionalTarget ) {
  10472. v1.subVectors( sphere.center, this.origin );
  10473. var tca = v1.dot( this.direction );
  10474. var d2 = v1.dot( v1 ) - tca * tca;
  10475. var radius2 = sphere.radius * sphere.radius;
  10476. if ( d2 > radius2 ) return null;
  10477. var thc = Math.sqrt( radius2 - d2 );
  10478. // t0 = first intersect point - entrance on front of sphere
  10479. var t0 = tca - thc;
  10480. // t1 = second intersect point - exit point on back of sphere
  10481. var t1 = tca + thc;
  10482. // test to see if both t0 and t1 are behind the ray - if so, return null
  10483. if ( t0 < 0 && t1 < 0 ) return null;
  10484. // test to see if t0 is behind the ray:
  10485. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  10486. // in order to always return an intersect point that is in front of the ray.
  10487. if ( t0 < 0 ) return this.at( t1, optionalTarget );
  10488. // else t0 is in front of the ray, so return the first collision point scaled by t0
  10489. return this.at( t0, optionalTarget );
  10490. };
  10491. }(),
  10492. intersectsSphere: function ( sphere ) {
  10493. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  10494. },
  10495. distanceToPlane: function ( plane ) {
  10496. var denominator = plane.normal.dot( this.direction );
  10497. if ( denominator === 0 ) {
  10498. // line is coplanar, return origin
  10499. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  10500. return 0;
  10501. }
  10502. // Null is preferable to undefined since undefined means.... it is undefined
  10503. return null;
  10504. }
  10505. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  10506. // Return if the ray never intersects the plane
  10507. return t >= 0 ? t : null;
  10508. },
  10509. intersectPlane: function ( plane, optionalTarget ) {
  10510. var t = this.distanceToPlane( plane );
  10511. if ( t === null ) {
  10512. return null;
  10513. }
  10514. return this.at( t, optionalTarget );
  10515. },
  10516. intersectsPlane: function ( plane ) {
  10517. // check if the ray lies on the plane first
  10518. var distToPoint = plane.distanceToPoint( this.origin );
  10519. if ( distToPoint === 0 ) {
  10520. return true;
  10521. }
  10522. var denominator = plane.normal.dot( this.direction );
  10523. if ( denominator * distToPoint < 0 ) {
  10524. return true;
  10525. }
  10526. // ray origin is behind the plane (and is pointing behind it)
  10527. return false;
  10528. },
  10529. intersectBox: function ( box, optionalTarget ) {
  10530. var tmin, tmax, tymin, tymax, tzmin, tzmax;
  10531. var invdirx = 1 / this.direction.x,
  10532. invdiry = 1 / this.direction.y,
  10533. invdirz = 1 / this.direction.z;
  10534. var origin = this.origin;
  10535. if ( invdirx >= 0 ) {
  10536. tmin = ( box.min.x - origin.x ) * invdirx;
  10537. tmax = ( box.max.x - origin.x ) * invdirx;
  10538. } else {
  10539. tmin = ( box.max.x - origin.x ) * invdirx;
  10540. tmax = ( box.min.x - origin.x ) * invdirx;
  10541. }
  10542. if ( invdiry >= 0 ) {
  10543. tymin = ( box.min.y - origin.y ) * invdiry;
  10544. tymax = ( box.max.y - origin.y ) * invdiry;
  10545. } else {
  10546. tymin = ( box.max.y - origin.y ) * invdiry;
  10547. tymax = ( box.min.y - origin.y ) * invdiry;
  10548. }
  10549. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  10550. // These lines also handle the case where tmin or tmax is NaN
  10551. // (result of 0 * Infinity). x !== x returns true if x is NaN
  10552. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  10553. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  10554. if ( invdirz >= 0 ) {
  10555. tzmin = ( box.min.z - origin.z ) * invdirz;
  10556. tzmax = ( box.max.z - origin.z ) * invdirz;
  10557. } else {
  10558. tzmin = ( box.max.z - origin.z ) * invdirz;
  10559. tzmax = ( box.min.z - origin.z ) * invdirz;
  10560. }
  10561. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  10562. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  10563. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  10564. //return point closest to the ray (positive side)
  10565. if ( tmax < 0 ) return null;
  10566. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  10567. },
  10568. intersectsBox: ( function () {
  10569. var v = new Vector3();
  10570. return function intersectsBox( box ) {
  10571. return this.intersectBox( box, v ) !== null;
  10572. };
  10573. } )(),
  10574. intersectTriangle: function () {
  10575. // Compute the offset origin, edges, and normal.
  10576. var diff = new Vector3();
  10577. var edge1 = new Vector3();
  10578. var edge2 = new Vector3();
  10579. var normal = new Vector3();
  10580. return function intersectTriangle( a, b, c, backfaceCulling, optionalTarget ) {
  10581. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  10582. edge1.subVectors( b, a );
  10583. edge2.subVectors( c, a );
  10584. normal.crossVectors( edge1, edge2 );
  10585. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  10586. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  10587. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  10588. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  10589. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  10590. var DdN = this.direction.dot( normal );
  10591. var sign;
  10592. if ( DdN > 0 ) {
  10593. if ( backfaceCulling ) return null;
  10594. sign = 1;
  10595. } else if ( DdN < 0 ) {
  10596. sign = - 1;
  10597. DdN = - DdN;
  10598. } else {
  10599. return null;
  10600. }
  10601. diff.subVectors( this.origin, a );
  10602. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  10603. // b1 < 0, no intersection
  10604. if ( DdQxE2 < 0 ) {
  10605. return null;
  10606. }
  10607. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  10608. // b2 < 0, no intersection
  10609. if ( DdE1xQ < 0 ) {
  10610. return null;
  10611. }
  10612. // b1+b2 > 1, no intersection
  10613. if ( DdQxE2 + DdE1xQ > DdN ) {
  10614. return null;
  10615. }
  10616. // Line intersects triangle, check if ray does.
  10617. var QdN = - sign * diff.dot( normal );
  10618. // t < 0, no intersection
  10619. if ( QdN < 0 ) {
  10620. return null;
  10621. }
  10622. // Ray intersects triangle.
  10623. return this.at( QdN / DdN, optionalTarget );
  10624. };
  10625. }(),
  10626. applyMatrix4: function ( matrix4 ) {
  10627. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  10628. this.origin.applyMatrix4( matrix4 );
  10629. this.direction.sub( this.origin );
  10630. this.direction.normalize();
  10631. return this;
  10632. },
  10633. equals: function ( ray ) {
  10634. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  10635. }
  10636. };
  10637. /**
  10638. * @author bhouston / http://clara.io
  10639. */
  10640. function Line3( start, end ) {
  10641. this.start = ( start !== undefined ) ? start : new Vector3();
  10642. this.end = ( end !== undefined ) ? end : new Vector3();
  10643. }
  10644. Line3.prototype = {
  10645. constructor: Line3,
  10646. set: function ( start, end ) {
  10647. this.start.copy( start );
  10648. this.end.copy( end );
  10649. return this;
  10650. },
  10651. clone: function () {
  10652. return new this.constructor().copy( this );
  10653. },
  10654. copy: function ( line ) {
  10655. this.start.copy( line.start );
  10656. this.end.copy( line.end );
  10657. return this;
  10658. },
  10659. center: function ( optionalTarget ) {
  10660. var result = optionalTarget || new Vector3();
  10661. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  10662. },
  10663. delta: function ( optionalTarget ) {
  10664. var result = optionalTarget || new Vector3();
  10665. return result.subVectors( this.end, this.start );
  10666. },
  10667. distanceSq: function () {
  10668. return this.start.distanceToSquared( this.end );
  10669. },
  10670. distance: function () {
  10671. return this.start.distanceTo( this.end );
  10672. },
  10673. at: function ( t, optionalTarget ) {
  10674. var result = optionalTarget || new Vector3();
  10675. return this.delta( result ).multiplyScalar( t ).add( this.start );
  10676. },
  10677. closestPointToPointParameter: function () {
  10678. var startP = new Vector3();
  10679. var startEnd = new Vector3();
  10680. return function closestPointToPointParameter( point, clampToLine ) {
  10681. startP.subVectors( point, this.start );
  10682. startEnd.subVectors( this.end, this.start );
  10683. var startEnd2 = startEnd.dot( startEnd );
  10684. var startEnd_startP = startEnd.dot( startP );
  10685. var t = startEnd_startP / startEnd2;
  10686. if ( clampToLine ) {
  10687. t = exports.Math.clamp( t, 0, 1 );
  10688. }
  10689. return t;
  10690. };
  10691. }(),
  10692. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  10693. var t = this.closestPointToPointParameter( point, clampToLine );
  10694. var result = optionalTarget || new Vector3();
  10695. return this.delta( result ).multiplyScalar( t ).add( this.start );
  10696. },
  10697. applyMatrix4: function ( matrix ) {
  10698. this.start.applyMatrix4( matrix );
  10699. this.end.applyMatrix4( matrix );
  10700. return this;
  10701. },
  10702. equals: function ( line ) {
  10703. return line.start.equals( this.start ) && line.end.equals( this.end );
  10704. }
  10705. };
  10706. /**
  10707. * @author bhouston / http://clara.io
  10708. * @author mrdoob / http://mrdoob.com/
  10709. */
  10710. function Triangle( a, b, c ) {
  10711. this.a = ( a !== undefined ) ? a : new Vector3();
  10712. this.b = ( b !== undefined ) ? b : new Vector3();
  10713. this.c = ( c !== undefined ) ? c : new Vector3();
  10714. }
  10715. Triangle.normal = function () {
  10716. var v0 = new Vector3();
  10717. return function normal( a, b, c, optionalTarget ) {
  10718. var result = optionalTarget || new Vector3();
  10719. result.subVectors( c, b );
  10720. v0.subVectors( a, b );
  10721. result.cross( v0 );
  10722. var resultLengthSq = result.lengthSq();
  10723. if ( resultLengthSq > 0 ) {
  10724. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  10725. }
  10726. return result.set( 0, 0, 0 );
  10727. };
  10728. }();
  10729. // static/instance method to calculate barycentric coordinates
  10730. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  10731. Triangle.barycoordFromPoint = function () {
  10732. var v0 = new Vector3();
  10733. var v1 = new Vector3();
  10734. var v2 = new Vector3();
  10735. return function barycoordFromPoint( point, a, b, c, optionalTarget ) {
  10736. v0.subVectors( c, a );
  10737. v1.subVectors( b, a );
  10738. v2.subVectors( point, a );
  10739. var dot00 = v0.dot( v0 );
  10740. var dot01 = v0.dot( v1 );
  10741. var dot02 = v0.dot( v2 );
  10742. var dot11 = v1.dot( v1 );
  10743. var dot12 = v1.dot( v2 );
  10744. var denom = ( dot00 * dot11 - dot01 * dot01 );
  10745. var result = optionalTarget || new Vector3();
  10746. // collinear or singular triangle
  10747. if ( denom === 0 ) {
  10748. // arbitrary location outside of triangle?
  10749. // not sure if this is the best idea, maybe should be returning undefined
  10750. return result.set( - 2, - 1, - 1 );
  10751. }
  10752. var invDenom = 1 / denom;
  10753. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  10754. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  10755. // barycentric coordinates must always sum to 1
  10756. return result.set( 1 - u - v, v, u );
  10757. };
  10758. }();
  10759. Triangle.containsPoint = function () {
  10760. var v1 = new Vector3();
  10761. return function containsPoint( point, a, b, c ) {
  10762. var result = Triangle.barycoordFromPoint( point, a, b, c, v1 );
  10763. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  10764. };
  10765. }();
  10766. Triangle.prototype = {
  10767. constructor: Triangle,
  10768. set: function ( a, b, c ) {
  10769. this.a.copy( a );
  10770. this.b.copy( b );
  10771. this.c.copy( c );
  10772. return this;
  10773. },
  10774. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  10775. this.a.copy( points[ i0 ] );
  10776. this.b.copy( points[ i1 ] );
  10777. this.c.copy( points[ i2 ] );
  10778. return this;
  10779. },
  10780. clone: function () {
  10781. return new this.constructor().copy( this );
  10782. },
  10783. copy: function ( triangle ) {
  10784. this.a.copy( triangle.a );
  10785. this.b.copy( triangle.b );
  10786. this.c.copy( triangle.c );
  10787. return this;
  10788. },
  10789. area: function () {
  10790. var v0 = new Vector3();
  10791. var v1 = new Vector3();
  10792. return function area() {
  10793. v0.subVectors( this.c, this.b );
  10794. v1.subVectors( this.a, this.b );
  10795. return v0.cross( v1 ).length() * 0.5;
  10796. };
  10797. }(),
  10798. midpoint: function ( optionalTarget ) {
  10799. var result = optionalTarget || new Vector3();
  10800. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  10801. },
  10802. normal: function ( optionalTarget ) {
  10803. return Triangle.normal( this.a, this.b, this.c, optionalTarget );
  10804. },
  10805. plane: function ( optionalTarget ) {
  10806. var result = optionalTarget || new Plane();
  10807. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  10808. },
  10809. barycoordFromPoint: function ( point, optionalTarget ) {
  10810. return Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  10811. },
  10812. containsPoint: function ( point ) {
  10813. return Triangle.containsPoint( point, this.a, this.b, this.c );
  10814. },
  10815. closestPointToPoint: function () {
  10816. var plane, edgeList, projectedPoint, closestPoint;
  10817. return function closestPointToPoint( point, optionalTarget ) {
  10818. if ( plane === undefined ) {
  10819. plane = new Plane();
  10820. edgeList = [ new Line3(), new Line3(), new Line3() ];
  10821. projectedPoint = new Vector3();
  10822. closestPoint = new Vector3();
  10823. }
  10824. var result = optionalTarget || new Vector3();
  10825. var minDistance = Infinity;
  10826. // project the point onto the plane of the triangle
  10827. plane.setFromCoplanarPoints( this.a, this.b, this.c );
  10828. plane.projectPoint( point, projectedPoint );
  10829. // check if the projection lies within the triangle
  10830. if( this.containsPoint( projectedPoint ) === true ) {
  10831. // if so, this is the closest point
  10832. result.copy( projectedPoint );
  10833. } else {
  10834. // if not, the point falls outside the triangle. the result is the closest point to the triangle's edges or vertices
  10835. edgeList[ 0 ].set( this.a, this.b );
  10836. edgeList[ 1 ].set( this.b, this.c );
  10837. edgeList[ 2 ].set( this.c, this.a );
  10838. for( var i = 0; i < edgeList.length; i ++ ) {
  10839. edgeList[ i ].closestPointToPoint( projectedPoint, true, closestPoint );
  10840. var distance = projectedPoint.distanceToSquared( closestPoint );
  10841. if( distance < minDistance ) {
  10842. minDistance = distance;
  10843. result.copy( closestPoint );
  10844. }
  10845. }
  10846. }
  10847. return result;
  10848. };
  10849. }(),
  10850. equals: function ( triangle ) {
  10851. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  10852. }
  10853. };
  10854. /**
  10855. * @author mrdoob / http://mrdoob.com/
  10856. * @author alteredq / http://alteredqualia.com/
  10857. *
  10858. * parameters = {
  10859. * color: <hex>,
  10860. * opacity: <float>,
  10861. * map: new THREE.Texture( <Image> ),
  10862. *
  10863. * aoMap: new THREE.Texture( <Image> ),
  10864. * aoMapIntensity: <float>
  10865. *
  10866. * specularMap: new THREE.Texture( <Image> ),
  10867. *
  10868. * alphaMap: new THREE.Texture( <Image> ),
  10869. *
  10870. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  10871. * combine: THREE.Multiply,
  10872. * reflectivity: <float>,
  10873. * refractionRatio: <float>,
  10874. *
  10875. * shading: THREE.SmoothShading,
  10876. * depthTest: <bool>,
  10877. * depthWrite: <bool>,
  10878. *
  10879. * wireframe: <boolean>,
  10880. * wireframeLinewidth: <float>,
  10881. *
  10882. * skinning: <bool>,
  10883. * morphTargets: <bool>
  10884. * }
  10885. */
  10886. function MeshBasicMaterial( parameters ) {
  10887. Material.call( this );
  10888. this.type = 'MeshBasicMaterial';
  10889. this.color = new Color( 0xffffff ); // emissive
  10890. this.map = null;
  10891. this.aoMap = null;
  10892. this.aoMapIntensity = 1.0;
  10893. this.specularMap = null;
  10894. this.alphaMap = null;
  10895. this.envMap = null;
  10896. this.combine = MultiplyOperation;
  10897. this.reflectivity = 1;
  10898. this.refractionRatio = 0.98;
  10899. this.wireframe = false;
  10900. this.wireframeLinewidth = 1;
  10901. this.wireframeLinecap = 'round';
  10902. this.wireframeLinejoin = 'round';
  10903. this.skinning = false;
  10904. this.morphTargets = false;
  10905. this.lights = false;
  10906. this.setValues( parameters );
  10907. }
  10908. MeshBasicMaterial.prototype = Object.create( Material.prototype );
  10909. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  10910. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  10911. MeshBasicMaterial.prototype.copy = function ( source ) {
  10912. Material.prototype.copy.call( this, source );
  10913. this.color.copy( source.color );
  10914. this.map = source.map;
  10915. this.aoMap = source.aoMap;
  10916. this.aoMapIntensity = source.aoMapIntensity;
  10917. this.specularMap = source.specularMap;
  10918. this.alphaMap = source.alphaMap;
  10919. this.envMap = source.envMap;
  10920. this.combine = source.combine;
  10921. this.reflectivity = source.reflectivity;
  10922. this.refractionRatio = source.refractionRatio;
  10923. this.wireframe = source.wireframe;
  10924. this.wireframeLinewidth = source.wireframeLinewidth;
  10925. this.wireframeLinecap = source.wireframeLinecap;
  10926. this.wireframeLinejoin = source.wireframeLinejoin;
  10927. this.skinning = source.skinning;
  10928. this.morphTargets = source.morphTargets;
  10929. return this;
  10930. };
  10931. /**
  10932. * @author mrdoob / http://mrdoob.com/
  10933. * @author alteredq / http://alteredqualia.com/
  10934. * @author mikael emtinger / http://gomo.se/
  10935. * @author jonobr1 / http://jonobr1.com/
  10936. */
  10937. function Mesh( geometry, material ) {
  10938. Object3D.call( this );
  10939. this.type = 'Mesh';
  10940. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  10941. this.material = material !== undefined ? material : new MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  10942. this.drawMode = TrianglesDrawMode;
  10943. this.updateMorphTargets();
  10944. }
  10945. Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), {
  10946. constructor: Mesh,
  10947. isMesh: true,
  10948. setDrawMode: function ( value ) {
  10949. this.drawMode = value;
  10950. },
  10951. copy: function ( source ) {
  10952. Object3D.prototype.copy.call( this, source );
  10953. this.drawMode = source.drawMode;
  10954. return this;
  10955. },
  10956. updateMorphTargets: function () {
  10957. if ( this.geometry.morphTargets !== undefined && this.geometry.morphTargets.length > 0 ) {
  10958. this.morphTargetBase = - 1;
  10959. this.morphTargetInfluences = [];
  10960. this.morphTargetDictionary = {};
  10961. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  10962. this.morphTargetInfluences.push( 0 );
  10963. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  10964. }
  10965. }
  10966. },
  10967. getMorphTargetIndexByName: function ( name ) {
  10968. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  10969. return this.morphTargetDictionary[ name ];
  10970. }
  10971. console.warn( 'THREE.Mesh.getMorphTargetIndexByName: morph target ' + name + ' does not exist. Returning 0.' );
  10972. return 0;
  10973. },
  10974. raycast: ( function () {
  10975. var inverseMatrix = new Matrix4();
  10976. var ray = new Ray();
  10977. var sphere = new Sphere();
  10978. var vA = new Vector3();
  10979. var vB = new Vector3();
  10980. var vC = new Vector3();
  10981. var tempA = new Vector3();
  10982. var tempB = new Vector3();
  10983. var tempC = new Vector3();
  10984. var uvA = new Vector2();
  10985. var uvB = new Vector2();
  10986. var uvC = new Vector2();
  10987. var barycoord = new Vector3();
  10988. var intersectionPoint = new Vector3();
  10989. var intersectionPointWorld = new Vector3();
  10990. function uvIntersection( point, p1, p2, p3, uv1, uv2, uv3 ) {
  10991. Triangle.barycoordFromPoint( point, p1, p2, p3, barycoord );
  10992. uv1.multiplyScalar( barycoord.x );
  10993. uv2.multiplyScalar( barycoord.y );
  10994. uv3.multiplyScalar( barycoord.z );
  10995. uv1.add( uv2 ).add( uv3 );
  10996. return uv1.clone();
  10997. }
  10998. function checkIntersection( object, raycaster, ray, pA, pB, pC, point ) {
  10999. var intersect;
  11000. var material = object.material;
  11001. if ( material.side === BackSide ) {
  11002. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  11003. } else {
  11004. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );
  11005. }
  11006. if ( intersect === null ) return null;
  11007. intersectionPointWorld.copy( point );
  11008. intersectionPointWorld.applyMatrix4( object.matrixWorld );
  11009. var distance = raycaster.ray.origin.distanceTo( intersectionPointWorld );
  11010. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  11011. return {
  11012. distance: distance,
  11013. point: intersectionPointWorld.clone(),
  11014. object: object
  11015. };
  11016. }
  11017. function checkBufferGeometryIntersection( object, raycaster, ray, positions, uvs, a, b, c ) {
  11018. vA.fromArray( positions, a * 3 );
  11019. vB.fromArray( positions, b * 3 );
  11020. vC.fromArray( positions, c * 3 );
  11021. var intersection = checkIntersection( object, raycaster, ray, vA, vB, vC, intersectionPoint );
  11022. if ( intersection ) {
  11023. if ( uvs ) {
  11024. uvA.fromArray( uvs, a * 2 );
  11025. uvB.fromArray( uvs, b * 2 );
  11026. uvC.fromArray( uvs, c * 2 );
  11027. intersection.uv = uvIntersection( intersectionPoint, vA, vB, vC, uvA, uvB, uvC );
  11028. }
  11029. intersection.face = new Face3( a, b, c, Triangle.normal( vA, vB, vC ) );
  11030. intersection.faceIndex = a;
  11031. }
  11032. return intersection;
  11033. }
  11034. return function raycast( raycaster, intersects ) {
  11035. var geometry = this.geometry;
  11036. var material = this.material;
  11037. var matrixWorld = this.matrixWorld;
  11038. if ( material === undefined ) return;
  11039. // Checking boundingSphere distance to ray
  11040. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  11041. sphere.copy( geometry.boundingSphere );
  11042. sphere.applyMatrix4( matrixWorld );
  11043. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  11044. //
  11045. inverseMatrix.getInverse( matrixWorld );
  11046. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  11047. // Check boundingBox before continuing
  11048. if ( geometry.boundingBox !== null ) {
  11049. if ( ray.intersectsBox( geometry.boundingBox ) === false ) return;
  11050. }
  11051. var uvs, intersection;
  11052. if ( (geometry && geometry.isBufferGeometry) ) {
  11053. var a, b, c;
  11054. var index = geometry.index;
  11055. var attributes = geometry.attributes;
  11056. var positions = attributes.position.array;
  11057. if ( attributes.uv !== undefined ) {
  11058. uvs = attributes.uv.array;
  11059. }
  11060. if ( index !== null ) {
  11061. var indices = index.array;
  11062. for ( var i = 0, l = indices.length; i < l; i += 3 ) {
  11063. a = indices[ i ];
  11064. b = indices[ i + 1 ];
  11065. c = indices[ i + 2 ];
  11066. intersection = checkBufferGeometryIntersection( this, raycaster, ray, positions, uvs, a, b, c );
  11067. if ( intersection ) {
  11068. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indices buffer semantics
  11069. intersects.push( intersection );
  11070. }
  11071. }
  11072. } else {
  11073. for ( var i = 0, l = positions.length; i < l; i += 9 ) {
  11074. a = i / 3;
  11075. b = a + 1;
  11076. c = a + 2;
  11077. intersection = checkBufferGeometryIntersection( this, raycaster, ray, positions, uvs, a, b, c );
  11078. if ( intersection ) {
  11079. intersection.index = a; // triangle number in positions buffer semantics
  11080. intersects.push( intersection );
  11081. }
  11082. }
  11083. }
  11084. } else if ( (geometry && geometry.isGeometry) ) {
  11085. var fvA, fvB, fvC;
  11086. var isFaceMaterial = (material && material.isMultiMaterial);
  11087. var materials = isFaceMaterial === true ? material.materials : null;
  11088. var vertices = geometry.vertices;
  11089. var faces = geometry.faces;
  11090. var faceVertexUvs = geometry.faceVertexUvs[ 0 ];
  11091. if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs;
  11092. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  11093. var face = faces[ f ];
  11094. var faceMaterial = isFaceMaterial === true ? materials[ face.materialIndex ] : material;
  11095. if ( faceMaterial === undefined ) continue;
  11096. fvA = vertices[ face.a ];
  11097. fvB = vertices[ face.b ];
  11098. fvC = vertices[ face.c ];
  11099. if ( faceMaterial.morphTargets === true ) {
  11100. var morphTargets = geometry.morphTargets;
  11101. var morphInfluences = this.morphTargetInfluences;
  11102. vA.set( 0, 0, 0 );
  11103. vB.set( 0, 0, 0 );
  11104. vC.set( 0, 0, 0 );
  11105. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  11106. var influence = morphInfluences[ t ];
  11107. if ( influence === 0 ) continue;
  11108. var targets = morphTargets[ t ].vertices;
  11109. vA.addScaledVector( tempA.subVectors( targets[ face.a ], fvA ), influence );
  11110. vB.addScaledVector( tempB.subVectors( targets[ face.b ], fvB ), influence );
  11111. vC.addScaledVector( tempC.subVectors( targets[ face.c ], fvC ), influence );
  11112. }
  11113. vA.add( fvA );
  11114. vB.add( fvB );
  11115. vC.add( fvC );
  11116. fvA = vA;
  11117. fvB = vB;
  11118. fvC = vC;
  11119. }
  11120. intersection = checkIntersection( this, raycaster, ray, fvA, fvB, fvC, intersectionPoint );
  11121. if ( intersection ) {
  11122. if ( uvs ) {
  11123. var uvs_f = uvs[ f ];
  11124. uvA.copy( uvs_f[ 0 ] );
  11125. uvB.copy( uvs_f[ 1 ] );
  11126. uvC.copy( uvs_f[ 2 ] );
  11127. intersection.uv = uvIntersection( intersectionPoint, fvA, fvB, fvC, uvA, uvB, uvC );
  11128. }
  11129. intersection.face = face;
  11130. intersection.faceIndex = f;
  11131. intersects.push( intersection );
  11132. }
  11133. }
  11134. }
  11135. };
  11136. }() ),
  11137. clone: function () {
  11138. return new this.constructor( this.geometry, this.material ).copy( this );
  11139. }
  11140. } );
  11141. /**
  11142. * @author mrdoob / http://mrdoob.com/
  11143. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  11144. */
  11145. function PlaneBufferGeometry( width, height, widthSegments, heightSegments ) {
  11146. BufferGeometry.call( this );
  11147. this.type = 'PlaneBufferGeometry';
  11148. this.parameters = {
  11149. width: width,
  11150. height: height,
  11151. widthSegments: widthSegments,
  11152. heightSegments: heightSegments
  11153. };
  11154. var width_half = width / 2;
  11155. var height_half = height / 2;
  11156. var gridX = Math.floor( widthSegments ) || 1;
  11157. var gridY = Math.floor( heightSegments ) || 1;
  11158. var gridX1 = gridX + 1;
  11159. var gridY1 = gridY + 1;
  11160. var segment_width = width / gridX;
  11161. var segment_height = height / gridY;
  11162. var vertices = new Float32Array( gridX1 * gridY1 * 3 );
  11163. var normals = new Float32Array( gridX1 * gridY1 * 3 );
  11164. var uvs = new Float32Array( gridX1 * gridY1 * 2 );
  11165. var offset = 0;
  11166. var offset2 = 0;
  11167. for ( var iy = 0; iy < gridY1; iy ++ ) {
  11168. var y = iy * segment_height - height_half;
  11169. for ( var ix = 0; ix < gridX1; ix ++ ) {
  11170. var x = ix * segment_width - width_half;
  11171. vertices[ offset ] = x;
  11172. vertices[ offset + 1 ] = - y;
  11173. normals[ offset + 2 ] = 1;
  11174. uvs[ offset2 ] = ix / gridX;
  11175. uvs[ offset2 + 1 ] = 1 - ( iy / gridY );
  11176. offset += 3;
  11177. offset2 += 2;
  11178. }
  11179. }
  11180. offset = 0;
  11181. var indices = new ( ( vertices.length / 3 ) > 65535 ? Uint32Array : Uint16Array )( gridX * gridY * 6 );
  11182. for ( var iy = 0; iy < gridY; iy ++ ) {
  11183. for ( var ix = 0; ix < gridX; ix ++ ) {
  11184. var a = ix + gridX1 * iy;
  11185. var b = ix + gridX1 * ( iy + 1 );
  11186. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  11187. var d = ( ix + 1 ) + gridX1 * iy;
  11188. indices[ offset ] = a;
  11189. indices[ offset + 1 ] = b;
  11190. indices[ offset + 2 ] = d;
  11191. indices[ offset + 3 ] = b;
  11192. indices[ offset + 4 ] = c;
  11193. indices[ offset + 5 ] = d;
  11194. offset += 6;
  11195. }
  11196. }
  11197. this.setIndex( new BufferAttribute( indices, 1 ) );
  11198. this.addAttribute( 'position', new BufferAttribute( vertices, 3 ) );
  11199. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) );
  11200. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) );
  11201. }
  11202. PlaneBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  11203. PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry;
  11204. /**
  11205. * @author mrdoob / http://mrdoob.com/
  11206. * @author mikael emtinger / http://gomo.se/
  11207. * @author WestLangley / http://github.com/WestLangley
  11208. */
  11209. function Camera() {
  11210. Object3D.call( this );
  11211. this.type = 'Camera';
  11212. this.matrixWorldInverse = new Matrix4();
  11213. this.projectionMatrix = new Matrix4();
  11214. }
  11215. Camera.prototype = Object.create( Object3D.prototype );
  11216. Camera.prototype.constructor = Camera;
  11217. Camera.prototype.isCamera = true;
  11218. Camera.prototype.getWorldDirection = function () {
  11219. var quaternion = new Quaternion();
  11220. return function getWorldDirection( optionalTarget ) {
  11221. var result = optionalTarget || new Vector3();
  11222. this.getWorldQuaternion( quaternion );
  11223. return result.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  11224. };
  11225. }();
  11226. Camera.prototype.lookAt = function () {
  11227. // This routine does not support cameras with rotated and/or translated parent(s)
  11228. var m1 = new Matrix4();
  11229. return function lookAt( vector ) {
  11230. m1.lookAt( this.position, vector, this.up );
  11231. this.quaternion.setFromRotationMatrix( m1 );
  11232. };
  11233. }();
  11234. Camera.prototype.clone = function () {
  11235. return new this.constructor().copy( this );
  11236. };
  11237. Camera.prototype.copy = function ( source ) {
  11238. Object3D.prototype.copy.call( this, source );
  11239. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  11240. this.projectionMatrix.copy( source.projectionMatrix );
  11241. return this;
  11242. };
  11243. /**
  11244. * @author mrdoob / http://mrdoob.com/
  11245. * @author greggman / http://games.greggman.com/
  11246. * @author zz85 / http://www.lab4games.net/zz85/blog
  11247. * @author tschw
  11248. */
  11249. function PerspectiveCamera( fov, aspect, near, far ) {
  11250. Camera.call( this );
  11251. this.type = 'PerspectiveCamera';
  11252. this.fov = fov !== undefined ? fov : 50;
  11253. this.zoom = 1;
  11254. this.near = near !== undefined ? near : 0.1;
  11255. this.far = far !== undefined ? far : 2000;
  11256. this.focus = 10;
  11257. this.aspect = aspect !== undefined ? aspect : 1;
  11258. this.view = null;
  11259. this.filmGauge = 35; // width of the film (default in millimeters)
  11260. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  11261. this.updateProjectionMatrix();
  11262. }
  11263. PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  11264. constructor: PerspectiveCamera,
  11265. isPerspectiveCamera: true,
  11266. copy: function ( source ) {
  11267. Camera.prototype.copy.call( this, source );
  11268. this.fov = source.fov;
  11269. this.zoom = source.zoom;
  11270. this.near = source.near;
  11271. this.far = source.far;
  11272. this.focus = source.focus;
  11273. this.aspect = source.aspect;
  11274. this.view = source.view === null ? null : Object.assign( {}, source.view );
  11275. this.filmGauge = source.filmGauge;
  11276. this.filmOffset = source.filmOffset;
  11277. return this;
  11278. },
  11279. /**
  11280. * Sets the FOV by focal length in respect to the current .filmGauge.
  11281. *
  11282. * The default film gauge is 35, so that the focal length can be specified for
  11283. * a 35mm (full frame) camera.
  11284. *
  11285. * Values for focal length and film gauge must have the same unit.
  11286. */
  11287. setFocalLength: function ( focalLength ) {
  11288. // see http://www.bobatkins.com/photography/technical/field_of_view.html
  11289. var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  11290. this.fov = exports.Math.RAD2DEG * 2 * Math.atan( vExtentSlope );
  11291. this.updateProjectionMatrix();
  11292. },
  11293. /**
  11294. * Calculates the focal length from the current .fov and .filmGauge.
  11295. */
  11296. getFocalLength: function () {
  11297. var vExtentSlope = Math.tan( exports.Math.DEG2RAD * 0.5 * this.fov );
  11298. return 0.5 * this.getFilmHeight() / vExtentSlope;
  11299. },
  11300. getEffectiveFOV: function () {
  11301. return exports.Math.RAD2DEG * 2 * Math.atan(
  11302. Math.tan( exports.Math.DEG2RAD * 0.5 * this.fov ) / this.zoom );
  11303. },
  11304. getFilmWidth: function () {
  11305. // film not completely covered in portrait format (aspect < 1)
  11306. return this.filmGauge * Math.min( this.aspect, 1 );
  11307. },
  11308. getFilmHeight: function () {
  11309. // film not completely covered in landscape format (aspect > 1)
  11310. return this.filmGauge / Math.max( this.aspect, 1 );
  11311. },
  11312. /**
  11313. * Sets an offset in a larger frustum. This is useful for multi-window or
  11314. * multi-monitor/multi-machine setups.
  11315. *
  11316. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  11317. * the monitors are in grid like this
  11318. *
  11319. * +---+---+---+
  11320. * | A | B | C |
  11321. * +---+---+---+
  11322. * | D | E | F |
  11323. * +---+---+---+
  11324. *
  11325. * then for each monitor you would call it like this
  11326. *
  11327. * var w = 1920;
  11328. * var h = 1080;
  11329. * var fullWidth = w * 3;
  11330. * var fullHeight = h * 2;
  11331. *
  11332. * --A--
  11333. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  11334. * --B--
  11335. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  11336. * --C--
  11337. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  11338. * --D--
  11339. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  11340. * --E--
  11341. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  11342. * --F--
  11343. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  11344. *
  11345. * Note there is no reason monitors have to be the same size or in a grid.
  11346. */
  11347. setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
  11348. this.aspect = fullWidth / fullHeight;
  11349. this.view = {
  11350. fullWidth: fullWidth,
  11351. fullHeight: fullHeight,
  11352. offsetX: x,
  11353. offsetY: y,
  11354. width: width,
  11355. height: height
  11356. };
  11357. this.updateProjectionMatrix();
  11358. },
  11359. clearViewOffset: function() {
  11360. this.view = null;
  11361. this.updateProjectionMatrix();
  11362. },
  11363. updateProjectionMatrix: function () {
  11364. var near = this.near,
  11365. top = near * Math.tan(
  11366. exports.Math.DEG2RAD * 0.5 * this.fov ) / this.zoom,
  11367. height = 2 * top,
  11368. width = this.aspect * height,
  11369. left = - 0.5 * width,
  11370. view = this.view;
  11371. if ( view !== null ) {
  11372. var fullWidth = view.fullWidth,
  11373. fullHeight = view.fullHeight;
  11374. left += view.offsetX * width / fullWidth;
  11375. top -= view.offsetY * height / fullHeight;
  11376. width *= view.width / fullWidth;
  11377. height *= view.height / fullHeight;
  11378. }
  11379. var skew = this.filmOffset;
  11380. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  11381. this.projectionMatrix.makeFrustum(
  11382. left, left + width, top - height, top, near, this.far );
  11383. },
  11384. toJSON: function ( meta ) {
  11385. var data = Object3D.prototype.toJSON.call( this, meta );
  11386. data.object.fov = this.fov;
  11387. data.object.zoom = this.zoom;
  11388. data.object.near = this.near;
  11389. data.object.far = this.far;
  11390. data.object.focus = this.focus;
  11391. data.object.aspect = this.aspect;
  11392. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  11393. data.object.filmGauge = this.filmGauge;
  11394. data.object.filmOffset = this.filmOffset;
  11395. return data;
  11396. }
  11397. } );
  11398. /**
  11399. * @author alteredq / http://alteredqualia.com/
  11400. * @author arose / http://github.com/arose
  11401. */
  11402. function OrthographicCamera( left, right, top, bottom, near, far ) {
  11403. Camera.call( this );
  11404. this.type = 'OrthographicCamera';
  11405. this.zoom = 1;
  11406. this.view = null;
  11407. this.left = left;
  11408. this.right = right;
  11409. this.top = top;
  11410. this.bottom = bottom;
  11411. this.near = ( near !== undefined ) ? near : 0.1;
  11412. this.far = ( far !== undefined ) ? far : 2000;
  11413. this.updateProjectionMatrix();
  11414. }
  11415. OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  11416. constructor: OrthographicCamera,
  11417. isOrthographicCamera: true,
  11418. copy: function ( source ) {
  11419. Camera.prototype.copy.call( this, source );
  11420. this.left = source.left;
  11421. this.right = source.right;
  11422. this.top = source.top;
  11423. this.bottom = source.bottom;
  11424. this.near = source.near;
  11425. this.far = source.far;
  11426. this.zoom = source.zoom;
  11427. this.view = source.view === null ? null : Object.assign( {}, source.view );
  11428. return this;
  11429. },
  11430. setViewOffset: function( fullWidth, fullHeight, x, y, width, height ) {
  11431. this.view = {
  11432. fullWidth: fullWidth,
  11433. fullHeight: fullHeight,
  11434. offsetX: x,
  11435. offsetY: y,
  11436. width: width,
  11437. height: height
  11438. };
  11439. this.updateProjectionMatrix();
  11440. },
  11441. clearViewOffset: function() {
  11442. this.view = null;
  11443. this.updateProjectionMatrix();
  11444. },
  11445. updateProjectionMatrix: function () {
  11446. var dx = ( this.right - this.left ) / ( 2 * this.zoom );
  11447. var dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  11448. var cx = ( this.right + this.left ) / 2;
  11449. var cy = ( this.top + this.bottom ) / 2;
  11450. var left = cx - dx;
  11451. var right = cx + dx;
  11452. var top = cy + dy;
  11453. var bottom = cy - dy;
  11454. if ( this.view !== null ) {
  11455. var zoomW = this.zoom / ( this.view.width / this.view.fullWidth );
  11456. var zoomH = this.zoom / ( this.view.height / this.view.fullHeight );
  11457. var scaleW = ( this.right - this.left ) / this.view.width;
  11458. var scaleH = ( this.top - this.bottom ) / this.view.height;
  11459. left += scaleW * ( this.view.offsetX / zoomW );
  11460. right = left + scaleW * ( this.view.width / zoomW );
  11461. top -= scaleH * ( this.view.offsetY / zoomH );
  11462. bottom = top - scaleH * ( this.view.height / zoomH );
  11463. }
  11464. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  11465. },
  11466. toJSON: function ( meta ) {
  11467. var data = Object3D.prototype.toJSON.call( this, meta );
  11468. data.object.zoom = this.zoom;
  11469. data.object.left = this.left;
  11470. data.object.right = this.right;
  11471. data.object.top = this.top;
  11472. data.object.bottom = this.bottom;
  11473. data.object.near = this.near;
  11474. data.object.far = this.far;
  11475. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  11476. return data;
  11477. }
  11478. } );
  11479. /**
  11480. * @author supereggbert / http://www.paulbrunt.co.uk/
  11481. * @author mrdoob / http://mrdoob.com/
  11482. * @author alteredq / http://alteredqualia.com/
  11483. * @author szimek / https://github.com/szimek/
  11484. * @author tschw
  11485. */
  11486. function WebGLRenderer( parameters ) {
  11487. console.log( 'THREE.WebGLRenderer', REVISION );
  11488. parameters = parameters || {};
  11489. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ),
  11490. _context = parameters.context !== undefined ? parameters.context : null,
  11491. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  11492. _depth = parameters.depth !== undefined ? parameters.depth : true,
  11493. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  11494. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  11495. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  11496. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false;
  11497. var lights = [];
  11498. var opaqueObjects = [];
  11499. var opaqueObjectsLastIndex = - 1;
  11500. var transparentObjects = [];
  11501. var transparentObjectsLastIndex = - 1;
  11502. var morphInfluences = new Float32Array( 8 );
  11503. var sprites = [];
  11504. var lensFlares = [];
  11505. // public properties
  11506. this.domElement = _canvas;
  11507. this.context = null;
  11508. // clearing
  11509. this.autoClear = true;
  11510. this.autoClearColor = true;
  11511. this.autoClearDepth = true;
  11512. this.autoClearStencil = true;
  11513. // scene graph
  11514. this.sortObjects = true;
  11515. // user-defined clipping
  11516. this.clippingPlanes = [];
  11517. this.localClippingEnabled = false;
  11518. // physically based shading
  11519. this.gammaFactor = 2.0; // for backwards compatibility
  11520. this.gammaInput = false;
  11521. this.gammaOutput = false;
  11522. // physical lights
  11523. this.physicallyCorrectLights = false;
  11524. // tone mapping
  11525. this.toneMapping = LinearToneMapping;
  11526. this.toneMappingExposure = 1.0;
  11527. this.toneMappingWhitePoint = 1.0;
  11528. // morphs
  11529. this.maxMorphTargets = 8;
  11530. this.maxMorphNormals = 4;
  11531. // internal properties
  11532. var _this = this,
  11533. // internal state cache
  11534. _currentProgram = null,
  11535. _currentRenderTarget = null,
  11536. _currentFramebuffer = null,
  11537. _currentMaterialId = - 1,
  11538. _currentGeometryProgram = '',
  11539. _currentCamera = null,
  11540. _currentScissor = new Vector4(),
  11541. _currentScissorTest = null,
  11542. _currentViewport = new Vector4(),
  11543. //
  11544. _usedTextureUnits = 0,
  11545. //
  11546. _clearColor = new Color( 0x000000 ),
  11547. _clearAlpha = 0,
  11548. _width = _canvas.width,
  11549. _height = _canvas.height,
  11550. _pixelRatio = 1,
  11551. _scissor = new Vector4( 0, 0, _width, _height ),
  11552. _scissorTest = false,
  11553. _viewport = new Vector4( 0, 0, _width, _height ),
  11554. // frustum
  11555. _frustum = new Frustum(),
  11556. // clipping
  11557. _clipping = new WebGLClipping(),
  11558. _clippingEnabled = false,
  11559. _localClippingEnabled = false,
  11560. _sphere = new Sphere(),
  11561. // camera matrices cache
  11562. _projScreenMatrix = new Matrix4(),
  11563. _vector3 = new Vector3(),
  11564. // light arrays cache
  11565. _lights = {
  11566. hash: '',
  11567. ambient: [ 0, 0, 0 ],
  11568. directional: [],
  11569. directionalShadowMap: [],
  11570. directionalShadowMatrix: [],
  11571. spot: [],
  11572. spotShadowMap: [],
  11573. spotShadowMatrix: [],
  11574. point: [],
  11575. pointShadowMap: [],
  11576. pointShadowMatrix: [],
  11577. hemi: [],
  11578. shadows: []
  11579. },
  11580. // info
  11581. _infoRender = {
  11582. calls: 0,
  11583. vertices: 0,
  11584. faces: 0,
  11585. points: 0
  11586. };
  11587. this.info = {
  11588. render: _infoRender,
  11589. memory: {
  11590. geometries: 0,
  11591. textures: 0
  11592. },
  11593. programs: null
  11594. };
  11595. // initialize
  11596. var _gl;
  11597. try {
  11598. var attributes = {
  11599. alpha: _alpha,
  11600. depth: _depth,
  11601. stencil: _stencil,
  11602. antialias: _antialias,
  11603. premultipliedAlpha: _premultipliedAlpha,
  11604. preserveDrawingBuffer: _preserveDrawingBuffer
  11605. };
  11606. _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  11607. if ( _gl === null ) {
  11608. if ( _canvas.getContext( 'webgl' ) !== null ) {
  11609. throw 'Error creating WebGL context with your selected attributes.';
  11610. } else {
  11611. throw 'Error creating WebGL context.';
  11612. }
  11613. }
  11614. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  11615. if ( _gl.getShaderPrecisionFormat === undefined ) {
  11616. _gl.getShaderPrecisionFormat = function () {
  11617. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  11618. };
  11619. }
  11620. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  11621. } catch ( error ) {
  11622. console.error( 'THREE.WebGLRenderer: ' + error );
  11623. }
  11624. var extensions = new WebGLExtensions( _gl );
  11625. extensions.get( 'WEBGL_depth_texture' );
  11626. extensions.get( 'OES_texture_float' );
  11627. extensions.get( 'OES_texture_float_linear' );
  11628. extensions.get( 'OES_texture_half_float' );
  11629. extensions.get( 'OES_texture_half_float_linear' );
  11630. extensions.get( 'OES_standard_derivatives' );
  11631. extensions.get( 'ANGLE_instanced_arrays' );
  11632. if ( extensions.get( 'OES_element_index_uint' ) ) {
  11633. BufferGeometry.MaxIndex = 4294967296;
  11634. }
  11635. var capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  11636. var state = new WebGLState( _gl, extensions, paramThreeToGL );
  11637. var properties = new WebGLProperties();
  11638. var textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, this.info );
  11639. var objects = new WebGLObjects( _gl, properties, this.info );
  11640. var programCache = new WebGLPrograms( this, capabilities );
  11641. var lightCache = new WebGLLights();
  11642. this.info.programs = programCache.programs;
  11643. var bufferRenderer = new WebGLBufferRenderer( _gl, extensions, _infoRender );
  11644. var indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, _infoRender );
  11645. //
  11646. var backgroundCamera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  11647. var backgroundCamera2 = new PerspectiveCamera();
  11648. var backgroundPlaneMesh = new Mesh(
  11649. new PlaneBufferGeometry( 2, 2 ),
  11650. new MeshBasicMaterial( { depthTest: false, depthWrite: false, fog: false } )
  11651. );
  11652. var backgroundBoxShader = exports.ShaderLib[ 'cube' ];
  11653. var backgroundBoxMesh = new Mesh(
  11654. new BoxBufferGeometry( 5, 5, 5 ),
  11655. new ShaderMaterial( {
  11656. uniforms: backgroundBoxShader.uniforms,
  11657. vertexShader: backgroundBoxShader.vertexShader,
  11658. fragmentShader: backgroundBoxShader.fragmentShader,
  11659. side: BackSide,
  11660. depthTest: false,
  11661. depthWrite: false,
  11662. fog: false
  11663. } )
  11664. );
  11665. //
  11666. function getTargetPixelRatio() {
  11667. return _currentRenderTarget === null ? _pixelRatio : 1;
  11668. }
  11669. function glClearColor( r, g, b, a ) {
  11670. if ( _premultipliedAlpha === true ) {
  11671. r *= a; g *= a; b *= a;
  11672. }
  11673. state.clearColor( r, g, b, a );
  11674. }
  11675. function setDefaultGLState() {
  11676. state.init();
  11677. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
  11678. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
  11679. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  11680. }
  11681. function resetGLState() {
  11682. _currentProgram = null;
  11683. _currentCamera = null;
  11684. _currentGeometryProgram = '';
  11685. _currentMaterialId = - 1;
  11686. state.reset();
  11687. }
  11688. setDefaultGLState();
  11689. this.context = _gl;
  11690. this.capabilities = capabilities;
  11691. this.extensions = extensions;
  11692. this.properties = properties;
  11693. this.state = state;
  11694. // shadow map
  11695. var shadowMap = new WebGLShadowMap( this, _lights, objects, capabilities );
  11696. this.shadowMap = shadowMap;
  11697. // Plugins
  11698. var spritePlugin = new SpritePlugin( this, sprites );
  11699. var lensFlarePlugin = new LensFlarePlugin( this, lensFlares );
  11700. // API
  11701. this.getContext = function () {
  11702. return _gl;
  11703. };
  11704. this.getContextAttributes = function () {
  11705. return _gl.getContextAttributes();
  11706. };
  11707. this.forceContextLoss = function () {
  11708. extensions.get( 'WEBGL_lose_context' ).loseContext();
  11709. };
  11710. this.getMaxAnisotropy = function () {
  11711. return capabilities.getMaxAnisotropy();
  11712. };
  11713. this.getPrecision = function () {
  11714. return capabilities.precision;
  11715. };
  11716. this.getPixelRatio = function () {
  11717. return _pixelRatio;
  11718. };
  11719. this.setPixelRatio = function ( value ) {
  11720. if ( value === undefined ) return;
  11721. _pixelRatio = value;
  11722. this.setSize( _viewport.z, _viewport.w, false );
  11723. };
  11724. this.getSize = function () {
  11725. return {
  11726. width: _width,
  11727. height: _height
  11728. };
  11729. };
  11730. this.setSize = function ( width, height, updateStyle ) {
  11731. _width = width;
  11732. _height = height;
  11733. _canvas.width = width * _pixelRatio;
  11734. _canvas.height = height * _pixelRatio;
  11735. if ( updateStyle !== false ) {
  11736. _canvas.style.width = width + 'px';
  11737. _canvas.style.height = height + 'px';
  11738. }
  11739. this.setViewport( 0, 0, width, height );
  11740. };
  11741. this.setViewport = function ( x, y, width, height ) {
  11742. state.viewport( _viewport.set( x, y, width, height ) );
  11743. };
  11744. this.setScissor = function ( x, y, width, height ) {
  11745. state.scissor( _scissor.set( x, y, width, height ) );
  11746. };
  11747. this.setScissorTest = function ( boolean ) {
  11748. state.setScissorTest( _scissorTest = boolean );
  11749. };
  11750. // Clearing
  11751. this.getClearColor = function () {
  11752. return _clearColor;
  11753. };
  11754. this.setClearColor = function ( color, alpha ) {
  11755. _clearColor.set( color );
  11756. _clearAlpha = alpha !== undefined ? alpha : 1;
  11757. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  11758. };
  11759. this.getClearAlpha = function () {
  11760. return _clearAlpha;
  11761. };
  11762. this.setClearAlpha = function ( alpha ) {
  11763. _clearAlpha = alpha;
  11764. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  11765. };
  11766. this.clear = function ( color, depth, stencil ) {
  11767. var bits = 0;
  11768. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  11769. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  11770. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  11771. _gl.clear( bits );
  11772. };
  11773. this.clearColor = function () {
  11774. this.clear( true, false, false );
  11775. };
  11776. this.clearDepth = function () {
  11777. this.clear( false, true, false );
  11778. };
  11779. this.clearStencil = function () {
  11780. this.clear( false, false, true );
  11781. };
  11782. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  11783. this.setRenderTarget( renderTarget );
  11784. this.clear( color, depth, stencil );
  11785. };
  11786. // Reset
  11787. this.resetGLState = resetGLState;
  11788. this.dispose = function() {
  11789. transparentObjects = [];
  11790. transparentObjectsLastIndex = -1;
  11791. opaqueObjects = [];
  11792. opaqueObjectsLastIndex = -1;
  11793. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  11794. };
  11795. // Events
  11796. function onContextLost( event ) {
  11797. event.preventDefault();
  11798. resetGLState();
  11799. setDefaultGLState();
  11800. properties.clear();
  11801. }
  11802. function onMaterialDispose( event ) {
  11803. var material = event.target;
  11804. material.removeEventListener( 'dispose', onMaterialDispose );
  11805. deallocateMaterial( material );
  11806. }
  11807. // Buffer deallocation
  11808. function deallocateMaterial( material ) {
  11809. releaseMaterialProgramReference( material );
  11810. properties.delete( material );
  11811. }
  11812. function releaseMaterialProgramReference( material ) {
  11813. var programInfo = properties.get( material ).program;
  11814. material.program = undefined;
  11815. if ( programInfo !== undefined ) {
  11816. programCache.releaseProgram( programInfo );
  11817. }
  11818. }
  11819. // Buffer rendering
  11820. this.renderBufferImmediate = function ( object, program, material ) {
  11821. state.initAttributes();
  11822. var buffers = properties.get( object );
  11823. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  11824. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  11825. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  11826. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  11827. var attributes = program.getAttributes();
  11828. if ( object.hasPositions ) {
  11829. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position );
  11830. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  11831. state.enableAttribute( attributes.position );
  11832. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11833. }
  11834. if ( object.hasNormals ) {
  11835. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal );
  11836. if ( material.type !== 'MeshPhongMaterial' && material.type !== 'MeshStandardMaterial' && material.type !== 'MeshPhysicalMaterial' && material.shading === FlatShading ) {
  11837. for ( var i = 0, l = object.count * 3; i < l; i += 9 ) {
  11838. var array = object.normalArray;
  11839. var nx = ( array[ i + 0 ] + array[ i + 3 ] + array[ i + 6 ] ) / 3;
  11840. var ny = ( array[ i + 1 ] + array[ i + 4 ] + array[ i + 7 ] ) / 3;
  11841. var nz = ( array[ i + 2 ] + array[ i + 5 ] + array[ i + 8 ] ) / 3;
  11842. array[ i + 0 ] = nx;
  11843. array[ i + 1 ] = ny;
  11844. array[ i + 2 ] = nz;
  11845. array[ i + 3 ] = nx;
  11846. array[ i + 4 ] = ny;
  11847. array[ i + 5 ] = nz;
  11848. array[ i + 6 ] = nx;
  11849. array[ i + 7 ] = ny;
  11850. array[ i + 8 ] = nz;
  11851. }
  11852. }
  11853. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  11854. state.enableAttribute( attributes.normal );
  11855. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  11856. }
  11857. if ( object.hasUvs && material.map ) {
  11858. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv );
  11859. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  11860. state.enableAttribute( attributes.uv );
  11861. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  11862. }
  11863. if ( object.hasColors && material.vertexColors !== NoColors ) {
  11864. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color );
  11865. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  11866. state.enableAttribute( attributes.color );
  11867. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  11868. }
  11869. state.disableUnusedAttributes();
  11870. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  11871. object.count = 0;
  11872. };
  11873. this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) {
  11874. setMaterial( material );
  11875. var program = setProgram( camera, fog, material, object );
  11876. var updateBuffers = false;
  11877. var geometryProgram = geometry.id + '_' + program.id + '_' + material.wireframe;
  11878. if ( geometryProgram !== _currentGeometryProgram ) {
  11879. _currentGeometryProgram = geometryProgram;
  11880. updateBuffers = true;
  11881. }
  11882. // morph targets
  11883. var morphTargetInfluences = object.morphTargetInfluences;
  11884. if ( morphTargetInfluences !== undefined ) {
  11885. var activeInfluences = [];
  11886. for ( var i = 0, l = morphTargetInfluences.length; i < l; i ++ ) {
  11887. var influence = morphTargetInfluences[ i ];
  11888. activeInfluences.push( [ influence, i ] );
  11889. }
  11890. activeInfluences.sort( absNumericalSort );
  11891. if ( activeInfluences.length > 8 ) {
  11892. activeInfluences.length = 8;
  11893. }
  11894. var morphAttributes = geometry.morphAttributes;
  11895. for ( var i = 0, l = activeInfluences.length; i < l; i ++ ) {
  11896. var influence = activeInfluences[ i ];
  11897. morphInfluences[ i ] = influence[ 0 ];
  11898. if ( influence[ 0 ] !== 0 ) {
  11899. var index = influence[ 1 ];
  11900. if ( material.morphTargets === true && morphAttributes.position ) geometry.addAttribute( 'morphTarget' + i, morphAttributes.position[ index ] );
  11901. if ( material.morphNormals === true && morphAttributes.normal ) geometry.addAttribute( 'morphNormal' + i, morphAttributes.normal[ index ] );
  11902. } else {
  11903. if ( material.morphTargets === true ) geometry.removeAttribute( 'morphTarget' + i );
  11904. if ( material.morphNormals === true ) geometry.removeAttribute( 'morphNormal' + i );
  11905. }
  11906. }
  11907. program.getUniforms().setValue(
  11908. _gl, 'morphTargetInfluences', morphInfluences );
  11909. updateBuffers = true;
  11910. }
  11911. //
  11912. var index = geometry.index;
  11913. var position = geometry.attributes.position;
  11914. if ( material.wireframe === true ) {
  11915. index = objects.getWireframeAttribute( geometry );
  11916. }
  11917. var renderer;
  11918. if ( index !== null ) {
  11919. renderer = indexedBufferRenderer;
  11920. renderer.setIndex( index );
  11921. } else {
  11922. renderer = bufferRenderer;
  11923. }
  11924. if ( updateBuffers ) {
  11925. setupVertexAttributes( material, program, geometry );
  11926. if ( index !== null ) {
  11927. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, objects.getAttributeBuffer( index ) );
  11928. }
  11929. }
  11930. //
  11931. var dataStart = 0;
  11932. var dataCount = Infinity;
  11933. if ( index !== null ) {
  11934. dataCount = index.count;
  11935. } else if ( position !== undefined ) {
  11936. dataCount = position.count;
  11937. }
  11938. var rangeStart = geometry.drawRange.start;
  11939. var rangeCount = geometry.drawRange.count;
  11940. var groupStart = group !== null ? group.start : 0;
  11941. var groupCount = group !== null ? group.count : Infinity;
  11942. var drawStart = Math.max( dataStart, rangeStart, groupStart );
  11943. var drawEnd = Math.min( dataStart + dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  11944. var drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  11945. //
  11946. if ( object && object.isMesh ) {
  11947. if ( material.wireframe === true ) {
  11948. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  11949. renderer.setMode( _gl.LINES );
  11950. } else {
  11951. switch ( object.drawMode ) {
  11952. case TrianglesDrawMode:
  11953. renderer.setMode( _gl.TRIANGLES );
  11954. break;
  11955. case TriangleStripDrawMode:
  11956. renderer.setMode( _gl.TRIANGLE_STRIP );
  11957. break;
  11958. case TriangleFanDrawMode:
  11959. renderer.setMode( _gl.TRIANGLE_FAN );
  11960. break;
  11961. }
  11962. }
  11963. } else if ( object && object.isLine ) {
  11964. var lineWidth = material.linewidth;
  11965. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  11966. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  11967. if ( object && object.isLineSegments ) {
  11968. renderer.setMode( _gl.LINES );
  11969. } else {
  11970. renderer.setMode( _gl.LINE_STRIP );
  11971. }
  11972. } else if ( object && object.isPoints ) {
  11973. renderer.setMode( _gl.POINTS );
  11974. }
  11975. if ( geometry && geometry.isInstancedBufferGeometry ) {
  11976. if ( geometry.maxInstancedCount > 0 ) {
  11977. renderer.renderInstances( geometry, drawStart, drawCount );
  11978. }
  11979. } else {
  11980. renderer.render( drawStart, drawCount );
  11981. }
  11982. };
  11983. function setupVertexAttributes( material, program, geometry, startIndex ) {
  11984. var extension;
  11985. if ( geometry && geometry.isInstancedBufferGeometry ) {
  11986. extension = extensions.get( 'ANGLE_instanced_arrays' );
  11987. if ( extension === null ) {
  11988. console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  11989. return;
  11990. }
  11991. }
  11992. if ( startIndex === undefined ) startIndex = 0;
  11993. state.initAttributes();
  11994. var geometryAttributes = geometry.attributes;
  11995. var programAttributes = program.getAttributes();
  11996. var materialDefaultAttributeValues = material.defaultAttributeValues;
  11997. for ( var name in programAttributes ) {
  11998. var programAttribute = programAttributes[ name ];
  11999. if ( programAttribute >= 0 ) {
  12000. var geometryAttribute = geometryAttributes[ name ];
  12001. if ( geometryAttribute !== undefined ) {
  12002. var type = _gl.FLOAT;
  12003. var array = geometryAttribute.array;
  12004. var normalized = geometryAttribute.normalized;
  12005. if ( array instanceof Float32Array ) {
  12006. type = _gl.FLOAT;
  12007. } else if ( array instanceof Float64Array ) {
  12008. console.warn( "Unsupported data buffer format: Float64Array" );
  12009. } else if ( array instanceof Uint16Array ) {
  12010. type = _gl.UNSIGNED_SHORT;
  12011. } else if ( array instanceof Int16Array ) {
  12012. type = _gl.SHORT;
  12013. } else if ( array instanceof Uint32Array ) {
  12014. type = _gl.UNSIGNED_INT;
  12015. } else if ( array instanceof Int32Array ) {
  12016. type = _gl.INT;
  12017. } else if ( array instanceof Int8Array ) {
  12018. type = _gl.BYTE;
  12019. } else if ( array instanceof Uint8Array ) {
  12020. type = _gl.UNSIGNED_BYTE;
  12021. }
  12022. var size = geometryAttribute.itemSize;
  12023. var buffer = objects.getAttributeBuffer( geometryAttribute );
  12024. if ( geometryAttribute && geometryAttribute.isInterleavedBufferAttribute ) {
  12025. var data = geometryAttribute.data;
  12026. var stride = data.stride;
  12027. var offset = geometryAttribute.offset;
  12028. if ( data && data.isInstancedInterleavedBuffer ) {
  12029. state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute, extension );
  12030. if ( geometry.maxInstancedCount === undefined ) {
  12031. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  12032. }
  12033. } else {
  12034. state.enableAttribute( programAttribute );
  12035. }
  12036. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  12037. _gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * data.array.BYTES_PER_ELEMENT, ( startIndex * stride + offset ) * data.array.BYTES_PER_ELEMENT );
  12038. } else {
  12039. if ( geometryAttribute && geometryAttribute.isInstancedBufferAttribute ) {
  12040. state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute, extension );
  12041. if ( geometry.maxInstancedCount === undefined ) {
  12042. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  12043. }
  12044. } else {
  12045. state.enableAttribute( programAttribute );
  12046. }
  12047. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  12048. _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, startIndex * size * geometryAttribute.array.BYTES_PER_ELEMENT );
  12049. }
  12050. } else if ( materialDefaultAttributeValues !== undefined ) {
  12051. var value = materialDefaultAttributeValues[ name ];
  12052. if ( value !== undefined ) {
  12053. switch ( value.length ) {
  12054. case 2:
  12055. _gl.vertexAttrib2fv( programAttribute, value );
  12056. break;
  12057. case 3:
  12058. _gl.vertexAttrib3fv( programAttribute, value );
  12059. break;
  12060. case 4:
  12061. _gl.vertexAttrib4fv( programAttribute, value );
  12062. break;
  12063. default:
  12064. _gl.vertexAttrib1fv( programAttribute, value );
  12065. }
  12066. }
  12067. }
  12068. }
  12069. }
  12070. state.disableUnusedAttributes();
  12071. }
  12072. // Sorting
  12073. function absNumericalSort( a, b ) {
  12074. return Math.abs( b[ 0 ] ) - Math.abs( a[ 0 ] );
  12075. }
  12076. function painterSortStable( a, b ) {
  12077. if ( a.object.renderOrder !== b.object.renderOrder ) {
  12078. return a.object.renderOrder - b.object.renderOrder;
  12079. } else if ( a.material.program && b.material.program && a.material.program !== b.material.program ) {
  12080. return a.material.program.id - b.material.program.id;
  12081. } else if ( a.material.id !== b.material.id ) {
  12082. return a.material.id - b.material.id;
  12083. } else if ( a.z !== b.z ) {
  12084. return a.z - b.z;
  12085. } else {
  12086. return a.id - b.id;
  12087. }
  12088. }
  12089. function reversePainterSortStable( a, b ) {
  12090. if ( a.object.renderOrder !== b.object.renderOrder ) {
  12091. return a.object.renderOrder - b.object.renderOrder;
  12092. } if ( a.z !== b.z ) {
  12093. return b.z - a.z;
  12094. } else {
  12095. return a.id - b.id;
  12096. }
  12097. }
  12098. // Rendering
  12099. this.render = function ( scene, camera, renderTarget, forceClear ) {
  12100. if ( ( camera && camera.isCamera ) === false ) {
  12101. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  12102. return;
  12103. }
  12104. var fog = scene.fog;
  12105. // reset caching for this frame
  12106. _currentGeometryProgram = '';
  12107. _currentMaterialId = - 1;
  12108. _currentCamera = null;
  12109. // update scene graph
  12110. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  12111. // update camera matrices and frustum
  12112. if ( camera.parent === null ) camera.updateMatrixWorld();
  12113. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  12114. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  12115. _frustum.setFromMatrix( _projScreenMatrix );
  12116. lights.length = 0;
  12117. opaqueObjectsLastIndex = - 1;
  12118. transparentObjectsLastIndex = - 1;
  12119. sprites.length = 0;
  12120. lensFlares.length = 0;
  12121. _localClippingEnabled = this.localClippingEnabled;
  12122. _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  12123. projectObject( scene, camera );
  12124. opaqueObjects.length = opaqueObjectsLastIndex + 1;
  12125. transparentObjects.length = transparentObjectsLastIndex + 1;
  12126. if ( _this.sortObjects === true ) {
  12127. opaqueObjects.sort( painterSortStable );
  12128. transparentObjects.sort( reversePainterSortStable );
  12129. }
  12130. //
  12131. if ( _clippingEnabled ) _clipping.beginShadows();
  12132. setupShadows( lights );
  12133. shadowMap.render( scene, camera );
  12134. setupLights( lights, camera );
  12135. if ( _clippingEnabled ) _clipping.endShadows();
  12136. //
  12137. _infoRender.calls = 0;
  12138. _infoRender.vertices = 0;
  12139. _infoRender.faces = 0;
  12140. _infoRender.points = 0;
  12141. if ( renderTarget === undefined ) {
  12142. renderTarget = null;
  12143. }
  12144. this.setRenderTarget( renderTarget );
  12145. //
  12146. var background = scene.background;
  12147. if ( background === null ) {
  12148. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  12149. } else if ( background && background.isColor ) {
  12150. glClearColor( background.r, background.g, background.b, 1 );
  12151. }
  12152. if ( this.autoClear || forceClear ) {
  12153. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  12154. }
  12155. if ( background && background.isCubeTexture ) {
  12156. backgroundCamera2.projectionMatrix.copy( camera.projectionMatrix );
  12157. backgroundCamera2.matrixWorld.extractRotation( camera.matrixWorld );
  12158. backgroundCamera2.matrixWorldInverse.getInverse( backgroundCamera2.matrixWorld );
  12159. backgroundBoxMesh.material.uniforms[ "tCube" ].value = background;
  12160. backgroundBoxMesh.modelViewMatrix.multiplyMatrices( backgroundCamera2.matrixWorldInverse, backgroundBoxMesh.matrixWorld );
  12161. objects.update( backgroundBoxMesh );
  12162. _this.renderBufferDirect( backgroundCamera2, null, backgroundBoxMesh.geometry, backgroundBoxMesh.material, backgroundBoxMesh, null );
  12163. } else if ( background && background.isTexture ) {
  12164. backgroundPlaneMesh.material.map = background;
  12165. objects.update( backgroundPlaneMesh );
  12166. _this.renderBufferDirect( backgroundCamera, null, backgroundPlaneMesh.geometry, backgroundPlaneMesh.material, backgroundPlaneMesh, null );
  12167. }
  12168. //
  12169. if ( scene.overrideMaterial ) {
  12170. var overrideMaterial = scene.overrideMaterial;
  12171. renderObjects( opaqueObjects, camera, fog, overrideMaterial );
  12172. renderObjects( transparentObjects, camera, fog, overrideMaterial );
  12173. } else {
  12174. // opaque pass (front-to-back order)
  12175. state.setBlending( NoBlending );
  12176. renderObjects( opaqueObjects, camera, fog );
  12177. // transparent pass (back-to-front order)
  12178. renderObjects( transparentObjects, camera, fog );
  12179. }
  12180. // custom render plugins (post pass)
  12181. spritePlugin.render( scene, camera );
  12182. lensFlarePlugin.render( scene, camera, _currentViewport );
  12183. // Generate mipmap if we're using any kind of mipmap filtering
  12184. if ( renderTarget ) {
  12185. textures.updateRenderTargetMipmap( renderTarget );
  12186. }
  12187. // Ensure depth buffer writing is enabled so it can be cleared on next render
  12188. state.setDepthTest( true );
  12189. state.setDepthWrite( true );
  12190. state.setColorWrite( true );
  12191. // _gl.finish();
  12192. };
  12193. function pushRenderItem( object, geometry, material, z, group ) {
  12194. var array, index;
  12195. // allocate the next position in the appropriate array
  12196. if ( material.transparent ) {
  12197. array = transparentObjects;
  12198. index = ++ transparentObjectsLastIndex;
  12199. } else {
  12200. array = opaqueObjects;
  12201. index = ++ opaqueObjectsLastIndex;
  12202. }
  12203. // recycle existing render item or grow the array
  12204. var renderItem = array[ index ];
  12205. if ( renderItem !== undefined ) {
  12206. renderItem.id = object.id;
  12207. renderItem.object = object;
  12208. renderItem.geometry = geometry;
  12209. renderItem.material = material;
  12210. renderItem.z = _vector3.z;
  12211. renderItem.group = group;
  12212. } else {
  12213. renderItem = {
  12214. id: object.id,
  12215. object: object,
  12216. geometry: geometry,
  12217. material: material,
  12218. z: _vector3.z,
  12219. group: group
  12220. };
  12221. // assert( index === array.length );
  12222. array.push( renderItem );
  12223. }
  12224. }
  12225. // TODO Duplicated code (Frustum)
  12226. function isObjectViewable( object ) {
  12227. var geometry = object.geometry;
  12228. if ( geometry.boundingSphere === null )
  12229. geometry.computeBoundingSphere();
  12230. _sphere.copy( geometry.boundingSphere ).
  12231. applyMatrix4( object.matrixWorld );
  12232. return isSphereViewable( _sphere );
  12233. }
  12234. function isSpriteViewable( sprite ) {
  12235. _sphere.center.set( 0, 0, 0 );
  12236. _sphere.radius = 0.7071067811865476;
  12237. _sphere.applyMatrix4( sprite.matrixWorld );
  12238. return isSphereViewable( _sphere );
  12239. }
  12240. function isSphereViewable( sphere ) {
  12241. if ( ! _frustum.intersectsSphere( sphere ) ) return false;
  12242. var numPlanes = _clipping.numPlanes;
  12243. if ( numPlanes === 0 ) return true;
  12244. var planes = _this.clippingPlanes,
  12245. center = sphere.center,
  12246. negRad = - sphere.radius,
  12247. i = 0;
  12248. do {
  12249. // out when deeper than radius in the negative halfspace
  12250. if ( planes[ i ].distanceToPoint( center ) < negRad ) return false;
  12251. } while ( ++ i !== numPlanes );
  12252. return true;
  12253. }
  12254. function projectObject( object, camera ) {
  12255. if ( object.visible === false ) return;
  12256. if ( object.layers.test( camera.layers ) ) {
  12257. if ( object && object.isLight ) {
  12258. lights.push( object );
  12259. } else if ( object && object.isSprite ) {
  12260. if ( object.frustumCulled === false || isSpriteViewable( object ) === true ) {
  12261. sprites.push( object );
  12262. }
  12263. } else if ( object && object.isLensFlare ) {
  12264. lensFlares.push( object );
  12265. } else if ( object && object.isImmediateRenderObject ) {
  12266. if ( _this.sortObjects === true ) {
  12267. _vector3.setFromMatrixPosition( object.matrixWorld );
  12268. _vector3.applyProjection( _projScreenMatrix );
  12269. }
  12270. pushRenderItem( object, null, object.material, _vector3.z, null );
  12271. } else if ( ( object && object.isMesh ) || ( object && object.isLine ) || ( object && object.isPoints ) ) {
  12272. if ( object && object.isSkinnedMesh ) {
  12273. object.skeleton.update();
  12274. }
  12275. if ( object.frustumCulled === false || isObjectViewable( object ) === true ) {
  12276. var material = object.material;
  12277. if ( material.visible === true ) {
  12278. if ( _this.sortObjects === true ) {
  12279. _vector3.setFromMatrixPosition( object.matrixWorld );
  12280. _vector3.applyProjection( _projScreenMatrix );
  12281. }
  12282. var geometry = objects.update( object );
  12283. if ( material && material.isMultiMaterial ) {
  12284. var groups = geometry.groups;
  12285. var materials = material.materials;
  12286. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  12287. var group = groups[ i ];
  12288. var groupMaterial = materials[ group.materialIndex ];
  12289. if ( groupMaterial.visible === true ) {
  12290. pushRenderItem( object, geometry, groupMaterial, _vector3.z, group );
  12291. }
  12292. }
  12293. } else {
  12294. pushRenderItem( object, geometry, material, _vector3.z, null );
  12295. }
  12296. }
  12297. }
  12298. }
  12299. }
  12300. var children = object.children;
  12301. for ( var i = 0, l = children.length; i < l; i ++ ) {
  12302. projectObject( children[ i ], camera );
  12303. }
  12304. }
  12305. function renderObjects( renderList, camera, fog, overrideMaterial ) {
  12306. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  12307. var renderItem = renderList[ i ];
  12308. var object = renderItem.object;
  12309. var geometry = renderItem.geometry;
  12310. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  12311. var group = renderItem.group;
  12312. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  12313. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  12314. if ( object && object.isImmediateRenderObject ) {
  12315. setMaterial( material );
  12316. var program = setProgram( camera, fog, material, object );
  12317. _currentGeometryProgram = '';
  12318. object.render( function ( object ) {
  12319. _this.renderBufferImmediate( object, program, material );
  12320. } );
  12321. } else {
  12322. _this.renderBufferDirect( camera, fog, geometry, material, object, group );
  12323. }
  12324. }
  12325. }
  12326. function initMaterial( material, fog, object ) {
  12327. var materialProperties = properties.get( material );
  12328. var parameters = programCache.getParameters(
  12329. material, _lights, fog, _clipping.numPlanes, object );
  12330. var code = programCache.getProgramCode( material, parameters );
  12331. var program = materialProperties.program;
  12332. var programChange = true;
  12333. if ( program === undefined ) {
  12334. // new material
  12335. material.addEventListener( 'dispose', onMaterialDispose );
  12336. } else if ( program.code !== code ) {
  12337. // changed glsl or parameters
  12338. releaseMaterialProgramReference( material );
  12339. } else if ( parameters.shaderID !== undefined ) {
  12340. // same glsl and uniform list
  12341. return;
  12342. } else {
  12343. // only rebuild uniform list
  12344. programChange = false;
  12345. }
  12346. if ( programChange ) {
  12347. if ( parameters.shaderID ) {
  12348. var shader = exports.ShaderLib[ parameters.shaderID ];
  12349. materialProperties.__webglShader = {
  12350. name: material.type,
  12351. uniforms: exports.UniformsUtils.clone( shader.uniforms ),
  12352. vertexShader: shader.vertexShader,
  12353. fragmentShader: shader.fragmentShader
  12354. };
  12355. } else {
  12356. materialProperties.__webglShader = {
  12357. name: material.type,
  12358. uniforms: material.uniforms,
  12359. vertexShader: material.vertexShader,
  12360. fragmentShader: material.fragmentShader
  12361. };
  12362. }
  12363. material.__webglShader = materialProperties.__webglShader;
  12364. program = programCache.acquireProgram( material, parameters, code );
  12365. materialProperties.program = program;
  12366. material.program = program;
  12367. }
  12368. var attributes = program.getAttributes();
  12369. if ( material.morphTargets ) {
  12370. material.numSupportedMorphTargets = 0;
  12371. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  12372. if ( attributes[ 'morphTarget' + i ] >= 0 ) {
  12373. material.numSupportedMorphTargets ++;
  12374. }
  12375. }
  12376. }
  12377. if ( material.morphNormals ) {
  12378. material.numSupportedMorphNormals = 0;
  12379. for ( var i = 0; i < _this.maxMorphNormals; i ++ ) {
  12380. if ( attributes[ 'morphNormal' + i ] >= 0 ) {
  12381. material.numSupportedMorphNormals ++;
  12382. }
  12383. }
  12384. }
  12385. var uniforms = materialProperties.__webglShader.uniforms;
  12386. if ( ! ( material && material.isShaderMaterial ) &&
  12387. ! ( material && material.isRawShaderMaterial ) ||
  12388. material.clipping === true ) {
  12389. materialProperties.numClippingPlanes = _clipping.numPlanes;
  12390. uniforms.clippingPlanes = _clipping.uniform;
  12391. }
  12392. if ( material.lights ) {
  12393. // store the light setup it was created for
  12394. materialProperties.lightsHash = _lights.hash;
  12395. // wire up the material to this renderer's lighting state
  12396. uniforms.ambientLightColor.value = _lights.ambient;
  12397. uniforms.directionalLights.value = _lights.directional;
  12398. uniforms.spotLights.value = _lights.spot;
  12399. uniforms.pointLights.value = _lights.point;
  12400. uniforms.hemisphereLights.value = _lights.hemi;
  12401. uniforms.directionalShadowMap.value = _lights.directionalShadowMap;
  12402. uniforms.directionalShadowMatrix.value = _lights.directionalShadowMatrix;
  12403. uniforms.spotShadowMap.value = _lights.spotShadowMap;
  12404. uniforms.spotShadowMatrix.value = _lights.spotShadowMatrix;
  12405. uniforms.pointShadowMap.value = _lights.pointShadowMap;
  12406. uniforms.pointShadowMatrix.value = _lights.pointShadowMatrix;
  12407. }
  12408. var progUniforms = materialProperties.program.getUniforms(),
  12409. uniformsList =
  12410. exports.WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  12411. materialProperties.uniformsList = uniformsList;
  12412. materialProperties.dynamicUniforms =
  12413. exports.WebGLUniforms.splitDynamic( uniformsList, uniforms );
  12414. }
  12415. function setMaterial( material ) {
  12416. if ( material.side !== DoubleSide )
  12417. state.enable( _gl.CULL_FACE );
  12418. else
  12419. state.disable( _gl.CULL_FACE );
  12420. state.setFlipSided( material.side === BackSide );
  12421. if ( material.transparent === true ) {
  12422. state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  12423. } else {
  12424. state.setBlending( NoBlending );
  12425. }
  12426. state.setDepthFunc( material.depthFunc );
  12427. state.setDepthTest( material.depthTest );
  12428. state.setDepthWrite( material.depthWrite );
  12429. state.setColorWrite( material.colorWrite );
  12430. state.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  12431. }
  12432. function setProgram( camera, fog, material, object ) {
  12433. _usedTextureUnits = 0;
  12434. var materialProperties = properties.get( material );
  12435. if ( _clippingEnabled ) {
  12436. if ( _localClippingEnabled || camera !== _currentCamera ) {
  12437. var useCache =
  12438. camera === _currentCamera &&
  12439. material.id === _currentMaterialId;
  12440. // we might want to call this function with some ClippingGroup
  12441. // object instead of the material, once it becomes feasible
  12442. // (#8465, #8379)
  12443. _clipping.setState(
  12444. material.clippingPlanes, material.clipShadows,
  12445. camera, materialProperties, useCache );
  12446. }
  12447. if ( materialProperties.numClippingPlanes !== undefined &&
  12448. materialProperties.numClippingPlanes !== _clipping.numPlanes ) {
  12449. material.needsUpdate = true;
  12450. }
  12451. }
  12452. if ( materialProperties.program === undefined ) {
  12453. material.needsUpdate = true;
  12454. }
  12455. if ( materialProperties.lightsHash !== undefined &&
  12456. materialProperties.lightsHash !== _lights.hash ) {
  12457. material.needsUpdate = true;
  12458. }
  12459. if ( material.needsUpdate ) {
  12460. initMaterial( material, fog, object );
  12461. material.needsUpdate = false;
  12462. }
  12463. var refreshProgram = false;
  12464. var refreshMaterial = false;
  12465. var refreshLights = false;
  12466. var program = materialProperties.program,
  12467. p_uniforms = program.getUniforms(),
  12468. m_uniforms = materialProperties.__webglShader.uniforms;
  12469. if ( program.id !== _currentProgram ) {
  12470. _gl.useProgram( program.program );
  12471. _currentProgram = program.id;
  12472. refreshProgram = true;
  12473. refreshMaterial = true;
  12474. refreshLights = true;
  12475. }
  12476. if ( material.id !== _currentMaterialId ) {
  12477. _currentMaterialId = material.id;
  12478. refreshMaterial = true;
  12479. }
  12480. if ( refreshProgram || camera !== _currentCamera ) {
  12481. p_uniforms.set( _gl, camera, 'projectionMatrix' );
  12482. if ( capabilities.logarithmicDepthBuffer ) {
  12483. p_uniforms.setValue( _gl, 'logDepthBufFC',
  12484. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  12485. }
  12486. if ( camera !== _currentCamera ) {
  12487. _currentCamera = camera;
  12488. // lighting uniforms depend on the camera so enforce an update
  12489. // now, in case this material supports lights - or later, when
  12490. // the next material that does gets activated:
  12491. refreshMaterial = true; // set to true on material change
  12492. refreshLights = true; // remains set until update done
  12493. }
  12494. // load material specific uniforms
  12495. // (shader material also gets them for the sake of genericity)
  12496. if ( ( material && material.isShaderMaterial ) ||
  12497. ( material && material.isMeshPhongMaterial ) ||
  12498. ( material && material.isMeshStandardMaterial ) ||
  12499. material.envMap ) {
  12500. var uCamPos = p_uniforms.map.cameraPosition;
  12501. if ( uCamPos !== undefined ) {
  12502. uCamPos.setValue( _gl,
  12503. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  12504. }
  12505. }
  12506. if ( ( material && material.isMeshPhongMaterial ) ||
  12507. ( material && material.isMeshLambertMaterial ) ||
  12508. ( material && material.isMeshBasicMaterial ) ||
  12509. ( material && material.isMeshStandardMaterial ) ||
  12510. ( material && material.isShaderMaterial ) ||
  12511. material.skinning ) {
  12512. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  12513. }
  12514. p_uniforms.set( _gl, _this, 'toneMappingExposure' );
  12515. p_uniforms.set( _gl, _this, 'toneMappingWhitePoint' );
  12516. }
  12517. // skinning uniforms must be set even if material didn't change
  12518. // auto-setting of texture unit for bone texture must go before other textures
  12519. // not sure why, but otherwise weird things happen
  12520. if ( material.skinning ) {
  12521. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  12522. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  12523. var skeleton = object.skeleton;
  12524. if ( skeleton ) {
  12525. if ( capabilities.floatVertexTextures && skeleton.useVertexTexture ) {
  12526. p_uniforms.set( _gl, skeleton, 'boneTexture' );
  12527. p_uniforms.set( _gl, skeleton, 'boneTextureWidth' );
  12528. p_uniforms.set( _gl, skeleton, 'boneTextureHeight' );
  12529. } else {
  12530. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  12531. }
  12532. }
  12533. }
  12534. if ( refreshMaterial ) {
  12535. if ( material.lights ) {
  12536. // the current material requires lighting info
  12537. // note: all lighting uniforms are always set correctly
  12538. // they simply reference the renderer's state for their
  12539. // values
  12540. //
  12541. // use the current material's .needsUpdate flags to set
  12542. // the GL state when required
  12543. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  12544. }
  12545. // refresh uniforms common to several materials
  12546. if ( fog && material.fog ) {
  12547. refreshUniformsFog( m_uniforms, fog );
  12548. }
  12549. if ( ( material && material.isMeshBasicMaterial ) ||
  12550. ( material && material.isMeshLambertMaterial ) ||
  12551. ( material && material.isMeshPhongMaterial ) ||
  12552. ( material && material.isMeshStandardMaterial ) ||
  12553. ( material && material.isMeshDepthMaterial ) ) {
  12554. refreshUniformsCommon( m_uniforms, material );
  12555. }
  12556. // refresh single material specific uniforms
  12557. if ( material && material.isLineBasicMaterial ) {
  12558. refreshUniformsLine( m_uniforms, material );
  12559. } else if ( material && material.isLineDashedMaterial ) {
  12560. refreshUniformsLine( m_uniforms, material );
  12561. refreshUniformsDash( m_uniforms, material );
  12562. } else if ( material && material.isPointsMaterial ) {
  12563. refreshUniformsPoints( m_uniforms, material );
  12564. } else if ( material && material.isMeshLambertMaterial ) {
  12565. refreshUniformsLambert( m_uniforms, material );
  12566. } else if ( material && material.isMeshPhongMaterial ) {
  12567. refreshUniformsPhong( m_uniforms, material );
  12568. } else if ( material && material.isMeshPhysicalMaterial ) {
  12569. refreshUniformsPhysical( m_uniforms, material );
  12570. } else if ( material && material.isMeshStandardMaterial ) {
  12571. refreshUniformsStandard( m_uniforms, material );
  12572. } else if ( material && material.isMeshDepthMaterial ) {
  12573. if ( material.displacementMap ) {
  12574. m_uniforms.displacementMap.value = material.displacementMap;
  12575. m_uniforms.displacementScale.value = material.displacementScale;
  12576. m_uniforms.displacementBias.value = material.displacementBias;
  12577. }
  12578. } else if ( material && material.isMeshNormalMaterial ) {
  12579. m_uniforms.opacity.value = material.opacity;
  12580. }
  12581. exports.WebGLUniforms.upload(
  12582. _gl, materialProperties.uniformsList, m_uniforms, _this );
  12583. }
  12584. // common matrices
  12585. p_uniforms.set( _gl, object, 'modelViewMatrix' );
  12586. p_uniforms.set( _gl, object, 'normalMatrix' );
  12587. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  12588. // dynamic uniforms
  12589. var dynUniforms = materialProperties.dynamicUniforms;
  12590. if ( dynUniforms !== null ) {
  12591. exports.WebGLUniforms.evalDynamic(
  12592. dynUniforms, m_uniforms, object, camera );
  12593. exports.WebGLUniforms.upload( _gl, dynUniforms, m_uniforms, _this );
  12594. }
  12595. return program;
  12596. }
  12597. // Uniforms (refresh uniforms objects)
  12598. function refreshUniformsCommon( uniforms, material ) {
  12599. uniforms.opacity.value = material.opacity;
  12600. uniforms.diffuse.value = material.color;
  12601. if ( material.emissive ) {
  12602. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  12603. }
  12604. uniforms.map.value = material.map;
  12605. uniforms.specularMap.value = material.specularMap;
  12606. uniforms.alphaMap.value = material.alphaMap;
  12607. if ( material.aoMap ) {
  12608. uniforms.aoMap.value = material.aoMap;
  12609. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  12610. }
  12611. // uv repeat and offset setting priorities
  12612. // 1. color map
  12613. // 2. specular map
  12614. // 3. normal map
  12615. // 4. bump map
  12616. // 5. alpha map
  12617. // 6. emissive map
  12618. var uvScaleMap;
  12619. if ( material.map ) {
  12620. uvScaleMap = material.map;
  12621. } else if ( material.specularMap ) {
  12622. uvScaleMap = material.specularMap;
  12623. } else if ( material.displacementMap ) {
  12624. uvScaleMap = material.displacementMap;
  12625. } else if ( material.normalMap ) {
  12626. uvScaleMap = material.normalMap;
  12627. } else if ( material.bumpMap ) {
  12628. uvScaleMap = material.bumpMap;
  12629. } else if ( material.roughnessMap ) {
  12630. uvScaleMap = material.roughnessMap;
  12631. } else if ( material.metalnessMap ) {
  12632. uvScaleMap = material.metalnessMap;
  12633. } else if ( material.alphaMap ) {
  12634. uvScaleMap = material.alphaMap;
  12635. } else if ( material.emissiveMap ) {
  12636. uvScaleMap = material.emissiveMap;
  12637. }
  12638. if ( uvScaleMap !== undefined ) {
  12639. // backwards compatibility
  12640. if ( (uvScaleMap && uvScaleMap.isWebGLRenderTarget) ) {
  12641. uvScaleMap = uvScaleMap.texture;
  12642. }
  12643. var offset = uvScaleMap.offset;
  12644. var repeat = uvScaleMap.repeat;
  12645. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  12646. }
  12647. uniforms.envMap.value = material.envMap;
  12648. // don't flip CubeTexture envMaps, flip everything else:
  12649. // WebGLRenderTargetCube will be flipped for backwards compatibility
  12650. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  12651. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  12652. uniforms.flipEnvMap.value = ( ! ( material.envMap && material.envMap.isCubeTexture ) ) ? 1 : - 1;
  12653. uniforms.reflectivity.value = material.reflectivity;
  12654. uniforms.refractionRatio.value = material.refractionRatio;
  12655. }
  12656. function refreshUniformsLine( uniforms, material ) {
  12657. uniforms.diffuse.value = material.color;
  12658. uniforms.opacity.value = material.opacity;
  12659. }
  12660. function refreshUniformsDash( uniforms, material ) {
  12661. uniforms.dashSize.value = material.dashSize;
  12662. uniforms.totalSize.value = material.dashSize + material.gapSize;
  12663. uniforms.scale.value = material.scale;
  12664. }
  12665. function refreshUniformsPoints( uniforms, material ) {
  12666. uniforms.diffuse.value = material.color;
  12667. uniforms.opacity.value = material.opacity;
  12668. uniforms.size.value = material.size * _pixelRatio;
  12669. uniforms.scale.value = _canvas.clientHeight * 0.5;
  12670. uniforms.map.value = material.map;
  12671. if ( material.map !== null ) {
  12672. var offset = material.map.offset;
  12673. var repeat = material.map.repeat;
  12674. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  12675. }
  12676. }
  12677. function refreshUniformsFog( uniforms, fog ) {
  12678. uniforms.fogColor.value = fog.color;
  12679. if ( fog && fog.isFog ) {
  12680. uniforms.fogNear.value = fog.near;
  12681. uniforms.fogFar.value = fog.far;
  12682. } else if ( fog && fog.isFogExp2 ) {
  12683. uniforms.fogDensity.value = fog.density;
  12684. }
  12685. }
  12686. function refreshUniformsLambert( uniforms, material ) {
  12687. if ( material.lightMap ) {
  12688. uniforms.lightMap.value = material.lightMap;
  12689. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  12690. }
  12691. if ( material.emissiveMap ) {
  12692. uniforms.emissiveMap.value = material.emissiveMap;
  12693. }
  12694. }
  12695. function refreshUniformsPhong( uniforms, material ) {
  12696. uniforms.specular.value = material.specular;
  12697. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  12698. if ( material.lightMap ) {
  12699. uniforms.lightMap.value = material.lightMap;
  12700. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  12701. }
  12702. if ( material.emissiveMap ) {
  12703. uniforms.emissiveMap.value = material.emissiveMap;
  12704. }
  12705. if ( material.bumpMap ) {
  12706. uniforms.bumpMap.value = material.bumpMap;
  12707. uniforms.bumpScale.value = material.bumpScale;
  12708. }
  12709. if ( material.normalMap ) {
  12710. uniforms.normalMap.value = material.normalMap;
  12711. uniforms.normalScale.value.copy( material.normalScale );
  12712. }
  12713. if ( material.displacementMap ) {
  12714. uniforms.displacementMap.value = material.displacementMap;
  12715. uniforms.displacementScale.value = material.displacementScale;
  12716. uniforms.displacementBias.value = material.displacementBias;
  12717. }
  12718. }
  12719. function refreshUniformsStandard( uniforms, material ) {
  12720. uniforms.roughness.value = material.roughness;
  12721. uniforms.metalness.value = material.metalness;
  12722. if ( material.roughnessMap ) {
  12723. uniforms.roughnessMap.value = material.roughnessMap;
  12724. }
  12725. if ( material.metalnessMap ) {
  12726. uniforms.metalnessMap.value = material.metalnessMap;
  12727. }
  12728. if ( material.lightMap ) {
  12729. uniforms.lightMap.value = material.lightMap;
  12730. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  12731. }
  12732. if ( material.emissiveMap ) {
  12733. uniforms.emissiveMap.value = material.emissiveMap;
  12734. }
  12735. if ( material.bumpMap ) {
  12736. uniforms.bumpMap.value = material.bumpMap;
  12737. uniforms.bumpScale.value = material.bumpScale;
  12738. }
  12739. if ( material.normalMap ) {
  12740. uniforms.normalMap.value = material.normalMap;
  12741. uniforms.normalScale.value.copy( material.normalScale );
  12742. }
  12743. if ( material.displacementMap ) {
  12744. uniforms.displacementMap.value = material.displacementMap;
  12745. uniforms.displacementScale.value = material.displacementScale;
  12746. uniforms.displacementBias.value = material.displacementBias;
  12747. }
  12748. if ( material.envMap ) {
  12749. //uniforms.envMap.value = material.envMap; // part of uniforms common
  12750. uniforms.envMapIntensity.value = material.envMapIntensity;
  12751. }
  12752. }
  12753. function refreshUniformsPhysical( uniforms, material ) {
  12754. uniforms.clearCoat.value = material.clearCoat;
  12755. uniforms.clearCoatRoughness.value = material.clearCoatRoughness;
  12756. refreshUniformsStandard( uniforms, material );
  12757. }
  12758. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  12759. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  12760. uniforms.ambientLightColor.needsUpdate = value;
  12761. uniforms.directionalLights.needsUpdate = value;
  12762. uniforms.pointLights.needsUpdate = value;
  12763. uniforms.spotLights.needsUpdate = value;
  12764. uniforms.hemisphereLights.needsUpdate = value;
  12765. }
  12766. // Lighting
  12767. function setupShadows( lights ) {
  12768. var lightShadowsLength = 0;
  12769. for ( var i = 0, l = lights.length; i < l; i ++ ) {
  12770. var light = lights[ i ];
  12771. if ( light.castShadow ) {
  12772. _lights.shadows[ lightShadowsLength ++ ] = light;
  12773. }
  12774. }
  12775. _lights.shadows.length = lightShadowsLength;
  12776. }
  12777. function setupLights( lights, camera ) {
  12778. var l, ll, light,
  12779. r = 0, g = 0, b = 0,
  12780. color,
  12781. intensity,
  12782. distance,
  12783. shadowMap,
  12784. viewMatrix = camera.matrixWorldInverse,
  12785. directionalLength = 0,
  12786. pointLength = 0,
  12787. spotLength = 0,
  12788. hemiLength = 0;
  12789. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  12790. light = lights[ l ];
  12791. color = light.color;
  12792. intensity = light.intensity;
  12793. distance = light.distance;
  12794. shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  12795. if ( light && light.isAmbientLight ) {
  12796. r += color.r * intensity;
  12797. g += color.g * intensity;
  12798. b += color.b * intensity;
  12799. } else if ( light && light.isDirectionalLight ) {
  12800. var uniforms = lightCache.get( light );
  12801. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  12802. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12803. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  12804. uniforms.direction.sub( _vector3 );
  12805. uniforms.direction.transformDirection( viewMatrix );
  12806. uniforms.shadow = light.castShadow;
  12807. if ( light.castShadow ) {
  12808. uniforms.shadowBias = light.shadow.bias;
  12809. uniforms.shadowRadius = light.shadow.radius;
  12810. uniforms.shadowMapSize = light.shadow.mapSize;
  12811. }
  12812. _lights.directionalShadowMap[ directionalLength ] = shadowMap;
  12813. _lights.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  12814. _lights.directional[ directionalLength ++ ] = uniforms;
  12815. } else if ( light && light.isSpotLight ) {
  12816. var uniforms = lightCache.get( light );
  12817. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12818. uniforms.position.applyMatrix4( viewMatrix );
  12819. uniforms.color.copy( color ).multiplyScalar( intensity );
  12820. uniforms.distance = distance;
  12821. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12822. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  12823. uniforms.direction.sub( _vector3 );
  12824. uniforms.direction.transformDirection( viewMatrix );
  12825. uniforms.coneCos = Math.cos( light.angle );
  12826. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  12827. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  12828. uniforms.shadow = light.castShadow;
  12829. if ( light.castShadow ) {
  12830. uniforms.shadowBias = light.shadow.bias;
  12831. uniforms.shadowRadius = light.shadow.radius;
  12832. uniforms.shadowMapSize = light.shadow.mapSize;
  12833. }
  12834. _lights.spotShadowMap[ spotLength ] = shadowMap;
  12835. _lights.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  12836. _lights.spot[ spotLength ++ ] = uniforms;
  12837. } else if ( light && light.isPointLight ) {
  12838. var uniforms = lightCache.get( light );
  12839. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12840. uniforms.position.applyMatrix4( viewMatrix );
  12841. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  12842. uniforms.distance = light.distance;
  12843. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  12844. uniforms.shadow = light.castShadow;
  12845. if ( light.castShadow ) {
  12846. uniforms.shadowBias = light.shadow.bias;
  12847. uniforms.shadowRadius = light.shadow.radius;
  12848. uniforms.shadowMapSize = light.shadow.mapSize;
  12849. }
  12850. _lights.pointShadowMap[ pointLength ] = shadowMap;
  12851. if ( _lights.pointShadowMatrix[ pointLength ] === undefined ) {
  12852. _lights.pointShadowMatrix[ pointLength ] = new Matrix4();
  12853. }
  12854. // for point lights we set the shadow matrix to be a translation-only matrix
  12855. // equal to inverse of the light's position
  12856. _vector3.setFromMatrixPosition( light.matrixWorld ).negate();
  12857. _lights.pointShadowMatrix[ pointLength ].identity().setPosition( _vector3 );
  12858. _lights.point[ pointLength ++ ] = uniforms;
  12859. } else if ( light && light.isHemisphereLight ) {
  12860. var uniforms = lightCache.get( light );
  12861. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12862. uniforms.direction.transformDirection( viewMatrix );
  12863. uniforms.direction.normalize();
  12864. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  12865. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  12866. _lights.hemi[ hemiLength ++ ] = uniforms;
  12867. }
  12868. }
  12869. _lights.ambient[ 0 ] = r;
  12870. _lights.ambient[ 1 ] = g;
  12871. _lights.ambient[ 2 ] = b;
  12872. _lights.directional.length = directionalLength;
  12873. _lights.spot.length = spotLength;
  12874. _lights.point.length = pointLength;
  12875. _lights.hemi.length = hemiLength;
  12876. _lights.hash = directionalLength + ',' + pointLength + ',' + spotLength + ',' + hemiLength + ',' + _lights.shadows.length;
  12877. }
  12878. // GL state setting
  12879. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  12880. state.setCullFace( cullFace );
  12881. state.setFlipSided( frontFaceDirection === FrontFaceDirectionCW );
  12882. };
  12883. // Textures
  12884. function allocTextureUnit() {
  12885. var textureUnit = _usedTextureUnits;
  12886. if ( textureUnit >= capabilities.maxTextures ) {
  12887. console.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  12888. }
  12889. _usedTextureUnits += 1;
  12890. return textureUnit;
  12891. }
  12892. this.allocTextureUnit = allocTextureUnit;
  12893. // this.setTexture2D = setTexture2D;
  12894. this.setTexture2D = ( function() {
  12895. var warned = false;
  12896. // backwards compatibility: peel texture.texture
  12897. return function setTexture2D( texture, slot ) {
  12898. if ( texture && texture.isWebGLRenderTarget ) {
  12899. if ( ! warned ) {
  12900. console.warn( "THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead." );
  12901. warned = true;
  12902. }
  12903. texture = texture.texture;
  12904. }
  12905. textures.setTexture2D( texture, slot );
  12906. };
  12907. }() );
  12908. this.setTexture = ( function() {
  12909. var warned = false;
  12910. return function setTexture( texture, slot ) {
  12911. if ( ! warned ) {
  12912. console.warn( "THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead." );
  12913. warned = true;
  12914. }
  12915. textures.setTexture2D( texture, slot );
  12916. };
  12917. }() );
  12918. this.setTextureCube = ( function() {
  12919. var warned = false;
  12920. return function setTextureCube( texture, slot ) {
  12921. // backwards compatibility: peel texture.texture
  12922. if ( texture && texture.isWebGLRenderTargetCube ) {
  12923. if ( ! warned ) {
  12924. console.warn( "THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead." );
  12925. warned = true;
  12926. }
  12927. texture = texture.texture;
  12928. }
  12929. // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture
  12930. // TODO: unify these code paths
  12931. if ( ( texture && texture.isCubeTexture ) ||
  12932. ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {
  12933. // CompressedTexture can have Array in image :/
  12934. // this function alone should take care of cube textures
  12935. textures.setTextureCube( texture, slot );
  12936. } else {
  12937. // assumed: texture property of THREE.WebGLRenderTargetCube
  12938. textures.setTextureCubeDynamic( texture, slot );
  12939. }
  12940. };
  12941. }() );
  12942. this.getCurrentRenderTarget = function() {
  12943. return _currentRenderTarget;
  12944. };
  12945. this.setRenderTarget = function ( renderTarget ) {
  12946. _currentRenderTarget = renderTarget;
  12947. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  12948. textures.setupRenderTarget( renderTarget );
  12949. }
  12950. var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube );
  12951. var framebuffer;
  12952. if ( renderTarget ) {
  12953. var renderTargetProperties = properties.get( renderTarget );
  12954. if ( isCube ) {
  12955. framebuffer = renderTargetProperties.__webglFramebuffer[ renderTarget.activeCubeFace ];
  12956. } else {
  12957. framebuffer = renderTargetProperties.__webglFramebuffer;
  12958. }
  12959. _currentScissor.copy( renderTarget.scissor );
  12960. _currentScissorTest = renderTarget.scissorTest;
  12961. _currentViewport.copy( renderTarget.viewport );
  12962. } else {
  12963. framebuffer = null;
  12964. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio );
  12965. _currentScissorTest = _scissorTest;
  12966. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio );
  12967. }
  12968. if ( _currentFramebuffer !== framebuffer ) {
  12969. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  12970. _currentFramebuffer = framebuffer;
  12971. }
  12972. state.scissor( _currentScissor );
  12973. state.setScissorTest( _currentScissorTest );
  12974. state.viewport( _currentViewport );
  12975. if ( isCube ) {
  12976. var textureProperties = properties.get( renderTarget.texture );
  12977. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, renderTarget.activeMipMapLevel );
  12978. }
  12979. };
  12980. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) {
  12981. if ( ( renderTarget && renderTarget.isWebGLRenderTarget ) === false ) {
  12982. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  12983. return;
  12984. }
  12985. var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  12986. if ( framebuffer ) {
  12987. var restore = false;
  12988. if ( framebuffer !== _currentFramebuffer ) {
  12989. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  12990. restore = true;
  12991. }
  12992. try {
  12993. var texture = renderTarget.texture;
  12994. if ( texture.format !== RGBAFormat && paramThreeToGL( texture.format ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  12995. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  12996. return;
  12997. }
  12998. if ( texture.type !== UnsignedByteType &&
  12999. paramThreeToGL( texture.type ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) &&
  13000. ! ( texture.type === FloatType && extensions.get( 'WEBGL_color_buffer_float' ) ) &&
  13001. ! ( texture.type === HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) {
  13002. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  13003. return;
  13004. }
  13005. if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
  13006. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  13007. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  13008. _gl.readPixels( x, y, width, height, paramThreeToGL( texture.format ), paramThreeToGL( texture.type ), buffer );
  13009. }
  13010. } else {
  13011. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  13012. }
  13013. } finally {
  13014. if ( restore ) {
  13015. _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
  13016. }
  13017. }
  13018. }
  13019. };
  13020. // Map three.js constants to WebGL constants
  13021. function paramThreeToGL( p ) {
  13022. var extension;
  13023. if ( p === RepeatWrapping ) return _gl.REPEAT;
  13024. if ( p === ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  13025. if ( p === MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  13026. if ( p === NearestFilter ) return _gl.NEAREST;
  13027. if ( p === NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  13028. if ( p === NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  13029. if ( p === LinearFilter ) return _gl.LINEAR;
  13030. if ( p === LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  13031. if ( p === LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  13032. if ( p === UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  13033. if ( p === UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  13034. if ( p === UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  13035. if ( p === UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  13036. if ( p === ByteType ) return _gl.BYTE;
  13037. if ( p === ShortType ) return _gl.SHORT;
  13038. if ( p === UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  13039. if ( p === IntType ) return _gl.INT;
  13040. if ( p === UnsignedIntType ) return _gl.UNSIGNED_INT;
  13041. if ( p === FloatType ) return _gl.FLOAT;
  13042. extension = extensions.get( 'OES_texture_half_float' );
  13043. if ( extension !== null ) {
  13044. if ( p === HalfFloatType ) return extension.HALF_FLOAT_OES;
  13045. }
  13046. if ( p === AlphaFormat ) return _gl.ALPHA;
  13047. if ( p === RGBFormat ) return _gl.RGB;
  13048. if ( p === RGBAFormat ) return _gl.RGBA;
  13049. if ( p === LuminanceFormat ) return _gl.LUMINANCE;
  13050. if ( p === LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  13051. if ( p === DepthFormat ) return _gl.DEPTH_COMPONENT;
  13052. if ( p === DepthStencilFormat ) return _gl.DEPTH_STENCIL;
  13053. if ( p === AddEquation ) return _gl.FUNC_ADD;
  13054. if ( p === SubtractEquation ) return _gl.FUNC_SUBTRACT;
  13055. if ( p === ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  13056. if ( p === ZeroFactor ) return _gl.ZERO;
  13057. if ( p === OneFactor ) return _gl.ONE;
  13058. if ( p === SrcColorFactor ) return _gl.SRC_COLOR;
  13059. if ( p === OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  13060. if ( p === SrcAlphaFactor ) return _gl.SRC_ALPHA;
  13061. if ( p === OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  13062. if ( p === DstAlphaFactor ) return _gl.DST_ALPHA;
  13063. if ( p === OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  13064. if ( p === DstColorFactor ) return _gl.DST_COLOR;
  13065. if ( p === OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  13066. if ( p === SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  13067. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  13068. if ( extension !== null ) {
  13069. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  13070. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  13071. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  13072. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  13073. }
  13074. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  13075. if ( extension !== null ) {
  13076. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  13077. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  13078. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  13079. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  13080. }
  13081. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  13082. if ( extension !== null ) {
  13083. if ( p === RGB_ETC1_Format ) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  13084. }
  13085. extension = extensions.get( 'EXT_blend_minmax' );
  13086. if ( extension !== null ) {
  13087. if ( p === MinEquation ) return extension.MIN_EXT;
  13088. if ( p === MaxEquation ) return extension.MAX_EXT;
  13089. }
  13090. extension = extensions.get( 'WEBGL_depth_texture' );
  13091. if ( extension !== null ){
  13092. if ( p === THREE.UnsignedInt248Type ) return extension.UNSIGNED_INT_24_8_WEBGL;
  13093. }
  13094. return 0;
  13095. }
  13096. }
  13097. /**
  13098. * @author mrdoob / http://mrdoob.com/
  13099. * @author alteredq / http://alteredqualia.com/
  13100. */
  13101. function FogExp2 ( color, density ) {
  13102. this.name = '';
  13103. this.color = new Color( color );
  13104. this.density = ( density !== undefined ) ? density : 0.00025;
  13105. }
  13106. FogExp2.prototype.isFogExp2 = true;
  13107. FogExp2.prototype.clone = function () {
  13108. return new FogExp2( this.color.getHex(), this.density );
  13109. };
  13110. FogExp2.prototype.toJSON = function ( meta ) {
  13111. return {
  13112. type: 'FogExp2',
  13113. color: this.color.getHex(),
  13114. density: this.density
  13115. };
  13116. };
  13117. /**
  13118. * @author mrdoob / http://mrdoob.com/
  13119. * @author alteredq / http://alteredqualia.com/
  13120. */
  13121. function Fog ( color, near, far ) {
  13122. this.name = '';
  13123. this.color = new Color( color );
  13124. this.near = ( near !== undefined ) ? near : 1;
  13125. this.far = ( far !== undefined ) ? far : 1000;
  13126. }
  13127. Fog.prototype.isFog = true;
  13128. Fog.prototype.clone = function () {
  13129. return new Fog( this.color.getHex(), this.near, this.far );
  13130. };
  13131. Fog.prototype.toJSON = function ( meta ) {
  13132. return {
  13133. type: 'Fog',
  13134. color: this.color.getHex(),
  13135. near: this.near,
  13136. far: this.far
  13137. };
  13138. };
  13139. /**
  13140. * @author mrdoob / http://mrdoob.com/
  13141. */
  13142. function Scene () {
  13143. Object3D.call( this );
  13144. this.type = 'Scene';
  13145. this.background = null;
  13146. this.fog = null;
  13147. this.overrideMaterial = null;
  13148. this.autoUpdate = true; // checked by the renderer
  13149. }
  13150. Scene.prototype = Object.create( Object3D.prototype );
  13151. Scene.prototype.constructor = Scene;
  13152. Scene.prototype.copy = function ( source, recursive ) {
  13153. Object3D.prototype.copy.call( this, source, recursive );
  13154. if ( source.background !== null ) this.background = source.background.clone();
  13155. if ( source.fog !== null ) this.fog = source.fog.clone();
  13156. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  13157. this.autoUpdate = source.autoUpdate;
  13158. this.matrixAutoUpdate = source.matrixAutoUpdate;
  13159. return this;
  13160. };
  13161. Scene.prototype.toJSON = function ( meta ) {
  13162. var data = Object3D.prototype.toJSON.call( this, meta );
  13163. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  13164. return data;
  13165. };
  13166. /**
  13167. * @author mikael emtinger / http://gomo.se/
  13168. * @author alteredq / http://alteredqualia.com/
  13169. */
  13170. function LensFlare( texture, size, distance, blending, color ) {
  13171. Object3D.call( this );
  13172. this.lensFlares = [];
  13173. this.positionScreen = new Vector3();
  13174. this.customUpdateCallback = undefined;
  13175. if ( texture !== undefined ) {
  13176. this.add( texture, size, distance, blending, color );
  13177. }
  13178. }
  13179. LensFlare.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13180. constructor: LensFlare,
  13181. isLensFlare: true,
  13182. copy: function ( source ) {
  13183. Object3D.prototype.copy.call( this, source );
  13184. this.positionScreen.copy( source.positionScreen );
  13185. this.customUpdateCallback = source.customUpdateCallback;
  13186. for ( var i = 0, l = source.lensFlares.length; i < l; i ++ ) {
  13187. this.lensFlares.push( source.lensFlares[ i ] );
  13188. }
  13189. return this;
  13190. },
  13191. add: function ( texture, size, distance, blending, color, opacity ) {
  13192. if ( size === undefined ) size = - 1;
  13193. if ( distance === undefined ) distance = 0;
  13194. if ( opacity === undefined ) opacity = 1;
  13195. if ( color === undefined ) color = new Color( 0xffffff );
  13196. if ( blending === undefined ) blending = NormalBlending;
  13197. distance = Math.min( distance, Math.max( 0, distance ) );
  13198. this.lensFlares.push( {
  13199. texture: texture, // THREE.Texture
  13200. size: size, // size in pixels (-1 = use texture.width)
  13201. distance: distance, // distance (0-1) from light source (0=at light source)
  13202. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is in front z = 1 is back
  13203. scale: 1, // scale
  13204. rotation: 0, // rotation
  13205. opacity: opacity, // opacity
  13206. color: color, // color
  13207. blending: blending // blending
  13208. } );
  13209. },
  13210. /*
  13211. * Update lens flares update positions on all flares based on the screen position
  13212. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  13213. */
  13214. updateLensFlares: function () {
  13215. var f, fl = this.lensFlares.length;
  13216. var flare;
  13217. var vecX = - this.positionScreen.x * 2;
  13218. var vecY = - this.positionScreen.y * 2;
  13219. for ( f = 0; f < fl; f ++ ) {
  13220. flare = this.lensFlares[ f ];
  13221. flare.x = this.positionScreen.x + vecX * flare.distance;
  13222. flare.y = this.positionScreen.y + vecY * flare.distance;
  13223. flare.wantedRotation = flare.x * Math.PI * 0.25;
  13224. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  13225. }
  13226. }
  13227. } );
  13228. /**
  13229. * @author alteredq / http://alteredqualia.com/
  13230. *
  13231. * parameters = {
  13232. * color: <hex>,
  13233. * opacity: <float>,
  13234. * map: new THREE.Texture( <Image> ),
  13235. *
  13236. * uvOffset: new THREE.Vector2(),
  13237. * uvScale: new THREE.Vector2()
  13238. * }
  13239. */
  13240. function SpriteMaterial( parameters ) {
  13241. Material.call( this );
  13242. this.type = 'SpriteMaterial';
  13243. this.color = new Color( 0xffffff );
  13244. this.map = null;
  13245. this.rotation = 0;
  13246. this.fog = false;
  13247. this.lights = false;
  13248. this.setValues( parameters );
  13249. }
  13250. SpriteMaterial.prototype = Object.create( Material.prototype );
  13251. SpriteMaterial.prototype.constructor = SpriteMaterial;
  13252. SpriteMaterial.prototype.copy = function ( source ) {
  13253. Material.prototype.copy.call( this, source );
  13254. this.color.copy( source.color );
  13255. this.map = source.map;
  13256. this.rotation = source.rotation;
  13257. return this;
  13258. };
  13259. /**
  13260. * @author mikael emtinger / http://gomo.se/
  13261. * @author alteredq / http://alteredqualia.com/
  13262. */
  13263. function Sprite( material ) {
  13264. Object3D.call( this );
  13265. this.type = 'Sprite';
  13266. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  13267. }
  13268. Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13269. constructor: Sprite,
  13270. isSprite: true,
  13271. raycast: ( function () {
  13272. var matrixPosition = new Vector3();
  13273. return function raycast( raycaster, intersects ) {
  13274. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  13275. var distanceSq = raycaster.ray.distanceSqToPoint( matrixPosition );
  13276. var guessSizeSq = this.scale.x * this.scale.y / 4;
  13277. if ( distanceSq > guessSizeSq ) {
  13278. return;
  13279. }
  13280. intersects.push( {
  13281. distance: Math.sqrt( distanceSq ),
  13282. point: this.position,
  13283. face: null,
  13284. object: this
  13285. } );
  13286. };
  13287. }() ),
  13288. clone: function () {
  13289. return new this.constructor( this.material ).copy( this );
  13290. }
  13291. } );
  13292. /**
  13293. * @author mikael emtinger / http://gomo.se/
  13294. * @author alteredq / http://alteredqualia.com/
  13295. * @author mrdoob / http://mrdoob.com/
  13296. */
  13297. function LOD() {
  13298. Object3D.call( this );
  13299. this.type = 'LOD';
  13300. Object.defineProperties( this, {
  13301. levels: {
  13302. enumerable: true,
  13303. value: []
  13304. }
  13305. } );
  13306. }
  13307. LOD.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13308. constructor: LOD,
  13309. copy: function ( source ) {
  13310. Object3D.prototype.copy.call( this, source, false );
  13311. var levels = source.levels;
  13312. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  13313. var level = levels[ i ];
  13314. this.addLevel( level.object.clone(), level.distance );
  13315. }
  13316. return this;
  13317. },
  13318. addLevel: function ( object, distance ) {
  13319. if ( distance === undefined ) distance = 0;
  13320. distance = Math.abs( distance );
  13321. var levels = this.levels;
  13322. for ( var l = 0; l < levels.length; l ++ ) {
  13323. if ( distance < levels[ l ].distance ) {
  13324. break;
  13325. }
  13326. }
  13327. levels.splice( l, 0, { distance: distance, object: object } );
  13328. this.add( object );
  13329. },
  13330. getObjectForDistance: function ( distance ) {
  13331. var levels = this.levels;
  13332. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  13333. if ( distance < levels[ i ].distance ) {
  13334. break;
  13335. }
  13336. }
  13337. return levels[ i - 1 ].object;
  13338. },
  13339. raycast: ( function () {
  13340. var matrixPosition = new Vector3();
  13341. return function raycast( raycaster, intersects ) {
  13342. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  13343. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  13344. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  13345. };
  13346. }() ),
  13347. update: function () {
  13348. var v1 = new Vector3();
  13349. var v2 = new Vector3();
  13350. return function update( camera ) {
  13351. var levels = this.levels;
  13352. if ( levels.length > 1 ) {
  13353. v1.setFromMatrixPosition( camera.matrixWorld );
  13354. v2.setFromMatrixPosition( this.matrixWorld );
  13355. var distance = v1.distanceTo( v2 );
  13356. levels[ 0 ].object.visible = true;
  13357. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  13358. if ( distance >= levels[ i ].distance ) {
  13359. levels[ i - 1 ].object.visible = false;
  13360. levels[ i ].object.visible = true;
  13361. } else {
  13362. break;
  13363. }
  13364. }
  13365. for ( ; i < l; i ++ ) {
  13366. levels[ i ].object.visible = false;
  13367. }
  13368. }
  13369. };
  13370. }(),
  13371. toJSON: function ( meta ) {
  13372. var data = Object3D.prototype.toJSON.call( this, meta );
  13373. data.object.levels = [];
  13374. var levels = this.levels;
  13375. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  13376. var level = levels[ i ];
  13377. data.object.levels.push( {
  13378. object: level.object.uuid,
  13379. distance: level.distance
  13380. } );
  13381. }
  13382. return data;
  13383. }
  13384. } );
  13385. /**
  13386. * @author alteredq / http://alteredqualia.com/
  13387. */
  13388. function DataTexture( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  13389. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  13390. this.image = { data: data, width: width, height: height };
  13391. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  13392. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  13393. this.flipY = false;
  13394. this.generateMipmaps = false;
  13395. }
  13396. DataTexture.prototype = Object.create( Texture.prototype );
  13397. DataTexture.prototype.constructor = DataTexture;
  13398. DataTexture.prototype.isDataTexture = true;
  13399. /**
  13400. * @author mikael emtinger / http://gomo.se/
  13401. * @author alteredq / http://alteredqualia.com/
  13402. * @author michael guerrero / http://realitymeltdown.com
  13403. * @author ikerr / http://verold.com
  13404. */
  13405. function Skeleton( bones, boneInverses, useVertexTexture ) {
  13406. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  13407. this.identityMatrix = new Matrix4();
  13408. // copy the bone array
  13409. bones = bones || [];
  13410. this.bones = bones.slice( 0 );
  13411. // create a bone texture or an array of floats
  13412. if ( this.useVertexTexture ) {
  13413. // layout (1 matrix = 4 pixels)
  13414. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  13415. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  13416. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  13417. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  13418. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  13419. var size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  13420. size = exports.Math.nextPowerOfTwo( Math.ceil( size ) );
  13421. size = Math.max( size, 4 );
  13422. this.boneTextureWidth = size;
  13423. this.boneTextureHeight = size;
  13424. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  13425. this.boneTexture = new DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, RGBAFormat, FloatType );
  13426. } else {
  13427. this.boneMatrices = new Float32Array( 16 * this.bones.length );
  13428. }
  13429. // use the supplied bone inverses or calculate the inverses
  13430. if ( boneInverses === undefined ) {
  13431. this.calculateInverses();
  13432. } else {
  13433. if ( this.bones.length === boneInverses.length ) {
  13434. this.boneInverses = boneInverses.slice( 0 );
  13435. } else {
  13436. console.warn( 'THREE.Skeleton bonInverses is the wrong length.' );
  13437. this.boneInverses = [];
  13438. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13439. this.boneInverses.push( new Matrix4() );
  13440. }
  13441. }
  13442. }
  13443. }
  13444. Object.assign( Skeleton.prototype, {
  13445. calculateInverses: function () {
  13446. this.boneInverses = [];
  13447. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13448. var inverse = new Matrix4();
  13449. if ( this.bones[ b ] ) {
  13450. inverse.getInverse( this.bones[ b ].matrixWorld );
  13451. }
  13452. this.boneInverses.push( inverse );
  13453. }
  13454. },
  13455. pose: function () {
  13456. var bone;
  13457. // recover the bind-time world matrices
  13458. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13459. bone = this.bones[ b ];
  13460. if ( bone ) {
  13461. bone.matrixWorld.getInverse( this.boneInverses[ b ] );
  13462. }
  13463. }
  13464. // compute the local matrices, positions, rotations and scales
  13465. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13466. bone = this.bones[ b ];
  13467. if ( bone ) {
  13468. if ( (bone.parent && bone.parent.isBone) ) {
  13469. bone.matrix.getInverse( bone.parent.matrixWorld );
  13470. bone.matrix.multiply( bone.matrixWorld );
  13471. } else {
  13472. bone.matrix.copy( bone.matrixWorld );
  13473. }
  13474. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  13475. }
  13476. }
  13477. },
  13478. update: ( function () {
  13479. var offsetMatrix = new Matrix4();
  13480. return function update() {
  13481. // flatten bone matrices to array
  13482. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13483. // compute the offset between the current and the original transform
  13484. var matrix = this.bones[ b ] ? this.bones[ b ].matrixWorld : this.identityMatrix;
  13485. offsetMatrix.multiplyMatrices( matrix, this.boneInverses[ b ] );
  13486. offsetMatrix.toArray( this.boneMatrices, b * 16 );
  13487. }
  13488. if ( this.useVertexTexture ) {
  13489. this.boneTexture.needsUpdate = true;
  13490. }
  13491. };
  13492. } )(),
  13493. clone: function () {
  13494. return new Skeleton( this.bones, this.boneInverses, this.useVertexTexture );
  13495. }
  13496. } );
  13497. /**
  13498. * @author mikael emtinger / http://gomo.se/
  13499. * @author alteredq / http://alteredqualia.com/
  13500. * @author ikerr / http://verold.com
  13501. */
  13502. function Bone( skin ) {
  13503. Object3D.call( this );
  13504. this.type = 'Bone';
  13505. this.skin = skin;
  13506. }
  13507. Bone.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13508. constructor: Bone,
  13509. isBone: true,
  13510. copy: function ( source ) {
  13511. Object3D.prototype.copy.call( this, source );
  13512. this.skin = source.skin;
  13513. return this;
  13514. }
  13515. } );
  13516. /**
  13517. * @author mikael emtinger / http://gomo.se/
  13518. * @author alteredq / http://alteredqualia.com/
  13519. * @author ikerr / http://verold.com
  13520. */
  13521. function SkinnedMesh( geometry, material, useVertexTexture ) {
  13522. Mesh.call( this, geometry, material );
  13523. this.type = 'SkinnedMesh';
  13524. this.bindMode = "attached";
  13525. this.bindMatrix = new Matrix4();
  13526. this.bindMatrixInverse = new Matrix4();
  13527. // init bones
  13528. // TODO: remove bone creation as there is no reason (other than
  13529. // convenience) for THREE.SkinnedMesh to do this.
  13530. var bones = [];
  13531. if ( this.geometry && this.geometry.bones !== undefined ) {
  13532. var bone, gbone;
  13533. for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {
  13534. gbone = this.geometry.bones[ b ];
  13535. bone = new Bone( this );
  13536. bones.push( bone );
  13537. bone.name = gbone.name;
  13538. bone.position.fromArray( gbone.pos );
  13539. bone.quaternion.fromArray( gbone.rotq );
  13540. if ( gbone.scl !== undefined ) bone.scale.fromArray( gbone.scl );
  13541. }
  13542. for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {
  13543. gbone = this.geometry.bones[ b ];
  13544. if ( gbone.parent !== - 1 && gbone.parent !== null &&
  13545. bones[ gbone.parent ] !== undefined ) {
  13546. bones[ gbone.parent ].add( bones[ b ] );
  13547. } else {
  13548. this.add( bones[ b ] );
  13549. }
  13550. }
  13551. }
  13552. this.normalizeSkinWeights();
  13553. this.updateMatrixWorld( true );
  13554. this.bind( new Skeleton( bones, undefined, useVertexTexture ), this.matrixWorld );
  13555. }
  13556. SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {
  13557. constructor: SkinnedMesh,
  13558. isSkinnedMesh: true,
  13559. bind: function( skeleton, bindMatrix ) {
  13560. this.skeleton = skeleton;
  13561. if ( bindMatrix === undefined ) {
  13562. this.updateMatrixWorld( true );
  13563. this.skeleton.calculateInverses();
  13564. bindMatrix = this.matrixWorld;
  13565. }
  13566. this.bindMatrix.copy( bindMatrix );
  13567. this.bindMatrixInverse.getInverse( bindMatrix );
  13568. },
  13569. pose: function () {
  13570. this.skeleton.pose();
  13571. },
  13572. normalizeSkinWeights: function () {
  13573. if ( (this.geometry && this.geometry.isGeometry) ) {
  13574. for ( var i = 0; i < this.geometry.skinWeights.length; i ++ ) {
  13575. var sw = this.geometry.skinWeights[ i ];
  13576. var scale = 1.0 / sw.lengthManhattan();
  13577. if ( scale !== Infinity ) {
  13578. sw.multiplyScalar( scale );
  13579. } else {
  13580. sw.set( 1, 0, 0, 0 ); // do something reasonable
  13581. }
  13582. }
  13583. } else if ( (this.geometry && this.geometry.isBufferGeometry) ) {
  13584. var vec = new Vector4();
  13585. var skinWeight = this.geometry.attributes.skinWeight;
  13586. for ( var i = 0; i < skinWeight.count; i ++ ) {
  13587. vec.x = skinWeight.getX( i );
  13588. vec.y = skinWeight.getY( i );
  13589. vec.z = skinWeight.getZ( i );
  13590. vec.w = skinWeight.getW( i );
  13591. var scale = 1.0 / vec.lengthManhattan();
  13592. if ( scale !== Infinity ) {
  13593. vec.multiplyScalar( scale );
  13594. } else {
  13595. vec.set( 1, 0, 0, 0 ); // do something reasonable
  13596. }
  13597. skinWeight.setXYZW( i, vec.x, vec.y, vec.z, vec.w );
  13598. }
  13599. }
  13600. },
  13601. updateMatrixWorld: function( force ) {
  13602. Mesh.prototype.updateMatrixWorld.call( this, true );
  13603. if ( this.bindMode === "attached" ) {
  13604. this.bindMatrixInverse.getInverse( this.matrixWorld );
  13605. } else if ( this.bindMode === "detached" ) {
  13606. this.bindMatrixInverse.getInverse( this.bindMatrix );
  13607. } else {
  13608. console.warn( 'THREE.SkinnedMesh unrecognized bindMode: ' + this.bindMode );
  13609. }
  13610. },
  13611. clone: function() {
  13612. return new this.constructor( this.geometry, this.material, this.skeleton.useVertexTexture ).copy( this );
  13613. }
  13614. } );
  13615. /**
  13616. * @author mrdoob / http://mrdoob.com/
  13617. * @author alteredq / http://alteredqualia.com/
  13618. *
  13619. * parameters = {
  13620. * color: <hex>,
  13621. * opacity: <float>,
  13622. *
  13623. * linewidth: <float>,
  13624. * linecap: "round",
  13625. * linejoin: "round"
  13626. * }
  13627. */
  13628. function LineBasicMaterial( parameters ) {
  13629. Material.call( this );
  13630. this.type = 'LineBasicMaterial';
  13631. this.color = new Color( 0xffffff );
  13632. this.linewidth = 1;
  13633. this.linecap = 'round';
  13634. this.linejoin = 'round';
  13635. this.lights = false;
  13636. this.setValues( parameters );
  13637. }
  13638. LineBasicMaterial.prototype = Object.create( Material.prototype );
  13639. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  13640. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  13641. LineBasicMaterial.prototype.copy = function ( source ) {
  13642. Material.prototype.copy.call( this, source );
  13643. this.color.copy( source.color );
  13644. this.linewidth = source.linewidth;
  13645. this.linecap = source.linecap;
  13646. this.linejoin = source.linejoin;
  13647. return this;
  13648. };
  13649. /**
  13650. * @author mrdoob / http://mrdoob.com/
  13651. */
  13652. function Line( geometry, material, mode ) {
  13653. if ( mode === 1 ) {
  13654. console.warn( 'THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead.' );
  13655. return new LineSegments( geometry, material );
  13656. }
  13657. Object3D.call( this );
  13658. this.type = 'Line';
  13659. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  13660. this.material = material !== undefined ? material : new LineBasicMaterial( { color: Math.random() * 0xffffff } );
  13661. }
  13662. Line.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13663. constructor: Line,
  13664. isLine: true,
  13665. raycast: ( function () {
  13666. var inverseMatrix = new Matrix4();
  13667. var ray = new Ray();
  13668. var sphere = new Sphere();
  13669. return function raycast( raycaster, intersects ) {
  13670. var precision = raycaster.linePrecision;
  13671. var precisionSq = precision * precision;
  13672. var geometry = this.geometry;
  13673. var matrixWorld = this.matrixWorld;
  13674. // Checking boundingSphere distance to ray
  13675. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  13676. sphere.copy( geometry.boundingSphere );
  13677. sphere.applyMatrix4( matrixWorld );
  13678. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  13679. //
  13680. inverseMatrix.getInverse( matrixWorld );
  13681. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  13682. var vStart = new Vector3();
  13683. var vEnd = new Vector3();
  13684. var interSegment = new Vector3();
  13685. var interRay = new Vector3();
  13686. var step = (this && this.isLineSegments) ? 2 : 1;
  13687. if ( (geometry && geometry.isBufferGeometry) ) {
  13688. var index = geometry.index;
  13689. var attributes = geometry.attributes;
  13690. var positions = attributes.position.array;
  13691. if ( index !== null ) {
  13692. var indices = index.array;
  13693. for ( var i = 0, l = indices.length - 1; i < l; i += step ) {
  13694. var a = indices[ i ];
  13695. var b = indices[ i + 1 ];
  13696. vStart.fromArray( positions, a * 3 );
  13697. vEnd.fromArray( positions, b * 3 );
  13698. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  13699. if ( distSq > precisionSq ) continue;
  13700. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  13701. var distance = raycaster.ray.origin.distanceTo( interRay );
  13702. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  13703. intersects.push( {
  13704. distance: distance,
  13705. // What do we want? intersection point on the ray or on the segment??
  13706. // point: raycaster.ray.at( distance ),
  13707. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  13708. index: i,
  13709. face: null,
  13710. faceIndex: null,
  13711. object: this
  13712. } );
  13713. }
  13714. } else {
  13715. for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) {
  13716. vStart.fromArray( positions, 3 * i );
  13717. vEnd.fromArray( positions, 3 * i + 3 );
  13718. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  13719. if ( distSq > precisionSq ) continue;
  13720. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  13721. var distance = raycaster.ray.origin.distanceTo( interRay );
  13722. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  13723. intersects.push( {
  13724. distance: distance,
  13725. // What do we want? intersection point on the ray or on the segment??
  13726. // point: raycaster.ray.at( distance ),
  13727. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  13728. index: i,
  13729. face: null,
  13730. faceIndex: null,
  13731. object: this
  13732. } );
  13733. }
  13734. }
  13735. } else if ( (geometry && geometry.isGeometry) ) {
  13736. var vertices = geometry.vertices;
  13737. var nbVertices = vertices.length;
  13738. for ( var i = 0; i < nbVertices - 1; i += step ) {
  13739. var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  13740. if ( distSq > precisionSq ) continue;
  13741. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  13742. var distance = raycaster.ray.origin.distanceTo( interRay );
  13743. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  13744. intersects.push( {
  13745. distance: distance,
  13746. // What do we want? intersection point on the ray or on the segment??
  13747. // point: raycaster.ray.at( distance ),
  13748. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  13749. index: i,
  13750. face: null,
  13751. faceIndex: null,
  13752. object: this
  13753. } );
  13754. }
  13755. }
  13756. };
  13757. }() ),
  13758. clone: function () {
  13759. return new this.constructor( this.geometry, this.material ).copy( this );
  13760. }
  13761. } );
  13762. /**
  13763. * @author mrdoob / http://mrdoob.com/
  13764. */
  13765. function LineSegments( geometry, material ) {
  13766. Line.call( this, geometry, material );
  13767. this.type = 'LineSegments';
  13768. }
  13769. LineSegments.prototype = Object.assign( Object.create( Line.prototype ), {
  13770. constructor: LineSegments,
  13771. isLineSegments: true
  13772. } );
  13773. /**
  13774. * @author mrdoob / http://mrdoob.com/
  13775. * @author alteredq / http://alteredqualia.com/
  13776. *
  13777. * parameters = {
  13778. * color: <hex>,
  13779. * opacity: <float>,
  13780. * map: new THREE.Texture( <Image> ),
  13781. *
  13782. * size: <float>,
  13783. * sizeAttenuation: <bool>
  13784. * }
  13785. */
  13786. function PointsMaterial( parameters ) {
  13787. Material.call( this );
  13788. this.type = 'PointsMaterial';
  13789. this.color = new Color( 0xffffff );
  13790. this.map = null;
  13791. this.size = 1;
  13792. this.sizeAttenuation = true;
  13793. this.lights = false;
  13794. this.setValues( parameters );
  13795. }
  13796. PointsMaterial.prototype = Object.create( Material.prototype );
  13797. PointsMaterial.prototype.constructor = PointsMaterial;
  13798. PointsMaterial.prototype.isPointsMaterial = true;
  13799. PointsMaterial.prototype.copy = function ( source ) {
  13800. Material.prototype.copy.call( this, source );
  13801. this.color.copy( source.color );
  13802. this.map = source.map;
  13803. this.size = source.size;
  13804. this.sizeAttenuation = source.sizeAttenuation;
  13805. return this;
  13806. };
  13807. /**
  13808. * @author alteredq / http://alteredqualia.com/
  13809. */
  13810. function Points( geometry, material ) {
  13811. Object3D.call( this );
  13812. this.type = 'Points';
  13813. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  13814. this.material = material !== undefined ? material : new PointsMaterial( { color: Math.random() * 0xffffff } );
  13815. }
  13816. Points.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13817. constructor: Points,
  13818. isPoints: true,
  13819. raycast: ( function () {
  13820. var inverseMatrix = new Matrix4();
  13821. var ray = new Ray();
  13822. var sphere = new Sphere();
  13823. return function raycast( raycaster, intersects ) {
  13824. var object = this;
  13825. var geometry = this.geometry;
  13826. var matrixWorld = this.matrixWorld;
  13827. var threshold = raycaster.params.Points.threshold;
  13828. // Checking boundingSphere distance to ray
  13829. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  13830. sphere.copy( geometry.boundingSphere );
  13831. sphere.applyMatrix4( matrixWorld );
  13832. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  13833. //
  13834. inverseMatrix.getInverse( matrixWorld );
  13835. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  13836. var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  13837. var localThresholdSq = localThreshold * localThreshold;
  13838. var position = new Vector3();
  13839. function testPoint( point, index ) {
  13840. var rayPointDistanceSq = ray.distanceSqToPoint( point );
  13841. if ( rayPointDistanceSq < localThresholdSq ) {
  13842. var intersectPoint = ray.closestPointToPoint( point );
  13843. intersectPoint.applyMatrix4( matrixWorld );
  13844. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  13845. if ( distance < raycaster.near || distance > raycaster.far ) return;
  13846. intersects.push( {
  13847. distance: distance,
  13848. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  13849. point: intersectPoint.clone(),
  13850. index: index,
  13851. face: null,
  13852. object: object
  13853. } );
  13854. }
  13855. }
  13856. if ( (geometry && geometry.isBufferGeometry) ) {
  13857. var index = geometry.index;
  13858. var attributes = geometry.attributes;
  13859. var positions = attributes.position.array;
  13860. if ( index !== null ) {
  13861. var indices = index.array;
  13862. for ( var i = 0, il = indices.length; i < il; i ++ ) {
  13863. var a = indices[ i ];
  13864. position.fromArray( positions, a * 3 );
  13865. testPoint( position, a );
  13866. }
  13867. } else {
  13868. for ( var i = 0, l = positions.length / 3; i < l; i ++ ) {
  13869. position.fromArray( positions, i * 3 );
  13870. testPoint( position, i );
  13871. }
  13872. }
  13873. } else {
  13874. var vertices = geometry.vertices;
  13875. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  13876. testPoint( vertices[ i ], i );
  13877. }
  13878. }
  13879. };
  13880. }() ),
  13881. clone: function () {
  13882. return new this.constructor( this.geometry, this.material ).copy( this );
  13883. }
  13884. } );
  13885. /**
  13886. * @author mrdoob / http://mrdoob.com/
  13887. */
  13888. function Group() {
  13889. Object3D.call( this );
  13890. this.type = 'Group';
  13891. }
  13892. Group.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13893. constructor: Group
  13894. } );
  13895. /**
  13896. * @author mrdoob / http://mrdoob.com/
  13897. */
  13898. function VideoTexture( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  13899. Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  13900. this.generateMipmaps = false;
  13901. var scope = this;
  13902. function update() {
  13903. requestAnimationFrame( update );
  13904. if ( video.readyState >= video.HAVE_CURRENT_DATA ) {
  13905. scope.needsUpdate = true;
  13906. }
  13907. }
  13908. update();
  13909. }
  13910. VideoTexture.prototype = Object.create( Texture.prototype );
  13911. VideoTexture.prototype.constructor = VideoTexture;
  13912. /**
  13913. * @author alteredq / http://alteredqualia.com/
  13914. */
  13915. function CompressedTexture( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  13916. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  13917. this.image = { width: width, height: height };
  13918. this.mipmaps = mipmaps;
  13919. // no flipping for cube textures
  13920. // (also flipping doesn't work for compressed textures )
  13921. this.flipY = false;
  13922. // can't generate mipmaps for compressed textures
  13923. // mips must be embedded in DDS files
  13924. this.generateMipmaps = false;
  13925. }
  13926. CompressedTexture.prototype = Object.create( Texture.prototype );
  13927. CompressedTexture.prototype.constructor = CompressedTexture;
  13928. CompressedTexture.prototype.isCompressedTexture = true;
  13929. /**
  13930. * @author mrdoob / http://mrdoob.com/
  13931. */
  13932. function CanvasTexture( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  13933. Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  13934. this.needsUpdate = true;
  13935. }
  13936. CanvasTexture.prototype = Object.create( Texture.prototype );
  13937. CanvasTexture.prototype.constructor = CanvasTexture;
  13938. /**
  13939. * @author Matt DesLauriers / @mattdesl
  13940. * @author atix / arthursilber.de
  13941. */
  13942. function DepthTexture( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  13943. format = format !== undefined ? format : DepthFormat;
  13944. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  13945. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' )
  13946. }
  13947. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  13948. this.image = { width: width, height: height };
  13949. this.type = type !== undefined ? type : UnsignedShortType;
  13950. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  13951. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  13952. this.flipY = false;
  13953. this.generateMipmaps = false;
  13954. }
  13955. DepthTexture.prototype = Object.create( Texture.prototype );
  13956. DepthTexture.prototype.constructor = DepthTexture;
  13957. DepthTexture.prototype.isDepthTexture = true;
  13958. /**
  13959. * @author mrdoob / http://mrdoob.com/
  13960. */
  13961. function ShadowMaterial() {
  13962. ShaderMaterial.call( this, {
  13963. uniforms: exports.UniformsUtils.merge( [
  13964. exports.UniformsLib[ "lights" ],
  13965. {
  13966. opacity: { value: 1.0 }
  13967. }
  13968. ] ),
  13969. vertexShader: ShaderChunk[ 'shadow_vert' ],
  13970. fragmentShader: ShaderChunk[ 'shadow_frag' ]
  13971. } );
  13972. this.lights = true;
  13973. this.transparent = true;
  13974. Object.defineProperties( this, {
  13975. opacity: {
  13976. enumerable: true,
  13977. get: function () {
  13978. return this.uniforms.opacity.value;
  13979. },
  13980. set: function ( value ) {
  13981. this.uniforms.opacity.value = value;
  13982. }
  13983. }
  13984. } );
  13985. }
  13986. ShadowMaterial.prototype = Object.create( ShaderMaterial.prototype );
  13987. ShadowMaterial.prototype.constructor = ShadowMaterial;
  13988. ShadowMaterial.prototype.isShadowMaterial = true;
  13989. /**
  13990. * @author mrdoob / http://mrdoob.com/
  13991. */
  13992. function RawShaderMaterial( parameters ) {
  13993. ShaderMaterial.call( this, parameters );
  13994. this.type = 'RawShaderMaterial';
  13995. }
  13996. RawShaderMaterial.prototype = Object.create( ShaderMaterial.prototype );
  13997. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  13998. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  13999. /**
  14000. * @author mrdoob / http://mrdoob.com/
  14001. */
  14002. function MultiMaterial( materials ) {
  14003. this.uuid = exports.Math.generateUUID();
  14004. this.type = 'MultiMaterial';
  14005. this.materials = materials instanceof Array ? materials : [];
  14006. this.visible = true;
  14007. }
  14008. MultiMaterial.prototype = {
  14009. constructor: MultiMaterial,
  14010. isMultiMaterial: true,
  14011. toJSON: function ( meta ) {
  14012. var output = {
  14013. metadata: {
  14014. version: 4.2,
  14015. type: 'material',
  14016. generator: 'MaterialExporter'
  14017. },
  14018. uuid: this.uuid,
  14019. type: this.type,
  14020. materials: []
  14021. };
  14022. var materials = this.materials;
  14023. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  14024. var material = materials[ i ].toJSON( meta );
  14025. delete material.metadata;
  14026. output.materials.push( material );
  14027. }
  14028. output.visible = this.visible;
  14029. return output;
  14030. },
  14031. clone: function () {
  14032. var material = new this.constructor();
  14033. for ( var i = 0; i < this.materials.length; i ++ ) {
  14034. material.materials.push( this.materials[ i ].clone() );
  14035. }
  14036. material.visible = this.visible;
  14037. return material;
  14038. }
  14039. };
  14040. /**
  14041. * @author WestLangley / http://github.com/WestLangley
  14042. *
  14043. * parameters = {
  14044. * color: <hex>,
  14045. * roughness: <float>,
  14046. * metalness: <float>,
  14047. * opacity: <float>,
  14048. *
  14049. * map: new THREE.Texture( <Image> ),
  14050. *
  14051. * lightMap: new THREE.Texture( <Image> ),
  14052. * lightMapIntensity: <float>
  14053. *
  14054. * aoMap: new THREE.Texture( <Image> ),
  14055. * aoMapIntensity: <float>
  14056. *
  14057. * emissive: <hex>,
  14058. * emissiveIntensity: <float>
  14059. * emissiveMap: new THREE.Texture( <Image> ),
  14060. *
  14061. * bumpMap: new THREE.Texture( <Image> ),
  14062. * bumpScale: <float>,
  14063. *
  14064. * normalMap: new THREE.Texture( <Image> ),
  14065. * normalScale: <Vector2>,
  14066. *
  14067. * displacementMap: new THREE.Texture( <Image> ),
  14068. * displacementScale: <float>,
  14069. * displacementBias: <float>,
  14070. *
  14071. * roughnessMap: new THREE.Texture( <Image> ),
  14072. *
  14073. * metalnessMap: new THREE.Texture( <Image> ),
  14074. *
  14075. * alphaMap: new THREE.Texture( <Image> ),
  14076. *
  14077. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  14078. * envMapIntensity: <float>
  14079. *
  14080. * refractionRatio: <float>,
  14081. *
  14082. * wireframe: <boolean>,
  14083. * wireframeLinewidth: <float>,
  14084. *
  14085. * skinning: <bool>,
  14086. * morphTargets: <bool>,
  14087. * morphNormals: <bool>
  14088. * }
  14089. */
  14090. function MeshStandardMaterial( parameters ) {
  14091. Material.call( this );
  14092. this.defines = { 'STANDARD': '' };
  14093. this.type = 'MeshStandardMaterial';
  14094. this.color = new Color( 0xffffff ); // diffuse
  14095. this.roughness = 0.5;
  14096. this.metalness = 0.5;
  14097. this.map = null;
  14098. this.lightMap = null;
  14099. this.lightMapIntensity = 1.0;
  14100. this.aoMap = null;
  14101. this.aoMapIntensity = 1.0;
  14102. this.emissive = new Color( 0x000000 );
  14103. this.emissiveIntensity = 1.0;
  14104. this.emissiveMap = null;
  14105. this.bumpMap = null;
  14106. this.bumpScale = 1;
  14107. this.normalMap = null;
  14108. this.normalScale = new Vector2( 1, 1 );
  14109. this.displacementMap = null;
  14110. this.displacementScale = 1;
  14111. this.displacementBias = 0;
  14112. this.roughnessMap = null;
  14113. this.metalnessMap = null;
  14114. this.alphaMap = null;
  14115. this.envMap = null;
  14116. this.envMapIntensity = 1.0;
  14117. this.refractionRatio = 0.98;
  14118. this.wireframe = false;
  14119. this.wireframeLinewidth = 1;
  14120. this.wireframeLinecap = 'round';
  14121. this.wireframeLinejoin = 'round';
  14122. this.skinning = false;
  14123. this.morphTargets = false;
  14124. this.morphNormals = false;
  14125. this.setValues( parameters );
  14126. }
  14127. MeshStandardMaterial.prototype = Object.create( Material.prototype );
  14128. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  14129. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  14130. MeshStandardMaterial.prototype.copy = function ( source ) {
  14131. Material.prototype.copy.call( this, source );
  14132. this.defines = { 'STANDARD': '' };
  14133. this.color.copy( source.color );
  14134. this.roughness = source.roughness;
  14135. this.metalness = source.metalness;
  14136. this.map = source.map;
  14137. this.lightMap = source.lightMap;
  14138. this.lightMapIntensity = source.lightMapIntensity;
  14139. this.aoMap = source.aoMap;
  14140. this.aoMapIntensity = source.aoMapIntensity;
  14141. this.emissive.copy( source.emissive );
  14142. this.emissiveMap = source.emissiveMap;
  14143. this.emissiveIntensity = source.emissiveIntensity;
  14144. this.bumpMap = source.bumpMap;
  14145. this.bumpScale = source.bumpScale;
  14146. this.normalMap = source.normalMap;
  14147. this.normalScale.copy( source.normalScale );
  14148. this.displacementMap = source.displacementMap;
  14149. this.displacementScale = source.displacementScale;
  14150. this.displacementBias = source.displacementBias;
  14151. this.roughnessMap = source.roughnessMap;
  14152. this.metalnessMap = source.metalnessMap;
  14153. this.alphaMap = source.alphaMap;
  14154. this.envMap = source.envMap;
  14155. this.envMapIntensity = source.envMapIntensity;
  14156. this.refractionRatio = source.refractionRatio;
  14157. this.wireframe = source.wireframe;
  14158. this.wireframeLinewidth = source.wireframeLinewidth;
  14159. this.wireframeLinecap = source.wireframeLinecap;
  14160. this.wireframeLinejoin = source.wireframeLinejoin;
  14161. this.skinning = source.skinning;
  14162. this.morphTargets = source.morphTargets;
  14163. this.morphNormals = source.morphNormals;
  14164. return this;
  14165. };
  14166. /**
  14167. * @author WestLangley / http://github.com/WestLangley
  14168. *
  14169. * parameters = {
  14170. * reflectivity: <float>
  14171. * }
  14172. */
  14173. function MeshPhysicalMaterial( parameters ) {
  14174. MeshStandardMaterial.call( this );
  14175. this.defines = { 'PHYSICAL': '' };
  14176. this.type = 'MeshPhysicalMaterial';
  14177. this.reflectivity = 0.5; // maps to F0 = 0.04
  14178. this.clearCoat = 0.0;
  14179. this.clearCoatRoughness = 0.0;
  14180. this.setValues( parameters );
  14181. }
  14182. MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype );
  14183. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  14184. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  14185. MeshPhysicalMaterial.prototype.copy = function ( source ) {
  14186. MeshStandardMaterial.prototype.copy.call( this, source );
  14187. this.defines = { 'PHYSICAL': '' };
  14188. this.reflectivity = source.reflectivity;
  14189. this.clearCoat = source.clearCoat;
  14190. this.clearCoatRoughness = source.clearCoatRoughness;
  14191. return this;
  14192. };
  14193. /**
  14194. * @author mrdoob / http://mrdoob.com/
  14195. * @author alteredq / http://alteredqualia.com/
  14196. *
  14197. * parameters = {
  14198. * color: <hex>,
  14199. * specular: <hex>,
  14200. * shininess: <float>,
  14201. * opacity: <float>,
  14202. *
  14203. * map: new THREE.Texture( <Image> ),
  14204. *
  14205. * lightMap: new THREE.Texture( <Image> ),
  14206. * lightMapIntensity: <float>
  14207. *
  14208. * aoMap: new THREE.Texture( <Image> ),
  14209. * aoMapIntensity: <float>
  14210. *
  14211. * emissive: <hex>,
  14212. * emissiveIntensity: <float>
  14213. * emissiveMap: new THREE.Texture( <Image> ),
  14214. *
  14215. * bumpMap: new THREE.Texture( <Image> ),
  14216. * bumpScale: <float>,
  14217. *
  14218. * normalMap: new THREE.Texture( <Image> ),
  14219. * normalScale: <Vector2>,
  14220. *
  14221. * displacementMap: new THREE.Texture( <Image> ),
  14222. * displacementScale: <float>,
  14223. * displacementBias: <float>,
  14224. *
  14225. * specularMap: new THREE.Texture( <Image> ),
  14226. *
  14227. * alphaMap: new THREE.Texture( <Image> ),
  14228. *
  14229. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  14230. * combine: THREE.Multiply,
  14231. * reflectivity: <float>,
  14232. * refractionRatio: <float>,
  14233. *
  14234. * wireframe: <boolean>,
  14235. * wireframeLinewidth: <float>,
  14236. *
  14237. * skinning: <bool>,
  14238. * morphTargets: <bool>,
  14239. * morphNormals: <bool>
  14240. * }
  14241. */
  14242. function MeshPhongMaterial( parameters ) {
  14243. Material.call( this );
  14244. this.type = 'MeshPhongMaterial';
  14245. this.color = new Color( 0xffffff ); // diffuse
  14246. this.specular = new Color( 0x111111 );
  14247. this.shininess = 30;
  14248. this.map = null;
  14249. this.lightMap = null;
  14250. this.lightMapIntensity = 1.0;
  14251. this.aoMap = null;
  14252. this.aoMapIntensity = 1.0;
  14253. this.emissive = new Color( 0x000000 );
  14254. this.emissiveIntensity = 1.0;
  14255. this.emissiveMap = null;
  14256. this.bumpMap = null;
  14257. this.bumpScale = 1;
  14258. this.normalMap = null;
  14259. this.normalScale = new Vector2( 1, 1 );
  14260. this.displacementMap = null;
  14261. this.displacementScale = 1;
  14262. this.displacementBias = 0;
  14263. this.specularMap = null;
  14264. this.alphaMap = null;
  14265. this.envMap = null;
  14266. this.combine = MultiplyOperation;
  14267. this.reflectivity = 1;
  14268. this.refractionRatio = 0.98;
  14269. this.wireframe = false;
  14270. this.wireframeLinewidth = 1;
  14271. this.wireframeLinecap = 'round';
  14272. this.wireframeLinejoin = 'round';
  14273. this.skinning = false;
  14274. this.morphTargets = false;
  14275. this.morphNormals = false;
  14276. this.setValues( parameters );
  14277. }
  14278. MeshPhongMaterial.prototype = Object.create( Material.prototype );
  14279. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  14280. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  14281. MeshPhongMaterial.prototype.copy = function ( source ) {
  14282. Material.prototype.copy.call( this, source );
  14283. this.color.copy( source.color );
  14284. this.specular.copy( source.specular );
  14285. this.shininess = source.shininess;
  14286. this.map = source.map;
  14287. this.lightMap = source.lightMap;
  14288. this.lightMapIntensity = source.lightMapIntensity;
  14289. this.aoMap = source.aoMap;
  14290. this.aoMapIntensity = source.aoMapIntensity;
  14291. this.emissive.copy( source.emissive );
  14292. this.emissiveMap = source.emissiveMap;
  14293. this.emissiveIntensity = source.emissiveIntensity;
  14294. this.bumpMap = source.bumpMap;
  14295. this.bumpScale = source.bumpScale;
  14296. this.normalMap = source.normalMap;
  14297. this.normalScale.copy( source.normalScale );
  14298. this.displacementMap = source.displacementMap;
  14299. this.displacementScale = source.displacementScale;
  14300. this.displacementBias = source.displacementBias;
  14301. this.specularMap = source.specularMap;
  14302. this.alphaMap = source.alphaMap;
  14303. this.envMap = source.envMap;
  14304. this.combine = source.combine;
  14305. this.reflectivity = source.reflectivity;
  14306. this.refractionRatio = source.refractionRatio;
  14307. this.wireframe = source.wireframe;
  14308. this.wireframeLinewidth = source.wireframeLinewidth;
  14309. this.wireframeLinecap = source.wireframeLinecap;
  14310. this.wireframeLinejoin = source.wireframeLinejoin;
  14311. this.skinning = source.skinning;
  14312. this.morphTargets = source.morphTargets;
  14313. this.morphNormals = source.morphNormals;
  14314. return this;
  14315. };
  14316. /**
  14317. * @author mrdoob / http://mrdoob.com/
  14318. *
  14319. * parameters = {
  14320. * opacity: <float>,
  14321. *
  14322. * wireframe: <boolean>,
  14323. * wireframeLinewidth: <float>
  14324. * }
  14325. */
  14326. function MeshNormalMaterial( parameters ) {
  14327. Material.call( this, parameters );
  14328. this.type = 'MeshNormalMaterial';
  14329. this.wireframe = false;
  14330. this.wireframeLinewidth = 1;
  14331. this.fog = false;
  14332. this.lights = false;
  14333. this.morphTargets = false;
  14334. this.setValues( parameters );
  14335. }
  14336. MeshNormalMaterial.prototype = Object.create( Material.prototype );
  14337. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  14338. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  14339. MeshNormalMaterial.prototype.copy = function ( source ) {
  14340. Material.prototype.copy.call( this, source );
  14341. this.wireframe = source.wireframe;
  14342. this.wireframeLinewidth = source.wireframeLinewidth;
  14343. return this;
  14344. };
  14345. /**
  14346. * @author mrdoob / http://mrdoob.com/
  14347. * @author alteredq / http://alteredqualia.com/
  14348. *
  14349. * parameters = {
  14350. * color: <hex>,
  14351. * opacity: <float>,
  14352. *
  14353. * map: new THREE.Texture( <Image> ),
  14354. *
  14355. * lightMap: new THREE.Texture( <Image> ),
  14356. * lightMapIntensity: <float>
  14357. *
  14358. * aoMap: new THREE.Texture( <Image> ),
  14359. * aoMapIntensity: <float>
  14360. *
  14361. * emissive: <hex>,
  14362. * emissiveIntensity: <float>
  14363. * emissiveMap: new THREE.Texture( <Image> ),
  14364. *
  14365. * specularMap: new THREE.Texture( <Image> ),
  14366. *
  14367. * alphaMap: new THREE.Texture( <Image> ),
  14368. *
  14369. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  14370. * combine: THREE.Multiply,
  14371. * reflectivity: <float>,
  14372. * refractionRatio: <float>,
  14373. *
  14374. * wireframe: <boolean>,
  14375. * wireframeLinewidth: <float>,
  14376. *
  14377. * skinning: <bool>,
  14378. * morphTargets: <bool>,
  14379. * morphNormals: <bool>
  14380. * }
  14381. */
  14382. function MeshLambertMaterial( parameters ) {
  14383. Material.call( this );
  14384. this.type = 'MeshLambertMaterial';
  14385. this.color = new Color( 0xffffff ); // diffuse
  14386. this.map = null;
  14387. this.lightMap = null;
  14388. this.lightMapIntensity = 1.0;
  14389. this.aoMap = null;
  14390. this.aoMapIntensity = 1.0;
  14391. this.emissive = new Color( 0x000000 );
  14392. this.emissiveIntensity = 1.0;
  14393. this.emissiveMap = null;
  14394. this.specularMap = null;
  14395. this.alphaMap = null;
  14396. this.envMap = null;
  14397. this.combine = MultiplyOperation;
  14398. this.reflectivity = 1;
  14399. this.refractionRatio = 0.98;
  14400. this.wireframe = false;
  14401. this.wireframeLinewidth = 1;
  14402. this.wireframeLinecap = 'round';
  14403. this.wireframeLinejoin = 'round';
  14404. this.skinning = false;
  14405. this.morphTargets = false;
  14406. this.morphNormals = false;
  14407. this.setValues( parameters );
  14408. }
  14409. MeshLambertMaterial.prototype = Object.create( Material.prototype );
  14410. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  14411. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  14412. MeshLambertMaterial.prototype.copy = function ( source ) {
  14413. Material.prototype.copy.call( this, source );
  14414. this.color.copy( source.color );
  14415. this.map = source.map;
  14416. this.lightMap = source.lightMap;
  14417. this.lightMapIntensity = source.lightMapIntensity;
  14418. this.aoMap = source.aoMap;
  14419. this.aoMapIntensity = source.aoMapIntensity;
  14420. this.emissive.copy( source.emissive );
  14421. this.emissiveMap = source.emissiveMap;
  14422. this.emissiveIntensity = source.emissiveIntensity;
  14423. this.specularMap = source.specularMap;
  14424. this.alphaMap = source.alphaMap;
  14425. this.envMap = source.envMap;
  14426. this.combine = source.combine;
  14427. this.reflectivity = source.reflectivity;
  14428. this.refractionRatio = source.refractionRatio;
  14429. this.wireframe = source.wireframe;
  14430. this.wireframeLinewidth = source.wireframeLinewidth;
  14431. this.wireframeLinecap = source.wireframeLinecap;
  14432. this.wireframeLinejoin = source.wireframeLinejoin;
  14433. this.skinning = source.skinning;
  14434. this.morphTargets = source.morphTargets;
  14435. this.morphNormals = source.morphNormals;
  14436. return this;
  14437. };
  14438. /**
  14439. * @author alteredq / http://alteredqualia.com/
  14440. *
  14441. * parameters = {
  14442. * color: <hex>,
  14443. * opacity: <float>,
  14444. *
  14445. * linewidth: <float>,
  14446. *
  14447. * scale: <float>,
  14448. * dashSize: <float>,
  14449. * gapSize: <float>
  14450. * }
  14451. */
  14452. function LineDashedMaterial( parameters ) {
  14453. Material.call( this );
  14454. this.type = 'LineDashedMaterial';
  14455. this.color = new Color( 0xffffff );
  14456. this.linewidth = 1;
  14457. this.scale = 1;
  14458. this.dashSize = 3;
  14459. this.gapSize = 1;
  14460. this.lights = false;
  14461. this.setValues( parameters );
  14462. }
  14463. LineDashedMaterial.prototype = Object.create( Material.prototype );
  14464. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  14465. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  14466. LineDashedMaterial.prototype.copy = function ( source ) {
  14467. Material.prototype.copy.call( this, source );
  14468. this.color.copy( source.color );
  14469. this.linewidth = source.linewidth;
  14470. this.scale = source.scale;
  14471. this.dashSize = source.dashSize;
  14472. this.gapSize = source.gapSize;
  14473. return this;
  14474. };
  14475. /**
  14476. * @author mrdoob / http://mrdoob.com/
  14477. */
  14478. exports.Cache = {
  14479. enabled: false,
  14480. files: {},
  14481. add: function ( key, file ) {
  14482. if ( this.enabled === false ) return;
  14483. // console.log( 'THREE.Cache', 'Adding key:', key );
  14484. this.files[ key ] = file;
  14485. },
  14486. get: function ( key ) {
  14487. if ( this.enabled === false ) return;
  14488. // console.log( 'THREE.Cache', 'Checking key:', key );
  14489. return this.files[ key ];
  14490. },
  14491. remove: function ( key ) {
  14492. delete this.files[ key ];
  14493. },
  14494. clear: function () {
  14495. this.files = {};
  14496. }
  14497. };
  14498. /**
  14499. * @author mrdoob / http://mrdoob.com/
  14500. */
  14501. function LoadingManager( onLoad, onProgress, onError ) {
  14502. var scope = this;
  14503. var isLoading = false, itemsLoaded = 0, itemsTotal = 0;
  14504. this.onStart = undefined;
  14505. this.onLoad = onLoad;
  14506. this.onProgress = onProgress;
  14507. this.onError = onError;
  14508. this.itemStart = function ( url ) {
  14509. itemsTotal ++;
  14510. if ( isLoading === false ) {
  14511. if ( scope.onStart !== undefined ) {
  14512. scope.onStart( url, itemsLoaded, itemsTotal );
  14513. }
  14514. }
  14515. isLoading = true;
  14516. };
  14517. this.itemEnd = function ( url ) {
  14518. itemsLoaded ++;
  14519. if ( scope.onProgress !== undefined ) {
  14520. scope.onProgress( url, itemsLoaded, itemsTotal );
  14521. }
  14522. if ( itemsLoaded === itemsTotal ) {
  14523. isLoading = false;
  14524. if ( scope.onLoad !== undefined ) {
  14525. scope.onLoad();
  14526. }
  14527. }
  14528. };
  14529. this.itemError = function ( url ) {
  14530. if ( scope.onError !== undefined ) {
  14531. scope.onError( url );
  14532. }
  14533. };
  14534. }
  14535. exports.DefaultLoadingManager = new LoadingManager();
  14536. /**
  14537. * @author mrdoob / http://mrdoob.com/
  14538. */
  14539. function XHRLoader( manager ) {
  14540. this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager;
  14541. }
  14542. Object.assign( XHRLoader.prototype, {
  14543. load: function ( url, onLoad, onProgress, onError ) {
  14544. if ( this.path !== undefined ) url = this.path + url;
  14545. var scope = this;
  14546. var cached = exports.Cache.get( url );
  14547. if ( cached !== undefined ) {
  14548. scope.manager.itemStart( url );
  14549. setTimeout( function () {
  14550. if ( onLoad ) onLoad( cached );
  14551. scope.manager.itemEnd( url );
  14552. }, 0 );
  14553. return cached;
  14554. }
  14555. var request = new XMLHttpRequest();
  14556. request.open( 'GET', url, true );
  14557. request.addEventListener( 'load', function ( event ) {
  14558. var response = event.target.response;
  14559. exports.Cache.add( url, response );
  14560. if ( this.status === 200 ) {
  14561. if ( onLoad ) onLoad( response );
  14562. scope.manager.itemEnd( url );
  14563. } else if ( this.status === 0 ) {
  14564. // Some browsers return HTTP Status 0 when using non-http protocol
  14565. // e.g. 'file://' or 'data://'. Handle as success.
  14566. console.warn( 'THREE.XHRLoader: HTTP Status 0 received.' );
  14567. if ( onLoad ) onLoad( response );
  14568. scope.manager.itemEnd( url );
  14569. } else {
  14570. if ( onError ) onError( event );
  14571. scope.manager.itemError( url );
  14572. }
  14573. }, false );
  14574. if ( onProgress !== undefined ) {
  14575. request.addEventListener( 'progress', function ( event ) {
  14576. onProgress( event );
  14577. }, false );
  14578. }
  14579. request.addEventListener( 'error', function ( event ) {
  14580. if ( onError ) onError( event );
  14581. scope.manager.itemError( url );
  14582. }, false );
  14583. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  14584. if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;
  14585. if ( request.overrideMimeType ) request.overrideMimeType( 'text/plain' );
  14586. request.send( null );
  14587. scope.manager.itemStart( url );
  14588. return request;
  14589. },
  14590. setPath: function ( value ) {
  14591. this.path = value;
  14592. return this;
  14593. },
  14594. setResponseType: function ( value ) {
  14595. this.responseType = value;
  14596. return this;
  14597. },
  14598. setWithCredentials: function ( value ) {
  14599. this.withCredentials = value;
  14600. return this;
  14601. }
  14602. } );
  14603. /**
  14604. * @author mrdoob / http://mrdoob.com/
  14605. *
  14606. * Abstract Base class to block based textures loader (dds, pvr, ...)
  14607. */
  14608. function CompressedTextureLoader( manager ) {
  14609. this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager;
  14610. // override in sub classes
  14611. this._parser = null;
  14612. }
  14613. Object.assign( CompressedTextureLoader.prototype, {
  14614. load: function ( url, onLoad, onProgress, onError ) {
  14615. var scope = this;
  14616. var images = [];
  14617. var texture = new CompressedTexture();
  14618. texture.image = images;
  14619. var loader = new XHRLoader( this.manager );
  14620. loader.setPath( this.path );
  14621. loader.setResponseType( 'arraybuffer' );
  14622. function loadTexture( i ) {
  14623. loader.load( url[ i ], function ( buffer ) {
  14624. var texDatas = scope._parser( buffer, true );
  14625. images[ i ] = {
  14626. width: texDatas.width,
  14627. height: texDatas.height,
  14628. format: texDatas.format,
  14629. mipmaps: texDatas.mipmaps
  14630. };
  14631. loaded += 1;
  14632. if ( loaded === 6 ) {
  14633. if ( texDatas.mipmapCount === 1 )
  14634. texture.minFilter = LinearFilter;
  14635. texture.format = texDatas.format;
  14636. texture.needsUpdate = true;
  14637. if ( onLoad ) onLoad( texture );
  14638. }
  14639. }, onProgress, onError );
  14640. }
  14641. if ( Array.isArray( url ) ) {
  14642. var loaded = 0;
  14643. for ( var i = 0, il = url.length; i < il; ++ i ) {
  14644. loadTexture( i );
  14645. }
  14646. } else {
  14647. // compressed cubemap texture stored in a single DDS file
  14648. loader.load( url, function ( buffer ) {
  14649. var texDatas = scope._parser( buffer, true );
  14650. if ( texDatas.isCubemap ) {
  14651. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  14652. for ( var f = 0; f < faces; f ++ ) {
  14653. images[ f ] = { mipmaps : [] };
  14654. for ( var i = 0; i < texDatas.mipmapCount; i ++ ) {
  14655. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  14656. images[ f ].format = texDatas.format;
  14657. images[ f ].width = texDatas.width;
  14658. images[ f ].height = texDatas.height;
  14659. }
  14660. }
  14661. } else {
  14662. texture.image.width = texDatas.width;
  14663. texture.image.height = texDatas.height;
  14664. texture.mipmaps = texDatas.mipmaps;
  14665. }
  14666. if ( texDatas.mipmapCount === 1 ) {
  14667. texture.minFilter = LinearFilter;
  14668. }
  14669. texture.format = texDatas.format;
  14670. texture.needsUpdate = true;
  14671. if ( onLoad ) onLoad( texture );
  14672. }, onProgress, onError );
  14673. }
  14674. return texture;
  14675. },
  14676. setPath: function ( value ) {
  14677. this.path = value;
  14678. return this;
  14679. }
  14680. } );
  14681. /**
  14682. * @author Nikos M. / https://github.com/foo123/
  14683. *
  14684. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  14685. */
  14686. var DataTextureLoader = BinaryTextureLoader;
  14687. function BinaryTextureLoader( manager ) {
  14688. this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager;
  14689. // override in sub classes
  14690. this._parser = null;
  14691. }
  14692. Object.assign( BinaryTextureLoader.prototype, {
  14693. load: function ( url, onLoad, onProgress, onError ) {
  14694. var scope = this;
  14695. var texture = new DataTexture();
  14696. var loader = new XHRLoader( this.manager );
  14697. loader.setResponseType( 'arraybuffer' );
  14698. loader.load( url, function ( buffer ) {
  14699. var texData = scope._parser( buffer );
  14700. if ( ! texData ) return;
  14701. if ( undefined !== texData.image ) {
  14702. texture.image = texData.image;
  14703. } else if ( undefined !== texData.data ) {
  14704. texture.image.width = texData.width;
  14705. texture.image.height = texData.height;
  14706. texture.image.data = texData.data;
  14707. }
  14708. texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : ClampToEdgeWrapping;
  14709. texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : ClampToEdgeWrapping;
  14710. texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : LinearFilter;
  14711. texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : LinearMipMapLinearFilter;
  14712. texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1;
  14713. if ( undefined !== texData.format ) {
  14714. texture.format = texData.format;
  14715. }
  14716. if ( undefined !== texData.type ) {
  14717. texture.type = texData.type;
  14718. }
  14719. if ( undefined !== texData.mipmaps ) {
  14720. texture.mipmaps = texData.mipmaps;
  14721. }
  14722. if ( 1 === texData.mipmapCount ) {
  14723. texture.minFilter = LinearFilter;
  14724. }
  14725. texture.needsUpdate = true;
  14726. if ( onLoad ) onLoad( texture, texData );
  14727. }, onProgress, onError );
  14728. return texture;
  14729. }
  14730. } );
  14731. /**
  14732. * @author mrdoob / http://mrdoob.com/
  14733. */
  14734. function ImageLoader( manager ) {
  14735. this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager;
  14736. }
  14737. Object.assign( ImageLoader.prototype, {
  14738. load: function ( url, onLoad, onProgress, onError ) {
  14739. var scope = this;
  14740. var image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' );
  14741. image.onload = function () {
  14742. URL.revokeObjectURL( image.src );
  14743. if ( onLoad ) onLoad( image );
  14744. scope.manager.itemEnd( url );
  14745. };
  14746. if ( url.indexOf( 'data:' ) === 0 ) {
  14747. image.src = url;
  14748. } else {
  14749. var loader = new XHRLoader();
  14750. loader.setPath( this.path );
  14751. loader.setResponseType( 'blob' );
  14752. loader.setWithCredentials( this.withCredentials );
  14753. loader.load( url, function ( blob ) {
  14754. image.src = URL.createObjectURL( blob );
  14755. }, onProgress, onError );
  14756. }
  14757. scope.manager.itemStart( url );
  14758. return image;
  14759. },
  14760. setCrossOrigin: function ( value ) {
  14761. this.crossOrigin = value;
  14762. return this;
  14763. },
  14764. setWithCredentials: function ( value ) {
  14765. this.withCredentials = value;
  14766. return this;
  14767. },
  14768. setPath: function ( value ) {
  14769. this.path = value;
  14770. return this;
  14771. }
  14772. } );
  14773. /**
  14774. * @author mrdoob / http://mrdoob.com/
  14775. */
  14776. function CubeTextureLoader( manager ) {
  14777. this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager;
  14778. }
  14779. Object.assign( CubeTextureLoader.prototype, {
  14780. load: function ( urls, onLoad, onProgress, onError ) {
  14781. var texture = new CubeTexture();
  14782. var loader = new ImageLoader( this.manager );
  14783. loader.setCrossOrigin( this.crossOrigin );
  14784. loader.setPath( this.path );
  14785. var loaded = 0;
  14786. function loadTexture( i ) {
  14787. loader.load( urls[ i ], function ( image ) {
  14788. texture.images[ i ] = image;
  14789. loaded ++;
  14790. if ( loaded === 6 ) {
  14791. texture.needsUpdate = true;
  14792. if ( onLoad ) onLoad( texture );
  14793. }
  14794. }, undefined, onError );
  14795. }
  14796. for ( var i = 0; i < urls.length; ++ i ) {
  14797. loadTexture( i );
  14798. }
  14799. return texture;
  14800. },
  14801. setCrossOrigin: function ( value ) {
  14802. this.crossOrigin = value;
  14803. return this;
  14804. },
  14805. setPath: function ( value ) {
  14806. this.path = value;
  14807. return this;
  14808. }
  14809. } );
  14810. /**
  14811. * @author mrdoob / http://mrdoob.com/
  14812. */
  14813. function TextureLoader( manager ) {
  14814. this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager;
  14815. }
  14816. Object.assign( TextureLoader.prototype, {
  14817. load: function ( url, onLoad, onProgress, onError ) {
  14818. var texture = new Texture();
  14819. var loader = new ImageLoader( this.manager );
  14820. loader.setCrossOrigin( this.crossOrigin );
  14821. loader.setWithCredentials( this.withCredentials );
  14822. loader.setPath( this.path );
  14823. loader.load( url, function ( image ) {
  14824. // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  14825. var isJPEG = url.search( /\.(jpg|jpeg)$/ ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0;
  14826. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  14827. texture.image = image;
  14828. texture.needsUpdate = true;
  14829. if ( onLoad !== undefined ) {
  14830. onLoad( texture );
  14831. }
  14832. }, onProgress, onError );
  14833. return texture;
  14834. },
  14835. setCrossOrigin: function ( value ) {
  14836. this.crossOrigin = value;
  14837. return this;
  14838. },
  14839. setWithCredentials: function ( value ) {
  14840. this.withCredentials = value;
  14841. return this;
  14842. },
  14843. setPath: function ( value ) {
  14844. this.path = value;
  14845. return this;
  14846. }
  14847. } );
  14848. /**
  14849. * @author mrdoob / http://mrdoob.com/
  14850. * @author alteredq / http://alteredqualia.com/
  14851. */
  14852. function Light( color, intensity ) {
  14853. Object3D.call( this );
  14854. this.type = 'Light';
  14855. this.color = new Color( color );
  14856. this.intensity = intensity !== undefined ? intensity : 1;
  14857. this.receiveShadow = undefined;
  14858. }
  14859. Light.prototype = Object.assign( Object.create( Object3D.prototype ), {
  14860. constructor: Light,
  14861. isLight: true,
  14862. copy: function ( source ) {
  14863. Object3D.prototype.copy.call( this, source );
  14864. this.color.copy( source.color );
  14865. this.intensity = source.intensity;
  14866. return this;
  14867. },
  14868. toJSON: function ( meta ) {
  14869. var data = Object3D.prototype.toJSON.call( this, meta );
  14870. data.object.color = this.color.getHex();
  14871. data.object.intensity = this.intensity;
  14872. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  14873. if ( this.distance !== undefined ) data.object.distance = this.distance;
  14874. if ( this.angle !== undefined ) data.object.angle = this.angle;
  14875. if ( this.decay !== undefined ) data.object.decay = this.decay;
  14876. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  14877. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  14878. return data;
  14879. }
  14880. } );
  14881. /**
  14882. * @author alteredq / http://alteredqualia.com/
  14883. */
  14884. function HemisphereLight( skyColor, groundColor, intensity ) {
  14885. Light.call( this, skyColor, intensity );
  14886. this.type = 'HemisphereLight';
  14887. this.castShadow = undefined;
  14888. this.position.copy( Object3D.DefaultUp );
  14889. this.updateMatrix();
  14890. this.groundColor = new Color( groundColor );
  14891. }
  14892. HemisphereLight.prototype = Object.assign( Object.create( Light.prototype ), {
  14893. constructor: HemisphereLight,
  14894. isHemisphereLight: true,
  14895. copy: function ( source ) {
  14896. Light.prototype.copy.call( this, source );
  14897. this.groundColor.copy( source.groundColor );
  14898. return this;
  14899. }
  14900. } );
  14901. /**
  14902. * @author mrdoob / http://mrdoob.com/
  14903. */
  14904. function LightShadow( camera ) {
  14905. this.camera = camera;
  14906. this.bias = 0;
  14907. this.radius = 1;
  14908. this.mapSize = new Vector2( 512, 512 );
  14909. this.map = null;
  14910. this.matrix = new Matrix4();
  14911. }
  14912. Object.assign( LightShadow.prototype, {
  14913. copy: function ( source ) {
  14914. this.camera = source.camera.clone();
  14915. this.bias = source.bias;
  14916. this.radius = source.radius;
  14917. this.mapSize.copy( source.mapSize );
  14918. return this;
  14919. },
  14920. clone: function () {
  14921. return new this.constructor().copy( this );
  14922. },
  14923. toJSON: function () {
  14924. var object = {};
  14925. if ( this.bias !== 0 ) object.bias = this.bias;
  14926. if ( this.radius !== 1 ) object.radius = this.radius;
  14927. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  14928. object.camera = this.camera.toJSON( false ).object;
  14929. delete object.camera.matrix;
  14930. return object;
  14931. }
  14932. } );
  14933. /**
  14934. * @author mrdoob / http://mrdoob.com/
  14935. */
  14936. function SpotLightShadow() {
  14937. LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  14938. }
  14939. SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  14940. constructor: SpotLightShadow,
  14941. isSpotLightShadow: true,
  14942. update: function ( light ) {
  14943. var fov = exports.Math.RAD2DEG * 2 * light.angle;
  14944. var aspect = this.mapSize.width / this.mapSize.height;
  14945. var far = light.distance || 500;
  14946. var camera = this.camera;
  14947. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  14948. camera.fov = fov;
  14949. camera.aspect = aspect;
  14950. camera.far = far;
  14951. camera.updateProjectionMatrix();
  14952. }
  14953. }
  14954. } );
  14955. /**
  14956. * @author alteredq / http://alteredqualia.com/
  14957. */
  14958. function SpotLight( color, intensity, distance, angle, penumbra, decay ) {
  14959. Light.call( this, color, intensity );
  14960. this.type = 'SpotLight';
  14961. this.position.copy( Object3D.DefaultUp );
  14962. this.updateMatrix();
  14963. this.target = new Object3D();
  14964. Object.defineProperty( this, 'power', {
  14965. get: function () {
  14966. // intensity = power per solid angle.
  14967. // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  14968. return this.intensity * Math.PI;
  14969. },
  14970. set: function ( power ) {
  14971. // intensity = power per solid angle.
  14972. // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  14973. this.intensity = power / Math.PI;
  14974. }
  14975. } );
  14976. this.distance = ( distance !== undefined ) ? distance : 0;
  14977. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  14978. this.penumbra = ( penumbra !== undefined ) ? penumbra : 0;
  14979. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  14980. this.shadow = new SpotLightShadow();
  14981. }
  14982. SpotLight.prototype = Object.assign( Object.create( Light.prototype ), {
  14983. constructor: SpotLight,
  14984. isSpotLight: true,
  14985. copy: function ( source ) {
  14986. Light.prototype.copy.call( this, source );
  14987. this.distance = source.distance;
  14988. this.angle = source.angle;
  14989. this.penumbra = source.penumbra;
  14990. this.decay = source.decay;
  14991. this.target = source.target.clone();
  14992. this.shadow = source.shadow.clone();
  14993. return this;
  14994. }
  14995. } );
  14996. /**
  14997. * @author mrdoob / http://mrdoob.com/
  14998. */
  14999. function PointLight( color, intensity, distance, decay ) {
  15000. Light.call( this, color, intensity );
  15001. this.type = 'PointLight';
  15002. Object.defineProperty( this, 'power', {
  15003. get: function () {
  15004. // intensity = power per solid angle.
  15005. // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  15006. return this.intensity * 4 * Math.PI;
  15007. },
  15008. set: function ( power ) {
  15009. // intensity = power per solid angle.
  15010. // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  15011. this.intensity = power / ( 4 * Math.PI );
  15012. }
  15013. } );
  15014. this.distance = ( distance !== undefined ) ? distance : 0;
  15015. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  15016. this.shadow = new LightShadow( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  15017. }
  15018. PointLight.prototype = Object.assign( Object.create( Light.prototype ), {
  15019. constructor: PointLight,
  15020. isPointLight: true,
  15021. copy: function ( source ) {
  15022. Light.prototype.copy.call( this, source );
  15023. this.distance = source.distance;
  15024. this.decay = source.decay;
  15025. this.shadow = source.shadow.clone();
  15026. return this;
  15027. }
  15028. } );
  15029. /**
  15030. * @author mrdoob / http://mrdoob.com/
  15031. */
  15032. function DirectionalLightShadow( light ) {
  15033. LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  15034. }
  15035. DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  15036. constructor: DirectionalLightShadow
  15037. } );
  15038. /**
  15039. * @author mrdoob / http://mrdoob.com/
  15040. * @author alteredq / http://alteredqualia.com/
  15041. */
  15042. function DirectionalLight( color, intensity ) {
  15043. Light.call( this, color, intensity );
  15044. this.type = 'DirectionalLight';
  15045. this.position.copy( Object3D.DefaultUp );
  15046. this.updateMatrix();
  15047. this.target = new Object3D();
  15048. this.shadow = new DirectionalLightShadow();
  15049. }
  15050. DirectionalLight.prototype = Object.assign( Object.create( Light.prototype ), {
  15051. constructor: DirectionalLight,
  15052. isDirectionalLight: true,
  15053. copy: function ( source ) {
  15054. Light.prototype.copy.call( this, source );
  15055. this.target = source.target.clone();
  15056. this.shadow = source.shadow.clone();
  15057. return this;
  15058. }
  15059. } );
  15060. /**
  15061. * @author mrdoob / http://mrdoob.com/
  15062. */
  15063. function AmbientLight( color, intensity ) {
  15064. Light.call( this, color, intensity );
  15065. this.type = 'AmbientLight';
  15066. this.castShadow = undefined;
  15067. }
  15068. AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), {
  15069. constructor: AmbientLight,
  15070. isAmbientLight: true,
  15071. } );
  15072. /**
  15073. * @author tschw
  15074. * @author Ben Houston / http://clara.io/
  15075. * @author David Sarno / http://lighthaus.us/
  15076. */
  15077. exports.AnimationUtils = {
  15078. // same as Array.prototype.slice, but also works on typed arrays
  15079. arraySlice: function( array, from, to ) {
  15080. if ( exports.AnimationUtils.isTypedArray( array ) ) {
  15081. return new array.constructor( array.subarray( from, to ) );
  15082. }
  15083. return array.slice( from, to );
  15084. },
  15085. // converts an array to a specific type
  15086. convertArray: function( array, type, forceClone ) {
  15087. if ( ! array || // let 'undefined' and 'null' pass
  15088. ! forceClone && array.constructor === type ) return array;
  15089. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  15090. return new type( array ); // create typed array
  15091. }
  15092. return Array.prototype.slice.call( array ); // create Array
  15093. },
  15094. isTypedArray: function( object ) {
  15095. return ArrayBuffer.isView( object ) &&
  15096. ! ( object instanceof DataView );
  15097. },
  15098. // returns an array by which times and values can be sorted
  15099. getKeyframeOrder: function( times ) {
  15100. function compareTime( i, j ) {
  15101. return times[ i ] - times[ j ];
  15102. }
  15103. var n = times.length;
  15104. var result = new Array( n );
  15105. for ( var i = 0; i !== n; ++ i ) result[ i ] = i;
  15106. result.sort( compareTime );
  15107. return result;
  15108. },
  15109. // uses the array previously returned by 'getKeyframeOrder' to sort data
  15110. sortedArray: function( values, stride, order ) {
  15111. var nValues = values.length;
  15112. var result = new values.constructor( nValues );
  15113. for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  15114. var srcOffset = order[ i ] * stride;
  15115. for ( var j = 0; j !== stride; ++ j ) {
  15116. result[ dstOffset ++ ] = values[ srcOffset + j ];
  15117. }
  15118. }
  15119. return result;
  15120. },
  15121. // function for parsing AOS keyframe formats
  15122. flattenJSON: function( jsonKeys, times, values, valuePropertyName ) {
  15123. var i = 1, key = jsonKeys[ 0 ];
  15124. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  15125. key = jsonKeys[ i ++ ];
  15126. }
  15127. if ( key === undefined ) return; // no data
  15128. var value = key[ valuePropertyName ];
  15129. if ( value === undefined ) return; // no data
  15130. if ( Array.isArray( value ) ) {
  15131. do {
  15132. value = key[ valuePropertyName ];
  15133. if ( value !== undefined ) {
  15134. times.push( key.time );
  15135. values.push.apply( values, value ); // push all elements
  15136. }
  15137. key = jsonKeys[ i ++ ];
  15138. } while ( key !== undefined );
  15139. } else if ( value.toArray !== undefined ) {
  15140. // ...assume THREE.Math-ish
  15141. do {
  15142. value = key[ valuePropertyName ];
  15143. if ( value !== undefined ) {
  15144. times.push( key.time );
  15145. value.toArray( values, values.length );
  15146. }
  15147. key = jsonKeys[ i ++ ];
  15148. } while ( key !== undefined );
  15149. } else {
  15150. // otherwise push as-is
  15151. do {
  15152. value = key[ valuePropertyName ];
  15153. if ( value !== undefined ) {
  15154. times.push( key.time );
  15155. values.push( value );
  15156. }
  15157. key = jsonKeys[ i ++ ];
  15158. } while ( key !== undefined );
  15159. }
  15160. }
  15161. };
  15162. /**
  15163. * Abstract base class of interpolants over parametric samples.
  15164. *
  15165. * The parameter domain is one dimensional, typically the time or a path
  15166. * along a curve defined by the data.
  15167. *
  15168. * The sample values can have any dimensionality and derived classes may
  15169. * apply special interpretations to the data.
  15170. *
  15171. * This class provides the interval seek in a Template Method, deferring
  15172. * the actual interpolation to derived classes.
  15173. *
  15174. * Time complexity is O(1) for linear access crossing at most two points
  15175. * and O(log N) for random access, where N is the number of positions.
  15176. *
  15177. * References:
  15178. *
  15179. * http://www.oodesign.com/template-method-pattern.html
  15180. *
  15181. * @author tschw
  15182. */
  15183. function Interpolant(
  15184. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  15185. this.parameterPositions = parameterPositions;
  15186. this._cachedIndex = 0;
  15187. this.resultBuffer = resultBuffer !== undefined ?
  15188. resultBuffer : new sampleValues.constructor( sampleSize );
  15189. this.sampleValues = sampleValues;
  15190. this.valueSize = sampleSize;
  15191. }
  15192. Interpolant.prototype = {
  15193. constructor: Interpolant,
  15194. evaluate: function( t ) {
  15195. var pp = this.parameterPositions,
  15196. i1 = this._cachedIndex,
  15197. t1 = pp[ i1 ],
  15198. t0 = pp[ i1 - 1 ];
  15199. validate_interval: {
  15200. seek: {
  15201. var right;
  15202. linear_scan: {
  15203. //- See http://jsperf.com/comparison-to-undefined/3
  15204. //- slower code:
  15205. //-
  15206. //- if ( t >= t1 || t1 === undefined ) {
  15207. forward_scan: if ( ! ( t < t1 ) ) {
  15208. for ( var giveUpAt = i1 + 2; ;) {
  15209. if ( t1 === undefined ) {
  15210. if ( t < t0 ) break forward_scan;
  15211. // after end
  15212. i1 = pp.length;
  15213. this._cachedIndex = i1;
  15214. return this.afterEnd_( i1 - 1, t, t0 );
  15215. }
  15216. if ( i1 === giveUpAt ) break; // this loop
  15217. t0 = t1;
  15218. t1 = pp[ ++ i1 ];
  15219. if ( t < t1 ) {
  15220. // we have arrived at the sought interval
  15221. break seek;
  15222. }
  15223. }
  15224. // prepare binary search on the right side of the index
  15225. right = pp.length;
  15226. break linear_scan;
  15227. }
  15228. //- slower code:
  15229. //- if ( t < t0 || t0 === undefined ) {
  15230. if ( ! ( t >= t0 ) ) {
  15231. // looping?
  15232. var t1global = pp[ 1 ];
  15233. if ( t < t1global ) {
  15234. i1 = 2; // + 1, using the scan for the details
  15235. t0 = t1global;
  15236. }
  15237. // linear reverse scan
  15238. for ( var giveUpAt = i1 - 2; ;) {
  15239. if ( t0 === undefined ) {
  15240. // before start
  15241. this._cachedIndex = 0;
  15242. return this.beforeStart_( 0, t, t1 );
  15243. }
  15244. if ( i1 === giveUpAt ) break; // this loop
  15245. t1 = t0;
  15246. t0 = pp[ -- i1 - 1 ];
  15247. if ( t >= t0 ) {
  15248. // we have arrived at the sought interval
  15249. break seek;
  15250. }
  15251. }
  15252. // prepare binary search on the left side of the index
  15253. right = i1;
  15254. i1 = 0;
  15255. break linear_scan;
  15256. }
  15257. // the interval is valid
  15258. break validate_interval;
  15259. } // linear scan
  15260. // binary search
  15261. while ( i1 < right ) {
  15262. var mid = ( i1 + right ) >>> 1;
  15263. if ( t < pp[ mid ] ) {
  15264. right = mid;
  15265. } else {
  15266. i1 = mid + 1;
  15267. }
  15268. }
  15269. t1 = pp[ i1 ];
  15270. t0 = pp[ i1 - 1 ];
  15271. // check boundary cases, again
  15272. if ( t0 === undefined ) {
  15273. this._cachedIndex = 0;
  15274. return this.beforeStart_( 0, t, t1 );
  15275. }
  15276. if ( t1 === undefined ) {
  15277. i1 = pp.length;
  15278. this._cachedIndex = i1;
  15279. return this.afterEnd_( i1 - 1, t0, t );
  15280. }
  15281. } // seek
  15282. this._cachedIndex = i1;
  15283. this.intervalChanged_( i1, t0, t1 );
  15284. } // validate_interval
  15285. return this.interpolate_( i1, t0, t, t1 );
  15286. },
  15287. settings: null, // optional, subclass-specific settings structure
  15288. // Note: The indirection allows central control of many interpolants.
  15289. // --- Protected interface
  15290. DefaultSettings_: {},
  15291. getSettings_: function() {
  15292. return this.settings || this.DefaultSettings_;
  15293. },
  15294. copySampleValue_: function( index ) {
  15295. // copies a sample value to the result buffer
  15296. var result = this.resultBuffer,
  15297. values = this.sampleValues,
  15298. stride = this.valueSize,
  15299. offset = index * stride;
  15300. for ( var i = 0; i !== stride; ++ i ) {
  15301. result[ i ] = values[ offset + i ];
  15302. }
  15303. return result;
  15304. },
  15305. // Template methods for derived classes:
  15306. interpolate_: function( i1, t0, t, t1 ) {
  15307. throw new Error( "call to abstract method" );
  15308. // implementations shall return this.resultBuffer
  15309. },
  15310. intervalChanged_: function( i1, t0, t1 ) {
  15311. // empty
  15312. }
  15313. };
  15314. Object.assign( Interpolant.prototype, {
  15315. beforeStart_: //( 0, t, t0 ), returns this.resultBuffer
  15316. Interpolant.prototype.copySampleValue_,
  15317. afterEnd_: //( N-1, tN-1, t ), returns this.resultBuffer
  15318. Interpolant.prototype.copySampleValue_
  15319. } );
  15320. /**
  15321. * Fast and simple cubic spline interpolant.
  15322. *
  15323. * It was derived from a Hermitian construction setting the first derivative
  15324. * at each sample position to the linear slope between neighboring positions
  15325. * over their parameter interval.
  15326. *
  15327. * @author tschw
  15328. */
  15329. function CubicInterpolant(
  15330. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  15331. Interpolant.call(
  15332. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  15333. this._weightPrev = -0;
  15334. this._offsetPrev = -0;
  15335. this._weightNext = -0;
  15336. this._offsetNext = -0;
  15337. }
  15338. CubicInterpolant.prototype =
  15339. Object.assign( Object.create( Interpolant.prototype ), {
  15340. constructor: CubicInterpolant,
  15341. DefaultSettings_: {
  15342. endingStart: ZeroCurvatureEnding,
  15343. endingEnd: ZeroCurvatureEnding
  15344. },
  15345. intervalChanged_: function( i1, t0, t1 ) {
  15346. var pp = this.parameterPositions,
  15347. iPrev = i1 - 2,
  15348. iNext = i1 + 1,
  15349. tPrev = pp[ iPrev ],
  15350. tNext = pp[ iNext ];
  15351. if ( tPrev === undefined ) {
  15352. switch ( this.getSettings_().endingStart ) {
  15353. case ZeroSlopeEnding:
  15354. // f'(t0) = 0
  15355. iPrev = i1;
  15356. tPrev = 2 * t0 - t1;
  15357. break;
  15358. case WrapAroundEnding:
  15359. // use the other end of the curve
  15360. iPrev = pp.length - 2;
  15361. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  15362. break;
  15363. default: // ZeroCurvatureEnding
  15364. // f''(t0) = 0 a.k.a. Natural Spline
  15365. iPrev = i1;
  15366. tPrev = t1;
  15367. }
  15368. }
  15369. if ( tNext === undefined ) {
  15370. switch ( this.getSettings_().endingEnd ) {
  15371. case ZeroSlopeEnding:
  15372. // f'(tN) = 0
  15373. iNext = i1;
  15374. tNext = 2 * t1 - t0;
  15375. break;
  15376. case WrapAroundEnding:
  15377. // use the other end of the curve
  15378. iNext = 1;
  15379. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  15380. break;
  15381. default: // ZeroCurvatureEnding
  15382. // f''(tN) = 0, a.k.a. Natural Spline
  15383. iNext = i1 - 1;
  15384. tNext = t0;
  15385. }
  15386. }
  15387. var halfDt = ( t1 - t0 ) * 0.5,
  15388. stride = this.valueSize;
  15389. this._weightPrev = halfDt / ( t0 - tPrev );
  15390. this._weightNext = halfDt / ( tNext - t1 );
  15391. this._offsetPrev = iPrev * stride;
  15392. this._offsetNext = iNext * stride;
  15393. },
  15394. interpolate_: function( i1, t0, t, t1 ) {
  15395. var result = this.resultBuffer,
  15396. values = this.sampleValues,
  15397. stride = this.valueSize,
  15398. o1 = i1 * stride, o0 = o1 - stride,
  15399. oP = this._offsetPrev, oN = this._offsetNext,
  15400. wP = this._weightPrev, wN = this._weightNext,
  15401. p = ( t - t0 ) / ( t1 - t0 ),
  15402. pp = p * p,
  15403. ppp = pp * p;
  15404. // evaluate polynomials
  15405. var sP = - wP * ppp + 2 * wP * pp - wP * p;
  15406. var s0 = ( 1 + wP ) * ppp + (-1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  15407. var s1 = (-1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  15408. var sN = wN * ppp - wN * pp;
  15409. // combine data linearly
  15410. for ( var i = 0; i !== stride; ++ i ) {
  15411. result[ i ] =
  15412. sP * values[ oP + i ] +
  15413. s0 * values[ o0 + i ] +
  15414. s1 * values[ o1 + i ] +
  15415. sN * values[ oN + i ];
  15416. }
  15417. return result;
  15418. }
  15419. } );
  15420. /**
  15421. * @author tschw
  15422. */
  15423. function LinearInterpolant(
  15424. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  15425. Interpolant.call(
  15426. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  15427. }
  15428. LinearInterpolant.prototype =
  15429. Object.assign( Object.create( Interpolant.prototype ), {
  15430. constructor: LinearInterpolant,
  15431. interpolate_: function( i1, t0, t, t1 ) {
  15432. var result = this.resultBuffer,
  15433. values = this.sampleValues,
  15434. stride = this.valueSize,
  15435. offset1 = i1 * stride,
  15436. offset0 = offset1 - stride,
  15437. weight1 = ( t - t0 ) / ( t1 - t0 ),
  15438. weight0 = 1 - weight1;
  15439. for ( var i = 0; i !== stride; ++ i ) {
  15440. result[ i ] =
  15441. values[ offset0 + i ] * weight0 +
  15442. values[ offset1 + i ] * weight1;
  15443. }
  15444. return result;
  15445. }
  15446. } );
  15447. /**
  15448. *
  15449. * Interpolant that evaluates to the sample value at the position preceeding
  15450. * the parameter.
  15451. *
  15452. * @author tschw
  15453. */
  15454. function DiscreteInterpolant(
  15455. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  15456. Interpolant.call(
  15457. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  15458. }
  15459. DiscreteInterpolant.prototype =
  15460. Object.assign( Object.create( Interpolant.prototype ), {
  15461. constructor: DiscreteInterpolant,
  15462. interpolate_: function( i1, t0, t, t1 ) {
  15463. return this.copySampleValue_( i1 - 1 );
  15464. }
  15465. } );
  15466. var KeyframeTrackPrototype;
  15467. KeyframeTrackPrototype = {
  15468. TimeBufferType: Float32Array,
  15469. ValueBufferType: Float32Array,
  15470. DefaultInterpolation: InterpolateLinear,
  15471. InterpolantFactoryMethodDiscrete: function( result ) {
  15472. return new DiscreteInterpolant(
  15473. this.times, this.values, this.getValueSize(), result );
  15474. },
  15475. InterpolantFactoryMethodLinear: function( result ) {
  15476. return new LinearInterpolant(
  15477. this.times, this.values, this.getValueSize(), result );
  15478. },
  15479. InterpolantFactoryMethodSmooth: function( result ) {
  15480. return new CubicInterpolant(
  15481. this.times, this.values, this.getValueSize(), result );
  15482. },
  15483. setInterpolation: function( interpolation ) {
  15484. var factoryMethod;
  15485. switch ( interpolation ) {
  15486. case InterpolateDiscrete:
  15487. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  15488. break;
  15489. case InterpolateLinear:
  15490. factoryMethod = this.InterpolantFactoryMethodLinear;
  15491. break;
  15492. case InterpolateSmooth:
  15493. factoryMethod = this.InterpolantFactoryMethodSmooth;
  15494. break;
  15495. }
  15496. if ( factoryMethod === undefined ) {
  15497. var message = "unsupported interpolation for " +
  15498. this.ValueTypeName + " keyframe track named " + this.name;
  15499. if ( this.createInterpolant === undefined ) {
  15500. // fall back to default, unless the default itself is messed up
  15501. if ( interpolation !== this.DefaultInterpolation ) {
  15502. this.setInterpolation( this.DefaultInterpolation );
  15503. } else {
  15504. throw new Error( message ); // fatal, in this case
  15505. }
  15506. }
  15507. console.warn( message );
  15508. return;
  15509. }
  15510. this.createInterpolant = factoryMethod;
  15511. },
  15512. getInterpolation: function() {
  15513. switch ( this.createInterpolant ) {
  15514. case this.InterpolantFactoryMethodDiscrete:
  15515. return InterpolateDiscrete;
  15516. case this.InterpolantFactoryMethodLinear:
  15517. return InterpolateLinear;
  15518. case this.InterpolantFactoryMethodSmooth:
  15519. return InterpolateSmooth;
  15520. }
  15521. },
  15522. getValueSize: function() {
  15523. return this.values.length / this.times.length;
  15524. },
  15525. // move all keyframes either forwards or backwards in time
  15526. shift: function( timeOffset ) {
  15527. if( timeOffset !== 0.0 ) {
  15528. var times = this.times;
  15529. for( var i = 0, n = times.length; i !== n; ++ i ) {
  15530. times[ i ] += timeOffset;
  15531. }
  15532. }
  15533. return this;
  15534. },
  15535. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  15536. scale: function( timeScale ) {
  15537. if( timeScale !== 1.0 ) {
  15538. var times = this.times;
  15539. for( var i = 0, n = times.length; i !== n; ++ i ) {
  15540. times[ i ] *= timeScale;
  15541. }
  15542. }
  15543. return this;
  15544. },
  15545. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  15546. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  15547. trim: function( startTime, endTime ) {
  15548. var times = this.times,
  15549. nKeys = times.length,
  15550. from = 0,
  15551. to = nKeys - 1;
  15552. while ( from !== nKeys && times[ from ] < startTime ) ++ from;
  15553. while ( to !== -1 && times[ to ] > endTime ) -- to;
  15554. ++ to; // inclusive -> exclusive bound
  15555. if( from !== 0 || to !== nKeys ) {
  15556. // empty tracks are forbidden, so keep at least one keyframe
  15557. if ( from >= to ) to = Math.max( to , 1 ), from = to - 1;
  15558. var stride = this.getValueSize();
  15559. this.times = exports.AnimationUtils.arraySlice( times, from, to );
  15560. this.values = exports.AnimationUtils.
  15561. arraySlice( this.values, from * stride, to * stride );
  15562. }
  15563. return this;
  15564. },
  15565. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  15566. validate: function() {
  15567. var valid = true;
  15568. var valueSize = this.getValueSize();
  15569. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  15570. console.error( "invalid value size in track", this );
  15571. valid = false;
  15572. }
  15573. var times = this.times,
  15574. values = this.values,
  15575. nKeys = times.length;
  15576. if( nKeys === 0 ) {
  15577. console.error( "track is empty", this );
  15578. valid = false;
  15579. }
  15580. var prevTime = null;
  15581. for( var i = 0; i !== nKeys; i ++ ) {
  15582. var currTime = times[ i ];
  15583. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  15584. console.error( "time is not a valid number", this, i, currTime );
  15585. valid = false;
  15586. break;
  15587. }
  15588. if( prevTime !== null && prevTime > currTime ) {
  15589. console.error( "out of order keys", this, i, currTime, prevTime );
  15590. valid = false;
  15591. break;
  15592. }
  15593. prevTime = currTime;
  15594. }
  15595. if ( values !== undefined ) {
  15596. if ( exports.AnimationUtils.isTypedArray( values ) ) {
  15597. for ( var i = 0, n = values.length; i !== n; ++ i ) {
  15598. var value = values[ i ];
  15599. if ( isNaN( value ) ) {
  15600. console.error( "value is not a valid number", this, i, value );
  15601. valid = false;
  15602. break;
  15603. }
  15604. }
  15605. }
  15606. }
  15607. return valid;
  15608. },
  15609. // removes equivalent sequential keys as common in morph target sequences
  15610. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  15611. optimize: function() {
  15612. var times = this.times,
  15613. values = this.values,
  15614. stride = this.getValueSize(),
  15615. writeIndex = 1;
  15616. for( var i = 1, n = times.length - 1; i <= n; ++ i ) {
  15617. var keep = false;
  15618. var time = times[ i ];
  15619. var timeNext = times[ i + 1 ];
  15620. // remove adjacent keyframes scheduled at the same time
  15621. if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) {
  15622. // remove unnecessary keyframes same as their neighbors
  15623. var offset = i * stride,
  15624. offsetP = offset - stride,
  15625. offsetN = offset + stride;
  15626. for ( var j = 0; j !== stride; ++ j ) {
  15627. var value = values[ offset + j ];
  15628. if ( value !== values[ offsetP + j ] ||
  15629. value !== values[ offsetN + j ] ) {
  15630. keep = true;
  15631. break;
  15632. }
  15633. }
  15634. }
  15635. // in-place compaction
  15636. if ( keep ) {
  15637. if ( i !== writeIndex ) {
  15638. times[ writeIndex ] = times[ i ];
  15639. var readOffset = i * stride,
  15640. writeOffset = writeIndex * stride;
  15641. for ( var j = 0; j !== stride; ++ j ) {
  15642. values[ writeOffset + j ] = values[ readOffset + j ];
  15643. }
  15644. }
  15645. ++ writeIndex;
  15646. }
  15647. }
  15648. if ( writeIndex !== times.length ) {
  15649. this.times = exports.AnimationUtils.arraySlice( times, 0, writeIndex );
  15650. this.values = exports.AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  15651. }
  15652. return this;
  15653. }
  15654. }
  15655. function KeyframeTrackConstructor( name, times, values, interpolation ) {
  15656. if( name === undefined ) throw new Error( "track name is undefined" );
  15657. if( times === undefined || times.length === 0 ) {
  15658. throw new Error( "no keyframes in track named " + name );
  15659. }
  15660. this.name = name;
  15661. this.times = exports.AnimationUtils.convertArray( times, this.TimeBufferType );
  15662. this.values = exports.AnimationUtils.convertArray( values, this.ValueBufferType );
  15663. this.setInterpolation( interpolation || this.DefaultInterpolation );
  15664. this.validate();
  15665. this.optimize();
  15666. }
  15667. /**
  15668. *
  15669. * A Track of vectored keyframe values.
  15670. *
  15671. *
  15672. * @author Ben Houston / http://clara.io/
  15673. * @author David Sarno / http://lighthaus.us/
  15674. * @author tschw
  15675. */
  15676. function VectorKeyframeTrack( name, times, values, interpolation ) {
  15677. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  15678. }
  15679. VectorKeyframeTrack.prototype =
  15680. Object.assign( Object.create( KeyframeTrackPrototype ), {
  15681. constructor: VectorKeyframeTrack,
  15682. ValueTypeName: 'vector'
  15683. // ValueBufferType is inherited
  15684. // DefaultInterpolation is inherited
  15685. } );
  15686. /**
  15687. * Spherical linear unit quaternion interpolant.
  15688. *
  15689. * @author tschw
  15690. */
  15691. function QuaternionLinearInterpolant(
  15692. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  15693. Interpolant.call(
  15694. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  15695. }
  15696. QuaternionLinearInterpolant.prototype =
  15697. Object.assign( Object.create( Interpolant.prototype ), {
  15698. constructor: QuaternionLinearInterpolant,
  15699. interpolate_: function( i1, t0, t, t1 ) {
  15700. var result = this.resultBuffer,
  15701. values = this.sampleValues,
  15702. stride = this.valueSize,
  15703. offset = i1 * stride,
  15704. alpha = ( t - t0 ) / ( t1 - t0 );
  15705. for ( var end = offset + stride; offset !== end; offset += 4 ) {
  15706. Quaternion.slerpFlat( result, 0,
  15707. values, offset - stride, values, offset, alpha );
  15708. }
  15709. return result;
  15710. }
  15711. } );
  15712. /**
  15713. *
  15714. * A Track of quaternion keyframe values.
  15715. *
  15716. * @author Ben Houston / http://clara.io/
  15717. * @author David Sarno / http://lighthaus.us/
  15718. * @author tschw
  15719. */
  15720. function QuaternionKeyframeTrack( name, times, values, interpolation ) {
  15721. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  15722. }
  15723. QuaternionKeyframeTrack.prototype =
  15724. Object.assign( Object.create( KeyframeTrackPrototype ), {
  15725. constructor: QuaternionKeyframeTrack,
  15726. ValueTypeName: 'quaternion',
  15727. // ValueBufferType is inherited
  15728. DefaultInterpolation: InterpolateLinear,
  15729. InterpolantFactoryMethodLinear: function( result ) {
  15730. return new QuaternionLinearInterpolant(
  15731. this.times, this.values, this.getValueSize(), result );
  15732. },
  15733. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  15734. } );
  15735. /**
  15736. *
  15737. * A Track of numeric keyframe values.
  15738. *
  15739. * @author Ben Houston / http://clara.io/
  15740. * @author David Sarno / http://lighthaus.us/
  15741. * @author tschw
  15742. */
  15743. function NumberKeyframeTrack( name, times, values, interpolation ) {
  15744. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  15745. }
  15746. NumberKeyframeTrack.prototype =
  15747. Object.assign( Object.create( KeyframeTrackPrototype ), {
  15748. constructor: NumberKeyframeTrack,
  15749. ValueTypeName: 'number',
  15750. // ValueBufferType is inherited
  15751. // DefaultInterpolation is inherited
  15752. } );
  15753. /**
  15754. *
  15755. * A Track that interpolates Strings
  15756. *
  15757. *
  15758. * @author Ben Houston / http://clara.io/
  15759. * @author David Sarno / http://lighthaus.us/
  15760. * @author tschw
  15761. */
  15762. function StringKeyframeTrack( name, times, values, interpolation ) {
  15763. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  15764. }
  15765. StringKeyframeTrack.prototype =
  15766. Object.assign( Object.create( KeyframeTrackPrototype ), {
  15767. constructor: StringKeyframeTrack,
  15768. ValueTypeName: 'string',
  15769. ValueBufferType: Array,
  15770. DefaultInterpolation: InterpolateDiscrete,
  15771. InterpolantFactoryMethodLinear: undefined,
  15772. InterpolantFactoryMethodSmooth: undefined
  15773. } );
  15774. /**
  15775. *
  15776. * A Track of Boolean keyframe values.
  15777. *
  15778. *
  15779. * @author Ben Houston / http://clara.io/
  15780. * @author David Sarno / http://lighthaus.us/
  15781. * @author tschw
  15782. */
  15783. function BooleanKeyframeTrack( name, times, values ) {
  15784. KeyframeTrackConstructor.call( this, name, times, values );
  15785. }
  15786. BooleanKeyframeTrack.prototype =
  15787. Object.assign( Object.create( KeyframeTrackPrototype ), {
  15788. constructor: BooleanKeyframeTrack,
  15789. ValueTypeName: 'bool',
  15790. ValueBufferType: Array,
  15791. DefaultInterpolation: InterpolateDiscrete,
  15792. InterpolantFactoryMethodLinear: undefined,
  15793. InterpolantFactoryMethodSmooth: undefined
  15794. // Note: Actually this track could have a optimized / compressed
  15795. // representation of a single value and a custom interpolant that
  15796. // computes "firstValue ^ isOdd( index )".
  15797. } );
  15798. /**
  15799. *
  15800. * A Track of keyframe values that represent color.
  15801. *
  15802. *
  15803. * @author Ben Houston / http://clara.io/
  15804. * @author David Sarno / http://lighthaus.us/
  15805. * @author tschw
  15806. */
  15807. function ColorKeyframeTrack( name, times, values, interpolation ) {
  15808. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  15809. }
  15810. ColorKeyframeTrack.prototype =
  15811. Object.assign( Object.create( KeyframeTrackPrototype ), {
  15812. constructor: ColorKeyframeTrack,
  15813. ValueTypeName: 'color'
  15814. // ValueBufferType is inherited
  15815. // DefaultInterpolation is inherited
  15816. // Note: Very basic implementation and nothing special yet.
  15817. // However, this is the place for color space parameterization.
  15818. } );
  15819. /**
  15820. *
  15821. * A timed sequence of keyframes for a specific property.
  15822. *
  15823. *
  15824. * @author Ben Houston / http://clara.io/
  15825. * @author David Sarno / http://lighthaus.us/
  15826. * @author tschw
  15827. */
  15828. function KeyframeTrack( name, times, values, interpolation ) {
  15829. KeyframeTrackConstructor.apply( this, arguments );
  15830. }
  15831. KeyframeTrack.prototype = KeyframeTrackPrototype;
  15832. KeyframeTrackPrototype.constructor = KeyframeTrack;
  15833. // Static methods:
  15834. Object.assign( KeyframeTrack, {
  15835. // Serialization (in static context, because of constructor invocation
  15836. // and automatic invocation of .toJSON):
  15837. parse: function( json ) {
  15838. if( json.type === undefined ) {
  15839. throw new Error( "track type undefined, can not parse" );
  15840. }
  15841. var trackType = KeyframeTrack._getTrackTypeForValueTypeName( json.type );
  15842. if ( json.times === undefined ) {
  15843. var times = [], values = [];
  15844. exports.AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  15845. json.times = times;
  15846. json.values = values;
  15847. }
  15848. // derived classes can define a static parse method
  15849. if ( trackType.parse !== undefined ) {
  15850. return trackType.parse( json );
  15851. } else {
  15852. // by default, we asssume a constructor compatible with the base
  15853. return new trackType(
  15854. json.name, json.times, json.values, json.interpolation );
  15855. }
  15856. },
  15857. toJSON: function( track ) {
  15858. var trackType = track.constructor;
  15859. var json;
  15860. // derived classes can define a static toJSON method
  15861. if ( trackType.toJSON !== undefined ) {
  15862. json = trackType.toJSON( track );
  15863. } else {
  15864. // by default, we assume the data can be serialized as-is
  15865. json = {
  15866. 'name': track.name,
  15867. 'times': exports.AnimationUtils.convertArray( track.times, Array ),
  15868. 'values': exports.AnimationUtils.convertArray( track.values, Array )
  15869. };
  15870. var interpolation = track.getInterpolation();
  15871. if ( interpolation !== track.DefaultInterpolation ) {
  15872. json.interpolation = interpolation;
  15873. }
  15874. }
  15875. json.type = track.ValueTypeName; // mandatory
  15876. return json;
  15877. },
  15878. _getTrackTypeForValueTypeName: function( typeName ) {
  15879. switch( typeName.toLowerCase() ) {
  15880. case "scalar":
  15881. case "double":
  15882. case "float":
  15883. case "number":
  15884. case "integer":
  15885. return NumberKeyframeTrack;
  15886. case "vector":
  15887. case "vector2":
  15888. case "vector3":
  15889. case "vector4":
  15890. return VectorKeyframeTrack;
  15891. case "color":
  15892. return ColorKeyframeTrack;
  15893. case "quaternion":
  15894. return QuaternionKeyframeTrack;
  15895. case "bool":
  15896. case "boolean":
  15897. return BooleanKeyframeTrack;
  15898. case "string":
  15899. return StringKeyframeTrack;
  15900. }
  15901. throw new Error( "Unsupported typeName: " + typeName );
  15902. }
  15903. } );
  15904. /**
  15905. *
  15906. * Reusable set of Tracks that represent an animation.
  15907. *
  15908. * @author Ben Houston / http://clara.io/
  15909. * @author David Sarno / http://lighthaus.us/
  15910. */
  15911. function AnimationClip( name, duration, tracks ) {
  15912. this.name = name;
  15913. this.tracks = tracks;
  15914. this.duration = ( duration !== undefined ) ? duration : -1;
  15915. this.uuid = exports.Math.generateUUID();
  15916. // this means it should figure out its duration by scanning the tracks
  15917. if ( this.duration < 0 ) {
  15918. this.resetDuration();
  15919. }
  15920. // maybe only do these on demand, as doing them here could potentially slow down loading
  15921. // but leaving these here during development as this ensures a lot of testing of these functions
  15922. this.trim();
  15923. this.optimize();
  15924. }
  15925. AnimationClip.prototype = {
  15926. constructor: AnimationClip,
  15927. resetDuration: function() {
  15928. var tracks = this.tracks,
  15929. duration = 0;
  15930. for ( var i = 0, n = tracks.length; i !== n; ++ i ) {
  15931. var track = this.tracks[ i ];
  15932. duration = Math.max(
  15933. duration, track.times[ track.times.length - 1 ] );
  15934. }
  15935. this.duration = duration;
  15936. },
  15937. trim: function() {
  15938. for ( var i = 0; i < this.tracks.length; i ++ ) {
  15939. this.tracks[ i ].trim( 0, this.duration );
  15940. }
  15941. return this;
  15942. },
  15943. optimize: function() {
  15944. for ( var i = 0; i < this.tracks.length; i ++ ) {
  15945. this.tracks[ i ].optimize();
  15946. }
  15947. return this;
  15948. }
  15949. };
  15950. // Static methods:
  15951. Object.assign( AnimationClip, {
  15952. parse: function( json ) {
  15953. var tracks = [],
  15954. jsonTracks = json.tracks,
  15955. frameTime = 1.0 / ( json.fps || 1.0 );
  15956. for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  15957. tracks.push( KeyframeTrack.parse( jsonTracks[ i ] ).scale( frameTime ) );
  15958. }
  15959. return new AnimationClip( json.name, json.duration, tracks );
  15960. },
  15961. toJSON: function( clip ) {
  15962. var tracks = [],
  15963. clipTracks = clip.tracks;
  15964. var json = {
  15965. 'name': clip.name,
  15966. 'duration': clip.duration,
  15967. 'tracks': tracks
  15968. };
  15969. for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) {
  15970. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  15971. }
  15972. return json;
  15973. },
  15974. CreateFromMorphTargetSequence: function( name, morphTargetSequence, fps, noLoop ) {
  15975. var numMorphTargets = morphTargetSequence.length;
  15976. var tracks = [];
  15977. for ( var i = 0; i < numMorphTargets; i ++ ) {
  15978. var times = [];
  15979. var values = [];
  15980. times.push(
  15981. ( i + numMorphTargets - 1 ) % numMorphTargets,
  15982. i,
  15983. ( i + 1 ) % numMorphTargets );
  15984. values.push( 0, 1, 0 );
  15985. var order = exports.AnimationUtils.getKeyframeOrder( times );
  15986. times = exports.AnimationUtils.sortedArray( times, 1, order );
  15987. values = exports.AnimationUtils.sortedArray( values, 1, order );
  15988. // if there is a key at the first frame, duplicate it as the
  15989. // last frame as well for perfect loop.
  15990. if ( ! noLoop && times[ 0 ] === 0 ) {
  15991. times.push( numMorphTargets );
  15992. values.push( values[ 0 ] );
  15993. }
  15994. tracks.push(
  15995. new NumberKeyframeTrack(
  15996. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  15997. times, values
  15998. ).scale( 1.0 / fps ) );
  15999. }
  16000. return new AnimationClip( name, -1, tracks );
  16001. },
  16002. findByName: function( objectOrClipArray, name ) {
  16003. var clipArray = objectOrClipArray;
  16004. if ( ! Array.isArray( objectOrClipArray ) ) {
  16005. var o = objectOrClipArray;
  16006. clipArray = o.geometry && o.geometry.animations || o.animations;
  16007. }
  16008. for ( var i = 0; i < clipArray.length; i ++ ) {
  16009. if ( clipArray[ i ].name === name ) {
  16010. return clipArray[ i ];
  16011. }
  16012. }
  16013. return null;
  16014. },
  16015. CreateClipsFromMorphTargetSequences: function( morphTargets, fps, noLoop ) {
  16016. var animationToMorphTargets = {};
  16017. // tested with https://regex101.com/ on trick sequences
  16018. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  16019. var pattern = /^([\w-]*?)([\d]+)$/;
  16020. // sort morph target names into animation groups based
  16021. // patterns like Walk_001, Walk_002, Run_001, Run_002
  16022. for ( var i = 0, il = morphTargets.length; i < il; i ++ ) {
  16023. var morphTarget = morphTargets[ i ];
  16024. var parts = morphTarget.name.match( pattern );
  16025. if ( parts && parts.length > 1 ) {
  16026. var name = parts[ 1 ];
  16027. var animationMorphTargets = animationToMorphTargets[ name ];
  16028. if ( ! animationMorphTargets ) {
  16029. animationToMorphTargets[ name ] = animationMorphTargets = [];
  16030. }
  16031. animationMorphTargets.push( morphTarget );
  16032. }
  16033. }
  16034. var clips = [];
  16035. for ( var name in animationToMorphTargets ) {
  16036. clips.push( AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  16037. }
  16038. return clips;
  16039. },
  16040. // parse the animation.hierarchy format
  16041. parseAnimation: function( animation, bones, nodeName ) {
  16042. if ( ! animation ) {
  16043. console.error( " no animation in JSONLoader data" );
  16044. return null;
  16045. }
  16046. var addNonemptyTrack = function(
  16047. trackType, trackName, animationKeys, propertyName, destTracks ) {
  16048. // only return track if there are actually keys.
  16049. if ( animationKeys.length !== 0 ) {
  16050. var times = [];
  16051. var values = [];
  16052. exports.AnimationUtils.flattenJSON(
  16053. animationKeys, times, values, propertyName );
  16054. // empty keys are filtered out, so check again
  16055. if ( times.length !== 0 ) {
  16056. destTracks.push( new trackType( trackName, times, values ) );
  16057. }
  16058. }
  16059. };
  16060. var tracks = [];
  16061. var clipName = animation.name || 'default';
  16062. // automatic length determination in AnimationClip.
  16063. var duration = animation.length || -1;
  16064. var fps = animation.fps || 30;
  16065. var hierarchyTracks = animation.hierarchy || [];
  16066. for ( var h = 0; h < hierarchyTracks.length; h ++ ) {
  16067. var animationKeys = hierarchyTracks[ h ].keys;
  16068. // skip empty tracks
  16069. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  16070. // process morph targets in a way exactly compatible
  16071. // with AnimationHandler.init( animation )
  16072. if ( animationKeys[0].morphTargets ) {
  16073. // figure out all morph targets used in this track
  16074. var morphTargetNames = {};
  16075. for ( var k = 0; k < animationKeys.length; k ++ ) {
  16076. if ( animationKeys[k].morphTargets ) {
  16077. for ( var m = 0; m < animationKeys[k].morphTargets.length; m ++ ) {
  16078. morphTargetNames[ animationKeys[k].morphTargets[m] ] = -1;
  16079. }
  16080. }
  16081. }
  16082. // create a track for each morph target with all zero
  16083. // morphTargetInfluences except for the keys in which
  16084. // the morphTarget is named.
  16085. for ( var morphTargetName in morphTargetNames ) {
  16086. var times = [];
  16087. var values = [];
  16088. for ( var m = 0;
  16089. m !== animationKeys[k].morphTargets.length; ++ m ) {
  16090. var animationKey = animationKeys[k];
  16091. times.push( animationKey.time );
  16092. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  16093. }
  16094. tracks.push( new NumberKeyframeTrack(
  16095. '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  16096. }
  16097. duration = morphTargetNames.length * ( fps || 1.0 );
  16098. } else {
  16099. // ...assume skeletal animation
  16100. var boneName = '.bones[' + bones[ h ].name + ']';
  16101. addNonemptyTrack(
  16102. VectorKeyframeTrack, boneName + '.position',
  16103. animationKeys, 'pos', tracks );
  16104. addNonemptyTrack(
  16105. QuaternionKeyframeTrack, boneName + '.quaternion',
  16106. animationKeys, 'rot', tracks );
  16107. addNonemptyTrack(
  16108. VectorKeyframeTrack, boneName + '.scale',
  16109. animationKeys, 'scl', tracks );
  16110. }
  16111. }
  16112. if ( tracks.length === 0 ) {
  16113. return null;
  16114. }
  16115. var clip = new AnimationClip( clipName, duration, tracks );
  16116. return clip;
  16117. }
  16118. } );
  16119. /**
  16120. * @author mrdoob / http://mrdoob.com/
  16121. */
  16122. function MaterialLoader( manager ) {
  16123. this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager;
  16124. this.textures = {};
  16125. }
  16126. Object.assign( MaterialLoader.prototype, {
  16127. load: function ( url, onLoad, onProgress, onError ) {
  16128. var scope = this;
  16129. var loader = new XHRLoader( scope.manager );
  16130. loader.load( url, function ( text ) {
  16131. onLoad( scope.parse( JSON.parse( text ) ) );
  16132. }, onProgress, onError );
  16133. },
  16134. setTextures: function ( value ) {
  16135. this.textures = value;
  16136. },
  16137. getTexture: function ( name ) {
  16138. var textures = this.textures;
  16139. if ( textures[ name ] === undefined ) {
  16140. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  16141. }
  16142. return textures[ name ];
  16143. },
  16144. parse: function ( json ) {
  16145. var material = new THREE[ json.type ];
  16146. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  16147. if ( json.name !== undefined ) material.name = json.name;
  16148. if ( json.color !== undefined ) material.color.setHex( json.color );
  16149. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  16150. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  16151. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  16152. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  16153. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  16154. if ( json.uniforms !== undefined ) material.uniforms = json.uniforms;
  16155. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  16156. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  16157. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  16158. if ( json.fog !== undefined ) material.fog = json.fog;
  16159. if ( json.shading !== undefined ) material.shading = json.shading;
  16160. if ( json.blending !== undefined ) material.blending = json.blending;
  16161. if ( json.side !== undefined ) material.side = json.side;
  16162. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  16163. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  16164. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  16165. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  16166. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  16167. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  16168. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  16169. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  16170. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  16171. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  16172. if ( json.skinning !== undefined ) material.skinning = json.skinning;
  16173. if ( json.morphTargets !== undefined ) material.wireframe = json.morphTargets;
  16174. // for PointsMaterial
  16175. if ( json.size !== undefined ) material.size = json.size;
  16176. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  16177. // maps
  16178. if ( json.map !== undefined ) material.map = this.getTexture( json.map );
  16179. if ( json.alphaMap !== undefined ) {
  16180. material.alphaMap = this.getTexture( json.alphaMap );
  16181. material.transparent = true;
  16182. }
  16183. if ( json.bumpMap !== undefined ) material.bumpMap = this.getTexture( json.bumpMap );
  16184. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  16185. if ( json.normalMap !== undefined ) material.normalMap = this.getTexture( json.normalMap );
  16186. if ( json.normalScale !== undefined ) {
  16187. var normalScale = json.normalScale;
  16188. if ( Array.isArray( normalScale ) === false ) {
  16189. // Blender exporter used to export a scalar. See #7459
  16190. normalScale = [ normalScale, normalScale ];
  16191. }
  16192. material.normalScale = new Vector2().fromArray( normalScale );
  16193. }
  16194. if ( json.displacementMap !== undefined ) material.displacementMap = this.getTexture( json.displacementMap );
  16195. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  16196. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  16197. if ( json.roughnessMap !== undefined ) material.roughnessMap = this.getTexture( json.roughnessMap );
  16198. if ( json.metalnessMap !== undefined ) material.metalnessMap = this.getTexture( json.metalnessMap );
  16199. if ( json.emissiveMap !== undefined ) material.emissiveMap = this.getTexture( json.emissiveMap );
  16200. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  16201. if ( json.specularMap !== undefined ) material.specularMap = this.getTexture( json.specularMap );
  16202. if ( json.envMap !== undefined ) {
  16203. material.envMap = this.getTexture( json.envMap );
  16204. material.combine = MultiplyOperation;
  16205. }
  16206. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  16207. if ( json.lightMap !== undefined ) material.lightMap = this.getTexture( json.lightMap );
  16208. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  16209. if ( json.aoMap !== undefined ) material.aoMap = this.getTexture( json.aoMap );
  16210. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  16211. // MultiMaterial
  16212. if ( json.materials !== undefined ) {
  16213. for ( var i = 0, l = json.materials.length; i < l; i ++ ) {
  16214. material.materials.push( this.parse( json.materials[ i ] ) );
  16215. }
  16216. }
  16217. return material;
  16218. }
  16219. } );
  16220. /**
  16221. * @author mrdoob / http://mrdoob.com/
  16222. */
  16223. function BufferGeometryLoader( manager ) {
  16224. this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager;
  16225. }
  16226. Object.assign( BufferGeometryLoader.prototype, {
  16227. load: function ( url, onLoad, onProgress, onError ) {
  16228. var scope = this;
  16229. var loader = new XHRLoader( scope.manager );
  16230. loader.load( url, function ( text ) {
  16231. onLoad( scope.parse( JSON.parse( text ) ) );
  16232. }, onProgress, onError );
  16233. },
  16234. parse: function ( json ) {
  16235. var geometry = new BufferGeometry();
  16236. var index = json.data.index;
  16237. var TYPED_ARRAYS = {
  16238. 'Int8Array': Int8Array,
  16239. 'Uint8Array': Uint8Array,
  16240. 'Uint8ClampedArray': Uint8ClampedArray,
  16241. 'Int16Array': Int16Array,
  16242. 'Uint16Array': Uint16Array,
  16243. 'Int32Array': Int32Array,
  16244. 'Uint32Array': Uint32Array,
  16245. 'Float32Array': Float32Array,
  16246. 'Float64Array': Float64Array
  16247. };
  16248. if ( index !== undefined ) {
  16249. var typedArray = new TYPED_ARRAYS[ index.type ]( index.array );
  16250. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  16251. }
  16252. var attributes = json.data.attributes;
  16253. for ( var key in attributes ) {
  16254. var attribute = attributes[ key ];
  16255. var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array );
  16256. geometry.addAttribute( key, new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ) );
  16257. }
  16258. var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  16259. if ( groups !== undefined ) {
  16260. for ( var i = 0, n = groups.length; i !== n; ++ i ) {
  16261. var group = groups[ i ];
  16262. geometry.addGroup( group.start, group.count, group.materialIndex );
  16263. }
  16264. }
  16265. var boundingSphere = json.data.boundingSphere;
  16266. if ( boundingSphere !== undefined ) {
  16267. var center = new Vector3();
  16268. if ( boundingSphere.center !== undefined ) {
  16269. center.fromArray( boundingSphere.center );
  16270. }
  16271. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  16272. }
  16273. return geometry;
  16274. }
  16275. } );
  16276. /**
  16277. * @author alteredq / http://alteredqualia.com/
  16278. */
  16279. function Loader() {
  16280. this.onLoadStart = function () {};
  16281. this.onLoadProgress = function () {};
  16282. this.onLoadComplete = function () {};
  16283. }
  16284. Loader.prototype = {
  16285. constructor: Loader,
  16286. crossOrigin: undefined,
  16287. extractUrlBase: function ( url ) {
  16288. var parts = url.split( '/' );
  16289. if ( parts.length === 1 ) return './';
  16290. parts.pop();
  16291. return parts.join( '/' ) + '/';
  16292. },
  16293. initMaterials: function ( materials, texturePath, crossOrigin ) {
  16294. var array = [];
  16295. for ( var i = 0; i < materials.length; ++ i ) {
  16296. array[ i ] = this.createMaterial( materials[ i ], texturePath, crossOrigin );
  16297. }
  16298. return array;
  16299. },
  16300. createMaterial: ( function () {
  16301. var color, textureLoader, materialLoader;
  16302. return function createMaterial( m, texturePath, crossOrigin ) {
  16303. if ( color === undefined ) color = new Color();
  16304. if ( textureLoader === undefined ) textureLoader = new TextureLoader();
  16305. if ( materialLoader === undefined ) materialLoader = new MaterialLoader();
  16306. // convert from old material format
  16307. var textures = {};
  16308. function loadTexture( path, repeat, offset, wrap, anisotropy ) {
  16309. var fullPath = texturePath + path;
  16310. var loader = Loader.Handlers.get( fullPath );
  16311. var texture;
  16312. if ( loader !== null ) {
  16313. texture = loader.load( fullPath );
  16314. } else {
  16315. textureLoader.setCrossOrigin( crossOrigin );
  16316. texture = textureLoader.load( fullPath );
  16317. }
  16318. if ( repeat !== undefined ) {
  16319. texture.repeat.fromArray( repeat );
  16320. if ( repeat[ 0 ] !== 1 ) texture.wrapS = RepeatWrapping;
  16321. if ( repeat[ 1 ] !== 1 ) texture.wrapT = RepeatWrapping;
  16322. }
  16323. if ( offset !== undefined ) {
  16324. texture.offset.fromArray( offset );
  16325. }
  16326. if ( wrap !== undefined ) {
  16327. if ( wrap[ 0 ] === 'repeat' ) texture.wrapS = RepeatWrapping;
  16328. if ( wrap[ 0 ] === 'mirror' ) texture.wrapS = MirroredRepeatWrapping;
  16329. if ( wrap[ 1 ] === 'repeat' ) texture.wrapT = RepeatWrapping;
  16330. if ( wrap[ 1 ] === 'mirror' ) texture.wrapT = MirroredRepeatWrapping;
  16331. }
  16332. if ( anisotropy !== undefined ) {
  16333. texture.anisotropy = anisotropy;
  16334. }
  16335. var uuid = exports.Math.generateUUID();
  16336. textures[ uuid ] = texture;
  16337. return uuid;
  16338. }
  16339. //
  16340. var json = {
  16341. uuid: exports.Math.generateUUID(),
  16342. type: 'MeshLambertMaterial'
  16343. };
  16344. for ( var name in m ) {
  16345. var value = m[ name ];
  16346. switch ( name ) {
  16347. case 'DbgColor':
  16348. case 'DbgIndex':
  16349. case 'opticalDensity':
  16350. case 'illumination':
  16351. break;
  16352. case 'DbgName':
  16353. json.name = value;
  16354. break;
  16355. case 'blending':
  16356. json.blending = THREE[ value ];
  16357. break;
  16358. case 'colorAmbient':
  16359. case 'mapAmbient':
  16360. console.warn( 'THREE.Loader.createMaterial:', name, 'is no longer supported.' );
  16361. break;
  16362. case 'colorDiffuse':
  16363. json.color = color.fromArray( value ).getHex();
  16364. break;
  16365. case 'colorSpecular':
  16366. json.specular = color.fromArray( value ).getHex();
  16367. break;
  16368. case 'colorEmissive':
  16369. json.emissive = color.fromArray( value ).getHex();
  16370. break;
  16371. case 'specularCoef':
  16372. json.shininess = value;
  16373. break;
  16374. case 'shading':
  16375. if ( value.toLowerCase() === 'basic' ) json.type = 'MeshBasicMaterial';
  16376. if ( value.toLowerCase() === 'phong' ) json.type = 'MeshPhongMaterial';
  16377. if ( value.toLowerCase() === 'standard' ) json.type = 'MeshStandardMaterial';
  16378. break;
  16379. case 'mapDiffuse':
  16380. json.map = loadTexture( value, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  16381. break;
  16382. case 'mapDiffuseRepeat':
  16383. case 'mapDiffuseOffset':
  16384. case 'mapDiffuseWrap':
  16385. case 'mapDiffuseAnisotropy':
  16386. break;
  16387. case 'mapEmissive':
  16388. json.emissiveMap = loadTexture( value, m.mapEmissiveRepeat, m.mapEmissiveOffset, m.mapEmissiveWrap, m.mapEmissiveAnisotropy );
  16389. break;
  16390. case 'mapEmissiveRepeat':
  16391. case 'mapEmissiveOffset':
  16392. case 'mapEmissiveWrap':
  16393. case 'mapEmissiveAnisotropy':
  16394. break;
  16395. case 'mapLight':
  16396. json.lightMap = loadTexture( value, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  16397. break;
  16398. case 'mapLightRepeat':
  16399. case 'mapLightOffset':
  16400. case 'mapLightWrap':
  16401. case 'mapLightAnisotropy':
  16402. break;
  16403. case 'mapAO':
  16404. json.aoMap = loadTexture( value, m.mapAORepeat, m.mapAOOffset, m.mapAOWrap, m.mapAOAnisotropy );
  16405. break;
  16406. case 'mapAORepeat':
  16407. case 'mapAOOffset':
  16408. case 'mapAOWrap':
  16409. case 'mapAOAnisotropy':
  16410. break;
  16411. case 'mapBump':
  16412. json.bumpMap = loadTexture( value, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  16413. break;
  16414. case 'mapBumpScale':
  16415. json.bumpScale = value;
  16416. break;
  16417. case 'mapBumpRepeat':
  16418. case 'mapBumpOffset':
  16419. case 'mapBumpWrap':
  16420. case 'mapBumpAnisotropy':
  16421. break;
  16422. case 'mapNormal':
  16423. json.normalMap = loadTexture( value, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  16424. break;
  16425. case 'mapNormalFactor':
  16426. json.normalScale = [ value, value ];
  16427. break;
  16428. case 'mapNormalRepeat':
  16429. case 'mapNormalOffset':
  16430. case 'mapNormalWrap':
  16431. case 'mapNormalAnisotropy':
  16432. break;
  16433. case 'mapSpecular':
  16434. json.specularMap = loadTexture( value, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  16435. break;
  16436. case 'mapSpecularRepeat':
  16437. case 'mapSpecularOffset':
  16438. case 'mapSpecularWrap':
  16439. case 'mapSpecularAnisotropy':
  16440. break;
  16441. case 'mapMetalness':
  16442. json.metalnessMap = loadTexture( value, m.mapMetalnessRepeat, m.mapMetalnessOffset, m.mapMetalnessWrap, m.mapMetalnessAnisotropy );
  16443. break;
  16444. case 'mapMetalnessRepeat':
  16445. case 'mapMetalnessOffset':
  16446. case 'mapMetalnessWrap':
  16447. case 'mapMetalnessAnisotropy':
  16448. break;
  16449. case 'mapRoughness':
  16450. json.roughnessMap = loadTexture( value, m.mapRoughnessRepeat, m.mapRoughnessOffset, m.mapRoughnessWrap, m.mapRoughnessAnisotropy );
  16451. break;
  16452. case 'mapRoughnessRepeat':
  16453. case 'mapRoughnessOffset':
  16454. case 'mapRoughnessWrap':
  16455. case 'mapRoughnessAnisotropy':
  16456. break;
  16457. case 'mapAlpha':
  16458. json.alphaMap = loadTexture( value, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy );
  16459. break;
  16460. case 'mapAlphaRepeat':
  16461. case 'mapAlphaOffset':
  16462. case 'mapAlphaWrap':
  16463. case 'mapAlphaAnisotropy':
  16464. break;
  16465. case 'flipSided':
  16466. json.side = BackSide;
  16467. break;
  16468. case 'doubleSided':
  16469. json.side = DoubleSide;
  16470. break;
  16471. case 'transparency':
  16472. console.warn( 'THREE.Loader.createMaterial: transparency has been renamed to opacity' );
  16473. json.opacity = value;
  16474. break;
  16475. case 'depthTest':
  16476. case 'depthWrite':
  16477. case 'colorWrite':
  16478. case 'opacity':
  16479. case 'reflectivity':
  16480. case 'transparent':
  16481. case 'visible':
  16482. case 'wireframe':
  16483. json[ name ] = value;
  16484. break;
  16485. case 'vertexColors':
  16486. if ( value === true ) json.vertexColors = VertexColors;
  16487. if ( value === 'face' ) json.vertexColors = FaceColors;
  16488. break;
  16489. default:
  16490. console.error( 'THREE.Loader.createMaterial: Unsupported', name, value );
  16491. break;
  16492. }
  16493. }
  16494. if ( json.type === 'MeshBasicMaterial' ) delete json.emissive;
  16495. if ( json.type !== 'MeshPhongMaterial' ) delete json.specular;
  16496. if ( json.opacity < 1 ) json.transparent = true;
  16497. materialLoader.setTextures( textures );
  16498. return materialLoader.parse( json );
  16499. };
  16500. } )()
  16501. };
  16502. Loader.Handlers = {
  16503. handlers: [],
  16504. add: function ( regex, loader ) {
  16505. this.handlers.push( regex, loader );
  16506. },
  16507. get: function ( file ) {
  16508. var handlers = this.handlers;
  16509. for ( var i = 0, l = handlers.length; i < l; i += 2 ) {
  16510. var regex = handlers[ i ];
  16511. var loader = handlers[ i + 1 ];
  16512. if ( regex.test( file ) ) {
  16513. return loader;
  16514. }
  16515. }
  16516. return null;
  16517. }
  16518. };
  16519. /**
  16520. * @author mrdoob / http://mrdoob.com/
  16521. * @author alteredq / http://alteredqualia.com/
  16522. */
  16523. function JSONLoader( manager ) {
  16524. if ( typeof manager === 'boolean' ) {
  16525. console.warn( 'THREE.JSONLoader: showStatus parameter has been removed from constructor.' );
  16526. manager = undefined;
  16527. }
  16528. this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager;
  16529. this.withCredentials = false;
  16530. }
  16531. Object.assign( JSONLoader.prototype, {
  16532. load: function( url, onLoad, onProgress, onError ) {
  16533. var scope = this;
  16534. var texturePath = this.texturePath && ( typeof this.texturePath === "string" ) ? this.texturePath : Loader.prototype.extractUrlBase( url );
  16535. var loader = new XHRLoader( this.manager );
  16536. loader.setWithCredentials( this.withCredentials );
  16537. loader.load( url, function ( text ) {
  16538. var json = JSON.parse( text );
  16539. var metadata = json.metadata;
  16540. if ( metadata !== undefined ) {
  16541. var type = metadata.type;
  16542. if ( type !== undefined ) {
  16543. if ( type.toLowerCase() === 'object' ) {
  16544. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' );
  16545. return;
  16546. }
  16547. if ( type.toLowerCase() === 'scene' ) {
  16548. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.SceneLoader instead.' );
  16549. return;
  16550. }
  16551. }
  16552. }
  16553. var object = scope.parse( json, texturePath );
  16554. onLoad( object.geometry, object.materials );
  16555. }, onProgress, onError );
  16556. },
  16557. setTexturePath: function ( value ) {
  16558. this.texturePath = value;
  16559. },
  16560. parse: function ( json, texturePath ) {
  16561. var geometry = new Geometry(),
  16562. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  16563. parseModel( scale );
  16564. parseSkin();
  16565. parseMorphing( scale );
  16566. parseAnimations();
  16567. geometry.computeFaceNormals();
  16568. geometry.computeBoundingSphere();
  16569. function parseModel( scale ) {
  16570. function isBitSet( value, position ) {
  16571. return value & ( 1 << position );
  16572. }
  16573. var i, j, fi,
  16574. offset, zLength,
  16575. colorIndex, normalIndex, uvIndex, materialIndex,
  16576. type,
  16577. isQuad,
  16578. hasMaterial,
  16579. hasFaceVertexUv,
  16580. hasFaceNormal, hasFaceVertexNormal,
  16581. hasFaceColor, hasFaceVertexColor,
  16582. vertex, face, faceA, faceB, hex, normal,
  16583. uvLayer, uv, u, v,
  16584. faces = json.faces,
  16585. vertices = json.vertices,
  16586. normals = json.normals,
  16587. colors = json.colors,
  16588. nUvLayers = 0;
  16589. if ( json.uvs !== undefined ) {
  16590. // disregard empty arrays
  16591. for ( i = 0; i < json.uvs.length; i ++ ) {
  16592. if ( json.uvs[ i ].length ) nUvLayers ++;
  16593. }
  16594. for ( i = 0; i < nUvLayers; i ++ ) {
  16595. geometry.faceVertexUvs[ i ] = [];
  16596. }
  16597. }
  16598. offset = 0;
  16599. zLength = vertices.length;
  16600. while ( offset < zLength ) {
  16601. vertex = new Vector3();
  16602. vertex.x = vertices[ offset ++ ] * scale;
  16603. vertex.y = vertices[ offset ++ ] * scale;
  16604. vertex.z = vertices[ offset ++ ] * scale;
  16605. geometry.vertices.push( vertex );
  16606. }
  16607. offset = 0;
  16608. zLength = faces.length;
  16609. while ( offset < zLength ) {
  16610. type = faces[ offset ++ ];
  16611. isQuad = isBitSet( type, 0 );
  16612. hasMaterial = isBitSet( type, 1 );
  16613. hasFaceVertexUv = isBitSet( type, 3 );
  16614. hasFaceNormal = isBitSet( type, 4 );
  16615. hasFaceVertexNormal = isBitSet( type, 5 );
  16616. hasFaceColor = isBitSet( type, 6 );
  16617. hasFaceVertexColor = isBitSet( type, 7 );
  16618. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  16619. if ( isQuad ) {
  16620. faceA = new Face3();
  16621. faceA.a = faces[ offset ];
  16622. faceA.b = faces[ offset + 1 ];
  16623. faceA.c = faces[ offset + 3 ];
  16624. faceB = new Face3();
  16625. faceB.a = faces[ offset + 1 ];
  16626. faceB.b = faces[ offset + 2 ];
  16627. faceB.c = faces[ offset + 3 ];
  16628. offset += 4;
  16629. if ( hasMaterial ) {
  16630. materialIndex = faces[ offset ++ ];
  16631. faceA.materialIndex = materialIndex;
  16632. faceB.materialIndex = materialIndex;
  16633. }
  16634. // to get face <=> uv index correspondence
  16635. fi = geometry.faces.length;
  16636. if ( hasFaceVertexUv ) {
  16637. for ( i = 0; i < nUvLayers; i ++ ) {
  16638. uvLayer = json.uvs[ i ];
  16639. geometry.faceVertexUvs[ i ][ fi ] = [];
  16640. geometry.faceVertexUvs[ i ][ fi + 1 ] = [];
  16641. for ( j = 0; j < 4; j ++ ) {
  16642. uvIndex = faces[ offset ++ ];
  16643. u = uvLayer[ uvIndex * 2 ];
  16644. v = uvLayer[ uvIndex * 2 + 1 ];
  16645. uv = new Vector2( u, v );
  16646. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  16647. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  16648. }
  16649. }
  16650. }
  16651. if ( hasFaceNormal ) {
  16652. normalIndex = faces[ offset ++ ] * 3;
  16653. faceA.normal.set(
  16654. normals[ normalIndex ++ ],
  16655. normals[ normalIndex ++ ],
  16656. normals[ normalIndex ]
  16657. );
  16658. faceB.normal.copy( faceA.normal );
  16659. }
  16660. if ( hasFaceVertexNormal ) {
  16661. for ( i = 0; i < 4; i ++ ) {
  16662. normalIndex = faces[ offset ++ ] * 3;
  16663. normal = new Vector3(
  16664. normals[ normalIndex ++ ],
  16665. normals[ normalIndex ++ ],
  16666. normals[ normalIndex ]
  16667. );
  16668. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  16669. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  16670. }
  16671. }
  16672. if ( hasFaceColor ) {
  16673. colorIndex = faces[ offset ++ ];
  16674. hex = colors[ colorIndex ];
  16675. faceA.color.setHex( hex );
  16676. faceB.color.setHex( hex );
  16677. }
  16678. if ( hasFaceVertexColor ) {
  16679. for ( i = 0; i < 4; i ++ ) {
  16680. colorIndex = faces[ offset ++ ];
  16681. hex = colors[ colorIndex ];
  16682. if ( i !== 2 ) faceA.vertexColors.push( new Color( hex ) );
  16683. if ( i !== 0 ) faceB.vertexColors.push( new Color( hex ) );
  16684. }
  16685. }
  16686. geometry.faces.push( faceA );
  16687. geometry.faces.push( faceB );
  16688. } else {
  16689. face = new Face3();
  16690. face.a = faces[ offset ++ ];
  16691. face.b = faces[ offset ++ ];
  16692. face.c = faces[ offset ++ ];
  16693. if ( hasMaterial ) {
  16694. materialIndex = faces[ offset ++ ];
  16695. face.materialIndex = materialIndex;
  16696. }
  16697. // to get face <=> uv index correspondence
  16698. fi = geometry.faces.length;
  16699. if ( hasFaceVertexUv ) {
  16700. for ( i = 0; i < nUvLayers; i ++ ) {
  16701. uvLayer = json.uvs[ i ];
  16702. geometry.faceVertexUvs[ i ][ fi ] = [];
  16703. for ( j = 0; j < 3; j ++ ) {
  16704. uvIndex = faces[ offset ++ ];
  16705. u = uvLayer[ uvIndex * 2 ];
  16706. v = uvLayer[ uvIndex * 2 + 1 ];
  16707. uv = new Vector2( u, v );
  16708. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  16709. }
  16710. }
  16711. }
  16712. if ( hasFaceNormal ) {
  16713. normalIndex = faces[ offset ++ ] * 3;
  16714. face.normal.set(
  16715. normals[ normalIndex ++ ],
  16716. normals[ normalIndex ++ ],
  16717. normals[ normalIndex ]
  16718. );
  16719. }
  16720. if ( hasFaceVertexNormal ) {
  16721. for ( i = 0; i < 3; i ++ ) {
  16722. normalIndex = faces[ offset ++ ] * 3;
  16723. normal = new Vector3(
  16724. normals[ normalIndex ++ ],
  16725. normals[ normalIndex ++ ],
  16726. normals[ normalIndex ]
  16727. );
  16728. face.vertexNormals.push( normal );
  16729. }
  16730. }
  16731. if ( hasFaceColor ) {
  16732. colorIndex = faces[ offset ++ ];
  16733. face.color.setHex( colors[ colorIndex ] );
  16734. }
  16735. if ( hasFaceVertexColor ) {
  16736. for ( i = 0; i < 3; i ++ ) {
  16737. colorIndex = faces[ offset ++ ];
  16738. face.vertexColors.push( new Color( colors[ colorIndex ] ) );
  16739. }
  16740. }
  16741. geometry.faces.push( face );
  16742. }
  16743. }
  16744. }
  16745. function parseSkin() {
  16746. var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2;
  16747. if ( json.skinWeights ) {
  16748. for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {
  16749. var x = json.skinWeights[ i ];
  16750. var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
  16751. var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
  16752. var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;
  16753. geometry.skinWeights.push( new Vector4( x, y, z, w ) );
  16754. }
  16755. }
  16756. if ( json.skinIndices ) {
  16757. for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {
  16758. var a = json.skinIndices[ i ];
  16759. var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
  16760. var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
  16761. var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;
  16762. geometry.skinIndices.push( new Vector4( a, b, c, d ) );
  16763. }
  16764. }
  16765. geometry.bones = json.bones;
  16766. if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {
  16767. console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
  16768. geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );
  16769. }
  16770. }
  16771. function parseMorphing( scale ) {
  16772. if ( json.morphTargets !== undefined ) {
  16773. for ( var i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  16774. geometry.morphTargets[ i ] = {};
  16775. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  16776. geometry.morphTargets[ i ].vertices = [];
  16777. var dstVertices = geometry.morphTargets[ i ].vertices;
  16778. var srcVertices = json.morphTargets[ i ].vertices;
  16779. for ( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  16780. var vertex = new Vector3();
  16781. vertex.x = srcVertices[ v ] * scale;
  16782. vertex.y = srcVertices[ v + 1 ] * scale;
  16783. vertex.z = srcVertices[ v + 2 ] * scale;
  16784. dstVertices.push( vertex );
  16785. }
  16786. }
  16787. }
  16788. if ( json.morphColors !== undefined && json.morphColors.length > 0 ) {
  16789. console.warn( 'THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.' );
  16790. var faces = geometry.faces;
  16791. var morphColors = json.morphColors[ 0 ].colors;
  16792. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  16793. faces[ i ].color.fromArray( morphColors, i * 3 );
  16794. }
  16795. }
  16796. }
  16797. function parseAnimations() {
  16798. var outputAnimations = [];
  16799. // parse old style Bone/Hierarchy animations
  16800. var animations = [];
  16801. if ( json.animation !== undefined ) {
  16802. animations.push( json.animation );
  16803. }
  16804. if ( json.animations !== undefined ) {
  16805. if ( json.animations.length ) {
  16806. animations = animations.concat( json.animations );
  16807. } else {
  16808. animations.push( json.animations );
  16809. }
  16810. }
  16811. for ( var i = 0; i < animations.length; i ++ ) {
  16812. var clip = AnimationClip.parseAnimation( animations[ i ], geometry.bones );
  16813. if ( clip ) outputAnimations.push( clip );
  16814. }
  16815. // parse implicit morph animations
  16816. if ( geometry.morphTargets ) {
  16817. // TODO: Figure out what an appropraite FPS is for morph target animations -- defaulting to 10, but really it is completely arbitrary.
  16818. var morphAnimationClips = AnimationClip.CreateClipsFromMorphTargetSequences( geometry.morphTargets, 10 );
  16819. outputAnimations = outputAnimations.concat( morphAnimationClips );
  16820. }
  16821. if ( outputAnimations.length > 0 ) geometry.animations = outputAnimations;
  16822. }
  16823. if ( json.materials === undefined || json.materials.length === 0 ) {
  16824. return { geometry: geometry };
  16825. } else {
  16826. var materials = Loader.prototype.initMaterials( json.materials, texturePath, this.crossOrigin );
  16827. return { geometry: geometry, materials: materials };
  16828. }
  16829. }
  16830. } );
  16831. /**
  16832. * @author mrdoob / http://mrdoob.com/
  16833. */
  16834. function ObjectLoader ( manager ) {
  16835. this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager;
  16836. this.texturePath = '';
  16837. }
  16838. Object.assign( ObjectLoader.prototype, {
  16839. load: function ( url, onLoad, onProgress, onError ) {
  16840. if ( this.texturePath === '' ) {
  16841. this.texturePath = url.substring( 0, url.lastIndexOf( '/' ) + 1 );
  16842. }
  16843. var scope = this;
  16844. var loader = new XHRLoader( scope.manager );
  16845. loader.load( url, function ( text ) {
  16846. scope.parse( JSON.parse( text ), onLoad );
  16847. }, onProgress, onError );
  16848. },
  16849. setTexturePath: function ( value ) {
  16850. this.texturePath = value;
  16851. },
  16852. setCrossOrigin: function ( value ) {
  16853. this.crossOrigin = value;
  16854. },
  16855. parse: function ( json, onLoad ) {
  16856. var geometries = this.parseGeometries( json.geometries );
  16857. var images = this.parseImages( json.images, function () {
  16858. if ( onLoad !== undefined ) onLoad( object );
  16859. } );
  16860. var textures = this.parseTextures( json.textures, images );
  16861. var materials = this.parseMaterials( json.materials, textures );
  16862. var object = this.parseObject( json.object, geometries, materials );
  16863. if ( json.animations ) {
  16864. object.animations = this.parseAnimations( json.animations );
  16865. }
  16866. if ( json.images === undefined || json.images.length === 0 ) {
  16867. if ( onLoad !== undefined ) onLoad( object );
  16868. }
  16869. return object;
  16870. },
  16871. parseGeometries: function ( json ) {
  16872. var geometries = {};
  16873. if ( json !== undefined ) {
  16874. var geometryLoader = new JSONLoader();
  16875. var bufferGeometryLoader = new BufferGeometryLoader();
  16876. for ( var i = 0, l = json.length; i < l; i ++ ) {
  16877. var geometry;
  16878. var data = json[ i ];
  16879. switch ( data.type ) {
  16880. case 'PlaneGeometry':
  16881. case 'PlaneBufferGeometry':
  16882. geometry = new THREE[ data.type ](
  16883. data.width,
  16884. data.height,
  16885. data.widthSegments,
  16886. data.heightSegments
  16887. );
  16888. break;
  16889. case 'BoxGeometry':
  16890. case 'BoxBufferGeometry':
  16891. case 'CubeGeometry': // backwards compatible
  16892. geometry = new THREE[ data.type ](
  16893. data.width,
  16894. data.height,
  16895. data.depth,
  16896. data.widthSegments,
  16897. data.heightSegments,
  16898. data.depthSegments
  16899. );
  16900. break;
  16901. case 'CircleGeometry':
  16902. case 'CircleBufferGeometry':
  16903. geometry = new THREE[ data.type ](
  16904. data.radius,
  16905. data.segments,
  16906. data.thetaStart,
  16907. data.thetaLength
  16908. );
  16909. break;
  16910. case 'CylinderGeometry':
  16911. case 'CylinderBufferGeometry':
  16912. geometry = new THREE[ data.type ](
  16913. data.radiusTop,
  16914. data.radiusBottom,
  16915. data.height,
  16916. data.radialSegments,
  16917. data.heightSegments,
  16918. data.openEnded,
  16919. data.thetaStart,
  16920. data.thetaLength
  16921. );
  16922. break;
  16923. case 'ConeGeometry':
  16924. case 'ConeBufferGeometry':
  16925. geometry = new THREE [ data.type ](
  16926. data.radius,
  16927. data.height,
  16928. data.radialSegments,
  16929. data.heightSegments,
  16930. data.openEnded,
  16931. data.thetaStart,
  16932. data.thetaLength
  16933. );
  16934. break;
  16935. case 'SphereGeometry':
  16936. case 'SphereBufferGeometry':
  16937. geometry = new THREE[ data.type ](
  16938. data.radius,
  16939. data.widthSegments,
  16940. data.heightSegments,
  16941. data.phiStart,
  16942. data.phiLength,
  16943. data.thetaStart,
  16944. data.thetaLength
  16945. );
  16946. break;
  16947. case 'DodecahedronGeometry':
  16948. case 'IcosahedronGeometry':
  16949. case 'OctahedronGeometry':
  16950. case 'TetrahedronGeometry':
  16951. geometry = new THREE[ data.type ](
  16952. data.radius,
  16953. data.detail
  16954. );
  16955. break;
  16956. case 'RingGeometry':
  16957. case 'RingBufferGeometry':
  16958. geometry = new THREE[ data.type ](
  16959. data.innerRadius,
  16960. data.outerRadius,
  16961. data.thetaSegments,
  16962. data.phiSegments,
  16963. data.thetaStart,
  16964. data.thetaLength
  16965. );
  16966. break;
  16967. case 'TorusGeometry':
  16968. case 'TorusBufferGeometry':
  16969. geometry = new THREE[ data.type ](
  16970. data.radius,
  16971. data.tube,
  16972. data.radialSegments,
  16973. data.tubularSegments,
  16974. data.arc
  16975. );
  16976. break;
  16977. case 'TorusKnotGeometry':
  16978. case 'TorusKnotBufferGeometry':
  16979. geometry = new THREE[ data.type ](
  16980. data.radius,
  16981. data.tube,
  16982. data.tubularSegments,
  16983. data.radialSegments,
  16984. data.p,
  16985. data.q
  16986. );
  16987. break;
  16988. case 'LatheGeometry':
  16989. case 'LatheBufferGeometry':
  16990. geometry = new THREE[ data.type ](
  16991. data.points,
  16992. data.segments,
  16993. data.phiStart,
  16994. data.phiLength
  16995. );
  16996. break;
  16997. case 'BufferGeometry':
  16998. geometry = bufferGeometryLoader.parse( data );
  16999. break;
  17000. case 'Geometry':
  17001. geometry = geometryLoader.parse( data.data, this.texturePath ).geometry;
  17002. break;
  17003. default:
  17004. console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' );
  17005. continue;
  17006. }
  17007. geometry.uuid = data.uuid;
  17008. if ( data.name !== undefined ) geometry.name = data.name;
  17009. geometries[ data.uuid ] = geometry;
  17010. }
  17011. }
  17012. return geometries;
  17013. },
  17014. parseMaterials: function ( json, textures ) {
  17015. var materials = {};
  17016. if ( json !== undefined ) {
  17017. var loader = new MaterialLoader();
  17018. loader.setTextures( textures );
  17019. for ( var i = 0, l = json.length; i < l; i ++ ) {
  17020. var material = loader.parse( json[ i ] );
  17021. materials[ material.uuid ] = material;
  17022. }
  17023. }
  17024. return materials;
  17025. },
  17026. parseAnimations: function ( json ) {
  17027. var animations = [];
  17028. for ( var i = 0; i < json.length; i ++ ) {
  17029. var clip = AnimationClip.parse( json[ i ] );
  17030. animations.push( clip );
  17031. }
  17032. return animations;
  17033. },
  17034. parseImages: function ( json, onLoad ) {
  17035. var scope = this;
  17036. var images = {};
  17037. function loadImage( url ) {
  17038. scope.manager.itemStart( url );
  17039. return loader.load( url, function () {
  17040. scope.manager.itemEnd( url );
  17041. }, undefined, function () {
  17042. scope.manager.itemError( url );
  17043. } );
  17044. }
  17045. if ( json !== undefined && json.length > 0 ) {
  17046. var manager = new LoadingManager( onLoad );
  17047. var loader = new ImageLoader( manager );
  17048. loader.setCrossOrigin( this.crossOrigin );
  17049. for ( var i = 0, l = json.length; i < l; i ++ ) {
  17050. var image = json[ i ];
  17051. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.texturePath + image.url;
  17052. images[ image.uuid ] = loadImage( path );
  17053. }
  17054. }
  17055. return images;
  17056. },
  17057. parseTextures: function ( json, images ) {
  17058. function parseConstant( value ) {
  17059. if ( typeof( value ) === 'number' ) return value;
  17060. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  17061. return THREE[ value ];
  17062. }
  17063. var textures = {};
  17064. if ( json !== undefined ) {
  17065. for ( var i = 0, l = json.length; i < l; i ++ ) {
  17066. var data = json[ i ];
  17067. if ( data.image === undefined ) {
  17068. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  17069. }
  17070. if ( images[ data.image ] === undefined ) {
  17071. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  17072. }
  17073. var texture = new Texture( images[ data.image ] );
  17074. texture.needsUpdate = true;
  17075. texture.uuid = data.uuid;
  17076. if ( data.name !== undefined ) texture.name = data.name;
  17077. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping );
  17078. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  17079. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  17080. if ( data.wrap !== undefined ) {
  17081. texture.wrapS = parseConstant( data.wrap[ 0 ] );
  17082. texture.wrapT = parseConstant( data.wrap[ 1 ] );
  17083. }
  17084. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter );
  17085. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter );
  17086. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  17087. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  17088. textures[ data.uuid ] = texture;
  17089. }
  17090. }
  17091. return textures;
  17092. },
  17093. parseObject: function () {
  17094. var matrix = new Matrix4();
  17095. return function parseObject( data, geometries, materials ) {
  17096. var object;
  17097. function getGeometry( name ) {
  17098. if ( geometries[ name ] === undefined ) {
  17099. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  17100. }
  17101. return geometries[ name ];
  17102. }
  17103. function getMaterial( name ) {
  17104. if ( name === undefined ) return undefined;
  17105. if ( materials[ name ] === undefined ) {
  17106. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  17107. }
  17108. return materials[ name ];
  17109. }
  17110. switch ( data.type ) {
  17111. case 'Scene':
  17112. object = new Scene();
  17113. if ( data.fog !== undefined ) {
  17114. if ( data.fog.type === 'FogExp2' ) {
  17115. object.fog = new FogExp2(data.fog.color, data.fog.density);
  17116. } else if ( data.fog.type === 'Fog' ) {
  17117. object.fog = new Fog(data.fog.color, data.fog.near, data.fog.far);
  17118. }
  17119. }
  17120. break;
  17121. case 'PerspectiveCamera':
  17122. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  17123. if ( data.focus !== undefined ) object.focus = data.focus;
  17124. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  17125. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  17126. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  17127. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  17128. break;
  17129. case 'OrthographicCamera':
  17130. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  17131. break;
  17132. case 'AmbientLight':
  17133. object = new AmbientLight( data.color, data.intensity );
  17134. break;
  17135. case 'DirectionalLight':
  17136. object = new DirectionalLight( data.color, data.intensity );
  17137. break;
  17138. case 'PointLight':
  17139. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  17140. break;
  17141. case 'SpotLight':
  17142. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  17143. break;
  17144. case 'HemisphereLight':
  17145. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  17146. break;
  17147. case 'Mesh':
  17148. var geometry = getGeometry( data.geometry );
  17149. var material = getMaterial( data.material );
  17150. if ( geometry.bones && geometry.bones.length > 0 ) {
  17151. object = new SkinnedMesh( geometry, material );
  17152. } else {
  17153. object = new Mesh( geometry, material );
  17154. }
  17155. break;
  17156. case 'LOD':
  17157. object = new LOD();
  17158. break;
  17159. case 'Line':
  17160. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode );
  17161. break;
  17162. case 'LineSegments':
  17163. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  17164. break;
  17165. case 'PointCloud':
  17166. case 'Points':
  17167. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  17168. break;
  17169. case 'Sprite':
  17170. object = new Sprite( getMaterial( data.material ) );
  17171. break;
  17172. case 'Group':
  17173. object = new Group();
  17174. break;
  17175. default:
  17176. object = new Object3D();
  17177. }
  17178. object.uuid = data.uuid;
  17179. if ( data.name !== undefined ) object.name = data.name;
  17180. if ( data.matrix !== undefined ) {
  17181. matrix.fromArray( data.matrix );
  17182. matrix.decompose( object.position, object.quaternion, object.scale );
  17183. } else {
  17184. if ( data.position !== undefined ) object.position.fromArray( data.position );
  17185. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  17186. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  17187. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  17188. }
  17189. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  17190. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  17191. if ( data.shadow ) {
  17192. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  17193. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  17194. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  17195. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  17196. }
  17197. if ( data.visible !== undefined ) object.visible = data.visible;
  17198. if ( data.userData !== undefined ) object.userData = data.userData;
  17199. if ( data.children !== undefined ) {
  17200. for ( var child in data.children ) {
  17201. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  17202. }
  17203. }
  17204. if ( data.type === 'LOD' ) {
  17205. var levels = data.levels;
  17206. for ( var l = 0; l < levels.length; l ++ ) {
  17207. var level = levels[ l ];
  17208. var child = object.getObjectByProperty( 'uuid', level.object );
  17209. if ( child !== undefined ) {
  17210. object.addLevel( child, level.distance );
  17211. }
  17212. }
  17213. }
  17214. return object;
  17215. };
  17216. }()
  17217. } );
  17218. /**
  17219. * @author zz85 / http://www.lab4games.net/zz85/blog
  17220. */
  17221. exports.ShapeUtils = {
  17222. // calculate area of the contour polygon
  17223. area: function ( contour ) {
  17224. var n = contour.length;
  17225. var a = 0.0;
  17226. for ( var p = n - 1, q = 0; q < n; p = q ++ ) {
  17227. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  17228. }
  17229. return a * 0.5;
  17230. },
  17231. triangulate: ( function () {
  17232. /**
  17233. * This code is a quick port of code written in C++ which was submitted to
  17234. * flipcode.com by John W. Ratcliff // July 22, 2000
  17235. * See original code and more information here:
  17236. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  17237. *
  17238. * ported to actionscript by Zevan Rosser
  17239. * www.actionsnippet.com
  17240. *
  17241. * ported to javascript by Joshua Koo
  17242. * http://www.lab4games.net/zz85/blog
  17243. *
  17244. */
  17245. function snip( contour, u, v, w, n, verts ) {
  17246. var p;
  17247. var ax, ay, bx, by;
  17248. var cx, cy, px, py;
  17249. ax = contour[ verts[ u ] ].x;
  17250. ay = contour[ verts[ u ] ].y;
  17251. bx = contour[ verts[ v ] ].x;
  17252. by = contour[ verts[ v ] ].y;
  17253. cx = contour[ verts[ w ] ].x;
  17254. cy = contour[ verts[ w ] ].y;
  17255. if ( Number.EPSILON > ( ( ( bx - ax ) * ( cy - ay ) ) - ( ( by - ay ) * ( cx - ax ) ) ) ) return false;
  17256. var aX, aY, bX, bY, cX, cY;
  17257. var apx, apy, bpx, bpy, cpx, cpy;
  17258. var cCROSSap, bCROSScp, aCROSSbp;
  17259. aX = cx - bx; aY = cy - by;
  17260. bX = ax - cx; bY = ay - cy;
  17261. cX = bx - ax; cY = by - ay;
  17262. for ( p = 0; p < n; p ++ ) {
  17263. px = contour[ verts[ p ] ].x;
  17264. py = contour[ verts[ p ] ].y;
  17265. if ( ( ( px === ax ) && ( py === ay ) ) ||
  17266. ( ( px === bx ) && ( py === by ) ) ||
  17267. ( ( px === cx ) && ( py === cy ) ) ) continue;
  17268. apx = px - ax; apy = py - ay;
  17269. bpx = px - bx; bpy = py - by;
  17270. cpx = px - cx; cpy = py - cy;
  17271. // see if p is inside triangle abc
  17272. aCROSSbp = aX * bpy - aY * bpx;
  17273. cCROSSap = cX * apy - cY * apx;
  17274. bCROSScp = bX * cpy - bY * cpx;
  17275. if ( ( aCROSSbp >= - Number.EPSILON ) && ( bCROSScp >= - Number.EPSILON ) && ( cCROSSap >= - Number.EPSILON ) ) return false;
  17276. }
  17277. return true;
  17278. }
  17279. // takes in an contour array and returns
  17280. return function triangulate( contour, indices ) {
  17281. var n = contour.length;
  17282. if ( n < 3 ) return null;
  17283. var result = [],
  17284. verts = [],
  17285. vertIndices = [];
  17286. /* we want a counter-clockwise polygon in verts */
  17287. var u, v, w;
  17288. if ( exports.ShapeUtils.area( contour ) > 0.0 ) {
  17289. for ( v = 0; v < n; v ++ ) verts[ v ] = v;
  17290. } else {
  17291. for ( v = 0; v < n; v ++ ) verts[ v ] = ( n - 1 ) - v;
  17292. }
  17293. var nv = n;
  17294. /* remove nv - 2 vertices, creating 1 triangle every time */
  17295. var count = 2 * nv; /* error detection */
  17296. for ( v = nv - 1; nv > 2; ) {
  17297. /* if we loop, it is probably a non-simple polygon */
  17298. if ( ( count -- ) <= 0 ) {
  17299. //** Triangulate: ERROR - probable bad polygon!
  17300. //throw ( "Warning, unable to triangulate polygon!" );
  17301. //return null;
  17302. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  17303. console.warn( 'THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()' );
  17304. if ( indices ) return vertIndices;
  17305. return result;
  17306. }
  17307. /* three consecutive vertices in current polygon, <u,v,w> */
  17308. u = v; if ( nv <= u ) u = 0; /* previous */
  17309. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  17310. w = v + 1; if ( nv <= w ) w = 0; /* next */
  17311. if ( snip( contour, u, v, w, nv, verts ) ) {
  17312. var a, b, c, s, t;
  17313. /* true names of the vertices */
  17314. a = verts[ u ];
  17315. b = verts[ v ];
  17316. c = verts[ w ];
  17317. /* output Triangle */
  17318. result.push( [ contour[ a ],
  17319. contour[ b ],
  17320. contour[ c ] ] );
  17321. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  17322. /* remove v from the remaining polygon */
  17323. for ( s = v, t = v + 1; t < nv; s ++, t ++ ) {
  17324. verts[ s ] = verts[ t ];
  17325. }
  17326. nv --;
  17327. /* reset error detection counter */
  17328. count = 2 * nv;
  17329. }
  17330. }
  17331. if ( indices ) return vertIndices;
  17332. return result;
  17333. }
  17334. } )(),
  17335. triangulateShape: function ( contour, holes ) {
  17336. function removeDupEndPts(points) {
  17337. var l = points.length;
  17338. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  17339. points.pop();
  17340. }
  17341. }
  17342. removeDupEndPts( contour );
  17343. holes.forEach( removeDupEndPts );
  17344. function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) {
  17345. // inOtherPt needs to be collinear to the inSegment
  17346. if ( inSegPt1.x !== inSegPt2.x ) {
  17347. if ( inSegPt1.x < inSegPt2.x ) {
  17348. return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) );
  17349. } else {
  17350. return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) );
  17351. }
  17352. } else {
  17353. if ( inSegPt1.y < inSegPt2.y ) {
  17354. return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) );
  17355. } else {
  17356. return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) );
  17357. }
  17358. }
  17359. }
  17360. function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) {
  17361. var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y;
  17362. var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y;
  17363. var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x;
  17364. var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y;
  17365. var limit = seg1dy * seg2dx - seg1dx * seg2dy;
  17366. var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy;
  17367. if ( Math.abs( limit ) > Number.EPSILON ) {
  17368. // not parallel
  17369. var perpSeg2;
  17370. if ( limit > 0 ) {
  17371. if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return [];
  17372. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  17373. if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return [];
  17374. } else {
  17375. if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return [];
  17376. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  17377. if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return [];
  17378. }
  17379. // i.e. to reduce rounding errors
  17380. // intersection at endpoint of segment#1?
  17381. if ( perpSeg2 === 0 ) {
  17382. if ( ( inExcludeAdjacentSegs ) &&
  17383. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  17384. return [ inSeg1Pt1 ];
  17385. }
  17386. if ( perpSeg2 === limit ) {
  17387. if ( ( inExcludeAdjacentSegs ) &&
  17388. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  17389. return [ inSeg1Pt2 ];
  17390. }
  17391. // intersection at endpoint of segment#2?
  17392. if ( perpSeg1 === 0 ) return [ inSeg2Pt1 ];
  17393. if ( perpSeg1 === limit ) return [ inSeg2Pt2 ];
  17394. // return real intersection point
  17395. var factorSeg1 = perpSeg2 / limit;
  17396. return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx,
  17397. y: inSeg1Pt1.y + factorSeg1 * seg1dy } ];
  17398. } else {
  17399. // parallel or collinear
  17400. if ( ( perpSeg1 !== 0 ) ||
  17401. ( seg2dy * seg1seg2dx !== seg2dx * seg1seg2dy ) ) return [];
  17402. // they are collinear or degenerate
  17403. var seg1Pt = ( ( seg1dx === 0 ) && ( seg1dy === 0 ) ); // segment1 is just a point?
  17404. var seg2Pt = ( ( seg2dx === 0 ) && ( seg2dy === 0 ) ); // segment2 is just a point?
  17405. // both segments are points
  17406. if ( seg1Pt && seg2Pt ) {
  17407. if ( ( inSeg1Pt1.x !== inSeg2Pt1.x ) ||
  17408. ( inSeg1Pt1.y !== inSeg2Pt1.y ) ) return []; // they are distinct points
  17409. return [ inSeg1Pt1 ]; // they are the same point
  17410. }
  17411. // segment#1 is a single point
  17412. if ( seg1Pt ) {
  17413. if ( ! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2
  17414. return [ inSeg1Pt1 ];
  17415. }
  17416. // segment#2 is a single point
  17417. if ( seg2Pt ) {
  17418. if ( ! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1
  17419. return [ inSeg2Pt1 ];
  17420. }
  17421. // they are collinear segments, which might overlap
  17422. var seg1min, seg1max, seg1minVal, seg1maxVal;
  17423. var seg2min, seg2max, seg2minVal, seg2maxVal;
  17424. if ( seg1dx !== 0 ) {
  17425. // the segments are NOT on a vertical line
  17426. if ( inSeg1Pt1.x < inSeg1Pt2.x ) {
  17427. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x;
  17428. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x;
  17429. } else {
  17430. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x;
  17431. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x;
  17432. }
  17433. if ( inSeg2Pt1.x < inSeg2Pt2.x ) {
  17434. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x;
  17435. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x;
  17436. } else {
  17437. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x;
  17438. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x;
  17439. }
  17440. } else {
  17441. // the segments are on a vertical line
  17442. if ( inSeg1Pt1.y < inSeg1Pt2.y ) {
  17443. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y;
  17444. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y;
  17445. } else {
  17446. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y;
  17447. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y;
  17448. }
  17449. if ( inSeg2Pt1.y < inSeg2Pt2.y ) {
  17450. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y;
  17451. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y;
  17452. } else {
  17453. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y;
  17454. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y;
  17455. }
  17456. }
  17457. if ( seg1minVal <= seg2minVal ) {
  17458. if ( seg1maxVal < seg2minVal ) return [];
  17459. if ( seg1maxVal === seg2minVal ) {
  17460. if ( inExcludeAdjacentSegs ) return [];
  17461. return [ seg2min ];
  17462. }
  17463. if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ];
  17464. return [ seg2min, seg2max ];
  17465. } else {
  17466. if ( seg1minVal > seg2maxVal ) return [];
  17467. if ( seg1minVal === seg2maxVal ) {
  17468. if ( inExcludeAdjacentSegs ) return [];
  17469. return [ seg1min ];
  17470. }
  17471. if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ];
  17472. return [ seg1min, seg2max ];
  17473. }
  17474. }
  17475. }
  17476. function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) {
  17477. // The order of legs is important
  17478. // translation of all points, so that Vertex is at (0,0)
  17479. var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y;
  17480. var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y;
  17481. var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y;
  17482. // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg.
  17483. var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX;
  17484. var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX;
  17485. if ( Math.abs( from2toAngle ) > Number.EPSILON ) {
  17486. // angle != 180 deg.
  17487. var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX;
  17488. // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle );
  17489. if ( from2toAngle > 0 ) {
  17490. // main angle < 180 deg.
  17491. return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) );
  17492. } else {
  17493. // main angle > 180 deg.
  17494. return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) );
  17495. }
  17496. } else {
  17497. // angle == 180 deg.
  17498. // console.log( "from2to: 180 deg., from2other: " + from2otherAngle );
  17499. return ( from2otherAngle > 0 );
  17500. }
  17501. }
  17502. function removeHoles( contour, holes ) {
  17503. var shape = contour.concat(); // work on this shape
  17504. var hole;
  17505. function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) {
  17506. // Check if hole point lies within angle around shape point
  17507. var lastShapeIdx = shape.length - 1;
  17508. var prevShapeIdx = inShapeIdx - 1;
  17509. if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx;
  17510. var nextShapeIdx = inShapeIdx + 1;
  17511. if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0;
  17512. var insideAngle = isPointInsideAngle( shape[ inShapeIdx ], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[ inHoleIdx ] );
  17513. if ( ! insideAngle ) {
  17514. // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y );
  17515. return false;
  17516. }
  17517. // Check if shape point lies within angle around hole point
  17518. var lastHoleIdx = hole.length - 1;
  17519. var prevHoleIdx = inHoleIdx - 1;
  17520. if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx;
  17521. var nextHoleIdx = inHoleIdx + 1;
  17522. if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0;
  17523. insideAngle = isPointInsideAngle( hole[ inHoleIdx ], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[ inShapeIdx ] );
  17524. if ( ! insideAngle ) {
  17525. // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y );
  17526. return false;
  17527. }
  17528. return true;
  17529. }
  17530. function intersectsShapeEdge( inShapePt, inHolePt ) {
  17531. // checks for intersections with shape edges
  17532. var sIdx, nextIdx, intersection;
  17533. for ( sIdx = 0; sIdx < shape.length; sIdx ++ ) {
  17534. nextIdx = sIdx + 1; nextIdx %= shape.length;
  17535. intersection = intersect_segments_2D( inShapePt, inHolePt, shape[ sIdx ], shape[ nextIdx ], true );
  17536. if ( intersection.length > 0 ) return true;
  17537. }
  17538. return false;
  17539. }
  17540. var indepHoles = [];
  17541. function intersectsHoleEdge( inShapePt, inHolePt ) {
  17542. // checks for intersections with hole edges
  17543. var ihIdx, chkHole,
  17544. hIdx, nextIdx, intersection;
  17545. for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx ++ ) {
  17546. chkHole = holes[ indepHoles[ ihIdx ]];
  17547. for ( hIdx = 0; hIdx < chkHole.length; hIdx ++ ) {
  17548. nextIdx = hIdx + 1; nextIdx %= chkHole.length;
  17549. intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[ hIdx ], chkHole[ nextIdx ], true );
  17550. if ( intersection.length > 0 ) return true;
  17551. }
  17552. }
  17553. return false;
  17554. }
  17555. var holeIndex, shapeIndex,
  17556. shapePt, holePt,
  17557. holeIdx, cutKey, failedCuts = [],
  17558. tmpShape1, tmpShape2,
  17559. tmpHole1, tmpHole2;
  17560. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  17561. indepHoles.push( h );
  17562. }
  17563. var minShapeIndex = 0;
  17564. var counter = indepHoles.length * 2;
  17565. while ( indepHoles.length > 0 ) {
  17566. counter --;
  17567. if ( counter < 0 ) {
  17568. console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" );
  17569. break;
  17570. }
  17571. // search for shape-vertex and hole-vertex,
  17572. // which can be connected without intersections
  17573. for ( shapeIndex = minShapeIndex; shapeIndex < shape.length; shapeIndex ++ ) {
  17574. shapePt = shape[ shapeIndex ];
  17575. holeIndex = - 1;
  17576. // search for hole which can be reached without intersections
  17577. for ( var h = 0; h < indepHoles.length; h ++ ) {
  17578. holeIdx = indepHoles[ h ];
  17579. // prevent multiple checks
  17580. cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx;
  17581. if ( failedCuts[ cutKey ] !== undefined ) continue;
  17582. hole = holes[ holeIdx ];
  17583. for ( var h2 = 0; h2 < hole.length; h2 ++ ) {
  17584. holePt = hole[ h2 ];
  17585. if ( ! isCutLineInsideAngles( shapeIndex, h2 ) ) continue;
  17586. if ( intersectsShapeEdge( shapePt, holePt ) ) continue;
  17587. if ( intersectsHoleEdge( shapePt, holePt ) ) continue;
  17588. holeIndex = h2;
  17589. indepHoles.splice( h, 1 );
  17590. tmpShape1 = shape.slice( 0, shapeIndex + 1 );
  17591. tmpShape2 = shape.slice( shapeIndex );
  17592. tmpHole1 = hole.slice( holeIndex );
  17593. tmpHole2 = hole.slice( 0, holeIndex + 1 );
  17594. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  17595. minShapeIndex = shapeIndex;
  17596. // Debug only, to show the selected cuts
  17597. // glob_CutLines.push( [ shapePt, holePt ] );
  17598. break;
  17599. }
  17600. if ( holeIndex >= 0 ) break; // hole-vertex found
  17601. failedCuts[ cutKey ] = true; // remember failure
  17602. }
  17603. if ( holeIndex >= 0 ) break; // hole-vertex found
  17604. }
  17605. }
  17606. return shape; /* shape with no holes */
  17607. }
  17608. var i, il, f, face,
  17609. key, index,
  17610. allPointsMap = {};
  17611. // 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.
  17612. var allpoints = contour.concat();
  17613. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  17614. Array.prototype.push.apply( allpoints, holes[ h ] );
  17615. }
  17616. //console.log( "allpoints",allpoints, allpoints.length );
  17617. // prepare all points map
  17618. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  17619. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  17620. if ( allPointsMap[ key ] !== undefined ) {
  17621. console.warn( "THREE.ShapeUtils: Duplicate point", key, i );
  17622. }
  17623. allPointsMap[ key ] = i;
  17624. }
  17625. // remove holes by cutting paths to holes and adding them to the shape
  17626. var shapeWithoutHoles = removeHoles( contour, holes );
  17627. var triangles = exports.ShapeUtils.triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape
  17628. //console.log( "triangles",triangles, triangles.length );
  17629. // check all face vertices against all points map
  17630. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  17631. face = triangles[ i ];
  17632. for ( f = 0; f < 3; f ++ ) {
  17633. key = face[ f ].x + ":" + face[ f ].y;
  17634. index = allPointsMap[ key ];
  17635. if ( index !== undefined ) {
  17636. face[ f ] = index;
  17637. }
  17638. }
  17639. }
  17640. return triangles.concat();
  17641. },
  17642. isClockWise: function ( pts ) {
  17643. return exports.ShapeUtils.area( pts ) < 0;
  17644. },
  17645. // Bezier Curves formulas obtained from
  17646. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  17647. // Quad Bezier Functions
  17648. b2: ( function () {
  17649. function b2p0( t, p ) {
  17650. var k = 1 - t;
  17651. return k * k * p;
  17652. }
  17653. function b2p1( t, p ) {
  17654. return 2 * ( 1 - t ) * t * p;
  17655. }
  17656. function b2p2( t, p ) {
  17657. return t * t * p;
  17658. }
  17659. return function b2( t, p0, p1, p2 ) {
  17660. return b2p0( t, p0 ) + b2p1( t, p1 ) + b2p2( t, p2 );
  17661. };
  17662. } )(),
  17663. // Cubic Bezier Functions
  17664. b3: ( function () {
  17665. function b3p0( t, p ) {
  17666. var k = 1 - t;
  17667. return k * k * k * p;
  17668. }
  17669. function b3p1( t, p ) {
  17670. var k = 1 - t;
  17671. return 3 * k * k * t * p;
  17672. }
  17673. function b3p2( t, p ) {
  17674. var k = 1 - t;
  17675. return 3 * k * t * t * p;
  17676. }
  17677. function b3p3( t, p ) {
  17678. return t * t * t * p;
  17679. }
  17680. return function b3( t, p0, p1, p2, p3 ) {
  17681. return b3p0( t, p0 ) + b3p1( t, p1 ) + b3p2( t, p2 ) + b3p3( t, p3 );
  17682. };
  17683. } )()
  17684. };
  17685. /**
  17686. * @author zz85 / http://www.lab4games.net/zz85/blog
  17687. * Extensible curve object
  17688. *
  17689. * Some common of Curve methods
  17690. * .getPoint(t), getTangent(t)
  17691. * .getPointAt(u), getTangentAt(u)
  17692. * .getPoints(), .getSpacedPoints()
  17693. * .getLength()
  17694. * .updateArcLengths()
  17695. *
  17696. * This following classes subclasses THREE.Curve:
  17697. *
  17698. * -- 2d classes --
  17699. * THREE.LineCurve
  17700. * THREE.QuadraticBezierCurve
  17701. * THREE.CubicBezierCurve
  17702. * THREE.SplineCurve
  17703. * THREE.ArcCurve
  17704. * THREE.EllipseCurve
  17705. *
  17706. * -- 3d classes --
  17707. * THREE.LineCurve3
  17708. * THREE.QuadraticBezierCurve3
  17709. * THREE.CubicBezierCurve3
  17710. * THREE.SplineCurve3
  17711. *
  17712. * A series of curves can be represented as a THREE.CurvePath
  17713. *
  17714. **/
  17715. /**************************************************************
  17716. * Abstract Curve base class
  17717. **************************************************************/
  17718. function Curve() {}
  17719. Curve.prototype = {
  17720. constructor: Curve,
  17721. // Virtual base class method to overwrite and implement in subclasses
  17722. // - t [0 .. 1]
  17723. getPoint: function ( t ) {
  17724. console.warn( "THREE.Curve: Warning, getPoint() not implemented!" );
  17725. return null;
  17726. },
  17727. // Get point at relative position in curve according to arc length
  17728. // - u [0 .. 1]
  17729. getPointAt: function ( u ) {
  17730. var t = this.getUtoTmapping( u );
  17731. return this.getPoint( t );
  17732. },
  17733. // Get sequence of points using getPoint( t )
  17734. getPoints: function ( divisions ) {
  17735. if ( ! divisions ) divisions = 5;
  17736. var points = [];
  17737. for ( var d = 0; d <= divisions; d ++ ) {
  17738. points.push( this.getPoint( d / divisions ) );
  17739. }
  17740. return points;
  17741. },
  17742. // Get sequence of points using getPointAt( u )
  17743. getSpacedPoints: function ( divisions ) {
  17744. if ( ! divisions ) divisions = 5;
  17745. var points = [];
  17746. for ( var d = 0; d <= divisions; d ++ ) {
  17747. points.push( this.getPointAt( d / divisions ) );
  17748. }
  17749. return points;
  17750. },
  17751. // Get total curve arc length
  17752. getLength: function () {
  17753. var lengths = this.getLengths();
  17754. return lengths[ lengths.length - 1 ];
  17755. },
  17756. // Get list of cumulative segment lengths
  17757. getLengths: function ( divisions ) {
  17758. if ( ! divisions ) divisions = ( this.__arcLengthDivisions ) ? ( this.__arcLengthDivisions ) : 200;
  17759. if ( this.cacheArcLengths
  17760. && ( this.cacheArcLengths.length === divisions + 1 )
  17761. && ! this.needsUpdate ) {
  17762. //console.log( "cached", this.cacheArcLengths );
  17763. return this.cacheArcLengths;
  17764. }
  17765. this.needsUpdate = false;
  17766. var cache = [];
  17767. var current, last = this.getPoint( 0 );
  17768. var p, sum = 0;
  17769. cache.push( 0 );
  17770. for ( p = 1; p <= divisions; p ++ ) {
  17771. current = this.getPoint ( p / divisions );
  17772. sum += current.distanceTo( last );
  17773. cache.push( sum );
  17774. last = current;
  17775. }
  17776. this.cacheArcLengths = cache;
  17777. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  17778. },
  17779. updateArcLengths: function() {
  17780. this.needsUpdate = true;
  17781. this.getLengths();
  17782. },
  17783. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  17784. getUtoTmapping: function ( u, distance ) {
  17785. var arcLengths = this.getLengths();
  17786. var i = 0, il = arcLengths.length;
  17787. var targetArcLength; // The targeted u distance value to get
  17788. if ( distance ) {
  17789. targetArcLength = distance;
  17790. } else {
  17791. targetArcLength = u * arcLengths[ il - 1 ];
  17792. }
  17793. //var time = Date.now();
  17794. // binary search for the index with largest value smaller than target u distance
  17795. var low = 0, high = il - 1, comparison;
  17796. while ( low <= high ) {
  17797. 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
  17798. comparison = arcLengths[ i ] - targetArcLength;
  17799. if ( comparison < 0 ) {
  17800. low = i + 1;
  17801. } else if ( comparison > 0 ) {
  17802. high = i - 1;
  17803. } else {
  17804. high = i;
  17805. break;
  17806. // DONE
  17807. }
  17808. }
  17809. i = high;
  17810. //console.log('b' , i, low, high, Date.now()- time);
  17811. if ( arcLengths[ i ] === targetArcLength ) {
  17812. var t = i / ( il - 1 );
  17813. return t;
  17814. }
  17815. // we could get finer grain at lengths, or use simple interpolation between two points
  17816. var lengthBefore = arcLengths[ i ];
  17817. var lengthAfter = arcLengths[ i + 1 ];
  17818. var segmentLength = lengthAfter - lengthBefore;
  17819. // determine where we are between the 'before' and 'after' points
  17820. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  17821. // add that fractional amount to t
  17822. var t = ( i + segmentFraction ) / ( il - 1 );
  17823. return t;
  17824. },
  17825. // Returns a unit vector tangent at t
  17826. // In case any sub curve does not implement its tangent derivation,
  17827. // 2 points a small delta apart will be used to find its gradient
  17828. // which seems to give a reasonable approximation
  17829. getTangent: function( t ) {
  17830. var delta = 0.0001;
  17831. var t1 = t - delta;
  17832. var t2 = t + delta;
  17833. // Capping in case of danger
  17834. if ( t1 < 0 ) t1 = 0;
  17835. if ( t2 > 1 ) t2 = 1;
  17836. var pt1 = this.getPoint( t1 );
  17837. var pt2 = this.getPoint( t2 );
  17838. var vec = pt2.clone().sub( pt1 );
  17839. return vec.normalize();
  17840. },
  17841. getTangentAt: function ( u ) {
  17842. var t = this.getUtoTmapping( u );
  17843. return this.getTangent( t );
  17844. }
  17845. };
  17846. // TODO: Transformation for Curves?
  17847. /**************************************************************
  17848. * 3D Curves
  17849. **************************************************************/
  17850. // A Factory method for creating new curve subclasses
  17851. Curve.create = function ( constructor, getPointFunc ) {
  17852. constructor.prototype = Object.create( Curve.prototype );
  17853. constructor.prototype.constructor = constructor;
  17854. constructor.prototype.getPoint = getPointFunc;
  17855. return constructor;
  17856. };
  17857. /**************************************************************
  17858. * Line
  17859. **************************************************************/
  17860. function LineCurve( v1, v2 ) {
  17861. this.v1 = v1;
  17862. this.v2 = v2;
  17863. }
  17864. LineCurve.prototype = Object.create( Curve.prototype );
  17865. LineCurve.prototype.constructor = LineCurve;
  17866. LineCurve.prototype.isLineCurve = true;
  17867. LineCurve.prototype.getPoint = function ( t ) {
  17868. if ( t === 1 ) {
  17869. return this.v2.clone();
  17870. }
  17871. var point = this.v2.clone().sub( this.v1 );
  17872. point.multiplyScalar( t ).add( this.v1 );
  17873. return point;
  17874. };
  17875. // Line curve is linear, so we can overwrite default getPointAt
  17876. LineCurve.prototype.getPointAt = function ( u ) {
  17877. return this.getPoint( u );
  17878. };
  17879. LineCurve.prototype.getTangent = function( t ) {
  17880. var tangent = this.v2.clone().sub( this.v1 );
  17881. return tangent.normalize();
  17882. };
  17883. /**
  17884. * @author zz85 / http://www.lab4games.net/zz85/blog
  17885. *
  17886. **/
  17887. /**************************************************************
  17888. * Curved Path - a curve path is simply a array of connected
  17889. * curves, but retains the api of a curve
  17890. **************************************************************/
  17891. function CurvePath() {
  17892. this.curves = [];
  17893. this.autoClose = false; // Automatically closes the path
  17894. }
  17895. CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), {
  17896. constructor: CurvePath,
  17897. add: function ( curve ) {
  17898. this.curves.push( curve );
  17899. },
  17900. closePath: function () {
  17901. // Add a line curve if start and end of lines are not connected
  17902. var startPoint = this.curves[ 0 ].getPoint( 0 );
  17903. var endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  17904. if ( ! startPoint.equals( endPoint ) ) {
  17905. this.curves.push( new LineCurve( endPoint, startPoint ) );
  17906. }
  17907. },
  17908. // To get accurate point with reference to
  17909. // entire path distance at time t,
  17910. // following has to be done:
  17911. // 1. Length of each sub path have to be known
  17912. // 2. Locate and identify type of curve
  17913. // 3. Get t for the curve
  17914. // 4. Return curve.getPointAt(t')
  17915. getPoint: function ( t ) {
  17916. var d = t * this.getLength();
  17917. var curveLengths = this.getCurveLengths();
  17918. var i = 0;
  17919. // To think about boundaries points.
  17920. while ( i < curveLengths.length ) {
  17921. if ( curveLengths[ i ] >= d ) {
  17922. var diff = curveLengths[ i ] - d;
  17923. var curve = this.curves[ i ];
  17924. var segmentLength = curve.getLength();
  17925. var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  17926. return curve.getPointAt( u );
  17927. }
  17928. i ++;
  17929. }
  17930. return null;
  17931. // loop where sum != 0, sum > d , sum+1 <d
  17932. },
  17933. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  17934. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  17935. // getPoint() depends on getLength
  17936. getLength: function () {
  17937. var lens = this.getCurveLengths();
  17938. return lens[ lens.length - 1 ];
  17939. },
  17940. // cacheLengths must be recalculated.
  17941. updateArcLengths: function () {
  17942. this.needsUpdate = true;
  17943. this.cacheLengths = null;
  17944. this.getLengths();
  17945. },
  17946. // Compute lengths and cache them
  17947. // We cannot overwrite getLengths() because UtoT mapping uses it.
  17948. getCurveLengths: function () {
  17949. // We use cache values if curves and cache array are same length
  17950. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  17951. return this.cacheLengths;
  17952. }
  17953. // Get length of sub-curve
  17954. // Push sums into cached array
  17955. var lengths = [], sums = 0;
  17956. for ( var i = 0, l = this.curves.length; i < l; i ++ ) {
  17957. sums += this.curves[ i ].getLength();
  17958. lengths.push( sums );
  17959. }
  17960. this.cacheLengths = lengths;
  17961. return lengths;
  17962. },
  17963. getSpacedPoints: function ( divisions ) {
  17964. if ( ! divisions ) divisions = 40;
  17965. var points = [];
  17966. for ( var i = 0; i <= divisions; i ++ ) {
  17967. points.push( this.getPoint( i / divisions ) );
  17968. }
  17969. if ( this.autoClose ) {
  17970. points.push( points[ 0 ] );
  17971. }
  17972. return points;
  17973. },
  17974. getPoints: function ( divisions ) {
  17975. divisions = divisions || 12;
  17976. var points = [], last;
  17977. for ( var i = 0, curves = this.curves; i < curves.length; i ++ ) {
  17978. var curve = curves[ i ];
  17979. var resolution = (curve && curve.isEllipseCurve) ? divisions * 2
  17980. : (curve && curve.isLineCurve) ? 1
  17981. : (curve && curve.isSplineCurve) ? divisions * curve.points.length
  17982. : divisions;
  17983. var pts = curve.getPoints( resolution );
  17984. for ( var j = 0; j < pts.length; j++ ) {
  17985. var point = pts[ j ];
  17986. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  17987. points.push( point );
  17988. last = point;
  17989. }
  17990. }
  17991. if ( this.autoClose && points.length > 1 && !points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  17992. points.push( points[ 0 ] );
  17993. }
  17994. return points;
  17995. },
  17996. /**************************************************************
  17997. * Create Geometries Helpers
  17998. **************************************************************/
  17999. /// Generate geometry from path points (for Line or Points objects)
  18000. createPointsGeometry: function ( divisions ) {
  18001. var pts = this.getPoints( divisions );
  18002. return this.createGeometry( pts );
  18003. },
  18004. // Generate geometry from equidistant sampling along the path
  18005. createSpacedPointsGeometry: function ( divisions ) {
  18006. var pts = this.getSpacedPoints( divisions );
  18007. return this.createGeometry( pts );
  18008. },
  18009. createGeometry: function ( points ) {
  18010. var geometry = new Geometry();
  18011. for ( var i = 0, l = points.length; i < l; i ++ ) {
  18012. var point = points[ i ];
  18013. geometry.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );
  18014. }
  18015. return geometry;
  18016. }
  18017. } );
  18018. /**************************************************************
  18019. * Ellipse curve
  18020. **************************************************************/
  18021. function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  18022. this.aX = aX;
  18023. this.aY = aY;
  18024. this.xRadius = xRadius;
  18025. this.yRadius = yRadius;
  18026. this.aStartAngle = aStartAngle;
  18027. this.aEndAngle = aEndAngle;
  18028. this.aClockwise = aClockwise;
  18029. this.aRotation = aRotation || 0;
  18030. }
  18031. EllipseCurve.prototype = Object.create( Curve.prototype );
  18032. EllipseCurve.prototype.constructor = EllipseCurve;
  18033. EllipseCurve.prototype.isEllipseCurve = true;
  18034. EllipseCurve.prototype.getPoint = function( t ) {
  18035. var twoPi = Math.PI * 2;
  18036. var deltaAngle = this.aEndAngle - this.aStartAngle;
  18037. var samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  18038. // ensures that deltaAngle is 0 .. 2 PI
  18039. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  18040. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  18041. if ( deltaAngle < Number.EPSILON ) {
  18042. if ( samePoints ) {
  18043. deltaAngle = 0;
  18044. } else {
  18045. deltaAngle = twoPi;
  18046. }
  18047. }
  18048. if ( this.aClockwise === true && ! samePoints ) {
  18049. if ( deltaAngle === twoPi ) {
  18050. deltaAngle = - twoPi;
  18051. } else {
  18052. deltaAngle = deltaAngle - twoPi;
  18053. }
  18054. }
  18055. var angle = this.aStartAngle + t * deltaAngle;
  18056. var x = this.aX + this.xRadius * Math.cos( angle );
  18057. var y = this.aY + this.yRadius * Math.sin( angle );
  18058. if ( this.aRotation !== 0 ) {
  18059. var cos = Math.cos( this.aRotation );
  18060. var sin = Math.sin( this.aRotation );
  18061. var tx = x - this.aX;
  18062. var ty = y - this.aY;
  18063. // Rotate the point about the center of the ellipse.
  18064. x = tx * cos - ty * sin + this.aX;
  18065. y = tx * sin + ty * cos + this.aY;
  18066. }
  18067. return new Vector2( x, y );
  18068. };
  18069. /**
  18070. * @author zz85 / http://www.lab4games.net/zz85/blog
  18071. */
  18072. exports.CurveUtils = {
  18073. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  18074. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  18075. },
  18076. // Puay Bing, thanks for helping with this derivative!
  18077. tangentCubicBezier: function ( t, p0, p1, p2, p3 ) {
  18078. return - 3 * p0 * ( 1 - t ) * ( 1 - t ) +
  18079. 3 * p1 * ( 1 - t ) * ( 1 - t ) - 6 * t * p1 * ( 1 - t ) +
  18080. 6 * t * p2 * ( 1 - t ) - 3 * t * t * p2 +
  18081. 3 * t * t * p3;
  18082. },
  18083. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  18084. // To check if my formulas are correct
  18085. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  18086. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  18087. var h01 = - 6 * t * t + 6 * t; // − 2t3 + 3t2
  18088. var h11 = 3 * t * t - 2 * t; // t3 − t2
  18089. return h00 + h10 + h01 + h11;
  18090. },
  18091. // Catmull-Rom
  18092. interpolate: function( p0, p1, p2, p3, t ) {
  18093. var v0 = ( p2 - p0 ) * 0.5;
  18094. var v1 = ( p3 - p1 ) * 0.5;
  18095. var t2 = t * t;
  18096. var t3 = t * t2;
  18097. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  18098. }
  18099. };
  18100. /**************************************************************
  18101. * Spline curve
  18102. **************************************************************/
  18103. function SplineCurve( points /* array of Vector2 */ ) {
  18104. this.points = ( points === undefined ) ? [] : points;
  18105. }
  18106. SplineCurve.prototype = Object.create( Curve.prototype );
  18107. SplineCurve.prototype.constructor = SplineCurve;
  18108. SplineCurve.prototype.isSplineCurve = true;
  18109. SplineCurve.prototype.getPoint = function ( t ) {
  18110. var points = this.points;
  18111. var point = ( points.length - 1 ) * t;
  18112. var intPoint = Math.floor( point );
  18113. var weight = point - intPoint;
  18114. var point0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  18115. var point1 = points[ intPoint ];
  18116. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  18117. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  18118. var interpolate = exports.CurveUtils.interpolate;
  18119. return new Vector2(
  18120. interpolate( point0.x, point1.x, point2.x, point3.x, weight ),
  18121. interpolate( point0.y, point1.y, point2.y, point3.y, weight )
  18122. );
  18123. };
  18124. /**************************************************************
  18125. * Cubic Bezier curve
  18126. **************************************************************/
  18127. function CubicBezierCurve( v0, v1, v2, v3 ) {
  18128. this.v0 = v0;
  18129. this.v1 = v1;
  18130. this.v2 = v2;
  18131. this.v3 = v3;
  18132. }
  18133. CubicBezierCurve.prototype = Object.create( Curve.prototype );
  18134. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  18135. CubicBezierCurve.prototype.getPoint = function ( t ) {
  18136. var b3 = exports.ShapeUtils.b3;
  18137. return new Vector2(
  18138. b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ),
  18139. b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y )
  18140. );
  18141. };
  18142. CubicBezierCurve.prototype.getTangent = function( t ) {
  18143. var tangentCubicBezier = exports.CurveUtils.tangentCubicBezier;
  18144. return new Vector2(
  18145. tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ),
  18146. tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y )
  18147. ).normalize();
  18148. };
  18149. /**************************************************************
  18150. * Quadratic Bezier curve
  18151. **************************************************************/
  18152. function QuadraticBezierCurve( v0, v1, v2 ) {
  18153. this.v0 = v0;
  18154. this.v1 = v1;
  18155. this.v2 = v2;
  18156. }
  18157. QuadraticBezierCurve.prototype = Object.create( Curve.prototype );
  18158. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  18159. QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  18160. var b2 = exports.ShapeUtils.b2;
  18161. return new Vector2(
  18162. b2( t, this.v0.x, this.v1.x, this.v2.x ),
  18163. b2( t, this.v0.y, this.v1.y, this.v2.y )
  18164. );
  18165. };
  18166. QuadraticBezierCurve.prototype.getTangent = function( t ) {
  18167. var tangentQuadraticBezier = exports.CurveUtils.tangentQuadraticBezier;
  18168. return new Vector2(
  18169. tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x ),
  18170. tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y )
  18171. ).normalize();
  18172. };
  18173. var PathPrototype = Object.assign( Object.create( CurvePath.prototype ), {
  18174. fromPoints: function ( vectors ) {
  18175. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  18176. for ( var i = 1, l = vectors.length; i < l; i ++ ) {
  18177. this.lineTo( vectors[ i ].x, vectors[ i ].y );
  18178. }
  18179. },
  18180. moveTo: function ( x, y ) {
  18181. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  18182. },
  18183. lineTo: function ( x, y ) {
  18184. var curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  18185. this.curves.push( curve );
  18186. this.currentPoint.set( x, y );
  18187. },
  18188. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  18189. var curve = new QuadraticBezierCurve(
  18190. this.currentPoint.clone(),
  18191. new Vector2( aCPx, aCPy ),
  18192. new Vector2( aX, aY )
  18193. );
  18194. this.curves.push( curve );
  18195. this.currentPoint.set( aX, aY );
  18196. },
  18197. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  18198. var curve = new CubicBezierCurve(
  18199. this.currentPoint.clone(),
  18200. new Vector2( aCP1x, aCP1y ),
  18201. new Vector2( aCP2x, aCP2y ),
  18202. new Vector2( aX, aY )
  18203. );
  18204. this.curves.push( curve );
  18205. this.currentPoint.set( aX, aY );
  18206. },
  18207. splineThru: function ( pts /*Array of Vector*/ ) {
  18208. var npts = [ this.currentPoint.clone() ].concat( pts );
  18209. var curve = new SplineCurve( npts );
  18210. this.curves.push( curve );
  18211. this.currentPoint.copy( pts[ pts.length - 1 ] );
  18212. },
  18213. arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  18214. var x0 = this.currentPoint.x;
  18215. var y0 = this.currentPoint.y;
  18216. this.absarc( aX + x0, aY + y0, aRadius,
  18217. aStartAngle, aEndAngle, aClockwise );
  18218. },
  18219. absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  18220. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  18221. },
  18222. ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  18223. var x0 = this.currentPoint.x;
  18224. var y0 = this.currentPoint.y;
  18225. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  18226. },
  18227. absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  18228. var curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  18229. if ( this.curves.length > 0 ) {
  18230. // if a previous curve is present, attempt to join
  18231. var firstPoint = curve.getPoint( 0 );
  18232. if ( ! firstPoint.equals( this.currentPoint ) ) {
  18233. this.lineTo( firstPoint.x, firstPoint.y );
  18234. }
  18235. }
  18236. this.curves.push( curve );
  18237. var lastPoint = curve.getPoint( 1 );
  18238. this.currentPoint.copy( lastPoint );
  18239. }
  18240. } );
  18241. /**
  18242. * @author WestLangley / https://github.com/WestLangley
  18243. * @author zz85 / https://github.com/zz85
  18244. * @author miningold / https://github.com/miningold
  18245. * @author jonobr1 / https://github.com/jonobr1
  18246. *
  18247. * Modified from the TorusKnotGeometry by @oosmoxiecode
  18248. *
  18249. * Creates a tube which extrudes along a 3d spline
  18250. *
  18251. * Uses parallel transport frames as described in
  18252. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  18253. */
  18254. function TubeGeometry( path, segments, radius, radialSegments, closed, taper ) {
  18255. Geometry.call( this );
  18256. this.type = 'TubeGeometry';
  18257. this.parameters = {
  18258. path: path,
  18259. segments: segments,
  18260. radius: radius,
  18261. radialSegments: radialSegments,
  18262. closed: closed,
  18263. taper: taper
  18264. };
  18265. segments = segments || 64;
  18266. radius = radius || 1;
  18267. radialSegments = radialSegments || 8;
  18268. closed = closed || false;
  18269. taper = taper || TubeGeometry.NoTaper;
  18270. var grid = [];
  18271. var scope = this,
  18272. tangent,
  18273. normal,
  18274. binormal,
  18275. numpoints = segments + 1,
  18276. u, v, r,
  18277. cx, cy,
  18278. pos, pos2 = new Vector3(),
  18279. i, j,
  18280. ip, jp,
  18281. a, b, c, d,
  18282. uva, uvb, uvc, uvd;
  18283. var frames = new TubeGeometry.FrenetFrames( path, segments, closed ),
  18284. tangents = frames.tangents,
  18285. normals = frames.normals,
  18286. binormals = frames.binormals;
  18287. // proxy internals
  18288. this.tangents = tangents;
  18289. this.normals = normals;
  18290. this.binormals = binormals;
  18291. function vert( x, y, z ) {
  18292. return scope.vertices.push( new Vector3( x, y, z ) ) - 1;
  18293. }
  18294. // construct the grid
  18295. for ( i = 0; i < numpoints; i ++ ) {
  18296. grid[ i ] = [];
  18297. u = i / ( numpoints - 1 );
  18298. pos = path.getPointAt( u );
  18299. tangent = tangents[ i ];
  18300. normal = normals[ i ];
  18301. binormal = binormals[ i ];
  18302. r = radius * taper( u );
  18303. for ( j = 0; j < radialSegments; j ++ ) {
  18304. v = j / radialSegments * 2 * Math.PI;
  18305. cx = - r * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  18306. cy = r * Math.sin( v );
  18307. pos2.copy( pos );
  18308. pos2.x += cx * normal.x + cy * binormal.x;
  18309. pos2.y += cx * normal.y + cy * binormal.y;
  18310. pos2.z += cx * normal.z + cy * binormal.z;
  18311. grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  18312. }
  18313. }
  18314. // construct the mesh
  18315. for ( i = 0; i < segments; i ++ ) {
  18316. for ( j = 0; j < radialSegments; j ++ ) {
  18317. ip = ( closed ) ? ( i + 1 ) % segments : i + 1;
  18318. jp = ( j + 1 ) % radialSegments;
  18319. a = grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  18320. b = grid[ ip ][ j ];
  18321. c = grid[ ip ][ jp ];
  18322. d = grid[ i ][ jp ];
  18323. uva = new Vector2( i / segments, j / radialSegments );
  18324. uvb = new Vector2( ( i + 1 ) / segments, j / radialSegments );
  18325. uvc = new Vector2( ( i + 1 ) / segments, ( j + 1 ) / radialSegments );
  18326. uvd = new Vector2( i / segments, ( j + 1 ) / radialSegments );
  18327. this.faces.push( new Face3( a, b, d ) );
  18328. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  18329. this.faces.push( new Face3( b, c, d ) );
  18330. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  18331. }
  18332. }
  18333. this.computeFaceNormals();
  18334. this.computeVertexNormals();
  18335. }
  18336. TubeGeometry.prototype = Object.create( Geometry.prototype );
  18337. TubeGeometry.prototype.constructor = TubeGeometry;
  18338. TubeGeometry.NoTaper = function ( u ) {
  18339. return 1;
  18340. };
  18341. TubeGeometry.SinusoidalTaper = function ( u ) {
  18342. return Math.sin( Math.PI * u );
  18343. };
  18344. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  18345. TubeGeometry.FrenetFrames = function ( path, segments, closed ) {
  18346. var normal = new Vector3(),
  18347. tangents = [],
  18348. normals = [],
  18349. binormals = [],
  18350. vec = new Vector3(),
  18351. mat = new Matrix4(),
  18352. numpoints = segments + 1,
  18353. theta,
  18354. smallest,
  18355. tx, ty, tz,
  18356. i, u;
  18357. // expose internals
  18358. this.tangents = tangents;
  18359. this.normals = normals;
  18360. this.binormals = binormals;
  18361. // compute the tangent vectors for each segment on the path
  18362. for ( i = 0; i < numpoints; i ++ ) {
  18363. u = i / ( numpoints - 1 );
  18364. tangents[ i ] = path.getTangentAt( u );
  18365. tangents[ i ].normalize();
  18366. }
  18367. initialNormal3();
  18368. /*
  18369. function initialNormal1(lastBinormal) {
  18370. // fixed start binormal. Has dangers of 0 vectors
  18371. normals[ 0 ] = new THREE.Vector3();
  18372. binormals[ 0 ] = new THREE.Vector3();
  18373. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  18374. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  18375. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  18376. }
  18377. function initialNormal2() {
  18378. // This uses the Frenet-Serret formula for deriving binormal
  18379. var t2 = path.getTangentAt( epsilon );
  18380. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  18381. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  18382. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  18383. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  18384. }
  18385. */
  18386. function initialNormal3() {
  18387. // select an initial normal vector perpendicular to the first tangent vector,
  18388. // and in the direction of the smallest tangent xyz component
  18389. normals[ 0 ] = new Vector3();
  18390. binormals[ 0 ] = new Vector3();
  18391. smallest = Number.MAX_VALUE;
  18392. tx = Math.abs( tangents[ 0 ].x );
  18393. ty = Math.abs( tangents[ 0 ].y );
  18394. tz = Math.abs( tangents[ 0 ].z );
  18395. if ( tx <= smallest ) {
  18396. smallest = tx;
  18397. normal.set( 1, 0, 0 );
  18398. }
  18399. if ( ty <= smallest ) {
  18400. smallest = ty;
  18401. normal.set( 0, 1, 0 );
  18402. }
  18403. if ( tz <= smallest ) {
  18404. normal.set( 0, 0, 1 );
  18405. }
  18406. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  18407. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  18408. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  18409. }
  18410. // compute the slowly-varying normal and binormal vectors for each segment on the path
  18411. for ( i = 1; i < numpoints; i ++ ) {
  18412. normals[ i ] = normals[ i - 1 ].clone();
  18413. binormals[ i ] = binormals[ i - 1 ].clone();
  18414. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  18415. if ( vec.length() > Number.EPSILON ) {
  18416. vec.normalize();
  18417. theta = Math.acos( exports.Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  18418. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  18419. }
  18420. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  18421. }
  18422. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  18423. if ( closed ) {
  18424. theta = Math.acos( exports.Math.clamp( normals[ 0 ].dot( normals[ numpoints - 1 ] ), - 1, 1 ) );
  18425. theta /= ( numpoints - 1 );
  18426. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints - 1 ] ) ) > 0 ) {
  18427. theta = - theta;
  18428. }
  18429. for ( i = 1; i < numpoints; i ++ ) {
  18430. // twist a little...
  18431. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  18432. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  18433. }
  18434. }
  18435. };
  18436. /**
  18437. * @author zz85 / http://www.lab4games.net/zz85/blog
  18438. *
  18439. * Creates extruded geometry from a path shape.
  18440. *
  18441. * parameters = {
  18442. *
  18443. * curveSegments: <int>, // number of points on the curves
  18444. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  18445. * amount: <int>, // Depth to extrude the shape
  18446. *
  18447. * bevelEnabled: <bool>, // turn on bevel
  18448. * bevelThickness: <float>, // how deep into the original shape bevel goes
  18449. * bevelSize: <float>, // how far from shape outline is bevel
  18450. * bevelSegments: <int>, // number of bevel layers
  18451. *
  18452. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  18453. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  18454. *
  18455. * uvGenerator: <Object> // object that provides UV generator functions
  18456. *
  18457. * }
  18458. **/
  18459. function ExtrudeGeometry( shapes, options ) {
  18460. if ( typeof( shapes ) === "undefined" ) {
  18461. shapes = [];
  18462. return;
  18463. }
  18464. Geometry.call( this );
  18465. this.type = 'ExtrudeGeometry';
  18466. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  18467. this.addShapeList( shapes, options );
  18468. this.computeFaceNormals();
  18469. // can't really use automatic vertex normals
  18470. // as then front and back sides get smoothed too
  18471. // should do separate smoothing just for sides
  18472. //this.computeVertexNormals();
  18473. //console.log( "took", ( Date.now() - startTime ) );
  18474. }
  18475. ExtrudeGeometry.prototype = Object.create( Geometry.prototype );
  18476. ExtrudeGeometry.prototype.constructor = ExtrudeGeometry;
  18477. ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18478. var sl = shapes.length;
  18479. for ( var s = 0; s < sl; s ++ ) {
  18480. var shape = shapes[ s ];
  18481. this.addShape( shape, options );
  18482. }
  18483. };
  18484. ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  18485. var amount = options.amount !== undefined ? options.amount : 100;
  18486. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  18487. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  18488. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18489. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  18490. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18491. var steps = options.steps !== undefined ? options.steps : 1;
  18492. var extrudePath = options.extrudePath;
  18493. var extrudePts, extrudeByPath = false;
  18494. // Use default WorldUVGenerator if no UV generators are specified.
  18495. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : ExtrudeGeometry.WorldUVGenerator;
  18496. var splineTube, binormal, normal, position2;
  18497. if ( extrudePath ) {
  18498. extrudePts = extrudePath.getSpacedPoints( steps );
  18499. extrudeByPath = true;
  18500. bevelEnabled = false; // bevels not supported for path extrusion
  18501. // SETUP TNB variables
  18502. // Reuse TNB from TubeGeomtry for now.
  18503. // TODO1 - have a .isClosed in spline?
  18504. splineTube = options.frames !== undefined ? options.frames : new TubeGeometry.FrenetFrames( extrudePath, steps, false );
  18505. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18506. binormal = new Vector3();
  18507. normal = new Vector3();
  18508. position2 = new Vector3();
  18509. }
  18510. // Safeguards if bevels are not enabled
  18511. if ( ! bevelEnabled ) {
  18512. bevelSegments = 0;
  18513. bevelThickness = 0;
  18514. bevelSize = 0;
  18515. }
  18516. // Variables initialization
  18517. var ahole, h, hl; // looping of holes
  18518. var scope = this;
  18519. var shapesOffset = this.vertices.length;
  18520. var shapePoints = shape.extractPoints( curveSegments );
  18521. var vertices = shapePoints.shape;
  18522. var holes = shapePoints.holes;
  18523. var reverse = ! exports.ShapeUtils.isClockWise( vertices );
  18524. if ( reverse ) {
  18525. vertices = vertices.reverse();
  18526. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18527. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18528. ahole = holes[ h ];
  18529. if ( exports.ShapeUtils.isClockWise( ahole ) ) {
  18530. holes[ h ] = ahole.reverse();
  18531. }
  18532. }
  18533. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  18534. }
  18535. var faces = exports.ShapeUtils.triangulateShape( vertices, holes );
  18536. /* Vertices */
  18537. var contour = vertices; // vertices has all points but contour has only points of circumference
  18538. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18539. ahole = holes[ h ];
  18540. vertices = vertices.concat( ahole );
  18541. }
  18542. function scalePt2( pt, vec, size ) {
  18543. if ( ! vec ) console.error( "THREE.ExtrudeGeometry: vec does not exist" );
  18544. return vec.clone().multiplyScalar( size ).add( pt );
  18545. }
  18546. var b, bs, t, z,
  18547. vert, vlen = vertices.length,
  18548. face, flen = faces.length;
  18549. // Find directions for point movement
  18550. function getBevelVec( inPt, inPrev, inNext ) {
  18551. // computes for inPt the corresponding point inPt' on a new contour
  18552. // shifted by 1 unit (length of normalized vector) to the left
  18553. // if we walk along contour clockwise, this new contour is outside the old one
  18554. //
  18555. // inPt' is the intersection of the two lines parallel to the two
  18556. // adjacent edges of inPt at a distance of 1 unit on the left side.
  18557. var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt
  18558. // good reading for geometry algorithms (here: line-line intersection)
  18559. // http://geomalgorithms.com/a05-_intersect-1.html
  18560. var v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y;
  18561. var v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y;
  18562. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  18563. // check for collinear edges
  18564. var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  18565. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  18566. // not collinear
  18567. // length of vectors for normalizing
  18568. var v_prev_len = Math.sqrt( v_prev_lensq );
  18569. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  18570. // shift adjacent points by unit vectors to the left
  18571. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  18572. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  18573. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  18574. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  18575. // scaling factor for v_prev to intersection point
  18576. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  18577. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  18578. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  18579. // vector from inPt to intersection point
  18580. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  18581. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  18582. // Don't normalize!, otherwise sharp corners become ugly
  18583. // but prevent crazy spikes
  18584. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  18585. if ( v_trans_lensq <= 2 ) {
  18586. return new Vector2( v_trans_x, v_trans_y );
  18587. } else {
  18588. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  18589. }
  18590. } else {
  18591. // handle special case of collinear edges
  18592. var direction_eq = false; // assumes: opposite
  18593. if ( v_prev_x > Number.EPSILON ) {
  18594. if ( v_next_x > Number.EPSILON ) {
  18595. direction_eq = true;
  18596. }
  18597. } else {
  18598. if ( v_prev_x < - Number.EPSILON ) {
  18599. if ( v_next_x < - Number.EPSILON ) {
  18600. direction_eq = true;
  18601. }
  18602. } else {
  18603. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  18604. direction_eq = true;
  18605. }
  18606. }
  18607. }
  18608. if ( direction_eq ) {
  18609. // console.log("Warning: lines are a straight sequence");
  18610. v_trans_x = - v_prev_y;
  18611. v_trans_y = v_prev_x;
  18612. shrink_by = Math.sqrt( v_prev_lensq );
  18613. } else {
  18614. // console.log("Warning: lines are a straight spike");
  18615. v_trans_x = v_prev_x;
  18616. v_trans_y = v_prev_y;
  18617. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  18618. }
  18619. }
  18620. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  18621. }
  18622. var contourMovements = [];
  18623. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18624. if ( j === il ) j = 0;
  18625. if ( k === il ) k = 0;
  18626. // (j)---(i)---(k)
  18627. // console.log('i,j,k', i, j , k)
  18628. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  18629. }
  18630. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  18631. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18632. ahole = holes[ h ];
  18633. oneHoleMovements = [];
  18634. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18635. if ( j === il ) j = 0;
  18636. if ( k === il ) k = 0;
  18637. // (j)---(i)---(k)
  18638. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  18639. }
  18640. holesMovements.push( oneHoleMovements );
  18641. verticesMovements = verticesMovements.concat( oneHoleMovements );
  18642. }
  18643. // Loop bevelSegments, 1 for the front, 1 for the back
  18644. for ( b = 0; b < bevelSegments; b ++ ) {
  18645. //for ( b = bevelSegments; b > 0; b -- ) {
  18646. t = b / bevelSegments;
  18647. z = bevelThickness * Math.cos( t * Math.PI / 2 );
  18648. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  18649. // contract shape
  18650. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18651. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18652. v( vert.x, vert.y, - z );
  18653. }
  18654. // expand holes
  18655. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18656. ahole = holes[ h ];
  18657. oneHoleMovements = holesMovements[ h ];
  18658. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  18659. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18660. v( vert.x, vert.y, - z );
  18661. }
  18662. }
  18663. }
  18664. bs = bevelSize;
  18665. // Back facing vertices
  18666. for ( i = 0; i < vlen; i ++ ) {
  18667. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18668. if ( ! extrudeByPath ) {
  18669. v( vert.x, vert.y, 0 );
  18670. } else {
  18671. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  18672. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  18673. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  18674. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  18675. v( position2.x, position2.y, position2.z );
  18676. }
  18677. }
  18678. // Add stepped vertices...
  18679. // Including front facing vertices
  18680. var s;
  18681. for ( s = 1; s <= steps; s ++ ) {
  18682. for ( i = 0; i < vlen; i ++ ) {
  18683. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18684. if ( ! extrudeByPath ) {
  18685. v( vert.x, vert.y, amount / steps * s );
  18686. } else {
  18687. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  18688. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  18689. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  18690. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  18691. v( position2.x, position2.y, position2.z );
  18692. }
  18693. }
  18694. }
  18695. // Add bevel segments planes
  18696. //for ( b = 1; b <= bevelSegments; b ++ ) {
  18697. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  18698. t = b / bevelSegments;
  18699. z = bevelThickness * Math.cos ( t * Math.PI / 2 );
  18700. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  18701. // contract shape
  18702. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18703. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18704. v( vert.x, vert.y, amount + z );
  18705. }
  18706. // expand holes
  18707. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18708. ahole = holes[ h ];
  18709. oneHoleMovements = holesMovements[ h ];
  18710. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  18711. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18712. if ( ! extrudeByPath ) {
  18713. v( vert.x, vert.y, amount + z );
  18714. } else {
  18715. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  18716. }
  18717. }
  18718. }
  18719. }
  18720. /* Faces */
  18721. // Top and bottom faces
  18722. buildLidFaces();
  18723. // Sides faces
  18724. buildSideFaces();
  18725. ///// Internal functions
  18726. function buildLidFaces() {
  18727. if ( bevelEnabled ) {
  18728. var layer = 0; // steps + 1
  18729. var offset = vlen * layer;
  18730. // Bottom faces
  18731. for ( i = 0; i < flen; i ++ ) {
  18732. face = faces[ i ];
  18733. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  18734. }
  18735. layer = steps + bevelSegments * 2;
  18736. offset = vlen * layer;
  18737. // Top faces
  18738. for ( i = 0; i < flen; i ++ ) {
  18739. face = faces[ i ];
  18740. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  18741. }
  18742. } else {
  18743. // Bottom faces
  18744. for ( i = 0; i < flen; i ++ ) {
  18745. face = faces[ i ];
  18746. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  18747. }
  18748. // Top faces
  18749. for ( i = 0; i < flen; i ++ ) {
  18750. face = faces[ i ];
  18751. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  18752. }
  18753. }
  18754. }
  18755. // Create faces for the z-sides of the shape
  18756. function buildSideFaces() {
  18757. var layeroffset = 0;
  18758. sidewalls( contour, layeroffset );
  18759. layeroffset += contour.length;
  18760. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18761. ahole = holes[ h ];
  18762. sidewalls( ahole, layeroffset );
  18763. //, true
  18764. layeroffset += ahole.length;
  18765. }
  18766. }
  18767. function sidewalls( contour, layeroffset ) {
  18768. var j, k;
  18769. i = contour.length;
  18770. while ( -- i >= 0 ) {
  18771. j = i;
  18772. k = i - 1;
  18773. if ( k < 0 ) k = contour.length - 1;
  18774. //console.log('b', i,j, i-1, k,vertices.length);
  18775. var s = 0, sl = steps + bevelSegments * 2;
  18776. for ( s = 0; s < sl; s ++ ) {
  18777. var slen1 = vlen * s;
  18778. var slen2 = vlen * ( s + 1 );
  18779. var a = layeroffset + j + slen1,
  18780. b = layeroffset + k + slen1,
  18781. c = layeroffset + k + slen2,
  18782. d = layeroffset + j + slen2;
  18783. f4( a, b, c, d, contour, s, sl, j, k );
  18784. }
  18785. }
  18786. }
  18787. function v( x, y, z ) {
  18788. scope.vertices.push( new Vector3( x, y, z ) );
  18789. }
  18790. function f3( a, b, c ) {
  18791. a += shapesOffset;
  18792. b += shapesOffset;
  18793. c += shapesOffset;
  18794. scope.faces.push( new Face3( a, b, c, null, null, 0 ) );
  18795. var uvs = uvgen.generateTopUV( scope, a, b, c );
  18796. scope.faceVertexUvs[ 0 ].push( uvs );
  18797. }
  18798. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  18799. a += shapesOffset;
  18800. b += shapesOffset;
  18801. c += shapesOffset;
  18802. d += shapesOffset;
  18803. scope.faces.push( new Face3( a, b, d, null, null, 1 ) );
  18804. scope.faces.push( new Face3( b, c, d, null, null, 1 ) );
  18805. var uvs = uvgen.generateSideWallUV( scope, a, b, c, d );
  18806. scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] );
  18807. scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] );
  18808. }
  18809. };
  18810. ExtrudeGeometry.WorldUVGenerator = {
  18811. generateTopUV: function ( geometry, indexA, indexB, indexC ) {
  18812. var vertices = geometry.vertices;
  18813. var a = vertices[ indexA ];
  18814. var b = vertices[ indexB ];
  18815. var c = vertices[ indexC ];
  18816. return [
  18817. new Vector2( a.x, a.y ),
  18818. new Vector2( b.x, b.y ),
  18819. new Vector2( c.x, c.y )
  18820. ];
  18821. },
  18822. generateSideWallUV: function ( geometry, indexA, indexB, indexC, indexD ) {
  18823. var vertices = geometry.vertices;
  18824. var a = vertices[ indexA ];
  18825. var b = vertices[ indexB ];
  18826. var c = vertices[ indexC ];
  18827. var d = vertices[ indexD ];
  18828. if ( Math.abs( a.y - b.y ) < 0.01 ) {
  18829. return [
  18830. new Vector2( a.x, 1 - a.z ),
  18831. new Vector2( b.x, 1 - b.z ),
  18832. new Vector2( c.x, 1 - c.z ),
  18833. new Vector2( d.x, 1 - d.z )
  18834. ];
  18835. } else {
  18836. return [
  18837. new Vector2( a.y, 1 - a.z ),
  18838. new Vector2( b.y, 1 - b.z ),
  18839. new Vector2( c.y, 1 - c.z ),
  18840. new Vector2( d.y, 1 - d.z )
  18841. ];
  18842. }
  18843. }
  18844. };
  18845. /**
  18846. * @author jonobr1 / http://jonobr1.com
  18847. *
  18848. * Creates a one-sided polygonal geometry from a path shape. Similar to
  18849. * ExtrudeGeometry.
  18850. *
  18851. * parameters = {
  18852. *
  18853. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  18854. *
  18855. * material: <int> // material index for front and back faces
  18856. * uvGenerator: <Object> // object that provides UV generator functions
  18857. *
  18858. * }
  18859. **/
  18860. function ShapeGeometry( shapes, options ) {
  18861. Geometry.call( this );
  18862. this.type = 'ShapeGeometry';
  18863. if ( Array.isArray( shapes ) === false ) shapes = [ shapes ];
  18864. this.addShapeList( shapes, options );
  18865. this.computeFaceNormals();
  18866. }
  18867. ShapeGeometry.prototype = Object.create( Geometry.prototype );
  18868. ShapeGeometry.prototype.constructor = ShapeGeometry;
  18869. /**
  18870. * Add an array of shapes to THREE.ShapeGeometry.
  18871. */
  18872. ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18873. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  18874. this.addShape( shapes[ i ], options );
  18875. }
  18876. return this;
  18877. };
  18878. /**
  18879. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  18880. */
  18881. ShapeGeometry.prototype.addShape = function ( shape, options ) {
  18882. if ( options === undefined ) options = {};
  18883. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18884. var material = options.material;
  18885. var uvgen = options.UVGenerator === undefined ? ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  18886. //
  18887. var i, l, hole;
  18888. var shapesOffset = this.vertices.length;
  18889. var shapePoints = shape.extractPoints( curveSegments );
  18890. var vertices = shapePoints.shape;
  18891. var holes = shapePoints.holes;
  18892. var reverse = ! exports.ShapeUtils.isClockWise( vertices );
  18893. if ( reverse ) {
  18894. vertices = vertices.reverse();
  18895. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  18896. for ( i = 0, l = holes.length; i < l; i ++ ) {
  18897. hole = holes[ i ];
  18898. if ( exports.ShapeUtils.isClockWise( hole ) ) {
  18899. holes[ i ] = hole.reverse();
  18900. }
  18901. }
  18902. reverse = false;
  18903. }
  18904. var faces = exports.ShapeUtils.triangulateShape( vertices, holes );
  18905. // Vertices
  18906. for ( i = 0, l = holes.length; i < l; i ++ ) {
  18907. hole = holes[ i ];
  18908. vertices = vertices.concat( hole );
  18909. }
  18910. //
  18911. var vert, vlen = vertices.length;
  18912. var face, flen = faces.length;
  18913. for ( i = 0; i < vlen; i ++ ) {
  18914. vert = vertices[ i ];
  18915. this.vertices.push( new Vector3( vert.x, vert.y, 0 ) );
  18916. }
  18917. for ( i = 0; i < flen; i ++ ) {
  18918. face = faces[ i ];
  18919. var a = face[ 0 ] + shapesOffset;
  18920. var b = face[ 1 ] + shapesOffset;
  18921. var c = face[ 2 ] + shapesOffset;
  18922. this.faces.push( new Face3( a, b, c, null, null, material ) );
  18923. this.faceVertexUvs[ 0 ].push( uvgen.generateTopUV( this, a, b, c ) );
  18924. }
  18925. };
  18926. /**
  18927. * @author zz85 / http://www.lab4games.net/zz85/blog
  18928. * Defines a 2d shape plane using paths.
  18929. **/
  18930. // STEP 1 Create a path.
  18931. // STEP 2 Turn path into shape.
  18932. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  18933. // STEP 3a - Extract points from each shape, turn to vertices
  18934. // STEP 3b - Triangulate each shape, add faces.
  18935. function Shape() {
  18936. Path.apply( this, arguments );
  18937. this.holes = [];
  18938. }
  18939. Shape.prototype = Object.assign( Object.create( PathPrototype ), {
  18940. constructor: Shape,
  18941. // Convenience method to return ExtrudeGeometry
  18942. extrude: function ( options ) {
  18943. return new ExtrudeGeometry( this, options );
  18944. },
  18945. // Convenience method to return ShapeGeometry
  18946. makeGeometry: function ( options ) {
  18947. return new ShapeGeometry( this, options );
  18948. },
  18949. getPointsHoles: function ( divisions ) {
  18950. var holesPts = [];
  18951. for ( var i = 0, l = this.holes.length; i < l; i ++ ) {
  18952. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  18953. }
  18954. return holesPts;
  18955. },
  18956. // Get points of shape and holes (keypoints based on segments parameter)
  18957. extractAllPoints: function ( divisions ) {
  18958. return {
  18959. shape: this.getPoints( divisions ),
  18960. holes: this.getPointsHoles( divisions )
  18961. };
  18962. },
  18963. extractPoints: function ( divisions ) {
  18964. return this.extractAllPoints( divisions );
  18965. }
  18966. } );
  18967. /**
  18968. * @author zz85 / http://www.lab4games.net/zz85/blog
  18969. * Creates free form 2d path using series of points, lines or curves.
  18970. *
  18971. **/
  18972. function Path( points ) {
  18973. CurvePath.call( this );
  18974. this.currentPoint = new Vector2();
  18975. if ( points ) {
  18976. this.fromPoints( points );
  18977. }
  18978. }
  18979. Path.prototype = PathPrototype;
  18980. PathPrototype.constructor = Path;
  18981. // minimal class for proxing functions to Path. Replaces old "extractSubpaths()"
  18982. function ShapePath() {
  18983. this.subPaths = [];
  18984. this.currentPath = null;
  18985. }
  18986. ShapePath.prototype = {
  18987. moveTo: function ( x, y ) {
  18988. this.currentPath = new Path();
  18989. this.subPaths.push(this.currentPath);
  18990. this.currentPath.moveTo( x, y );
  18991. },
  18992. lineTo: function ( x, y ) {
  18993. this.currentPath.lineTo( x, y );
  18994. },
  18995. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  18996. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  18997. },
  18998. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  18999. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  19000. },
  19001. splineThru: function ( pts ) {
  19002. this.currentPath.splineThru( pts );
  19003. },
  19004. toShapes: function ( isCCW, noHoles ) {
  19005. function toShapesNoHoles( inSubpaths ) {
  19006. var shapes = [];
  19007. for ( var i = 0, l = inSubpaths.length; i < l; i ++ ) {
  19008. var tmpPath = inSubpaths[ i ];
  19009. var tmpShape = new Shape();
  19010. tmpShape.curves = tmpPath.curves;
  19011. shapes.push( tmpShape );
  19012. }
  19013. return shapes;
  19014. }
  19015. function isPointInsidePolygon( inPt, inPolygon ) {
  19016. var polyLen = inPolygon.length;
  19017. // inPt on polygon contour => immediate success or
  19018. // toggling of inside/outside at every single! intersection point of an edge
  19019. // with the horizontal line through inPt, left of inPt
  19020. // not counting lowerY endpoints of edges and whole edges on that line
  19021. var inside = false;
  19022. for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  19023. var edgeLowPt = inPolygon[ p ];
  19024. var edgeHighPt = inPolygon[ q ];
  19025. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  19026. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  19027. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  19028. // not parallel
  19029. if ( edgeDy < 0 ) {
  19030. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  19031. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  19032. }
  19033. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  19034. if ( inPt.y === edgeLowPt.y ) {
  19035. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  19036. // continue; // no intersection or edgeLowPt => doesn't count !!!
  19037. } else {
  19038. var perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  19039. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  19040. if ( perpEdge < 0 ) continue;
  19041. inside = ! inside; // true intersection left of inPt
  19042. }
  19043. } else {
  19044. // parallel or collinear
  19045. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  19046. // edge lies on the same horizontal line as inPt
  19047. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  19048. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  19049. // continue;
  19050. }
  19051. }
  19052. return inside;
  19053. }
  19054. var isClockWise = exports.ShapeUtils.isClockWise;
  19055. var subPaths = this.subPaths;
  19056. if ( subPaths.length === 0 ) return [];
  19057. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  19058. var solid, tmpPath, tmpShape, shapes = [];
  19059. if ( subPaths.length === 1 ) {
  19060. tmpPath = subPaths[ 0 ];
  19061. tmpShape = new Shape();
  19062. tmpShape.curves = tmpPath.curves;
  19063. shapes.push( tmpShape );
  19064. return shapes;
  19065. }
  19066. var holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  19067. holesFirst = isCCW ? ! holesFirst : holesFirst;
  19068. // console.log("Holes first", holesFirst);
  19069. var betterShapeHoles = [];
  19070. var newShapes = [];
  19071. var newShapeHoles = [];
  19072. var mainIdx = 0;
  19073. var tmpPoints;
  19074. newShapes[ mainIdx ] = undefined;
  19075. newShapeHoles[ mainIdx ] = [];
  19076. for ( var i = 0, l = subPaths.length; i < l; i ++ ) {
  19077. tmpPath = subPaths[ i ];
  19078. tmpPoints = tmpPath.getPoints();
  19079. solid = isClockWise( tmpPoints );
  19080. solid = isCCW ? ! solid : solid;
  19081. if ( solid ) {
  19082. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  19083. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  19084. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  19085. if ( holesFirst ) mainIdx ++;
  19086. newShapeHoles[ mainIdx ] = [];
  19087. //console.log('cw', i);
  19088. } else {
  19089. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  19090. //console.log('ccw', i);
  19091. }
  19092. }
  19093. // only Holes? -> probably all Shapes with wrong orientation
  19094. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  19095. if ( newShapes.length > 1 ) {
  19096. var ambiguous = false;
  19097. var toChange = [];
  19098. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  19099. betterShapeHoles[ sIdx ] = [];
  19100. }
  19101. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  19102. var sho = newShapeHoles[ sIdx ];
  19103. for ( var hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  19104. var ho = sho[ hIdx ];
  19105. var hole_unassigned = true;
  19106. for ( var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  19107. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  19108. if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  19109. if ( hole_unassigned ) {
  19110. hole_unassigned = false;
  19111. betterShapeHoles[ s2Idx ].push( ho );
  19112. } else {
  19113. ambiguous = true;
  19114. }
  19115. }
  19116. }
  19117. if ( hole_unassigned ) {
  19118. betterShapeHoles[ sIdx ].push( ho );
  19119. }
  19120. }
  19121. }
  19122. // console.log("ambiguous: ", ambiguous);
  19123. if ( toChange.length > 0 ) {
  19124. // console.log("to change: ", toChange);
  19125. if ( ! ambiguous ) newShapeHoles = betterShapeHoles;
  19126. }
  19127. }
  19128. var tmpHoles;
  19129. for ( var i = 0, il = newShapes.length; i < il; i ++ ) {
  19130. tmpShape = newShapes[ i ].s;
  19131. shapes.push( tmpShape );
  19132. tmpHoles = newShapeHoles[ i ];
  19133. for ( var j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  19134. tmpShape.holes.push( tmpHoles[ j ].h );
  19135. }
  19136. }
  19137. //console.log("shape", shapes);
  19138. return shapes;
  19139. }
  19140. }
  19141. /**
  19142. * @author zz85 / http://www.lab4games.net/zz85/blog
  19143. * @author mrdoob / http://mrdoob.com/
  19144. */
  19145. function Font( data ) {
  19146. this.data = data;
  19147. }
  19148. Object.assign( Font.prototype, {
  19149. isFont: true,
  19150. generateShapes: function ( text, size, divisions ) {
  19151. function createPaths( text ) {
  19152. var chars = String( text ).split( '' );
  19153. var scale = size / data.resolution;
  19154. var offset = 0;
  19155. var paths = [];
  19156. for ( var i = 0; i < chars.length; i ++ ) {
  19157. var ret = createPath( chars[ i ], scale, offset );
  19158. offset += ret.offset;
  19159. paths.push( ret.path );
  19160. }
  19161. return paths;
  19162. }
  19163. function createPath( c, scale, offset ) {
  19164. var glyph = data.glyphs[ c ] || data.glyphs[ '?' ];
  19165. if ( ! glyph ) return;
  19166. var path = new ShapePath();
  19167. var pts = [], b2 = exports.ShapeUtils.b2, b3 = exports.ShapeUtils.b3;
  19168. var x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2, laste;
  19169. if ( glyph.o ) {
  19170. var outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  19171. for ( var i = 0, l = outline.length; i < l; ) {
  19172. var action = outline[ i ++ ];
  19173. switch ( action ) {
  19174. case 'm': // moveTo
  19175. x = outline[ i ++ ] * scale + offset;
  19176. y = outline[ i ++ ] * scale;
  19177. path.moveTo( x, y );
  19178. break;
  19179. case 'l': // lineTo
  19180. x = outline[ i ++ ] * scale + offset;
  19181. y = outline[ i ++ ] * scale;
  19182. path.lineTo( x, y );
  19183. break;
  19184. case 'q': // quadraticCurveTo
  19185. cpx = outline[ i ++ ] * scale + offset;
  19186. cpy = outline[ i ++ ] * scale;
  19187. cpx1 = outline[ i ++ ] * scale + offset;
  19188. cpy1 = outline[ i ++ ] * scale;
  19189. path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
  19190. laste = pts[ pts.length - 1 ];
  19191. if ( laste ) {
  19192. cpx0 = laste.x;
  19193. cpy0 = laste.y;
  19194. for ( var i2 = 1; i2 <= divisions; i2 ++ ) {
  19195. var t = i2 / divisions;
  19196. b2( t, cpx0, cpx1, cpx );
  19197. b2( t, cpy0, cpy1, cpy );
  19198. }
  19199. }
  19200. break;
  19201. case 'b': // bezierCurveTo
  19202. cpx = outline[ i ++ ] * scale + offset;
  19203. cpy = outline[ i ++ ] * scale;
  19204. cpx1 = outline[ i ++ ] * scale + offset;
  19205. cpy1 = outline[ i ++ ] * scale;
  19206. cpx2 = outline[ i ++ ] * scale + offset;
  19207. cpy2 = outline[ i ++ ] * scale;
  19208. path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
  19209. laste = pts[ pts.length - 1 ];
  19210. if ( laste ) {
  19211. cpx0 = laste.x;
  19212. cpy0 = laste.y;
  19213. for ( var i2 = 1; i2 <= divisions; i2 ++ ) {
  19214. var t = i2 / divisions;
  19215. b3( t, cpx0, cpx1, cpx2, cpx );
  19216. b3( t, cpy0, cpy1, cpy2, cpy );
  19217. }
  19218. }
  19219. break;
  19220. }
  19221. }
  19222. }
  19223. return { offset: glyph.ha * scale, path: path };
  19224. }
  19225. //
  19226. if ( size === undefined ) size = 100;
  19227. if ( divisions === undefined ) divisions = 4;
  19228. var data = this.data;
  19229. var paths = createPaths( text );
  19230. var shapes = [];
  19231. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  19232. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  19233. }
  19234. return shapes;
  19235. }
  19236. } );
  19237. /**
  19238. * @author mrdoob / http://mrdoob.com/
  19239. */
  19240. function FontLoader( manager ) {
  19241. this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager;
  19242. }
  19243. Object.assign( FontLoader.prototype, {
  19244. load: function ( url, onLoad, onProgress, onError ) {
  19245. var scope = this;
  19246. var loader = new XHRLoader( this.manager );
  19247. loader.load( url, function ( text ) {
  19248. var json;
  19249. try {
  19250. json = JSON.parse( text );
  19251. } catch ( e ) {
  19252. console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' );
  19253. json = JSON.parse( text.substring( 65, text.length - 2 ) );
  19254. }
  19255. var font = scope.parse( json );
  19256. if ( onLoad ) onLoad( font );
  19257. }, onProgress, onError );
  19258. },
  19259. parse: function ( json ) {
  19260. return new Font( json );
  19261. }
  19262. } );
  19263. var context;
  19264. function getAudioContext() {
  19265. if ( context === undefined ) {
  19266. context = new ( window.AudioContext || window.webkitAudioContext )();
  19267. }
  19268. return context;
  19269. }
  19270. /**
  19271. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  19272. */
  19273. function AudioLoader( manager ) {
  19274. this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager;
  19275. }
  19276. Object.assign( AudioLoader.prototype, {
  19277. load: function ( url, onLoad, onProgress, onError ) {
  19278. var loader = new XHRLoader( this.manager );
  19279. loader.setResponseType( 'arraybuffer' );
  19280. loader.load( url, function ( buffer ) {
  19281. var context = getAudioContext();
  19282. context.decodeAudioData( buffer, function ( audioBuffer ) {
  19283. onLoad( audioBuffer );
  19284. } );
  19285. }, onProgress, onError );
  19286. }
  19287. } );
  19288. /**
  19289. * @author mrdoob / http://mrdoob.com/
  19290. */
  19291. function StereoCamera() {
  19292. this.type = 'StereoCamera';
  19293. this.aspect = 1;
  19294. this.eyeSep = 0.064;
  19295. this.cameraL = new PerspectiveCamera();
  19296. this.cameraL.layers.enable( 1 );
  19297. this.cameraL.matrixAutoUpdate = false;
  19298. this.cameraR = new PerspectiveCamera();
  19299. this.cameraR.layers.enable( 2 );
  19300. this.cameraR.matrixAutoUpdate = false;
  19301. }
  19302. Object.assign( StereoCamera.prototype, {
  19303. update: ( function () {
  19304. var focus, fov, aspect, near, far;
  19305. var eyeRight = new Matrix4();
  19306. var eyeLeft = new Matrix4();
  19307. return function update( camera ) {
  19308. var needsUpdate = focus !== camera.focus || fov !== camera.fov ||
  19309. aspect !== camera.aspect * this.aspect || near !== camera.near ||
  19310. far !== camera.far;
  19311. if ( needsUpdate ) {
  19312. focus = camera.focus;
  19313. fov = camera.fov;
  19314. aspect = camera.aspect * this.aspect;
  19315. near = camera.near;
  19316. far = camera.far;
  19317. // Off-axis stereoscopic effect based on
  19318. // http://paulbourke.net/stereographics/stereorender/
  19319. var projectionMatrix = camera.projectionMatrix.clone();
  19320. var eyeSep = this.eyeSep / 2;
  19321. var eyeSepOnProjection = eyeSep * near / focus;
  19322. var ymax = near * Math.tan( exports.Math.DEG2RAD * fov * 0.5 );
  19323. var xmin, xmax;
  19324. // translate xOffset
  19325. eyeLeft.elements[ 12 ] = - eyeSep;
  19326. eyeRight.elements[ 12 ] = eyeSep;
  19327. // for left eye
  19328. xmin = - ymax * aspect + eyeSepOnProjection;
  19329. xmax = ymax * aspect + eyeSepOnProjection;
  19330. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  19331. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  19332. this.cameraL.projectionMatrix.copy( projectionMatrix );
  19333. // for right eye
  19334. xmin = - ymax * aspect - eyeSepOnProjection;
  19335. xmax = ymax * aspect - eyeSepOnProjection;
  19336. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  19337. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  19338. this.cameraR.projectionMatrix.copy( projectionMatrix );
  19339. }
  19340. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( eyeLeft );
  19341. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( eyeRight );
  19342. };
  19343. } )()
  19344. } );
  19345. /**
  19346. * Camera for rendering cube maps
  19347. * - renders scene into axis-aligned cube
  19348. *
  19349. * @author alteredq / http://alteredqualia.com/
  19350. */
  19351. function CubeCamera( near, far, cubeResolution ) {
  19352. Object3D.call( this );
  19353. this.type = 'CubeCamera';
  19354. var fov = 90, aspect = 1;
  19355. var cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  19356. cameraPX.up.set( 0, - 1, 0 );
  19357. cameraPX.lookAt( new Vector3( 1, 0, 0 ) );
  19358. this.add( cameraPX );
  19359. var cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  19360. cameraNX.up.set( 0, - 1, 0 );
  19361. cameraNX.lookAt( new Vector3( - 1, 0, 0 ) );
  19362. this.add( cameraNX );
  19363. var cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  19364. cameraPY.up.set( 0, 0, 1 );
  19365. cameraPY.lookAt( new Vector3( 0, 1, 0 ) );
  19366. this.add( cameraPY );
  19367. var cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  19368. cameraNY.up.set( 0, 0, - 1 );
  19369. cameraNY.lookAt( new Vector3( 0, - 1, 0 ) );
  19370. this.add( cameraNY );
  19371. var cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  19372. cameraPZ.up.set( 0, - 1, 0 );
  19373. cameraPZ.lookAt( new Vector3( 0, 0, 1 ) );
  19374. this.add( cameraPZ );
  19375. var cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  19376. cameraNZ.up.set( 0, - 1, 0 );
  19377. cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) );
  19378. this.add( cameraNZ );
  19379. var options = { format: RGBFormat, magFilter: LinearFilter, minFilter: LinearFilter };
  19380. this.renderTarget = new WebGLRenderTargetCube( cubeResolution, cubeResolution, options );
  19381. this.updateCubeMap = function ( renderer, scene ) {
  19382. if ( this.parent === null ) this.updateMatrixWorld();
  19383. var renderTarget = this.renderTarget;
  19384. var generateMipmaps = renderTarget.texture.generateMipmaps;
  19385. renderTarget.texture.generateMipmaps = false;
  19386. renderTarget.activeCubeFace = 0;
  19387. renderer.render( scene, cameraPX, renderTarget );
  19388. renderTarget.activeCubeFace = 1;
  19389. renderer.render( scene, cameraNX, renderTarget );
  19390. renderTarget.activeCubeFace = 2;
  19391. renderer.render( scene, cameraPY, renderTarget );
  19392. renderTarget.activeCubeFace = 3;
  19393. renderer.render( scene, cameraNY, renderTarget );
  19394. renderTarget.activeCubeFace = 4;
  19395. renderer.render( scene, cameraPZ, renderTarget );
  19396. renderTarget.texture.generateMipmaps = generateMipmaps;
  19397. renderTarget.activeCubeFace = 5;
  19398. renderer.render( scene, cameraNZ, renderTarget );
  19399. renderer.setRenderTarget( null );
  19400. };
  19401. }
  19402. CubeCamera.prototype = Object.create( Object3D.prototype );
  19403. CubeCamera.prototype.constructor = CubeCamera;
  19404. function AudioListener() {
  19405. Object3D.call( this );
  19406. this.type = 'AudioListener';
  19407. this.context = getAudioContext();
  19408. this.gain = this.context.createGain();
  19409. this.gain.connect( this.context.destination );
  19410. this.filter = null;
  19411. }
  19412. AudioListener.prototype = Object.assign( Object.create( Object3D.prototype ), {
  19413. constructor: AudioListener,
  19414. getInput: function () {
  19415. return this.gain;
  19416. },
  19417. removeFilter: function ( ) {
  19418. if ( this.filter !== null ) {
  19419. this.gain.disconnect( this.filter );
  19420. this.filter.disconnect( this.context.destination );
  19421. this.gain.connect( this.context.destination );
  19422. this.filter = null;
  19423. }
  19424. },
  19425. getFilter: function () {
  19426. return this.filter;
  19427. },
  19428. setFilter: function ( value ) {
  19429. if ( this.filter !== null ) {
  19430. this.gain.disconnect( this.filter );
  19431. this.filter.disconnect( this.context.destination );
  19432. } else {
  19433. this.gain.disconnect( this.context.destination );
  19434. }
  19435. this.filter = value;
  19436. this.gain.connect( this.filter );
  19437. this.filter.connect( this.context.destination );
  19438. },
  19439. getMasterVolume: function () {
  19440. return this.gain.gain.value;
  19441. },
  19442. setMasterVolume: function ( value ) {
  19443. this.gain.gain.value = value;
  19444. },
  19445. updateMatrixWorld: ( function () {
  19446. var position = new Vector3();
  19447. var quaternion = new Quaternion();
  19448. var scale = new Vector3();
  19449. var orientation = new Vector3();
  19450. return function updateMatrixWorld( force ) {
  19451. Object3D.prototype.updateMatrixWorld.call( this, force );
  19452. var listener = this.context.listener;
  19453. var up = this.up;
  19454. this.matrixWorld.decompose( position, quaternion, scale );
  19455. orientation.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  19456. listener.setPosition( position.x, position.y, position.z );
  19457. listener.setOrientation( orientation.x, orientation.y, orientation.z, up.x, up.y, up.z );
  19458. };
  19459. } )()
  19460. } );
  19461. function Audio( listener ) {
  19462. Object3D.call( this );
  19463. this.type = 'Audio';
  19464. this.context = listener.context;
  19465. this.source = this.context.createBufferSource();
  19466. this.source.onended = this.onEnded.bind( this );
  19467. this.gain = this.context.createGain();
  19468. this.gain.connect( listener.getInput() );
  19469. this.autoplay = false;
  19470. this.startTime = 0;
  19471. this.playbackRate = 1;
  19472. this.isPlaying = false;
  19473. this.hasPlaybackControl = true;
  19474. this.sourceType = 'empty';
  19475. this.filters = [];
  19476. }
  19477. Audio.prototype = Object.assign( Object.create( Object3D.prototype ), {
  19478. constructor: Audio,
  19479. getOutput: function () {
  19480. return this.gain;
  19481. },
  19482. setNodeSource: function ( audioNode ) {
  19483. this.hasPlaybackControl = false;
  19484. this.sourceType = 'audioNode';
  19485. this.source = audioNode;
  19486. this.connect();
  19487. return this;
  19488. },
  19489. setBuffer: function ( audioBuffer ) {
  19490. this.source.buffer = audioBuffer;
  19491. this.sourceType = 'buffer';
  19492. if ( this.autoplay ) this.play();
  19493. return this;
  19494. },
  19495. play: function () {
  19496. if ( this.isPlaying === true ) {
  19497. console.warn( 'THREE.Audio: Audio is already playing.' );
  19498. return;
  19499. }
  19500. if ( this.hasPlaybackControl === false ) {
  19501. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  19502. return;
  19503. }
  19504. var source = this.context.createBufferSource();
  19505. source.buffer = this.source.buffer;
  19506. source.loop = this.source.loop;
  19507. source.onended = this.source.onended;
  19508. source.start( 0, this.startTime );
  19509. source.playbackRate.value = this.playbackRate;
  19510. this.isPlaying = true;
  19511. this.source = source;
  19512. return this.connect();
  19513. },
  19514. pause: function () {
  19515. if ( this.hasPlaybackControl === false ) {
  19516. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  19517. return;
  19518. }
  19519. this.source.stop();
  19520. this.startTime = this.context.currentTime;
  19521. this.isPlaying = false;
  19522. return this;
  19523. },
  19524. stop: function () {
  19525. if ( this.hasPlaybackControl === false ) {
  19526. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  19527. return;
  19528. }
  19529. this.source.stop();
  19530. this.startTime = 0;
  19531. this.isPlaying = false;
  19532. return this;
  19533. },
  19534. connect: function () {
  19535. if ( this.filters.length > 0 ) {
  19536. this.source.connect( this.filters[ 0 ] );
  19537. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  19538. this.filters[ i - 1 ].connect( this.filters[ i ] );
  19539. }
  19540. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  19541. } else {
  19542. this.source.connect( this.getOutput() );
  19543. }
  19544. return this;
  19545. },
  19546. disconnect: function () {
  19547. if ( this.filters.length > 0 ) {
  19548. this.source.disconnect( this.filters[ 0 ] );
  19549. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  19550. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  19551. }
  19552. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  19553. } else {
  19554. this.source.disconnect( this.getOutput() );
  19555. }
  19556. return this;
  19557. },
  19558. getFilters: function () {
  19559. return this.filters;
  19560. },
  19561. setFilters: function ( value ) {
  19562. if ( ! value ) value = [];
  19563. if ( this.isPlaying === true ) {
  19564. this.disconnect();
  19565. this.filters = value;
  19566. this.connect();
  19567. } else {
  19568. this.filters = value;
  19569. }
  19570. return this;
  19571. },
  19572. getFilter: function () {
  19573. return this.getFilters()[ 0 ];
  19574. },
  19575. setFilter: function ( filter ) {
  19576. return this.setFilters( filter ? [ filter ] : [] );
  19577. },
  19578. setPlaybackRate: function ( value ) {
  19579. if ( this.hasPlaybackControl === false ) {
  19580. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  19581. return;
  19582. }
  19583. this.playbackRate = value;
  19584. if ( this.isPlaying === true ) {
  19585. this.source.playbackRate.value = this.playbackRate;
  19586. }
  19587. return this;
  19588. },
  19589. getPlaybackRate: function () {
  19590. return this.playbackRate;
  19591. },
  19592. onEnded: function () {
  19593. this.isPlaying = false;
  19594. },
  19595. getLoop: function () {
  19596. if ( this.hasPlaybackControl === false ) {
  19597. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  19598. return false;
  19599. }
  19600. return this.source.loop;
  19601. },
  19602. setLoop: function ( value ) {
  19603. if ( this.hasPlaybackControl === false ) {
  19604. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  19605. return;
  19606. }
  19607. this.source.loop = value;
  19608. },
  19609. getVolume: function () {
  19610. return this.gain.gain.value;
  19611. },
  19612. setVolume: function ( value ) {
  19613. this.gain.gain.value = value;
  19614. return this;
  19615. }
  19616. } );
  19617. function PositionalAudio( listener ) {
  19618. Audio.call( this, listener );
  19619. this.panner = this.context.createPanner();
  19620. this.panner.connect( this.gain );
  19621. }
  19622. PositionalAudio.prototype = Object.assign( Object.create( Audio.prototype ), {
  19623. constructor: PositionalAudio,
  19624. getOutput: function () {
  19625. return this.panner;
  19626. },
  19627. getRefDistance: function () {
  19628. return this.panner.refDistance;
  19629. },
  19630. setRefDistance: function ( value ) {
  19631. this.panner.refDistance = value;
  19632. },
  19633. getRolloffFactor: function () {
  19634. return this.panner.rolloffFactor;
  19635. },
  19636. setRolloffFactor: function ( value ) {
  19637. this.panner.rolloffFactor = value;
  19638. },
  19639. getDistanceModel: function () {
  19640. return this.panner.distanceModel;
  19641. },
  19642. setDistanceModel: function ( value ) {
  19643. this.panner.distanceModel = value;
  19644. },
  19645. getMaxDistance: function () {
  19646. return this.panner.maxDistance;
  19647. },
  19648. setMaxDistance: function ( value ) {
  19649. this.panner.maxDistance = value;
  19650. },
  19651. updateMatrixWorld: ( function () {
  19652. var position = new Vector3();
  19653. return function updateMatrixWorld( force ) {
  19654. Object3D.prototype.updateMatrixWorld.call( this, force );
  19655. position.setFromMatrixPosition( this.matrixWorld );
  19656. this.panner.setPosition( position.x, position.y, position.z );
  19657. };
  19658. } )()
  19659. } );
  19660. /**
  19661. * @author mrdoob / http://mrdoob.com/
  19662. */
  19663. function AudioAnalyser( audio, fftSize ) {
  19664. this.analyser = audio.context.createAnalyser();
  19665. this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048;
  19666. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  19667. audio.getOutput().connect( this.analyser );
  19668. }
  19669. Object.assign( AudioAnalyser.prototype, {
  19670. getFrequencyData: function () {
  19671. this.analyser.getByteFrequencyData( this.data );
  19672. return this.data;
  19673. },
  19674. getAverageFrequency: function () {
  19675. var value = 0, data = this.getFrequencyData();
  19676. for ( var i = 0; i < data.length; i ++ ) {
  19677. value += data[ i ];
  19678. }
  19679. return value / data.length;
  19680. }
  19681. } );
  19682. /**
  19683. *
  19684. * Buffered scene graph property that allows weighted accumulation.
  19685. *
  19686. *
  19687. * @author Ben Houston / http://clara.io/
  19688. * @author David Sarno / http://lighthaus.us/
  19689. * @author tschw
  19690. */
  19691. function PropertyMixer( binding, typeName, valueSize ) {
  19692. this.binding = binding;
  19693. this.valueSize = valueSize;
  19694. var bufferType = Float64Array,
  19695. mixFunction;
  19696. switch ( typeName ) {
  19697. case 'quaternion': mixFunction = this._slerp; break;
  19698. case 'string':
  19699. case 'bool':
  19700. bufferType = Array, mixFunction = this._select; break;
  19701. default: mixFunction = this._lerp;
  19702. }
  19703. this.buffer = new bufferType( valueSize * 4 );
  19704. // layout: [ incoming | accu0 | accu1 | orig ]
  19705. //
  19706. // interpolators can use .buffer as their .result
  19707. // the data then goes to 'incoming'
  19708. //
  19709. // 'accu0' and 'accu1' are used frame-interleaved for
  19710. // the cumulative result and are compared to detect
  19711. // changes
  19712. //
  19713. // 'orig' stores the original state of the property
  19714. this._mixBufferRegion = mixFunction;
  19715. this.cumulativeWeight = 0;
  19716. this.useCount = 0;
  19717. this.referenceCount = 0;
  19718. }
  19719. PropertyMixer.prototype = {
  19720. constructor: PropertyMixer,
  19721. // accumulate data in the 'incoming' region into 'accu<i>'
  19722. accumulate: function( accuIndex, weight ) {
  19723. // note: happily accumulating nothing when weight = 0, the caller knows
  19724. // the weight and shouldn't have made the call in the first place
  19725. var buffer = this.buffer,
  19726. stride = this.valueSize,
  19727. offset = accuIndex * stride + stride,
  19728. currentWeight = this.cumulativeWeight;
  19729. if ( currentWeight === 0 ) {
  19730. // accuN := incoming * weight
  19731. for ( var i = 0; i !== stride; ++ i ) {
  19732. buffer[ offset + i ] = buffer[ i ];
  19733. }
  19734. currentWeight = weight;
  19735. } else {
  19736. // accuN := accuN + incoming * weight
  19737. currentWeight += weight;
  19738. var mix = weight / currentWeight;
  19739. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  19740. }
  19741. this.cumulativeWeight = currentWeight;
  19742. },
  19743. // apply the state of 'accu<i>' to the binding when accus differ
  19744. apply: function( accuIndex ) {
  19745. var stride = this.valueSize,
  19746. buffer = this.buffer,
  19747. offset = accuIndex * stride + stride,
  19748. weight = this.cumulativeWeight,
  19749. binding = this.binding;
  19750. this.cumulativeWeight = 0;
  19751. if ( weight < 1 ) {
  19752. // accuN := accuN + original * ( 1 - cumulativeWeight )
  19753. var originalValueOffset = stride * 3;
  19754. this._mixBufferRegion(
  19755. buffer, offset, originalValueOffset, 1 - weight, stride );
  19756. }
  19757. for ( var i = stride, e = stride + stride; i !== e; ++ i ) {
  19758. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  19759. // value has changed -> update scene graph
  19760. binding.setValue( buffer, offset );
  19761. break;
  19762. }
  19763. }
  19764. },
  19765. // remember the state of the bound property and copy it to both accus
  19766. saveOriginalState: function() {
  19767. var binding = this.binding;
  19768. var buffer = this.buffer,
  19769. stride = this.valueSize,
  19770. originalValueOffset = stride * 3;
  19771. binding.getValue( buffer, originalValueOffset );
  19772. // accu[0..1] := orig -- initially detect changes against the original
  19773. for ( var i = stride, e = originalValueOffset; i !== e; ++ i ) {
  19774. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  19775. }
  19776. this.cumulativeWeight = 0;
  19777. },
  19778. // apply the state previously taken via 'saveOriginalState' to the binding
  19779. restoreOriginalState: function() {
  19780. var originalValueOffset = this.valueSize * 3;
  19781. this.binding.setValue( this.buffer, originalValueOffset );
  19782. },
  19783. // mix functions
  19784. _select: function( buffer, dstOffset, srcOffset, t, stride ) {
  19785. if ( t >= 0.5 ) {
  19786. for ( var i = 0; i !== stride; ++ i ) {
  19787. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  19788. }
  19789. }
  19790. },
  19791. _slerp: function( buffer, dstOffset, srcOffset, t, stride ) {
  19792. Quaternion.slerpFlat( buffer, dstOffset,
  19793. buffer, dstOffset, buffer, srcOffset, t );
  19794. },
  19795. _lerp: function( buffer, dstOffset, srcOffset, t, stride ) {
  19796. var s = 1 - t;
  19797. for ( var i = 0; i !== stride; ++ i ) {
  19798. var j = dstOffset + i;
  19799. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  19800. }
  19801. }
  19802. };
  19803. /**
  19804. *
  19805. * A reference to a real property in the scene graph.
  19806. *
  19807. *
  19808. * @author Ben Houston / http://clara.io/
  19809. * @author David Sarno / http://lighthaus.us/
  19810. * @author tschw
  19811. */
  19812. function PropertyBinding( rootNode, path, parsedPath ) {
  19813. this.path = path;
  19814. this.parsedPath = parsedPath ||
  19815. PropertyBinding.parseTrackName( path );
  19816. this.node = PropertyBinding.findNode(
  19817. rootNode, this.parsedPath.nodeName ) || rootNode;
  19818. this.rootNode = rootNode;
  19819. }
  19820. PropertyBinding.prototype = {
  19821. constructor: PropertyBinding,
  19822. getValue: function getValue_unbound( targetArray, offset ) {
  19823. this.bind();
  19824. this.getValue( targetArray, offset );
  19825. // Note: This class uses a State pattern on a per-method basis:
  19826. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  19827. // prototype version of these methods with one that represents
  19828. // the bound state. When the property is not found, the methods
  19829. // become no-ops.
  19830. },
  19831. setValue: function getValue_unbound( sourceArray, offset ) {
  19832. this.bind();
  19833. this.setValue( sourceArray, offset );
  19834. },
  19835. // create getter / setter pair for a property in the scene graph
  19836. bind: function() {
  19837. var targetObject = this.node,
  19838. parsedPath = this.parsedPath,
  19839. objectName = parsedPath.objectName,
  19840. propertyName = parsedPath.propertyName,
  19841. propertyIndex = parsedPath.propertyIndex;
  19842. if ( ! targetObject ) {
  19843. targetObject = PropertyBinding.findNode(
  19844. this.rootNode, parsedPath.nodeName ) || this.rootNode;
  19845. this.node = targetObject;
  19846. }
  19847. // set fail state so we can just 'return' on error
  19848. this.getValue = this._getValue_unavailable;
  19849. this.setValue = this._setValue_unavailable;
  19850. // ensure there is a value node
  19851. if ( ! targetObject ) {
  19852. console.error( " trying to update node for track: " + this.path + " but it wasn't found." );
  19853. return;
  19854. }
  19855. if ( objectName ) {
  19856. var objectIndex = parsedPath.objectIndex;
  19857. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  19858. switch ( objectName ) {
  19859. case 'materials':
  19860. if ( ! targetObject.material ) {
  19861. console.error( ' can not bind to material as node does not have a material', this );
  19862. return;
  19863. }
  19864. if ( ! targetObject.material.materials ) {
  19865. console.error( ' can not bind to material.materials as node.material does not have a materials array', this );
  19866. return;
  19867. }
  19868. targetObject = targetObject.material.materials;
  19869. break;
  19870. case 'bones':
  19871. if ( ! targetObject.skeleton ) {
  19872. console.error( ' can not bind to bones as node does not have a skeleton', this );
  19873. return;
  19874. }
  19875. // potential future optimization: skip this if propertyIndex is already an integer
  19876. // and convert the integer string to a true integer.
  19877. targetObject = targetObject.skeleton.bones;
  19878. // support resolving morphTarget names into indices.
  19879. for ( var i = 0; i < targetObject.length; i ++ ) {
  19880. if ( targetObject[ i ].name === objectIndex ) {
  19881. objectIndex = i;
  19882. break;
  19883. }
  19884. }
  19885. break;
  19886. default:
  19887. if ( targetObject[ objectName ] === undefined ) {
  19888. console.error( ' can not bind to objectName of node, undefined', this );
  19889. return;
  19890. }
  19891. targetObject = targetObject[ objectName ];
  19892. }
  19893. if ( objectIndex !== undefined ) {
  19894. if ( targetObject[ objectIndex ] === undefined ) {
  19895. console.error( " trying to bind to objectIndex of objectName, but is undefined:", this, targetObject );
  19896. return;
  19897. }
  19898. targetObject = targetObject[ objectIndex ];
  19899. }
  19900. }
  19901. // resolve property
  19902. var nodeProperty = targetObject[ propertyName ];
  19903. if ( nodeProperty === undefined ) {
  19904. var nodeName = parsedPath.nodeName;
  19905. console.error( " trying to update property for track: " + nodeName +
  19906. '.' + propertyName + " but it wasn't found.", targetObject );
  19907. return;
  19908. }
  19909. // determine versioning scheme
  19910. var versioning = this.Versioning.None;
  19911. if ( targetObject.needsUpdate !== undefined ) { // material
  19912. versioning = this.Versioning.NeedsUpdate;
  19913. this.targetObject = targetObject;
  19914. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  19915. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  19916. this.targetObject = targetObject;
  19917. }
  19918. // determine how the property gets bound
  19919. var bindingType = this.BindingType.Direct;
  19920. if ( propertyIndex !== undefined ) {
  19921. // access a sub element of the property array (only primitives are supported right now)
  19922. if ( propertyName === "morphTargetInfluences" ) {
  19923. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  19924. // support resolving morphTarget names into indices.
  19925. if ( ! targetObject.geometry ) {
  19926. console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry', this );
  19927. return;
  19928. }
  19929. if ( ! targetObject.geometry.morphTargets ) {
  19930. console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry.morphTargets', this );
  19931. return;
  19932. }
  19933. for ( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) {
  19934. if ( targetObject.geometry.morphTargets[ i ].name === propertyIndex ) {
  19935. propertyIndex = i;
  19936. break;
  19937. }
  19938. }
  19939. }
  19940. bindingType = this.BindingType.ArrayElement;
  19941. this.resolvedProperty = nodeProperty;
  19942. this.propertyIndex = propertyIndex;
  19943. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  19944. // must use copy for Object3D.Euler/Quaternion
  19945. bindingType = this.BindingType.HasFromToArray;
  19946. this.resolvedProperty = nodeProperty;
  19947. } else if ( nodeProperty.length !== undefined ) {
  19948. bindingType = this.BindingType.EntireArray;
  19949. this.resolvedProperty = nodeProperty;
  19950. } else {
  19951. this.propertyName = propertyName;
  19952. }
  19953. // select getter / setter
  19954. this.getValue = this.GetterByBindingType[ bindingType ];
  19955. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  19956. },
  19957. unbind: function() {
  19958. this.node = null;
  19959. // back to the prototype version of getValue / setValue
  19960. // note: avoiding to mutate the shape of 'this' via 'delete'
  19961. this.getValue = this._getValue_unbound;
  19962. this.setValue = this._setValue_unbound;
  19963. }
  19964. };
  19965. Object.assign( PropertyBinding.prototype, { // prototype, continued
  19966. // these are used to "bind" a nonexistent property
  19967. _getValue_unavailable: function() {},
  19968. _setValue_unavailable: function() {},
  19969. // initial state of these methods that calls 'bind'
  19970. _getValue_unbound: PropertyBinding.prototype.getValue,
  19971. _setValue_unbound: PropertyBinding.prototype.setValue,
  19972. BindingType: {
  19973. Direct: 0,
  19974. EntireArray: 1,
  19975. ArrayElement: 2,
  19976. HasFromToArray: 3
  19977. },
  19978. Versioning: {
  19979. None: 0,
  19980. NeedsUpdate: 1,
  19981. MatrixWorldNeedsUpdate: 2
  19982. },
  19983. GetterByBindingType: [
  19984. function getValue_direct( buffer, offset ) {
  19985. buffer[ offset ] = this.node[ this.propertyName ];
  19986. },
  19987. function getValue_array( buffer, offset ) {
  19988. var source = this.resolvedProperty;
  19989. for ( var i = 0, n = source.length; i !== n; ++ i ) {
  19990. buffer[ offset ++ ] = source[ i ];
  19991. }
  19992. },
  19993. function getValue_arrayElement( buffer, offset ) {
  19994. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  19995. },
  19996. function getValue_toArray( buffer, offset ) {
  19997. this.resolvedProperty.toArray( buffer, offset );
  19998. }
  19999. ],
  20000. SetterByBindingTypeAndVersioning: [
  20001. [
  20002. // Direct
  20003. function setValue_direct( buffer, offset ) {
  20004. this.node[ this.propertyName ] = buffer[ offset ];
  20005. },
  20006. function setValue_direct_setNeedsUpdate( buffer, offset ) {
  20007. this.node[ this.propertyName ] = buffer[ offset ];
  20008. this.targetObject.needsUpdate = true;
  20009. },
  20010. function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  20011. this.node[ this.propertyName ] = buffer[ offset ];
  20012. this.targetObject.matrixWorldNeedsUpdate = true;
  20013. }
  20014. ], [
  20015. // EntireArray
  20016. function setValue_array( buffer, offset ) {
  20017. var dest = this.resolvedProperty;
  20018. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  20019. dest[ i ] = buffer[ offset ++ ];
  20020. }
  20021. },
  20022. function setValue_array_setNeedsUpdate( buffer, offset ) {
  20023. var dest = this.resolvedProperty;
  20024. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  20025. dest[ i ] = buffer[ offset ++ ];
  20026. }
  20027. this.targetObject.needsUpdate = true;
  20028. },
  20029. function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  20030. var dest = this.resolvedProperty;
  20031. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  20032. dest[ i ] = buffer[ offset ++ ];
  20033. }
  20034. this.targetObject.matrixWorldNeedsUpdate = true;
  20035. }
  20036. ], [
  20037. // ArrayElement
  20038. function setValue_arrayElement( buffer, offset ) {
  20039. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  20040. },
  20041. function setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  20042. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  20043. this.targetObject.needsUpdate = true;
  20044. },
  20045. function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  20046. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  20047. this.targetObject.matrixWorldNeedsUpdate = true;
  20048. }
  20049. ], [
  20050. // HasToFromArray
  20051. function setValue_fromArray( buffer, offset ) {
  20052. this.resolvedProperty.fromArray( buffer, offset );
  20053. },
  20054. function setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  20055. this.resolvedProperty.fromArray( buffer, offset );
  20056. this.targetObject.needsUpdate = true;
  20057. },
  20058. function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  20059. this.resolvedProperty.fromArray( buffer, offset );
  20060. this.targetObject.matrixWorldNeedsUpdate = true;
  20061. }
  20062. ]
  20063. ]
  20064. } );
  20065. PropertyBinding.Composite =
  20066. function( targetGroup, path, optionalParsedPath ) {
  20067. var parsedPath = optionalParsedPath ||
  20068. PropertyBinding.parseTrackName( path );
  20069. this._targetGroup = targetGroup;
  20070. this._bindings = targetGroup.subscribe_( path, parsedPath );
  20071. };
  20072. PropertyBinding.Composite.prototype = {
  20073. constructor: PropertyBinding.Composite,
  20074. getValue: function( array, offset ) {
  20075. this.bind(); // bind all binding
  20076. var firstValidIndex = this._targetGroup.nCachedObjects_,
  20077. binding = this._bindings[ firstValidIndex ];
  20078. // and only call .getValue on the first
  20079. if ( binding !== undefined ) binding.getValue( array, offset );
  20080. },
  20081. setValue: function( array, offset ) {
  20082. var bindings = this._bindings;
  20083. for ( var i = this._targetGroup.nCachedObjects_,
  20084. n = bindings.length; i !== n; ++ i ) {
  20085. bindings[ i ].setValue( array, offset );
  20086. }
  20087. },
  20088. bind: function() {
  20089. var bindings = this._bindings;
  20090. for ( var i = this._targetGroup.nCachedObjects_,
  20091. n = bindings.length; i !== n; ++ i ) {
  20092. bindings[ i ].bind();
  20093. }
  20094. },
  20095. unbind: function() {
  20096. var bindings = this._bindings;
  20097. for ( var i = this._targetGroup.nCachedObjects_,
  20098. n = bindings.length; i !== n; ++ i ) {
  20099. bindings[ i ].unbind();
  20100. }
  20101. }
  20102. };
  20103. PropertyBinding.create = function( root, path, parsedPath ) {
  20104. if ( ! ( (root && root.isAnimationObjectGroup) ) ) {
  20105. return new PropertyBinding( root, path, parsedPath );
  20106. } else {
  20107. return new PropertyBinding.Composite( root, path, parsedPath );
  20108. }
  20109. };
  20110. PropertyBinding.parseTrackName = function( trackName ) {
  20111. // matches strings in the form of:
  20112. // nodeName.property
  20113. // nodeName.property[accessor]
  20114. // nodeName.material.property[accessor]
  20115. // uuid.property[accessor]
  20116. // uuid.objectName[objectIndex].propertyName[propertyIndex]
  20117. // parentName/nodeName.property
  20118. // parentName/parentName/nodeName.property[index]
  20119. // .bone[Armature.DEF_cog].position
  20120. // created and tested via https://regex101.com/#javascript
  20121. var re = /^((?:\w+\/)*)(\w+)?(?:\.(\w+)(?:\[(.+)\])?)?\.(\w+)(?:\[(.+)\])?$/;
  20122. var matches = re.exec( trackName );
  20123. if ( ! matches ) {
  20124. throw new Error( "cannot parse trackName at all: " + trackName );
  20125. }
  20126. var results = {
  20127. // directoryName: matches[ 1 ], // (tschw) currently unused
  20128. nodeName: matches[ 2 ], // allowed to be null, specified root node.
  20129. objectName: matches[ 3 ],
  20130. objectIndex: matches[ 4 ],
  20131. propertyName: matches[ 5 ],
  20132. propertyIndex: matches[ 6 ] // allowed to be null, specifies that the whole property is set.
  20133. };
  20134. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  20135. throw new Error( "can not parse propertyName from trackName: " + trackName );
  20136. }
  20137. return results;
  20138. };
  20139. PropertyBinding.findNode = function( root, nodeName ) {
  20140. if ( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  20141. return root;
  20142. }
  20143. // search into skeleton bones.
  20144. if ( root.skeleton ) {
  20145. var searchSkeleton = function( skeleton ) {
  20146. for( var i = 0; i < skeleton.bones.length; i ++ ) {
  20147. var bone = skeleton.bones[ i ];
  20148. if ( bone.name === nodeName ) {
  20149. return bone;
  20150. }
  20151. }
  20152. return null;
  20153. };
  20154. var bone = searchSkeleton( root.skeleton );
  20155. if ( bone ) {
  20156. return bone;
  20157. }
  20158. }
  20159. // search into node subtree.
  20160. if ( root.children ) {
  20161. var searchNodeSubtree = function( children ) {
  20162. for( var i = 0; i < children.length; i ++ ) {
  20163. var childNode = children[ i ];
  20164. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  20165. return childNode;
  20166. }
  20167. var result = searchNodeSubtree( childNode.children );
  20168. if ( result ) return result;
  20169. }
  20170. return null;
  20171. };
  20172. var subTreeNode = searchNodeSubtree( root.children );
  20173. if ( subTreeNode ) {
  20174. return subTreeNode;
  20175. }
  20176. }
  20177. return null;
  20178. };
  20179. /**
  20180. *
  20181. * A group of objects that receives a shared animation state.
  20182. *
  20183. * Usage:
  20184. *
  20185. * - Add objects you would otherwise pass as 'root' to the
  20186. * constructor or the .clipAction method of AnimationMixer.
  20187. *
  20188. * - Instead pass this object as 'root'.
  20189. *
  20190. * - You can also add and remove objects later when the mixer
  20191. * is running.
  20192. *
  20193. * Note:
  20194. *
  20195. * Objects of this class appear as one object to the mixer,
  20196. * so cache control of the individual objects must be done
  20197. * on the group.
  20198. *
  20199. * Limitation:
  20200. *
  20201. * - The animated properties must be compatible among the
  20202. * all objects in the group.
  20203. *
  20204. * - A single property can either be controlled through a
  20205. * target group or directly, but not both.
  20206. *
  20207. * @author tschw
  20208. */
  20209. function AnimationObjectGroup( var_args ) {
  20210. this.uuid = exports.Math.generateUUID();
  20211. // cached objects followed by the active ones
  20212. this._objects = Array.prototype.slice.call( arguments );
  20213. this.nCachedObjects_ = 0; // threshold
  20214. // note: read by PropertyBinding.Composite
  20215. var indices = {};
  20216. this._indicesByUUID = indices; // for bookkeeping
  20217. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  20218. indices[ arguments[ i ].uuid ] = i;
  20219. }
  20220. this._paths = []; // inside: string
  20221. this._parsedPaths = []; // inside: { we don't care, here }
  20222. this._bindings = []; // inside: Array< PropertyBinding >
  20223. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  20224. var scope = this;
  20225. this.stats = {
  20226. objects: {
  20227. get total() { return scope._objects.length; },
  20228. get inUse() { return this.total - scope.nCachedObjects_; }
  20229. },
  20230. get bindingsPerObject() { return scope._bindings.length; }
  20231. };
  20232. }
  20233. AnimationObjectGroup.prototype = {
  20234. constructor: AnimationObjectGroup,
  20235. isAnimationObjectGroup: true,
  20236. add: function( var_args ) {
  20237. var objects = this._objects,
  20238. nObjects = objects.length,
  20239. nCachedObjects = this.nCachedObjects_,
  20240. indicesByUUID = this._indicesByUUID,
  20241. paths = this._paths,
  20242. parsedPaths = this._parsedPaths,
  20243. bindings = this._bindings,
  20244. nBindings = bindings.length;
  20245. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  20246. var object = arguments[ i ],
  20247. uuid = object.uuid,
  20248. index = indicesByUUID[ uuid ];
  20249. if ( index === undefined ) {
  20250. // unknown object -> add it to the ACTIVE region
  20251. index = nObjects ++;
  20252. indicesByUUID[ uuid ] = index;
  20253. objects.push( object );
  20254. // accounting is done, now do the same for all bindings
  20255. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  20256. bindings[ j ].push(
  20257. new PropertyBinding(
  20258. object, paths[ j ], parsedPaths[ j ] ) );
  20259. }
  20260. } else if ( index < nCachedObjects ) {
  20261. var knownObject = objects[ index ];
  20262. // move existing object to the ACTIVE region
  20263. var firstActiveIndex = -- nCachedObjects,
  20264. lastCachedObject = objects[ firstActiveIndex ];
  20265. indicesByUUID[ lastCachedObject.uuid ] = index;
  20266. objects[ index ] = lastCachedObject;
  20267. indicesByUUID[ uuid ] = firstActiveIndex;
  20268. objects[ firstActiveIndex ] = object;
  20269. // accounting is done, now do the same for all bindings
  20270. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  20271. var bindingsForPath = bindings[ j ],
  20272. lastCached = bindingsForPath[ firstActiveIndex ],
  20273. binding = bindingsForPath[ index ];
  20274. bindingsForPath[ index ] = lastCached;
  20275. if ( binding === undefined ) {
  20276. // since we do not bother to create new bindings
  20277. // for objects that are cached, the binding may
  20278. // or may not exist
  20279. binding = new PropertyBinding(
  20280. object, paths[ j ], parsedPaths[ j ] );
  20281. }
  20282. bindingsForPath[ firstActiveIndex ] = binding;
  20283. }
  20284. } else if ( objects[ index ] !== knownObject) {
  20285. console.error( "Different objects with the same UUID " +
  20286. "detected. Clean the caches or recreate your " +
  20287. "infrastructure when reloading scenes..." );
  20288. } // else the object is already where we want it to be
  20289. } // for arguments
  20290. this.nCachedObjects_ = nCachedObjects;
  20291. },
  20292. remove: function( var_args ) {
  20293. var objects = this._objects,
  20294. nCachedObjects = this.nCachedObjects_,
  20295. indicesByUUID = this._indicesByUUID,
  20296. bindings = this._bindings,
  20297. nBindings = bindings.length;
  20298. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  20299. var object = arguments[ i ],
  20300. uuid = object.uuid,
  20301. index = indicesByUUID[ uuid ];
  20302. if ( index !== undefined && index >= nCachedObjects ) {
  20303. // move existing object into the CACHED region
  20304. var lastCachedIndex = nCachedObjects ++,
  20305. firstActiveObject = objects[ lastCachedIndex ];
  20306. indicesByUUID[ firstActiveObject.uuid ] = index;
  20307. objects[ index ] = firstActiveObject;
  20308. indicesByUUID[ uuid ] = lastCachedIndex;
  20309. objects[ lastCachedIndex ] = object;
  20310. // accounting is done, now do the same for all bindings
  20311. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  20312. var bindingsForPath = bindings[ j ],
  20313. firstActive = bindingsForPath[ lastCachedIndex ],
  20314. binding = bindingsForPath[ index ];
  20315. bindingsForPath[ index ] = firstActive;
  20316. bindingsForPath[ lastCachedIndex ] = binding;
  20317. }
  20318. }
  20319. } // for arguments
  20320. this.nCachedObjects_ = nCachedObjects;
  20321. },
  20322. // remove & forget
  20323. uncache: function( var_args ) {
  20324. var objects = this._objects,
  20325. nObjects = objects.length,
  20326. nCachedObjects = this.nCachedObjects_,
  20327. indicesByUUID = this._indicesByUUID,
  20328. bindings = this._bindings,
  20329. nBindings = bindings.length;
  20330. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  20331. var object = arguments[ i ],
  20332. uuid = object.uuid,
  20333. index = indicesByUUID[ uuid ];
  20334. if ( index !== undefined ) {
  20335. delete indicesByUUID[ uuid ];
  20336. if ( index < nCachedObjects ) {
  20337. // object is cached, shrink the CACHED region
  20338. var firstActiveIndex = -- nCachedObjects,
  20339. lastCachedObject = objects[ firstActiveIndex ],
  20340. lastIndex = -- nObjects,
  20341. lastObject = objects[ lastIndex ];
  20342. // last cached object takes this object's place
  20343. indicesByUUID[ lastCachedObject.uuid ] = index;
  20344. objects[ index ] = lastCachedObject;
  20345. // last object goes to the activated slot and pop
  20346. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  20347. objects[ firstActiveIndex ] = lastObject;
  20348. objects.pop();
  20349. // accounting is done, now do the same for all bindings
  20350. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  20351. var bindingsForPath = bindings[ j ],
  20352. lastCached = bindingsForPath[ firstActiveIndex ],
  20353. last = bindingsForPath[ lastIndex ];
  20354. bindingsForPath[ index ] = lastCached;
  20355. bindingsForPath[ firstActiveIndex ] = last;
  20356. bindingsForPath.pop();
  20357. }
  20358. } else {
  20359. // object is active, just swap with the last and pop
  20360. var lastIndex = -- nObjects,
  20361. lastObject = objects[ lastIndex ];
  20362. indicesByUUID[ lastObject.uuid ] = index;
  20363. objects[ index ] = lastObject;
  20364. objects.pop();
  20365. // accounting is done, now do the same for all bindings
  20366. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  20367. var bindingsForPath = bindings[ j ];
  20368. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  20369. bindingsForPath.pop();
  20370. }
  20371. } // cached or active
  20372. } // if object is known
  20373. } // for arguments
  20374. this.nCachedObjects_ = nCachedObjects;
  20375. },
  20376. // Internal interface used by befriended PropertyBinding.Composite:
  20377. subscribe_: function( path, parsedPath ) {
  20378. // returns an array of bindings for the given path that is changed
  20379. // according to the contained objects in the group
  20380. var indicesByPath = this._bindingsIndicesByPath,
  20381. index = indicesByPath[ path ],
  20382. bindings = this._bindings;
  20383. if ( index !== undefined ) return bindings[ index ];
  20384. var paths = this._paths,
  20385. parsedPaths = this._parsedPaths,
  20386. objects = this._objects,
  20387. nObjects = objects.length,
  20388. nCachedObjects = this.nCachedObjects_,
  20389. bindingsForPath = new Array( nObjects );
  20390. index = bindings.length;
  20391. indicesByPath[ path ] = index;
  20392. paths.push( path );
  20393. parsedPaths.push( parsedPath );
  20394. bindings.push( bindingsForPath );
  20395. for ( var i = nCachedObjects,
  20396. n = objects.length; i !== n; ++ i ) {
  20397. var object = objects[ i ];
  20398. bindingsForPath[ i ] =
  20399. new PropertyBinding( object, path, parsedPath );
  20400. }
  20401. return bindingsForPath;
  20402. },
  20403. unsubscribe_: function( path ) {
  20404. // tells the group to forget about a property path and no longer
  20405. // update the array previously obtained with 'subscribe_'
  20406. var indicesByPath = this._bindingsIndicesByPath,
  20407. index = indicesByPath[ path ];
  20408. if ( index !== undefined ) {
  20409. var paths = this._paths,
  20410. parsedPaths = this._parsedPaths,
  20411. bindings = this._bindings,
  20412. lastBindingsIndex = bindings.length - 1,
  20413. lastBindings = bindings[ lastBindingsIndex ],
  20414. lastBindingsPath = path[ lastBindingsIndex ];
  20415. indicesByPath[ lastBindingsPath ] = index;
  20416. bindings[ index ] = lastBindings;
  20417. bindings.pop();
  20418. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  20419. parsedPaths.pop();
  20420. paths[ index ] = paths[ lastBindingsIndex ];
  20421. paths.pop();
  20422. }
  20423. }
  20424. };
  20425. /**
  20426. *
  20427. * Action provided by AnimationMixer for scheduling clip playback on specific
  20428. * objects.
  20429. *
  20430. * @author Ben Houston / http://clara.io/
  20431. * @author David Sarno / http://lighthaus.us/
  20432. * @author tschw
  20433. *
  20434. */
  20435. function AnimationAction() {
  20436. throw new Error( "THREE.AnimationAction: " +
  20437. "Use mixer.clipAction for construction." );
  20438. }
  20439. AnimationAction._new =
  20440. function AnimationAction( mixer, clip, localRoot ) {
  20441. this._mixer = mixer;
  20442. this._clip = clip;
  20443. this._localRoot = localRoot || null;
  20444. var tracks = clip.tracks,
  20445. nTracks = tracks.length,
  20446. interpolants = new Array( nTracks );
  20447. var interpolantSettings = {
  20448. endingStart: ZeroCurvatureEnding,
  20449. endingEnd: ZeroCurvatureEnding
  20450. };
  20451. for ( var i = 0; i !== nTracks; ++ i ) {
  20452. var interpolant = tracks[ i ].createInterpolant( null );
  20453. interpolants[ i ] = interpolant;
  20454. interpolant.settings = interpolantSettings;
  20455. }
  20456. this._interpolantSettings = interpolantSettings;
  20457. this._interpolants = interpolants; // bound by the mixer
  20458. // inside: PropertyMixer (managed by the mixer)
  20459. this._propertyBindings = new Array( nTracks );
  20460. this._cacheIndex = null; // for the memory manager
  20461. this._byClipCacheIndex = null; // for the memory manager
  20462. this._timeScaleInterpolant = null;
  20463. this._weightInterpolant = null;
  20464. this.loop = LoopRepeat;
  20465. this._loopCount = -1;
  20466. // global mixer time when the action is to be started
  20467. // it's set back to 'null' upon start of the action
  20468. this._startTime = null;
  20469. // scaled local time of the action
  20470. // gets clamped or wrapped to 0..clip.duration according to loop
  20471. this.time = 0;
  20472. this.timeScale = 1;
  20473. this._effectiveTimeScale = 1;
  20474. this.weight = 1;
  20475. this._effectiveWeight = 1;
  20476. this.repetitions = Infinity; // no. of repetitions when looping
  20477. this.paused = false; // false -> zero effective time scale
  20478. this.enabled = true; // true -> zero effective weight
  20479. this.clampWhenFinished = false; // keep feeding the last frame?
  20480. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  20481. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  20482. };
  20483. AnimationAction._new.prototype = {
  20484. constructor: AnimationAction._new,
  20485. // State & Scheduling
  20486. play: function() {
  20487. this._mixer._activateAction( this );
  20488. return this;
  20489. },
  20490. stop: function() {
  20491. this._mixer._deactivateAction( this );
  20492. return this.reset();
  20493. },
  20494. reset: function() {
  20495. this.paused = false;
  20496. this.enabled = true;
  20497. this.time = 0; // restart clip
  20498. this._loopCount = -1; // forget previous loops
  20499. this._startTime = null; // forget scheduling
  20500. return this.stopFading().stopWarping();
  20501. },
  20502. isRunning: function() {
  20503. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  20504. this._startTime === null && this._mixer._isActiveAction( this );
  20505. },
  20506. // return true when play has been called
  20507. isScheduled: function() {
  20508. return this._mixer._isActiveAction( this );
  20509. },
  20510. startAt: function( time ) {
  20511. this._startTime = time;
  20512. return this;
  20513. },
  20514. setLoop: function( mode, repetitions ) {
  20515. this.loop = mode;
  20516. this.repetitions = repetitions;
  20517. return this;
  20518. },
  20519. // Weight
  20520. // set the weight stopping any scheduled fading
  20521. // although .enabled = false yields an effective weight of zero, this
  20522. // method does *not* change .enabled, because it would be confusing
  20523. setEffectiveWeight: function( weight ) {
  20524. this.weight = weight;
  20525. // note: same logic as when updated at runtime
  20526. this._effectiveWeight = this.enabled ? weight : 0;
  20527. return this.stopFading();
  20528. },
  20529. // return the weight considering fading and .enabled
  20530. getEffectiveWeight: function() {
  20531. return this._effectiveWeight;
  20532. },
  20533. fadeIn: function( duration ) {
  20534. return this._scheduleFading( duration, 0, 1 );
  20535. },
  20536. fadeOut: function( duration ) {
  20537. return this._scheduleFading( duration, 1, 0 );
  20538. },
  20539. crossFadeFrom: function( fadeOutAction, duration, warp ) {
  20540. fadeOutAction.fadeOut( duration );
  20541. this.fadeIn( duration );
  20542. if( warp ) {
  20543. var fadeInDuration = this._clip.duration,
  20544. fadeOutDuration = fadeOutAction._clip.duration,
  20545. startEndRatio = fadeOutDuration / fadeInDuration,
  20546. endStartRatio = fadeInDuration / fadeOutDuration;
  20547. fadeOutAction.warp( 1.0, startEndRatio, duration );
  20548. this.warp( endStartRatio, 1.0, duration );
  20549. }
  20550. return this;
  20551. },
  20552. crossFadeTo: function( fadeInAction, duration, warp ) {
  20553. return fadeInAction.crossFadeFrom( this, duration, warp );
  20554. },
  20555. stopFading: function() {
  20556. var weightInterpolant = this._weightInterpolant;
  20557. if ( weightInterpolant !== null ) {
  20558. this._weightInterpolant = null;
  20559. this._mixer._takeBackControlInterpolant( weightInterpolant );
  20560. }
  20561. return this;
  20562. },
  20563. // Time Scale Control
  20564. // set the weight stopping any scheduled warping
  20565. // although .paused = true yields an effective time scale of zero, this
  20566. // method does *not* change .paused, because it would be confusing
  20567. setEffectiveTimeScale: function( timeScale ) {
  20568. this.timeScale = timeScale;
  20569. this._effectiveTimeScale = this.paused ? 0 :timeScale;
  20570. return this.stopWarping();
  20571. },
  20572. // return the time scale considering warping and .paused
  20573. getEffectiveTimeScale: function() {
  20574. return this._effectiveTimeScale;
  20575. },
  20576. setDuration: function( duration ) {
  20577. this.timeScale = this._clip.duration / duration;
  20578. return this.stopWarping();
  20579. },
  20580. syncWith: function( action ) {
  20581. this.time = action.time;
  20582. this.timeScale = action.timeScale;
  20583. return this.stopWarping();
  20584. },
  20585. halt: function( duration ) {
  20586. return this.warp( this._effectiveTimeScale, 0, duration );
  20587. },
  20588. warp: function( startTimeScale, endTimeScale, duration ) {
  20589. var mixer = this._mixer, now = mixer.time,
  20590. interpolant = this._timeScaleInterpolant,
  20591. timeScale = this.timeScale;
  20592. if ( interpolant === null ) {
  20593. interpolant = mixer._lendControlInterpolant(),
  20594. this._timeScaleInterpolant = interpolant;
  20595. }
  20596. var times = interpolant.parameterPositions,
  20597. values = interpolant.sampleValues;
  20598. times[ 0 ] = now;
  20599. times[ 1 ] = now + duration;
  20600. values[ 0 ] = startTimeScale / timeScale;
  20601. values[ 1 ] = endTimeScale / timeScale;
  20602. return this;
  20603. },
  20604. stopWarping: function() {
  20605. var timeScaleInterpolant = this._timeScaleInterpolant;
  20606. if ( timeScaleInterpolant !== null ) {
  20607. this._timeScaleInterpolant = null;
  20608. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  20609. }
  20610. return this;
  20611. },
  20612. // Object Accessors
  20613. getMixer: function() {
  20614. return this._mixer;
  20615. },
  20616. getClip: function() {
  20617. return this._clip;
  20618. },
  20619. getRoot: function() {
  20620. return this._localRoot || this._mixer._root;
  20621. },
  20622. // Interna
  20623. _update: function( time, deltaTime, timeDirection, accuIndex ) {
  20624. // called by the mixer
  20625. var startTime = this._startTime;
  20626. if ( startTime !== null ) {
  20627. // check for scheduled start of action
  20628. var timeRunning = ( time - startTime ) * timeDirection;
  20629. if ( timeRunning < 0 || timeDirection === 0 ) {
  20630. return; // yet to come / don't decide when delta = 0
  20631. }
  20632. // start
  20633. this._startTime = null; // unschedule
  20634. deltaTime = timeDirection * timeRunning;
  20635. }
  20636. // apply time scale and advance time
  20637. deltaTime *= this._updateTimeScale( time );
  20638. var clipTime = this._updateTime( deltaTime );
  20639. // note: _updateTime may disable the action resulting in
  20640. // an effective weight of 0
  20641. var weight = this._updateWeight( time );
  20642. if ( weight > 0 ) {
  20643. var interpolants = this._interpolants;
  20644. var propertyMixers = this._propertyBindings;
  20645. for ( var j = 0, m = interpolants.length; j !== m; ++ j ) {
  20646. interpolants[ j ].evaluate( clipTime );
  20647. propertyMixers[ j ].accumulate( accuIndex, weight );
  20648. }
  20649. }
  20650. },
  20651. _updateWeight: function( time ) {
  20652. var weight = 0;
  20653. if ( this.enabled ) {
  20654. weight = this.weight;
  20655. var interpolant = this._weightInterpolant;
  20656. if ( interpolant !== null ) {
  20657. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  20658. weight *= interpolantValue;
  20659. if ( time > interpolant.parameterPositions[ 1 ] ) {
  20660. this.stopFading();
  20661. if ( interpolantValue === 0 ) {
  20662. // faded out, disable
  20663. this.enabled = false;
  20664. }
  20665. }
  20666. }
  20667. }
  20668. this._effectiveWeight = weight;
  20669. return weight;
  20670. },
  20671. _updateTimeScale: function( time ) {
  20672. var timeScale = 0;
  20673. if ( ! this.paused ) {
  20674. timeScale = this.timeScale;
  20675. var interpolant = this._timeScaleInterpolant;
  20676. if ( interpolant !== null ) {
  20677. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  20678. timeScale *= interpolantValue;
  20679. if ( time > interpolant.parameterPositions[ 1 ] ) {
  20680. this.stopWarping();
  20681. if ( timeScale === 0 ) {
  20682. // motion has halted, pause
  20683. this.paused = true;
  20684. } else {
  20685. // warp done - apply final time scale
  20686. this.timeScale = timeScale;
  20687. }
  20688. }
  20689. }
  20690. }
  20691. this._effectiveTimeScale = timeScale;
  20692. return timeScale;
  20693. },
  20694. _updateTime: function( deltaTime ) {
  20695. var time = this.time + deltaTime;
  20696. if ( deltaTime === 0 ) return time;
  20697. var duration = this._clip.duration,
  20698. loop = this.loop,
  20699. loopCount = this._loopCount;
  20700. if ( loop === LoopOnce ) {
  20701. if ( loopCount === -1 ) {
  20702. // just started
  20703. this.loopCount = 0;
  20704. this._setEndings( true, true, false );
  20705. }
  20706. handle_stop: {
  20707. if ( time >= duration ) {
  20708. time = duration;
  20709. } else if ( time < 0 ) {
  20710. time = 0;
  20711. } else break handle_stop;
  20712. if ( this.clampWhenFinished ) this.paused = true;
  20713. else this.enabled = false;
  20714. this._mixer.dispatchEvent( {
  20715. type: 'finished', action: this,
  20716. direction: deltaTime < 0 ? -1 : 1
  20717. } );
  20718. }
  20719. } else { // repetitive Repeat or PingPong
  20720. var pingPong = ( loop === LoopPingPong );
  20721. if ( loopCount === -1 ) {
  20722. // just started
  20723. if ( deltaTime >= 0 ) {
  20724. loopCount = 0;
  20725. this._setEndings(
  20726. true, this.repetitions === 0, pingPong );
  20727. } else {
  20728. // when looping in reverse direction, the initial
  20729. // transition through zero counts as a repetition,
  20730. // so leave loopCount at -1
  20731. this._setEndings(
  20732. this.repetitions === 0, true, pingPong );
  20733. }
  20734. }
  20735. if ( time >= duration || time < 0 ) {
  20736. // wrap around
  20737. var loopDelta = Math.floor( time / duration ); // signed
  20738. time -= duration * loopDelta;
  20739. loopCount += Math.abs( loopDelta );
  20740. var pending = this.repetitions - loopCount;
  20741. if ( pending < 0 ) {
  20742. // have to stop (switch state, clamp time, fire event)
  20743. if ( this.clampWhenFinished ) this.paused = true;
  20744. else this.enabled = false;
  20745. time = deltaTime > 0 ? duration : 0;
  20746. this._mixer.dispatchEvent( {
  20747. type: 'finished', action: this,
  20748. direction: deltaTime > 0 ? 1 : -1
  20749. } );
  20750. } else {
  20751. // keep running
  20752. if ( pending === 0 ) {
  20753. // entering the last round
  20754. var atStart = deltaTime < 0;
  20755. this._setEndings( atStart, ! atStart, pingPong );
  20756. } else {
  20757. this._setEndings( false, false, pingPong );
  20758. }
  20759. this._loopCount = loopCount;
  20760. this._mixer.dispatchEvent( {
  20761. type: 'loop', action: this, loopDelta: loopDelta
  20762. } );
  20763. }
  20764. }
  20765. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  20766. // invert time for the "pong round"
  20767. this.time = time;
  20768. return duration - time;
  20769. }
  20770. }
  20771. this.time = time;
  20772. return time;
  20773. },
  20774. _setEndings: function( atStart, atEnd, pingPong ) {
  20775. var settings = this._interpolantSettings;
  20776. if ( pingPong ) {
  20777. settings.endingStart = ZeroSlopeEnding;
  20778. settings.endingEnd = ZeroSlopeEnding;
  20779. } else {
  20780. // assuming for LoopOnce atStart == atEnd == true
  20781. if ( atStart ) {
  20782. settings.endingStart = this.zeroSlopeAtStart ?
  20783. ZeroSlopeEnding : ZeroCurvatureEnding;
  20784. } else {
  20785. settings.endingStart = WrapAroundEnding;
  20786. }
  20787. if ( atEnd ) {
  20788. settings.endingEnd = this.zeroSlopeAtEnd ?
  20789. ZeroSlopeEnding : ZeroCurvatureEnding;
  20790. } else {
  20791. settings.endingEnd = WrapAroundEnding;
  20792. }
  20793. }
  20794. },
  20795. _scheduleFading: function( duration, weightNow, weightThen ) {
  20796. var mixer = this._mixer, now = mixer.time,
  20797. interpolant = this._weightInterpolant;
  20798. if ( interpolant === null ) {
  20799. interpolant = mixer._lendControlInterpolant(),
  20800. this._weightInterpolant = interpolant;
  20801. }
  20802. var times = interpolant.parameterPositions,
  20803. values = interpolant.sampleValues;
  20804. times[ 0 ] = now; values[ 0 ] = weightNow;
  20805. times[ 1 ] = now + duration; values[ 1 ] = weightThen;
  20806. return this;
  20807. }
  20808. };
  20809. /**
  20810. *
  20811. * Player for AnimationClips.
  20812. *
  20813. *
  20814. * @author Ben Houston / http://clara.io/
  20815. * @author David Sarno / http://lighthaus.us/
  20816. * @author tschw
  20817. */
  20818. function AnimationMixer( root ) {
  20819. this._root = root;
  20820. this._initMemoryManager();
  20821. this._accuIndex = 0;
  20822. this.time = 0;
  20823. this.timeScale = 1.0;
  20824. }
  20825. Object.assign( AnimationMixer.prototype, EventDispatcher.prototype, {
  20826. // return an action for a clip optionally using a custom root target
  20827. // object (this method allocates a lot of dynamic memory in case a
  20828. // previously unknown clip/root combination is specified)
  20829. clipAction: function( clip, optionalRoot ) {
  20830. var root = optionalRoot || this._root,
  20831. rootUuid = root.uuid,
  20832. clipObject = typeof clip === 'string' ?
  20833. AnimationClip.findByName( root, clip ) : clip,
  20834. clipUuid = clipObject !== null ? clipObject.uuid : clip,
  20835. actionsForClip = this._actionsByClip[ clipUuid ],
  20836. prototypeAction = null;
  20837. if ( actionsForClip !== undefined ) {
  20838. var existingAction =
  20839. actionsForClip.actionByRoot[ rootUuid ];
  20840. if ( existingAction !== undefined ) {
  20841. return existingAction;
  20842. }
  20843. // we know the clip, so we don't have to parse all
  20844. // the bindings again but can just copy
  20845. prototypeAction = actionsForClip.knownActions[ 0 ];
  20846. // also, take the clip from the prototype action
  20847. if ( clipObject === null )
  20848. clipObject = prototypeAction._clip;
  20849. }
  20850. // clip must be known when specified via string
  20851. if ( clipObject === null ) return null;
  20852. // allocate all resources required to run it
  20853. var newAction = new AnimationMixer._Action( this, clipObject, optionalRoot );
  20854. this._bindAction( newAction, prototypeAction );
  20855. // and make the action known to the memory manager
  20856. this._addInactiveAction( newAction, clipUuid, rootUuid );
  20857. return newAction;
  20858. },
  20859. // get an existing action
  20860. existingAction: function( clip, optionalRoot ) {
  20861. var root = optionalRoot || this._root,
  20862. rootUuid = root.uuid,
  20863. clipObject = typeof clip === 'string' ?
  20864. AnimationClip.findByName( root, clip ) : clip,
  20865. clipUuid = clipObject ? clipObject.uuid : clip,
  20866. actionsForClip = this._actionsByClip[ clipUuid ];
  20867. if ( actionsForClip !== undefined ) {
  20868. return actionsForClip.actionByRoot[ rootUuid ] || null;
  20869. }
  20870. return null;
  20871. },
  20872. // deactivates all previously scheduled actions
  20873. stopAllAction: function() {
  20874. var actions = this._actions,
  20875. nActions = this._nActiveActions,
  20876. bindings = this._bindings,
  20877. nBindings = this._nActiveBindings;
  20878. this._nActiveActions = 0;
  20879. this._nActiveBindings = 0;
  20880. for ( var i = 0; i !== nActions; ++ i ) {
  20881. actions[ i ].reset();
  20882. }
  20883. for ( var i = 0; i !== nBindings; ++ i ) {
  20884. bindings[ i ].useCount = 0;
  20885. }
  20886. return this;
  20887. },
  20888. // advance the time and update apply the animation
  20889. update: function( deltaTime ) {
  20890. deltaTime *= this.timeScale;
  20891. var actions = this._actions,
  20892. nActions = this._nActiveActions,
  20893. time = this.time += deltaTime,
  20894. timeDirection = Math.sign( deltaTime ),
  20895. accuIndex = this._accuIndex ^= 1;
  20896. // run active actions
  20897. for ( var i = 0; i !== nActions; ++ i ) {
  20898. var action = actions[ i ];
  20899. if ( action.enabled ) {
  20900. action._update( time, deltaTime, timeDirection, accuIndex );
  20901. }
  20902. }
  20903. // update scene graph
  20904. var bindings = this._bindings,
  20905. nBindings = this._nActiveBindings;
  20906. for ( var i = 0; i !== nBindings; ++ i ) {
  20907. bindings[ i ].apply( accuIndex );
  20908. }
  20909. return this;
  20910. },
  20911. // return this mixer's root target object
  20912. getRoot: function() {
  20913. return this._root;
  20914. },
  20915. // free all resources specific to a particular clip
  20916. uncacheClip: function( clip ) {
  20917. var actions = this._actions,
  20918. clipUuid = clip.uuid,
  20919. actionsByClip = this._actionsByClip,
  20920. actionsForClip = actionsByClip[ clipUuid ];
  20921. if ( actionsForClip !== undefined ) {
  20922. // note: just calling _removeInactiveAction would mess up the
  20923. // iteration state and also require updating the state we can
  20924. // just throw away
  20925. var actionsToRemove = actionsForClip.knownActions;
  20926. for ( var i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  20927. var action = actionsToRemove[ i ];
  20928. this._deactivateAction( action );
  20929. var cacheIndex = action._cacheIndex,
  20930. lastInactiveAction = actions[ actions.length - 1 ];
  20931. action._cacheIndex = null;
  20932. action._byClipCacheIndex = null;
  20933. lastInactiveAction._cacheIndex = cacheIndex;
  20934. actions[ cacheIndex ] = lastInactiveAction;
  20935. actions.pop();
  20936. this._removeInactiveBindingsForAction( action );
  20937. }
  20938. delete actionsByClip[ clipUuid ];
  20939. }
  20940. },
  20941. // free all resources specific to a particular root target object
  20942. uncacheRoot: function( root ) {
  20943. var rootUuid = root.uuid,
  20944. actionsByClip = this._actionsByClip;
  20945. for ( var clipUuid in actionsByClip ) {
  20946. var actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  20947. action = actionByRoot[ rootUuid ];
  20948. if ( action !== undefined ) {
  20949. this._deactivateAction( action );
  20950. this._removeInactiveAction( action );
  20951. }
  20952. }
  20953. var bindingsByRoot = this._bindingsByRootAndName,
  20954. bindingByName = bindingsByRoot[ rootUuid ];
  20955. if ( bindingByName !== undefined ) {
  20956. for ( var trackName in bindingByName ) {
  20957. var binding = bindingByName[ trackName ];
  20958. binding.restoreOriginalState();
  20959. this._removeInactiveBinding( binding );
  20960. }
  20961. }
  20962. },
  20963. // remove a targeted clip from the cache
  20964. uncacheAction: function( clip, optionalRoot ) {
  20965. var action = this.existingAction( clip, optionalRoot );
  20966. if ( action !== null ) {
  20967. this._deactivateAction( action );
  20968. this._removeInactiveAction( action );
  20969. }
  20970. }
  20971. } );
  20972. AnimationMixer._Action = AnimationAction._new;
  20973. // Implementation details:
  20974. Object.assign( AnimationMixer.prototype, {
  20975. _bindAction: function( action, prototypeAction ) {
  20976. var root = action._localRoot || this._root,
  20977. tracks = action._clip.tracks,
  20978. nTracks = tracks.length,
  20979. bindings = action._propertyBindings,
  20980. interpolants = action._interpolants,
  20981. rootUuid = root.uuid,
  20982. bindingsByRoot = this._bindingsByRootAndName,
  20983. bindingsByName = bindingsByRoot[ rootUuid ];
  20984. if ( bindingsByName === undefined ) {
  20985. bindingsByName = {};
  20986. bindingsByRoot[ rootUuid ] = bindingsByName;
  20987. }
  20988. for ( var i = 0; i !== nTracks; ++ i ) {
  20989. var track = tracks[ i ],
  20990. trackName = track.name,
  20991. binding = bindingsByName[ trackName ];
  20992. if ( binding !== undefined ) {
  20993. bindings[ i ] = binding;
  20994. } else {
  20995. binding = bindings[ i ];
  20996. if ( binding !== undefined ) {
  20997. // existing binding, make sure the cache knows
  20998. if ( binding._cacheIndex === null ) {
  20999. ++ binding.referenceCount;
  21000. this._addInactiveBinding( binding, rootUuid, trackName );
  21001. }
  21002. continue;
  21003. }
  21004. var path = prototypeAction && prototypeAction.
  21005. _propertyBindings[ i ].binding.parsedPath;
  21006. binding = new PropertyMixer(
  21007. PropertyBinding.create( root, trackName, path ),
  21008. track.ValueTypeName, track.getValueSize() );
  21009. ++ binding.referenceCount;
  21010. this._addInactiveBinding( binding, rootUuid, trackName );
  21011. bindings[ i ] = binding;
  21012. }
  21013. interpolants[ i ].resultBuffer = binding.buffer;
  21014. }
  21015. },
  21016. _activateAction: function( action ) {
  21017. if ( ! this._isActiveAction( action ) ) {
  21018. if ( action._cacheIndex === null ) {
  21019. // this action has been forgotten by the cache, but the user
  21020. // appears to be still using it -> rebind
  21021. var rootUuid = ( action._localRoot || this._root ).uuid,
  21022. clipUuid = action._clip.uuid,
  21023. actionsForClip = this._actionsByClip[ clipUuid ];
  21024. this._bindAction( action,
  21025. actionsForClip && actionsForClip.knownActions[ 0 ] );
  21026. this._addInactiveAction( action, clipUuid, rootUuid );
  21027. }
  21028. var bindings = action._propertyBindings;
  21029. // increment reference counts / sort out state
  21030. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  21031. var binding = bindings[ i ];
  21032. if ( binding.useCount ++ === 0 ) {
  21033. this._lendBinding( binding );
  21034. binding.saveOriginalState();
  21035. }
  21036. }
  21037. this._lendAction( action );
  21038. }
  21039. },
  21040. _deactivateAction: function( action ) {
  21041. if ( this._isActiveAction( action ) ) {
  21042. var bindings = action._propertyBindings;
  21043. // decrement reference counts / sort out state
  21044. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  21045. var binding = bindings[ i ];
  21046. if ( -- binding.useCount === 0 ) {
  21047. binding.restoreOriginalState();
  21048. this._takeBackBinding( binding );
  21049. }
  21050. }
  21051. this._takeBackAction( action );
  21052. }
  21053. },
  21054. // Memory manager
  21055. _initMemoryManager: function() {
  21056. this._actions = []; // 'nActiveActions' followed by inactive ones
  21057. this._nActiveActions = 0;
  21058. this._actionsByClip = {};
  21059. // inside:
  21060. // {
  21061. // knownActions: Array< _Action > - used as prototypes
  21062. // actionByRoot: _Action - lookup
  21063. // }
  21064. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  21065. this._nActiveBindings = 0;
  21066. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  21067. this._controlInterpolants = []; // same game as above
  21068. this._nActiveControlInterpolants = 0;
  21069. var scope = this;
  21070. this.stats = {
  21071. actions: {
  21072. get total() { return scope._actions.length; },
  21073. get inUse() { return scope._nActiveActions; }
  21074. },
  21075. bindings: {
  21076. get total() { return scope._bindings.length; },
  21077. get inUse() { return scope._nActiveBindings; }
  21078. },
  21079. controlInterpolants: {
  21080. get total() { return scope._controlInterpolants.length; },
  21081. get inUse() { return scope._nActiveControlInterpolants; }
  21082. }
  21083. };
  21084. },
  21085. // Memory management for _Action objects
  21086. _isActiveAction: function( action ) {
  21087. var index = action._cacheIndex;
  21088. return index !== null && index < this._nActiveActions;
  21089. },
  21090. _addInactiveAction: function( action, clipUuid, rootUuid ) {
  21091. var actions = this._actions,
  21092. actionsByClip = this._actionsByClip,
  21093. actionsForClip = actionsByClip[ clipUuid ];
  21094. if ( actionsForClip === undefined ) {
  21095. actionsForClip = {
  21096. knownActions: [ action ],
  21097. actionByRoot: {}
  21098. };
  21099. action._byClipCacheIndex = 0;
  21100. actionsByClip[ clipUuid ] = actionsForClip;
  21101. } else {
  21102. var knownActions = actionsForClip.knownActions;
  21103. action._byClipCacheIndex = knownActions.length;
  21104. knownActions.push( action );
  21105. }
  21106. action._cacheIndex = actions.length;
  21107. actions.push( action );
  21108. actionsForClip.actionByRoot[ rootUuid ] = action;
  21109. },
  21110. _removeInactiveAction: function( action ) {
  21111. var actions = this._actions,
  21112. lastInactiveAction = actions[ actions.length - 1 ],
  21113. cacheIndex = action._cacheIndex;
  21114. lastInactiveAction._cacheIndex = cacheIndex;
  21115. actions[ cacheIndex ] = lastInactiveAction;
  21116. actions.pop();
  21117. action._cacheIndex = null;
  21118. var clipUuid = action._clip.uuid,
  21119. actionsByClip = this._actionsByClip,
  21120. actionsForClip = actionsByClip[ clipUuid ],
  21121. knownActionsForClip = actionsForClip.knownActions,
  21122. lastKnownAction =
  21123. knownActionsForClip[ knownActionsForClip.length - 1 ],
  21124. byClipCacheIndex = action._byClipCacheIndex;
  21125. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  21126. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  21127. knownActionsForClip.pop();
  21128. action._byClipCacheIndex = null;
  21129. var actionByRoot = actionsForClip.actionByRoot,
  21130. rootUuid = ( actions._localRoot || this._root ).uuid;
  21131. delete actionByRoot[ rootUuid ];
  21132. if ( knownActionsForClip.length === 0 ) {
  21133. delete actionsByClip[ clipUuid ];
  21134. }
  21135. this._removeInactiveBindingsForAction( action );
  21136. },
  21137. _removeInactiveBindingsForAction: function( action ) {
  21138. var bindings = action._propertyBindings;
  21139. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  21140. var binding = bindings[ i ];
  21141. if ( -- binding.referenceCount === 0 ) {
  21142. this._removeInactiveBinding( binding );
  21143. }
  21144. }
  21145. },
  21146. _lendAction: function( action ) {
  21147. // [ active actions | inactive actions ]
  21148. // [ active actions >| inactive actions ]
  21149. // s a
  21150. // <-swap->
  21151. // a s
  21152. var actions = this._actions,
  21153. prevIndex = action._cacheIndex,
  21154. lastActiveIndex = this._nActiveActions ++,
  21155. firstInactiveAction = actions[ lastActiveIndex ];
  21156. action._cacheIndex = lastActiveIndex;
  21157. actions[ lastActiveIndex ] = action;
  21158. firstInactiveAction._cacheIndex = prevIndex;
  21159. actions[ prevIndex ] = firstInactiveAction;
  21160. },
  21161. _takeBackAction: function( action ) {
  21162. // [ active actions | inactive actions ]
  21163. // [ active actions |< inactive actions ]
  21164. // a s
  21165. // <-swap->
  21166. // s a
  21167. var actions = this._actions,
  21168. prevIndex = action._cacheIndex,
  21169. firstInactiveIndex = -- this._nActiveActions,
  21170. lastActiveAction = actions[ firstInactiveIndex ];
  21171. action._cacheIndex = firstInactiveIndex;
  21172. actions[ firstInactiveIndex ] = action;
  21173. lastActiveAction._cacheIndex = prevIndex;
  21174. actions[ prevIndex ] = lastActiveAction;
  21175. },
  21176. // Memory management for PropertyMixer objects
  21177. _addInactiveBinding: function( binding, rootUuid, trackName ) {
  21178. var bindingsByRoot = this._bindingsByRootAndName,
  21179. bindingByName = bindingsByRoot[ rootUuid ],
  21180. bindings = this._bindings;
  21181. if ( bindingByName === undefined ) {
  21182. bindingByName = {};
  21183. bindingsByRoot[ rootUuid ] = bindingByName;
  21184. }
  21185. bindingByName[ trackName ] = binding;
  21186. binding._cacheIndex = bindings.length;
  21187. bindings.push( binding );
  21188. },
  21189. _removeInactiveBinding: function( binding ) {
  21190. var bindings = this._bindings,
  21191. propBinding = binding.binding,
  21192. rootUuid = propBinding.rootNode.uuid,
  21193. trackName = propBinding.path,
  21194. bindingsByRoot = this._bindingsByRootAndName,
  21195. bindingByName = bindingsByRoot[ rootUuid ],
  21196. lastInactiveBinding = bindings[ bindings.length - 1 ],
  21197. cacheIndex = binding._cacheIndex;
  21198. lastInactiveBinding._cacheIndex = cacheIndex;
  21199. bindings[ cacheIndex ] = lastInactiveBinding;
  21200. bindings.pop();
  21201. delete bindingByName[ trackName ];
  21202. remove_empty_map: {
  21203. for ( var _ in bindingByName ) break remove_empty_map;
  21204. delete bindingsByRoot[ rootUuid ];
  21205. }
  21206. },
  21207. _lendBinding: function( binding ) {
  21208. var bindings = this._bindings,
  21209. prevIndex = binding._cacheIndex,
  21210. lastActiveIndex = this._nActiveBindings ++,
  21211. firstInactiveBinding = bindings[ lastActiveIndex ];
  21212. binding._cacheIndex = lastActiveIndex;
  21213. bindings[ lastActiveIndex ] = binding;
  21214. firstInactiveBinding._cacheIndex = prevIndex;
  21215. bindings[ prevIndex ] = firstInactiveBinding;
  21216. },
  21217. _takeBackBinding: function( binding ) {
  21218. var bindings = this._bindings,
  21219. prevIndex = binding._cacheIndex,
  21220. firstInactiveIndex = -- this._nActiveBindings,
  21221. lastActiveBinding = bindings[ firstInactiveIndex ];
  21222. binding._cacheIndex = firstInactiveIndex;
  21223. bindings[ firstInactiveIndex ] = binding;
  21224. lastActiveBinding._cacheIndex = prevIndex;
  21225. bindings[ prevIndex ] = lastActiveBinding;
  21226. },
  21227. // Memory management of Interpolants for weight and time scale
  21228. _lendControlInterpolant: function() {
  21229. var interpolants = this._controlInterpolants,
  21230. lastActiveIndex = this._nActiveControlInterpolants ++,
  21231. interpolant = interpolants[ lastActiveIndex ];
  21232. if ( interpolant === undefined ) {
  21233. interpolant = new LinearInterpolant(
  21234. new Float32Array( 2 ), new Float32Array( 2 ),
  21235. 1, this._controlInterpolantsResultBuffer );
  21236. interpolant.__cacheIndex = lastActiveIndex;
  21237. interpolants[ lastActiveIndex ] = interpolant;
  21238. }
  21239. return interpolant;
  21240. },
  21241. _takeBackControlInterpolant: function( interpolant ) {
  21242. var interpolants = this._controlInterpolants,
  21243. prevIndex = interpolant.__cacheIndex,
  21244. firstInactiveIndex = -- this._nActiveControlInterpolants,
  21245. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  21246. interpolant.__cacheIndex = firstInactiveIndex;
  21247. interpolants[ firstInactiveIndex ] = interpolant;
  21248. lastActiveInterpolant.__cacheIndex = prevIndex;
  21249. interpolants[ prevIndex ] = lastActiveInterpolant;
  21250. },
  21251. _controlInterpolantsResultBuffer: new Float32Array( 1 )
  21252. } );
  21253. /**
  21254. * @author mrdoob / http://mrdoob.com/
  21255. */
  21256. function Uniform( value ) {
  21257. if ( typeof value === 'string' ) {
  21258. console.warn( 'THREE.Uniform: Type parameter is no longer needed.' );
  21259. value = arguments[ 1 ];
  21260. }
  21261. this.value = value;
  21262. this.dynamic = false;
  21263. }
  21264. Uniform.prototype = {
  21265. constructor: Uniform,
  21266. onUpdate: function ( callback ) {
  21267. this.dynamic = true;
  21268. this.onUpdateCallback = callback;
  21269. return this;
  21270. }
  21271. };
  21272. /**
  21273. * @author benaadams / https://twitter.com/ben_a_adams
  21274. */
  21275. function InstancedBufferGeometry() {
  21276. BufferGeometry.call( this );
  21277. this.type = 'InstancedBufferGeometry';
  21278. this.maxInstancedCount = undefined;
  21279. }
  21280. InstancedBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  21281. InstancedBufferGeometry.prototype.constructor = InstancedBufferGeometry;
  21282. InstancedBufferGeometry.prototype.isBufferGeometry = true;
  21283. InstancedBufferGeometry.prototype.addGroup = function ( start, count, instances ) {
  21284. this.groups.push( {
  21285. start: start,
  21286. count: count,
  21287. instances: instances
  21288. } );
  21289. };
  21290. InstancedBufferGeometry.prototype.copy = function ( source ) {
  21291. var index = source.index;
  21292. if ( index !== null ) {
  21293. this.setIndex( index.clone() );
  21294. }
  21295. var attributes = source.attributes;
  21296. for ( var name in attributes ) {
  21297. var attribute = attributes[ name ];
  21298. this.addAttribute( name, attribute.clone() );
  21299. }
  21300. var groups = source.groups;
  21301. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  21302. var group = groups[ i ];
  21303. this.addGroup( group.start, group.count, group.instances );
  21304. }
  21305. return this;
  21306. };
  21307. /**
  21308. * @author benaadams / https://twitter.com/ben_a_adams
  21309. */
  21310. function InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, normalized ) {
  21311. this.uuid = exports.Math.generateUUID();
  21312. this.data = interleavedBuffer;
  21313. this.itemSize = itemSize;
  21314. this.offset = offset;
  21315. this.normalized = normalized === true;
  21316. }
  21317. InterleavedBufferAttribute.prototype = {
  21318. constructor: InterleavedBufferAttribute,
  21319. isInterleavedBufferAttribute: true,
  21320. get length() {
  21321. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Please use .count.' );
  21322. return this.array.length;
  21323. },
  21324. get count() {
  21325. return this.data.count;
  21326. },
  21327. get array() {
  21328. return this.data.array;
  21329. },
  21330. setX: function ( index, x ) {
  21331. this.data.array[ index * this.data.stride + this.offset ] = x;
  21332. return this;
  21333. },
  21334. setY: function ( index, y ) {
  21335. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  21336. return this;
  21337. },
  21338. setZ: function ( index, z ) {
  21339. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  21340. return this;
  21341. },
  21342. setW: function ( index, w ) {
  21343. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  21344. return this;
  21345. },
  21346. getX: function ( index ) {
  21347. return this.data.array[ index * this.data.stride + this.offset ];
  21348. },
  21349. getY: function ( index ) {
  21350. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  21351. },
  21352. getZ: function ( index ) {
  21353. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  21354. },
  21355. getW: function ( index ) {
  21356. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  21357. },
  21358. setXY: function ( index, x, y ) {
  21359. index = index * this.data.stride + this.offset;
  21360. this.data.array[ index + 0 ] = x;
  21361. this.data.array[ index + 1 ] = y;
  21362. return this;
  21363. },
  21364. setXYZ: function ( index, x, y, z ) {
  21365. index = index * this.data.stride + this.offset;
  21366. this.data.array[ index + 0 ] = x;
  21367. this.data.array[ index + 1 ] = y;
  21368. this.data.array[ index + 2 ] = z;
  21369. return this;
  21370. },
  21371. setXYZW: function ( index, x, y, z, w ) {
  21372. index = index * this.data.stride + this.offset;
  21373. this.data.array[ index + 0 ] = x;
  21374. this.data.array[ index + 1 ] = y;
  21375. this.data.array[ index + 2 ] = z;
  21376. this.data.array[ index + 3 ] = w;
  21377. return this;
  21378. }
  21379. };
  21380. /**
  21381. * @author benaadams / https://twitter.com/ben_a_adams
  21382. */
  21383. function InterleavedBuffer( array, stride ) {
  21384. this.uuid = exports.Math.generateUUID();
  21385. this.array = array;
  21386. this.stride = stride;
  21387. this.dynamic = false;
  21388. this.updateRange = { offset: 0, count: - 1 };
  21389. this.version = 0;
  21390. }
  21391. InterleavedBuffer.prototype = {
  21392. constructor: InterleavedBuffer,
  21393. isInterleavedBuffer: true,
  21394. get length () {
  21395. return this.array.length;
  21396. },
  21397. get count () {
  21398. return this.array.length / this.stride;
  21399. },
  21400. set needsUpdate( value ) {
  21401. if ( value === true ) this.version ++;
  21402. },
  21403. setDynamic: function ( value ) {
  21404. this.dynamic = value;
  21405. return this;
  21406. },
  21407. copy: function ( source ) {
  21408. this.array = new source.array.constructor( source.array );
  21409. this.stride = source.stride;
  21410. this.dynamic = source.dynamic;
  21411. return this;
  21412. },
  21413. copyAt: function ( index1, attribute, index2 ) {
  21414. index1 *= this.stride;
  21415. index2 *= attribute.stride;
  21416. for ( var i = 0, l = this.stride; i < l; i ++ ) {
  21417. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  21418. }
  21419. return this;
  21420. },
  21421. set: function ( value, offset ) {
  21422. if ( offset === undefined ) offset = 0;
  21423. this.array.set( value, offset );
  21424. return this;
  21425. },
  21426. clone: function () {
  21427. return new this.constructor().copy( this );
  21428. }
  21429. };
  21430. /**
  21431. * @author benaadams / https://twitter.com/ben_a_adams
  21432. */
  21433. function InstancedInterleavedBuffer( array, stride, meshPerAttribute ) {
  21434. InterleavedBuffer.call( this, array, stride );
  21435. this.meshPerAttribute = meshPerAttribute || 1;
  21436. }
  21437. InstancedInterleavedBuffer.prototype = Object.create( InterleavedBuffer.prototype );
  21438. InstancedInterleavedBuffer.prototype.constructor = InstancedInterleavedBuffer;
  21439. InstancedInterleavedBuffer.prototype.isInstancedInterleavedBuffer = true;
  21440. InstancedInterleavedBuffer.prototype.copy = function ( source ) {
  21441. InterleavedBuffer.prototype.copy.call( this, source );
  21442. this.meshPerAttribute = source.meshPerAttribute;
  21443. return this;
  21444. };
  21445. /**
  21446. * @author benaadams / https://twitter.com/ben_a_adams
  21447. */
  21448. function InstancedBufferAttribute( array, itemSize, meshPerAttribute ) {
  21449. BufferAttribute.call( this, array, itemSize );
  21450. this.meshPerAttribute = meshPerAttribute || 1;
  21451. }
  21452. InstancedBufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  21453. InstancedBufferAttribute.prototype.constructor = InstancedBufferAttribute;
  21454. InstancedBufferAttribute.prototype.isInstancedBufferAttribute = true;
  21455. InstancedBufferAttribute.prototype.copy = function ( source ) {
  21456. BufferAttribute.prototype.copy.call( this, source );
  21457. this.meshPerAttribute = source.meshPerAttribute;
  21458. return this;
  21459. };
  21460. /**
  21461. * @author mrdoob / http://mrdoob.com/
  21462. * @author bhouston / http://clara.io/
  21463. * @author stephomi / http://stephaneginier.com/
  21464. */
  21465. function Raycaster( origin, direction, near, far ) {
  21466. this.ray = new Ray( origin, direction );
  21467. // direction is assumed to be normalized (for accurate distance calculations)
  21468. this.near = near || 0;
  21469. this.far = far || Infinity;
  21470. this.params = {
  21471. Mesh: {},
  21472. Line: {},
  21473. LOD: {},
  21474. Points: { threshold: 1 },
  21475. Sprite: {}
  21476. };
  21477. Object.defineProperties( this.params, {
  21478. PointCloud: {
  21479. get: function () {
  21480. console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' );
  21481. return this.Points;
  21482. }
  21483. }
  21484. } );
  21485. }
  21486. function ascSort( a, b ) {
  21487. return a.distance - b.distance;
  21488. }
  21489. function intersectObject( object, raycaster, intersects, recursive ) {
  21490. if ( object.visible === false ) return;
  21491. object.raycast( raycaster, intersects );
  21492. if ( recursive === true ) {
  21493. var children = object.children;
  21494. for ( var i = 0, l = children.length; i < l; i ++ ) {
  21495. intersectObject( children[ i ], raycaster, intersects, true );
  21496. }
  21497. }
  21498. }
  21499. //
  21500. Raycaster.prototype = {
  21501. constructor: Raycaster,
  21502. linePrecision: 1,
  21503. set: function ( origin, direction ) {
  21504. // direction is assumed to be normalized (for accurate distance calculations)
  21505. this.ray.set( origin, direction );
  21506. },
  21507. setFromCamera: function ( coords, camera ) {
  21508. if ( (camera && camera.isPerspectiveCamera) ) {
  21509. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  21510. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  21511. } else if ( (camera && camera.isOrthographicCamera) ) {
  21512. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  21513. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  21514. } else {
  21515. console.error( 'THREE.Raycaster: Unsupported camera type.' );
  21516. }
  21517. },
  21518. intersectObject: function ( object, recursive ) {
  21519. var intersects = [];
  21520. intersectObject( object, this, intersects, recursive );
  21521. intersects.sort( ascSort );
  21522. return intersects;
  21523. },
  21524. intersectObjects: function ( objects, recursive ) {
  21525. var intersects = [];
  21526. if ( Array.isArray( objects ) === false ) {
  21527. console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
  21528. return intersects;
  21529. }
  21530. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  21531. intersectObject( objects[ i ], this, intersects, recursive );
  21532. }
  21533. intersects.sort( ascSort );
  21534. return intersects;
  21535. }
  21536. };
  21537. /**
  21538. * @author alteredq / http://alteredqualia.com/
  21539. */
  21540. function Clock( autoStart ) {
  21541. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  21542. this.startTime = 0;
  21543. this.oldTime = 0;
  21544. this.elapsedTime = 0;
  21545. this.running = false;
  21546. }
  21547. Clock.prototype = {
  21548. constructor: Clock,
  21549. start: function () {
  21550. this.startTime = ( performance || Date ).now();
  21551. this.oldTime = this.startTime;
  21552. this.running = true;
  21553. },
  21554. stop: function () {
  21555. this.getElapsedTime();
  21556. this.running = false;
  21557. },
  21558. getElapsedTime: function () {
  21559. this.getDelta();
  21560. return this.elapsedTime;
  21561. },
  21562. getDelta: function () {
  21563. var diff = 0;
  21564. if ( this.autoStart && ! this.running ) {
  21565. this.start();
  21566. }
  21567. if ( this.running ) {
  21568. var newTime = ( performance || Date ).now();
  21569. diff = ( newTime - this.oldTime ) / 1000;
  21570. this.oldTime = newTime;
  21571. this.elapsedTime += diff;
  21572. }
  21573. return diff;
  21574. }
  21575. };
  21576. /**
  21577. * Spline from Tween.js, slightly optimized (and trashed)
  21578. * http://sole.github.com/tween.js/examples/05_spline.html
  21579. *
  21580. * @author mrdoob / http://mrdoob.com/
  21581. * @author alteredq / http://alteredqualia.com/
  21582. */
  21583. function Spline( points ) {
  21584. this.points = points;
  21585. var c = [], v3 = { x: 0, y: 0, z: 0 },
  21586. point, intPoint, weight, w2, w3,
  21587. pa, pb, pc, pd;
  21588. this.initFromArray = function ( a ) {
  21589. this.points = [];
  21590. for ( var i = 0; i < a.length; i ++ ) {
  21591. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  21592. }
  21593. };
  21594. this.getPoint = function ( k ) {
  21595. point = ( this.points.length - 1 ) * k;
  21596. intPoint = Math.floor( point );
  21597. weight = point - intPoint;
  21598. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  21599. c[ 1 ] = intPoint;
  21600. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  21601. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  21602. pa = this.points[ c[ 0 ] ];
  21603. pb = this.points[ c[ 1 ] ];
  21604. pc = this.points[ c[ 2 ] ];
  21605. pd = this.points[ c[ 3 ] ];
  21606. w2 = weight * weight;
  21607. w3 = weight * w2;
  21608. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  21609. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  21610. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  21611. return v3;
  21612. };
  21613. this.getControlPointsArray = function () {
  21614. var i, p, l = this.points.length,
  21615. coords = [];
  21616. for ( i = 0; i < l; i ++ ) {
  21617. p = this.points[ i ];
  21618. coords[ i ] = [ p.x, p.y, p.z ];
  21619. }
  21620. return coords;
  21621. };
  21622. // approximate length by summing linear segments
  21623. this.getLength = function ( nSubDivisions ) {
  21624. var i, index, nSamples, position,
  21625. point = 0, intPoint = 0, oldIntPoint = 0,
  21626. oldPosition = new Vector3(),
  21627. tmpVec = new Vector3(),
  21628. chunkLengths = [],
  21629. totalLength = 0;
  21630. // first point has 0 length
  21631. chunkLengths[ 0 ] = 0;
  21632. if ( ! nSubDivisions ) nSubDivisions = 100;
  21633. nSamples = this.points.length * nSubDivisions;
  21634. oldPosition.copy( this.points[ 0 ] );
  21635. for ( i = 1; i < nSamples; i ++ ) {
  21636. index = i / nSamples;
  21637. position = this.getPoint( index );
  21638. tmpVec.copy( position );
  21639. totalLength += tmpVec.distanceTo( oldPosition );
  21640. oldPosition.copy( position );
  21641. point = ( this.points.length - 1 ) * index;
  21642. intPoint = Math.floor( point );
  21643. if ( intPoint !== oldIntPoint ) {
  21644. chunkLengths[ intPoint ] = totalLength;
  21645. oldIntPoint = intPoint;
  21646. }
  21647. }
  21648. // last point ends with total length
  21649. chunkLengths[ chunkLengths.length ] = totalLength;
  21650. return { chunks: chunkLengths, total: totalLength };
  21651. };
  21652. this.reparametrizeByArcLength = function ( samplingCoef ) {
  21653. var i, j,
  21654. index, indexCurrent, indexNext,
  21655. realDistance,
  21656. sampling, position,
  21657. newpoints = [],
  21658. tmpVec = new Vector3(),
  21659. sl = this.getLength();
  21660. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  21661. for ( i = 1; i < this.points.length; i ++ ) {
  21662. //tmpVec.copy( this.points[ i - 1 ] );
  21663. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  21664. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  21665. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  21666. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  21667. indexNext = i / ( this.points.length - 1 );
  21668. for ( j = 1; j < sampling - 1; j ++ ) {
  21669. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  21670. position = this.getPoint( index );
  21671. newpoints.push( tmpVec.copy( position ).clone() );
  21672. }
  21673. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  21674. }
  21675. this.points = newpoints;
  21676. };
  21677. // Catmull-Rom
  21678. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  21679. var v0 = ( p2 - p0 ) * 0.5,
  21680. v1 = ( p3 - p1 ) * 0.5;
  21681. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  21682. }
  21683. }
  21684. /**
  21685. * @author bhouston / http://clara.io
  21686. * @author WestLangley / http://github.com/WestLangley
  21687. *
  21688. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  21689. *
  21690. * The poles (phi) are at the positive and negative y axis.
  21691. * The equator starts at positive z.
  21692. */
  21693. function Spherical( radius, phi, theta ) {
  21694. this.radius = ( radius !== undefined ) ? radius : 1.0;
  21695. this.phi = ( phi !== undefined ) ? phi : 0; // up / down towards top and bottom pole
  21696. this.theta = ( theta !== undefined ) ? theta : 0; // around the equator of the sphere
  21697. return this;
  21698. }
  21699. Spherical.prototype = {
  21700. constructor: Spherical,
  21701. set: function ( radius, phi, theta ) {
  21702. this.radius = radius;
  21703. this.phi = phi;
  21704. this.theta = theta;
  21705. return this;
  21706. },
  21707. clone: function () {
  21708. return new this.constructor().copy( this );
  21709. },
  21710. copy: function ( other ) {
  21711. this.radius.copy( other.radius );
  21712. this.phi.copy( other.phi );
  21713. this.theta.copy( other.theta );
  21714. return this;
  21715. },
  21716. // restrict phi to be betwee EPS and PI-EPS
  21717. makeSafe: function() {
  21718. var EPS = 0.000001;
  21719. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  21720. return this;
  21721. },
  21722. setFromVector3: function( vec3 ) {
  21723. this.radius = vec3.length();
  21724. if ( this.radius === 0 ) {
  21725. this.theta = 0;
  21726. this.phi = 0;
  21727. } else {
  21728. this.theta = Math.atan2( vec3.x, vec3.z ); // equator angle around y-up axis
  21729. this.phi = Math.acos( exports.Math.clamp( vec3.y / this.radius, - 1, 1 ) ); // polar angle
  21730. }
  21731. return this;
  21732. },
  21733. };
  21734. /**
  21735. * @author alteredq / http://alteredqualia.com/
  21736. */
  21737. function MorphBlendMesh( geometry, material ) {
  21738. Mesh.call( this, geometry, material );
  21739. this.animationsMap = {};
  21740. this.animationsList = [];
  21741. // prepare default animation
  21742. // (all frames played together in 1 second)
  21743. var numFrames = this.geometry.morphTargets.length;
  21744. var name = "__default";
  21745. var startFrame = 0;
  21746. var endFrame = numFrames - 1;
  21747. var fps = numFrames / 1;
  21748. this.createAnimation( name, startFrame, endFrame, fps );
  21749. this.setAnimationWeight( name, 1 );
  21750. }
  21751. MorphBlendMesh.prototype = Object.create( Mesh.prototype );
  21752. MorphBlendMesh.prototype.constructor = MorphBlendMesh;
  21753. MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  21754. var animation = {
  21755. start: start,
  21756. end: end,
  21757. length: end - start + 1,
  21758. fps: fps,
  21759. duration: ( end - start ) / fps,
  21760. lastFrame: 0,
  21761. currentFrame: 0,
  21762. active: false,
  21763. time: 0,
  21764. direction: 1,
  21765. weight: 1,
  21766. directionBackwards: false,
  21767. mirroredLoop: false
  21768. };
  21769. this.animationsMap[ name ] = animation;
  21770. this.animationsList.push( animation );
  21771. };
  21772. MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  21773. var pattern = /([a-z]+)_?(\d+)/i;
  21774. var firstAnimation, frameRanges = {};
  21775. var geometry = this.geometry;
  21776. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  21777. var morph = geometry.morphTargets[ i ];
  21778. var chunks = morph.name.match( pattern );
  21779. if ( chunks && chunks.length > 1 ) {
  21780. var name = chunks[ 1 ];
  21781. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: - Infinity };
  21782. var range = frameRanges[ name ];
  21783. if ( i < range.start ) range.start = i;
  21784. if ( i > range.end ) range.end = i;
  21785. if ( ! firstAnimation ) firstAnimation = name;
  21786. }
  21787. }
  21788. for ( var name in frameRanges ) {
  21789. var range = frameRanges[ name ];
  21790. this.createAnimation( name, range.start, range.end, fps );
  21791. }
  21792. this.firstAnimation = firstAnimation;
  21793. };
  21794. MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  21795. var animation = this.animationsMap[ name ];
  21796. if ( animation ) {
  21797. animation.direction = 1;
  21798. animation.directionBackwards = false;
  21799. }
  21800. };
  21801. MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  21802. var animation = this.animationsMap[ name ];
  21803. if ( animation ) {
  21804. animation.direction = - 1;
  21805. animation.directionBackwards = true;
  21806. }
  21807. };
  21808. MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  21809. var animation = this.animationsMap[ name ];
  21810. if ( animation ) {
  21811. animation.fps = fps;
  21812. animation.duration = ( animation.end - animation.start ) / animation.fps;
  21813. }
  21814. };
  21815. MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  21816. var animation = this.animationsMap[ name ];
  21817. if ( animation ) {
  21818. animation.duration = duration;
  21819. animation.fps = ( animation.end - animation.start ) / animation.duration;
  21820. }
  21821. };
  21822. MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  21823. var animation = this.animationsMap[ name ];
  21824. if ( animation ) {
  21825. animation.weight = weight;
  21826. }
  21827. };
  21828. MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  21829. var animation = this.animationsMap[ name ];
  21830. if ( animation ) {
  21831. animation.time = time;
  21832. }
  21833. };
  21834. MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  21835. var time = 0;
  21836. var animation = this.animationsMap[ name ];
  21837. if ( animation ) {
  21838. time = animation.time;
  21839. }
  21840. return time;
  21841. };
  21842. MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  21843. var duration = - 1;
  21844. var animation = this.animationsMap[ name ];
  21845. if ( animation ) {
  21846. duration = animation.duration;
  21847. }
  21848. return duration;
  21849. };
  21850. MorphBlendMesh.prototype.playAnimation = function ( name ) {
  21851. var animation = this.animationsMap[ name ];
  21852. if ( animation ) {
  21853. animation.time = 0;
  21854. animation.active = true;
  21855. } else {
  21856. console.warn( "THREE.MorphBlendMesh: animation[" + name + "] undefined in .playAnimation()" );
  21857. }
  21858. };
  21859. MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  21860. var animation = this.animationsMap[ name ];
  21861. if ( animation ) {
  21862. animation.active = false;
  21863. }
  21864. };
  21865. MorphBlendMesh.prototype.update = function ( delta ) {
  21866. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  21867. var animation = this.animationsList[ i ];
  21868. if ( ! animation.active ) continue;
  21869. var frameTime = animation.duration / animation.length;
  21870. animation.time += animation.direction * delta;
  21871. if ( animation.mirroredLoop ) {
  21872. if ( animation.time > animation.duration || animation.time < 0 ) {
  21873. animation.direction *= - 1;
  21874. if ( animation.time > animation.duration ) {
  21875. animation.time = animation.duration;
  21876. animation.directionBackwards = true;
  21877. }
  21878. if ( animation.time < 0 ) {
  21879. animation.time = 0;
  21880. animation.directionBackwards = false;
  21881. }
  21882. }
  21883. } else {
  21884. animation.time = animation.time % animation.duration;
  21885. if ( animation.time < 0 ) animation.time += animation.duration;
  21886. }
  21887. var keyframe = animation.start + exports.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  21888. var weight = animation.weight;
  21889. if ( keyframe !== animation.currentFrame ) {
  21890. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  21891. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  21892. this.morphTargetInfluences[ keyframe ] = 0;
  21893. animation.lastFrame = animation.currentFrame;
  21894. animation.currentFrame = keyframe;
  21895. }
  21896. var mix = ( animation.time % frameTime ) / frameTime;
  21897. if ( animation.directionBackwards ) mix = 1 - mix;
  21898. if ( animation.currentFrame !== animation.lastFrame ) {
  21899. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  21900. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  21901. } else {
  21902. this.morphTargetInfluences[ animation.currentFrame ] = weight;
  21903. }
  21904. }
  21905. };
  21906. /**
  21907. * @author alteredq / http://alteredqualia.com/
  21908. */
  21909. function ImmediateRenderObject( material ) {
  21910. Object3D.call( this );
  21911. this.material = material;
  21912. this.render = function ( renderCallback ) {};
  21913. }
  21914. ImmediateRenderObject.prototype = Object.create( Object3D.prototype );
  21915. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  21916. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  21917. /**
  21918. * @author mrdoob / http://mrdoob.com/
  21919. */
  21920. function WireframeGeometry( geometry ) {
  21921. BufferGeometry.call( this );
  21922. var edge = [ 0, 0 ], hash = {};
  21923. function sortFunction( a, b ) {
  21924. return a - b;
  21925. }
  21926. var keys = [ 'a', 'b', 'c' ];
  21927. if ( (geometry && geometry.isGeometry) ) {
  21928. var vertices = geometry.vertices;
  21929. var faces = geometry.faces;
  21930. var numEdges = 0;
  21931. // allocate maximal size
  21932. var edges = new Uint32Array( 6 * faces.length );
  21933. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21934. var face = faces[ i ];
  21935. for ( var j = 0; j < 3; j ++ ) {
  21936. edge[ 0 ] = face[ keys[ j ] ];
  21937. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  21938. edge.sort( sortFunction );
  21939. var key = edge.toString();
  21940. if ( hash[ key ] === undefined ) {
  21941. edges[ 2 * numEdges ] = edge[ 0 ];
  21942. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  21943. hash[ key ] = true;
  21944. numEdges ++;
  21945. }
  21946. }
  21947. }
  21948. var coords = new Float32Array( numEdges * 2 * 3 );
  21949. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  21950. for ( var j = 0; j < 2; j ++ ) {
  21951. var vertex = vertices[ edges [ 2 * i + j ] ];
  21952. var index = 6 * i + 3 * j;
  21953. coords[ index + 0 ] = vertex.x;
  21954. coords[ index + 1 ] = vertex.y;
  21955. coords[ index + 2 ] = vertex.z;
  21956. }
  21957. }
  21958. this.addAttribute( 'position', new BufferAttribute( coords, 3 ) );
  21959. } else if ( (geometry && geometry.isBufferGeometry) ) {
  21960. if ( geometry.index !== null ) {
  21961. // Indexed BufferGeometry
  21962. var indices = geometry.index.array;
  21963. var vertices = geometry.attributes.position;
  21964. var groups = geometry.groups;
  21965. var numEdges = 0;
  21966. if ( groups.length === 0 ) {
  21967. geometry.addGroup( 0, indices.length );
  21968. }
  21969. // allocate maximal size
  21970. var edges = new Uint32Array( 2 * indices.length );
  21971. for ( var o = 0, ol = groups.length; o < ol; ++ o ) {
  21972. var group = groups[ o ];
  21973. var start = group.start;
  21974. var count = group.count;
  21975. for ( var i = start, il = start + count; i < il; i += 3 ) {
  21976. for ( var j = 0; j < 3; j ++ ) {
  21977. edge[ 0 ] = indices[ i + j ];
  21978. edge[ 1 ] = indices[ i + ( j + 1 ) % 3 ];
  21979. edge.sort( sortFunction );
  21980. var key = edge.toString();
  21981. if ( hash[ key ] === undefined ) {
  21982. edges[ 2 * numEdges ] = edge[ 0 ];
  21983. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  21984. hash[ key ] = true;
  21985. numEdges ++;
  21986. }
  21987. }
  21988. }
  21989. }
  21990. var coords = new Float32Array( numEdges * 2 * 3 );
  21991. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  21992. for ( var j = 0; j < 2; j ++ ) {
  21993. var index = 6 * i + 3 * j;
  21994. var index2 = edges[ 2 * i + j ];
  21995. coords[ index + 0 ] = vertices.getX( index2 );
  21996. coords[ index + 1 ] = vertices.getY( index2 );
  21997. coords[ index + 2 ] = vertices.getZ( index2 );
  21998. }
  21999. }
  22000. this.addAttribute( 'position', new BufferAttribute( coords, 3 ) );
  22001. } else {
  22002. // non-indexed BufferGeometry
  22003. var vertices = geometry.attributes.position.array;
  22004. var numEdges = vertices.length / 3;
  22005. var numTris = numEdges / 3;
  22006. var coords = new Float32Array( numEdges * 2 * 3 );
  22007. for ( var i = 0, l = numTris; i < l; i ++ ) {
  22008. for ( var j = 0; j < 3; j ++ ) {
  22009. var index = 18 * i + 6 * j;
  22010. var index1 = 9 * i + 3 * j;
  22011. coords[ index + 0 ] = vertices[ index1 ];
  22012. coords[ index + 1 ] = vertices[ index1 + 1 ];
  22013. coords[ index + 2 ] = vertices[ index1 + 2 ];
  22014. var index2 = 9 * i + 3 * ( ( j + 1 ) % 3 );
  22015. coords[ index + 3 ] = vertices[ index2 ];
  22016. coords[ index + 4 ] = vertices[ index2 + 1 ];
  22017. coords[ index + 5 ] = vertices[ index2 + 2 ];
  22018. }
  22019. }
  22020. this.addAttribute( 'position', new BufferAttribute( coords, 3 ) );
  22021. }
  22022. }
  22023. }
  22024. WireframeGeometry.prototype = Object.create( BufferGeometry.prototype );
  22025. WireframeGeometry.prototype.constructor = WireframeGeometry;
  22026. /**
  22027. * @author mrdoob / http://mrdoob.com/
  22028. */
  22029. function WireframeHelper( object, hex ) {
  22030. var color = ( hex !== undefined ) ? hex : 0xffffff;
  22031. LineSegments.call( this, new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: color } ) );
  22032. this.matrix = object.matrixWorld;
  22033. this.matrixAutoUpdate = false;
  22034. }
  22035. WireframeHelper.prototype = Object.create( LineSegments.prototype );
  22036. WireframeHelper.prototype.constructor = WireframeHelper;
  22037. /**
  22038. * @author mrdoob / http://mrdoob.com/
  22039. * @author WestLangley / http://github.com/WestLangley
  22040. */
  22041. function VertexNormalsHelper( object, size, hex, linewidth ) {
  22042. this.object = object;
  22043. this.size = ( size !== undefined ) ? size : 1;
  22044. var color = ( hex !== undefined ) ? hex : 0xff0000;
  22045. var width = ( linewidth !== undefined ) ? linewidth : 1;
  22046. //
  22047. var nNormals = 0;
  22048. var objGeometry = this.object.geometry;
  22049. if ( (objGeometry && objGeometry.isGeometry) ) {
  22050. nNormals = objGeometry.faces.length * 3;
  22051. } else if ( (objGeometry && objGeometry.isBufferGeometry) ) {
  22052. nNormals = objGeometry.attributes.normal.count;
  22053. }
  22054. //
  22055. var geometry = new BufferGeometry();
  22056. var positions = new Float32Attribute( nNormals * 2 * 3, 3 );
  22057. geometry.addAttribute( 'position', positions );
  22058. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  22059. //
  22060. this.matrixAutoUpdate = false;
  22061. this.update();
  22062. }
  22063. VertexNormalsHelper.prototype = Object.create( LineSegments.prototype );
  22064. VertexNormalsHelper.prototype.constructor = VertexNormalsHelper;
  22065. VertexNormalsHelper.prototype.update = ( function () {
  22066. var v1 = new Vector3();
  22067. var v2 = new Vector3();
  22068. var normalMatrix = new Matrix3();
  22069. return function update() {
  22070. var keys = [ 'a', 'b', 'c' ];
  22071. this.object.updateMatrixWorld( true );
  22072. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  22073. var matrixWorld = this.object.matrixWorld;
  22074. var position = this.geometry.attributes.position;
  22075. //
  22076. var objGeometry = this.object.geometry;
  22077. if ( (objGeometry && objGeometry.isGeometry) ) {
  22078. var vertices = objGeometry.vertices;
  22079. var faces = objGeometry.faces;
  22080. var idx = 0;
  22081. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  22082. var face = faces[ i ];
  22083. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  22084. var vertex = vertices[ face[ keys[ j ] ] ];
  22085. var normal = face.vertexNormals[ j ];
  22086. v1.copy( vertex ).applyMatrix4( matrixWorld );
  22087. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  22088. position.setXYZ( idx, v1.x, v1.y, v1.z );
  22089. idx = idx + 1;
  22090. position.setXYZ( idx, v2.x, v2.y, v2.z );
  22091. idx = idx + 1;
  22092. }
  22093. }
  22094. } else if ( (objGeometry && objGeometry.isBufferGeometry) ) {
  22095. var objPos = objGeometry.attributes.position;
  22096. var objNorm = objGeometry.attributes.normal;
  22097. var idx = 0;
  22098. // for simplicity, ignore index and drawcalls, and render every normal
  22099. for ( var j = 0, jl = objPos.count; j < jl; j ++ ) {
  22100. v1.set( objPos.getX( j ), objPos.getY( j ), objPos.getZ( j ) ).applyMatrix4( matrixWorld );
  22101. v2.set( objNorm.getX( j ), objNorm.getY( j ), objNorm.getZ( j ) );
  22102. v2.applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  22103. position.setXYZ( idx, v1.x, v1.y, v1.z );
  22104. idx = idx + 1;
  22105. position.setXYZ( idx, v2.x, v2.y, v2.z );
  22106. idx = idx + 1;
  22107. }
  22108. }
  22109. position.needsUpdate = true;
  22110. return this;
  22111. };
  22112. }() );
  22113. /**
  22114. * @author alteredq / http://alteredqualia.com/
  22115. * @author mrdoob / http://mrdoob.com/
  22116. * @author WestLangley / http://github.com/WestLangley
  22117. */
  22118. function SpotLightHelper( light ) {
  22119. Object3D.call( this );
  22120. this.light = light;
  22121. this.light.updateMatrixWorld();
  22122. this.matrix = light.matrixWorld;
  22123. this.matrixAutoUpdate = false;
  22124. var geometry = new BufferGeometry();
  22125. var positions = [
  22126. 0, 0, 0, 0, 0, 1,
  22127. 0, 0, 0, 1, 0, 1,
  22128. 0, 0, 0, - 1, 0, 1,
  22129. 0, 0, 0, 0, 1, 1,
  22130. 0, 0, 0, 0, - 1, 1
  22131. ];
  22132. for ( var i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  22133. var p1 = ( i / l ) * Math.PI * 2;
  22134. var p2 = ( j / l ) * Math.PI * 2;
  22135. positions.push(
  22136. Math.cos( p1 ), Math.sin( p1 ), 1,
  22137. Math.cos( p2 ), Math.sin( p2 ), 1
  22138. );
  22139. }
  22140. geometry.addAttribute( 'position', new Float32Attribute( positions, 3 ) );
  22141. var material = new LineBasicMaterial( { fog: false } );
  22142. this.cone = new LineSegments( geometry, material );
  22143. this.add( this.cone );
  22144. this.update();
  22145. }
  22146. SpotLightHelper.prototype = Object.create( Object3D.prototype );
  22147. SpotLightHelper.prototype.constructor = SpotLightHelper;
  22148. SpotLightHelper.prototype.dispose = function () {
  22149. this.cone.geometry.dispose();
  22150. this.cone.material.dispose();
  22151. };
  22152. SpotLightHelper.prototype.update = function () {
  22153. var vector = new Vector3();
  22154. var vector2 = new Vector3();
  22155. return function update() {
  22156. var coneLength = this.light.distance ? this.light.distance : 1000;
  22157. var coneWidth = coneLength * Math.tan( this.light.angle );
  22158. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  22159. vector.setFromMatrixPosition( this.light.matrixWorld );
  22160. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  22161. this.cone.lookAt( vector2.sub( vector ) );
  22162. this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  22163. };
  22164. }();
  22165. /**
  22166. * @author Sean Griffin / http://twitter.com/sgrif
  22167. * @author Michael Guerrero / http://realitymeltdown.com
  22168. * @author mrdoob / http://mrdoob.com/
  22169. * @author ikerr / http://verold.com
  22170. */
  22171. function SkeletonHelper( object ) {
  22172. this.bones = this.getBoneList( object );
  22173. var geometry = new Geometry();
  22174. for ( var i = 0; i < this.bones.length; i ++ ) {
  22175. var bone = this.bones[ i ];
  22176. if ( (bone.parent && bone.parent.isBone) ) {
  22177. geometry.vertices.push( new Vector3() );
  22178. geometry.vertices.push( new Vector3() );
  22179. geometry.colors.push( new Color( 0, 0, 1 ) );
  22180. geometry.colors.push( new Color( 0, 1, 0 ) );
  22181. }
  22182. }
  22183. geometry.dynamic = true;
  22184. var material = new LineBasicMaterial( { vertexColors: VertexColors, depthTest: false, depthWrite: false, transparent: true } );
  22185. LineSegments.call( this, geometry, material );
  22186. this.root = object;
  22187. this.matrix = object.matrixWorld;
  22188. this.matrixAutoUpdate = false;
  22189. this.update();
  22190. }
  22191. SkeletonHelper.prototype = Object.create( LineSegments.prototype );
  22192. SkeletonHelper.prototype.constructor = SkeletonHelper;
  22193. SkeletonHelper.prototype.getBoneList = function( object ) {
  22194. var boneList = [];
  22195. if ( (object && object.isBone) ) {
  22196. boneList.push( object );
  22197. }
  22198. for ( var i = 0; i < object.children.length; i ++ ) {
  22199. boneList.push.apply( boneList, this.getBoneList( object.children[ i ] ) );
  22200. }
  22201. return boneList;
  22202. };
  22203. SkeletonHelper.prototype.update = function () {
  22204. var geometry = this.geometry;
  22205. var matrixWorldInv = new Matrix4().getInverse( this.root.matrixWorld );
  22206. var boneMatrix = new Matrix4();
  22207. var j = 0;
  22208. for ( var i = 0; i < this.bones.length; i ++ ) {
  22209. var bone = this.bones[ i ];
  22210. if ( (bone.parent && bone.parent.isBone) ) {
  22211. boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld );
  22212. geometry.vertices[ j ].setFromMatrixPosition( boneMatrix );
  22213. boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld );
  22214. geometry.vertices[ j + 1 ].setFromMatrixPosition( boneMatrix );
  22215. j += 2;
  22216. }
  22217. }
  22218. geometry.verticesNeedUpdate = true;
  22219. geometry.computeBoundingSphere();
  22220. };
  22221. /**
  22222. * @author benaadams / https://twitter.com/ben_a_adams
  22223. * based on THREE.SphereGeometry
  22224. */
  22225. function SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  22226. BufferGeometry.call( this );
  22227. this.type = 'SphereBufferGeometry';
  22228. this.parameters = {
  22229. radius: radius,
  22230. widthSegments: widthSegments,
  22231. heightSegments: heightSegments,
  22232. phiStart: phiStart,
  22233. phiLength: phiLength,
  22234. thetaStart: thetaStart,
  22235. thetaLength: thetaLength
  22236. };
  22237. radius = radius || 50;
  22238. widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  22239. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  22240. phiStart = phiStart !== undefined ? phiStart : 0;
  22241. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  22242. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  22243. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  22244. var thetaEnd = thetaStart + thetaLength;
  22245. var vertexCount = ( ( widthSegments + 1 ) * ( heightSegments + 1 ) );
  22246. var positions = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  22247. var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  22248. var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  22249. var index = 0, vertices = [], normal = new Vector3();
  22250. for ( var y = 0; y <= heightSegments; y ++ ) {
  22251. var verticesRow = [];
  22252. var v = y / heightSegments;
  22253. for ( var x = 0; x <= widthSegments; x ++ ) {
  22254. var u = x / widthSegments;
  22255. var px = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  22256. var py = radius * Math.cos( thetaStart + v * thetaLength );
  22257. var pz = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  22258. normal.set( px, py, pz ).normalize();
  22259. positions.setXYZ( index, px, py, pz );
  22260. normals.setXYZ( index, normal.x, normal.y, normal.z );
  22261. uvs.setXY( index, u, 1 - v );
  22262. verticesRow.push( index );
  22263. index ++;
  22264. }
  22265. vertices.push( verticesRow );
  22266. }
  22267. var indices = [];
  22268. for ( var y = 0; y < heightSegments; y ++ ) {
  22269. for ( var x = 0; x < widthSegments; x ++ ) {
  22270. var v1 = vertices[ y ][ x + 1 ];
  22271. var v2 = vertices[ y ][ x ];
  22272. var v3 = vertices[ y + 1 ][ x ];
  22273. var v4 = vertices[ y + 1 ][ x + 1 ];
  22274. if ( y !== 0 || thetaStart > 0 ) indices.push( v1, v2, v4 );
  22275. if ( y !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( v2, v3, v4 );
  22276. }
  22277. }
  22278. this.setIndex( new ( positions.count > 65535 ? Uint32Attribute : Uint16Attribute )( indices, 1 ) );
  22279. this.addAttribute( 'position', positions );
  22280. this.addAttribute( 'normal', normals );
  22281. this.addAttribute( 'uv', uvs );
  22282. this.boundingSphere = new Sphere( new Vector3(), radius );
  22283. }
  22284. SphereBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  22285. SphereBufferGeometry.prototype.constructor = SphereBufferGeometry;
  22286. /**
  22287. * @author alteredq / http://alteredqualia.com/
  22288. * @author mrdoob / http://mrdoob.com/
  22289. */
  22290. function PointLightHelper( light, sphereSize ) {
  22291. this.light = light;
  22292. this.light.updateMatrixWorld();
  22293. var geometry = new SphereBufferGeometry( sphereSize, 4, 2 );
  22294. var material = new MeshBasicMaterial( { wireframe: true, fog: false } );
  22295. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  22296. Mesh.call( this, geometry, material );
  22297. this.matrix = this.light.matrixWorld;
  22298. this.matrixAutoUpdate = false;
  22299. /*
  22300. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  22301. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  22302. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  22303. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  22304. var d = light.distance;
  22305. if ( d === 0.0 ) {
  22306. this.lightDistance.visible = false;
  22307. } else {
  22308. this.lightDistance.scale.set( d, d, d );
  22309. }
  22310. this.add( this.lightDistance );
  22311. */
  22312. }
  22313. PointLightHelper.prototype = Object.create( Mesh.prototype );
  22314. PointLightHelper.prototype.constructor = PointLightHelper;
  22315. PointLightHelper.prototype.dispose = function () {
  22316. this.geometry.dispose();
  22317. this.material.dispose();
  22318. };
  22319. PointLightHelper.prototype.update = function () {
  22320. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  22321. /*
  22322. var d = this.light.distance;
  22323. if ( d === 0.0 ) {
  22324. this.lightDistance.visible = false;
  22325. } else {
  22326. this.lightDistance.visible = true;
  22327. this.lightDistance.scale.set( d, d, d );
  22328. }
  22329. */
  22330. };
  22331. /**
  22332. * @author mrdoob / http://mrdoob.com/
  22333. */
  22334. function SphereGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  22335. Geometry.call( this );
  22336. this.type = 'SphereGeometry';
  22337. this.parameters = {
  22338. radius: radius,
  22339. widthSegments: widthSegments,
  22340. heightSegments: heightSegments,
  22341. phiStart: phiStart,
  22342. phiLength: phiLength,
  22343. thetaStart: thetaStart,
  22344. thetaLength: thetaLength
  22345. };
  22346. this.fromBufferGeometry( new SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) );
  22347. }
  22348. SphereGeometry.prototype = Object.create( Geometry.prototype );
  22349. SphereGeometry.prototype.constructor = SphereGeometry;
  22350. /**
  22351. * @author alteredq / http://alteredqualia.com/
  22352. * @author mrdoob / http://mrdoob.com/
  22353. */
  22354. function HemisphereLightHelper( light, sphereSize ) {
  22355. Object3D.call( this );
  22356. this.light = light;
  22357. this.light.updateMatrixWorld();
  22358. this.matrix = light.matrixWorld;
  22359. this.matrixAutoUpdate = false;
  22360. this.colors = [ new Color(), new Color() ];
  22361. var geometry = new SphereGeometry( sphereSize, 4, 2 );
  22362. geometry.rotateX( - Math.PI / 2 );
  22363. for ( var i = 0, il = 8; i < il; i ++ ) {
  22364. geometry.faces[ i ].color = this.colors[ i < 4 ? 0 : 1 ];
  22365. }
  22366. var material = new MeshBasicMaterial( { vertexColors: FaceColors, wireframe: true } );
  22367. this.lightSphere = new Mesh( geometry, material );
  22368. this.add( this.lightSphere );
  22369. this.update();
  22370. }
  22371. HemisphereLightHelper.prototype = Object.create( Object3D.prototype );
  22372. HemisphereLightHelper.prototype.constructor = HemisphereLightHelper;
  22373. HemisphereLightHelper.prototype.dispose = function () {
  22374. this.lightSphere.geometry.dispose();
  22375. this.lightSphere.material.dispose();
  22376. };
  22377. HemisphereLightHelper.prototype.update = function () {
  22378. var vector = new Vector3();
  22379. return function update() {
  22380. this.colors[ 0 ].copy( this.light.color ).multiplyScalar( this.light.intensity );
  22381. this.colors[ 1 ].copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  22382. this.lightSphere.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  22383. this.lightSphere.geometry.colorsNeedUpdate = true;
  22384. };
  22385. }();
  22386. /**
  22387. * @author mrdoob / http://mrdoob.com/
  22388. */
  22389. function GridHelper( size, divisions, color1, color2 ) {
  22390. divisions = divisions || 1;
  22391. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  22392. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  22393. var center = divisions / 2;
  22394. var step = ( size * 2 ) / divisions;
  22395. var vertices = [], colors = [];
  22396. for ( var i = 0, j = 0, k = - size; i <= divisions; i ++, k += step ) {
  22397. vertices.push( - size, 0, k, size, 0, k );
  22398. vertices.push( k, 0, - size, k, 0, size );
  22399. var color = i === center ? color1 : color2;
  22400. color.toArray( colors, j ); j += 3;
  22401. color.toArray( colors, j ); j += 3;
  22402. color.toArray( colors, j ); j += 3;
  22403. color.toArray( colors, j ); j += 3;
  22404. }
  22405. var geometry = new BufferGeometry();
  22406. geometry.addAttribute( 'position', new Float32Attribute( vertices, 3 ) );
  22407. geometry.addAttribute( 'color', new Float32Attribute( colors, 3 ) );
  22408. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  22409. LineSegments.call( this, geometry, material );
  22410. }
  22411. GridHelper.prototype = Object.create( LineSegments.prototype );
  22412. GridHelper.prototype.constructor = GridHelper;
  22413. GridHelper.prototype.setColors = function () {
  22414. console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' );
  22415. };
  22416. /**
  22417. * @author mrdoob / http://mrdoob.com/
  22418. * @author WestLangley / http://github.com/WestLangley
  22419. */
  22420. function FaceNormalsHelper( object, size, hex, linewidth ) {
  22421. // FaceNormalsHelper only supports THREE.Geometry
  22422. this.object = object;
  22423. this.size = ( size !== undefined ) ? size : 1;
  22424. var color = ( hex !== undefined ) ? hex : 0xffff00;
  22425. var width = ( linewidth !== undefined ) ? linewidth : 1;
  22426. //
  22427. var nNormals = 0;
  22428. var objGeometry = this.object.geometry;
  22429. if ( (objGeometry && objGeometry.isGeometry) ) {
  22430. nNormals = objGeometry.faces.length;
  22431. } else {
  22432. console.warn( 'THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.' );
  22433. }
  22434. //
  22435. var geometry = new BufferGeometry();
  22436. var positions = new Float32Attribute( nNormals * 2 * 3, 3 );
  22437. geometry.addAttribute( 'position', positions );
  22438. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  22439. //
  22440. this.matrixAutoUpdate = false;
  22441. this.update();
  22442. }
  22443. FaceNormalsHelper.prototype = Object.create( LineSegments.prototype );
  22444. FaceNormalsHelper.prototype.constructor = FaceNormalsHelper;
  22445. FaceNormalsHelper.prototype.update = ( function () {
  22446. var v1 = new Vector3();
  22447. var v2 = new Vector3();
  22448. var normalMatrix = new Matrix3();
  22449. return function update() {
  22450. this.object.updateMatrixWorld( true );
  22451. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  22452. var matrixWorld = this.object.matrixWorld;
  22453. var position = this.geometry.attributes.position;
  22454. //
  22455. var objGeometry = this.object.geometry;
  22456. var vertices = objGeometry.vertices;
  22457. var faces = objGeometry.faces;
  22458. var idx = 0;
  22459. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  22460. var face = faces[ i ];
  22461. var normal = face.normal;
  22462. v1.copy( vertices[ face.a ] )
  22463. .add( vertices[ face.b ] )
  22464. .add( vertices[ face.c ] )
  22465. .divideScalar( 3 )
  22466. .applyMatrix4( matrixWorld );
  22467. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  22468. position.setXYZ( idx, v1.x, v1.y, v1.z );
  22469. idx = idx + 1;
  22470. position.setXYZ( idx, v2.x, v2.y, v2.z );
  22471. idx = idx + 1;
  22472. }
  22473. position.needsUpdate = true;
  22474. return this;
  22475. };
  22476. }() );
  22477. /**
  22478. * @author WestLangley / http://github.com/WestLangley
  22479. */
  22480. function EdgesGeometry( geometry, thresholdAngle ) {
  22481. BufferGeometry.call( this );
  22482. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  22483. var thresholdDot = Math.cos( exports.Math.DEG2RAD * thresholdAngle );
  22484. var edge = [ 0, 0 ], hash = {};
  22485. function sortFunction( a, b ) {
  22486. return a - b;
  22487. }
  22488. var keys = [ 'a', 'b', 'c' ];
  22489. var geometry2;
  22490. if ( (geometry && geometry.isBufferGeometry) ) {
  22491. geometry2 = new Geometry();
  22492. geometry2.fromBufferGeometry( geometry );
  22493. } else {
  22494. geometry2 = geometry.clone();
  22495. }
  22496. geometry2.mergeVertices();
  22497. geometry2.computeFaceNormals();
  22498. var vertices = geometry2.vertices;
  22499. var faces = geometry2.faces;
  22500. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  22501. var face = faces[ i ];
  22502. for ( var j = 0; j < 3; j ++ ) {
  22503. edge[ 0 ] = face[ keys[ j ] ];
  22504. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  22505. edge.sort( sortFunction );
  22506. var key = edge.toString();
  22507. if ( hash[ key ] === undefined ) {
  22508. hash[ key ] = { vert1: edge[ 0 ], vert2: edge[ 1 ], face1: i, face2: undefined };
  22509. } else {
  22510. hash[ key ].face2 = i;
  22511. }
  22512. }
  22513. }
  22514. var coords = [];
  22515. for ( var key in hash ) {
  22516. var h = hash[ key ];
  22517. if ( h.face2 === undefined || faces[ h.face1 ].normal.dot( faces[ h.face2 ].normal ) <= thresholdDot ) {
  22518. var vertex = vertices[ h.vert1 ];
  22519. coords.push( vertex.x );
  22520. coords.push( vertex.y );
  22521. coords.push( vertex.z );
  22522. vertex = vertices[ h.vert2 ];
  22523. coords.push( vertex.x );
  22524. coords.push( vertex.y );
  22525. coords.push( vertex.z );
  22526. }
  22527. }
  22528. this.addAttribute( 'position', new BufferAttribute( new Float32Array( coords ), 3 ) );
  22529. }
  22530. EdgesGeometry.prototype = Object.create( BufferGeometry.prototype );
  22531. EdgesGeometry.prototype.constructor = EdgesGeometry;
  22532. /**
  22533. * @author WestLangley / http://github.com/WestLangley
  22534. * @param object THREE.Mesh whose geometry will be used
  22535. * @param hex line color
  22536. * @param thresholdAngle the minimum angle (in degrees),
  22537. * between the face normals of adjacent faces,
  22538. * that is required to render an edge. A value of 10 means
  22539. * an edge is only rendered if the angle is at least 10 degrees.
  22540. */
  22541. function EdgesHelper( object, hex, thresholdAngle ) {
  22542. var color = ( hex !== undefined ) ? hex : 0xffffff;
  22543. LineSegments.call( this, new EdgesGeometry( object.geometry, thresholdAngle ), new LineBasicMaterial( { color: color } ) );
  22544. this.matrix = object.matrixWorld;
  22545. this.matrixAutoUpdate = false;
  22546. }
  22547. EdgesHelper.prototype = Object.create( LineSegments.prototype );
  22548. EdgesHelper.prototype.constructor = EdgesHelper;
  22549. /**
  22550. * @author alteredq / http://alteredqualia.com/
  22551. * @author mrdoob / http://mrdoob.com/
  22552. * @author WestLangley / http://github.com/WestLangley
  22553. */
  22554. function DirectionalLightHelper( light, size ) {
  22555. Object3D.call( this );
  22556. this.light = light;
  22557. this.light.updateMatrixWorld();
  22558. this.matrix = light.matrixWorld;
  22559. this.matrixAutoUpdate = false;
  22560. if ( size === undefined ) size = 1;
  22561. var geometry = new BufferGeometry();
  22562. geometry.addAttribute( 'position', new Float32Attribute( [
  22563. - size, size, 0,
  22564. size, size, 0,
  22565. size, - size, 0,
  22566. - size, - size, 0,
  22567. - size, size, 0
  22568. ], 3 ) );
  22569. var material = new LineBasicMaterial( { fog: false } );
  22570. this.add( new Line( geometry, material ) );
  22571. geometry = new BufferGeometry();
  22572. geometry.addAttribute( 'position', new Float32Attribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  22573. this.add( new Line( geometry, material ));
  22574. this.update();
  22575. }
  22576. DirectionalLightHelper.prototype = Object.create( Object3D.prototype );
  22577. DirectionalLightHelper.prototype.constructor = DirectionalLightHelper;
  22578. DirectionalLightHelper.prototype.dispose = function () {
  22579. var lightPlane = this.children[ 0 ];
  22580. var targetLine = this.children[ 1 ];
  22581. lightPlane.geometry.dispose();
  22582. lightPlane.material.dispose();
  22583. targetLine.geometry.dispose();
  22584. targetLine.material.dispose();
  22585. };
  22586. DirectionalLightHelper.prototype.update = function () {
  22587. var v1 = new Vector3();
  22588. var v2 = new Vector3();
  22589. var v3 = new Vector3();
  22590. return function update() {
  22591. v1.setFromMatrixPosition( this.light.matrixWorld );
  22592. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  22593. v3.subVectors( v2, v1 );
  22594. var lightPlane = this.children[ 0 ];
  22595. var targetLine = this.children[ 1 ];
  22596. lightPlane.lookAt( v3 );
  22597. lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  22598. targetLine.lookAt( v3 );
  22599. targetLine.scale.z = v3.length();
  22600. };
  22601. }();
  22602. /**
  22603. * @author alteredq / http://alteredqualia.com/
  22604. *
  22605. * - shows frustum, line of sight and up of the camera
  22606. * - suitable for fast updates
  22607. * - based on frustum visualization in lightgl.js shadowmap example
  22608. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  22609. */
  22610. function CameraHelper( camera ) {
  22611. var geometry = new Geometry();
  22612. var material = new LineBasicMaterial( { color: 0xffffff, vertexColors: FaceColors } );
  22613. var pointMap = {};
  22614. // colors
  22615. var hexFrustum = 0xffaa00;
  22616. var hexCone = 0xff0000;
  22617. var hexUp = 0x00aaff;
  22618. var hexTarget = 0xffffff;
  22619. var hexCross = 0x333333;
  22620. // near
  22621. addLine( "n1", "n2", hexFrustum );
  22622. addLine( "n2", "n4", hexFrustum );
  22623. addLine( "n4", "n3", hexFrustum );
  22624. addLine( "n3", "n1", hexFrustum );
  22625. // far
  22626. addLine( "f1", "f2", hexFrustum );
  22627. addLine( "f2", "f4", hexFrustum );
  22628. addLine( "f4", "f3", hexFrustum );
  22629. addLine( "f3", "f1", hexFrustum );
  22630. // sides
  22631. addLine( "n1", "f1", hexFrustum );
  22632. addLine( "n2", "f2", hexFrustum );
  22633. addLine( "n3", "f3", hexFrustum );
  22634. addLine( "n4", "f4", hexFrustum );
  22635. // cone
  22636. addLine( "p", "n1", hexCone );
  22637. addLine( "p", "n2", hexCone );
  22638. addLine( "p", "n3", hexCone );
  22639. addLine( "p", "n4", hexCone );
  22640. // up
  22641. addLine( "u1", "u2", hexUp );
  22642. addLine( "u2", "u3", hexUp );
  22643. addLine( "u3", "u1", hexUp );
  22644. // target
  22645. addLine( "c", "t", hexTarget );
  22646. addLine( "p", "c", hexCross );
  22647. // cross
  22648. addLine( "cn1", "cn2", hexCross );
  22649. addLine( "cn3", "cn4", hexCross );
  22650. addLine( "cf1", "cf2", hexCross );
  22651. addLine( "cf3", "cf4", hexCross );
  22652. function addLine( a, b, hex ) {
  22653. addPoint( a, hex );
  22654. addPoint( b, hex );
  22655. }
  22656. function addPoint( id, hex ) {
  22657. geometry.vertices.push( new Vector3() );
  22658. geometry.colors.push( new Color( hex ) );
  22659. if ( pointMap[ id ] === undefined ) {
  22660. pointMap[ id ] = [];
  22661. }
  22662. pointMap[ id ].push( geometry.vertices.length - 1 );
  22663. }
  22664. LineSegments.call( this, geometry, material );
  22665. this.camera = camera;
  22666. if( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  22667. this.matrix = camera.matrixWorld;
  22668. this.matrixAutoUpdate = false;
  22669. this.pointMap = pointMap;
  22670. this.update();
  22671. }
  22672. CameraHelper.prototype = Object.create( LineSegments.prototype );
  22673. CameraHelper.prototype.constructor = CameraHelper;
  22674. CameraHelper.prototype.update = function () {
  22675. var geometry, pointMap;
  22676. var vector = new Vector3();
  22677. var camera = new Camera();
  22678. function setPoint( point, x, y, z ) {
  22679. vector.set( x, y, z ).unproject( camera );
  22680. var points = pointMap[ point ];
  22681. if ( points !== undefined ) {
  22682. for ( var i = 0, il = points.length; i < il; i ++ ) {
  22683. geometry.vertices[ points[ i ] ].copy( vector );
  22684. }
  22685. }
  22686. }
  22687. return function update() {
  22688. geometry = this.geometry;
  22689. pointMap = this.pointMap;
  22690. var w = 1, h = 1;
  22691. // we need just camera projection matrix
  22692. // world matrix must be identity
  22693. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  22694. // center / target
  22695. setPoint( "c", 0, 0, - 1 );
  22696. setPoint( "t", 0, 0, 1 );
  22697. // near
  22698. setPoint( "n1", - w, - h, - 1 );
  22699. setPoint( "n2", w, - h, - 1 );
  22700. setPoint( "n3", - w, h, - 1 );
  22701. setPoint( "n4", w, h, - 1 );
  22702. // far
  22703. setPoint( "f1", - w, - h, 1 );
  22704. setPoint( "f2", w, - h, 1 );
  22705. setPoint( "f3", - w, h, 1 );
  22706. setPoint( "f4", w, h, 1 );
  22707. // up
  22708. setPoint( "u1", w * 0.7, h * 1.1, - 1 );
  22709. setPoint( "u2", - w * 0.7, h * 1.1, - 1 );
  22710. setPoint( "u3", 0, h * 2, - 1 );
  22711. // cross
  22712. setPoint( "cf1", - w, 0, 1 );
  22713. setPoint( "cf2", w, 0, 1 );
  22714. setPoint( "cf3", 0, - h, 1 );
  22715. setPoint( "cf4", 0, h, 1 );
  22716. setPoint( "cn1", - w, 0, - 1 );
  22717. setPoint( "cn2", w, 0, - 1 );
  22718. setPoint( "cn3", 0, - h, - 1 );
  22719. setPoint( "cn4", 0, h, - 1 );
  22720. geometry.verticesNeedUpdate = true;
  22721. };
  22722. }();
  22723. /**
  22724. * @author mrdoob / http://mrdoob.com/
  22725. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  22726. */
  22727. function BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  22728. Geometry.call( this );
  22729. this.type = 'BoxGeometry';
  22730. this.parameters = {
  22731. width: width,
  22732. height: height,
  22733. depth: depth,
  22734. widthSegments: widthSegments,
  22735. heightSegments: heightSegments,
  22736. depthSegments: depthSegments
  22737. };
  22738. this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) );
  22739. this.mergeVertices();
  22740. }
  22741. BoxGeometry.prototype = Object.create( Geometry.prototype );
  22742. BoxGeometry.prototype.constructor = BoxGeometry;
  22743. /**
  22744. * @author WestLangley / http://github.com/WestLangley
  22745. */
  22746. // a helper to show the world-axis-aligned bounding box for an object
  22747. function BoundingBoxHelper( object, hex ) {
  22748. var color = ( hex !== undefined ) ? hex : 0x888888;
  22749. this.object = object;
  22750. this.box = new Box3();
  22751. Mesh.call( this, new BoxGeometry( 1, 1, 1 ), new MeshBasicMaterial( { color: color, wireframe: true } ) );
  22752. }
  22753. BoundingBoxHelper.prototype = Object.create( Mesh.prototype );
  22754. BoundingBoxHelper.prototype.constructor = BoundingBoxHelper;
  22755. BoundingBoxHelper.prototype.update = function () {
  22756. this.box.setFromObject( this.object );
  22757. this.box.size( this.scale );
  22758. this.box.center( this.position );
  22759. };
  22760. /**
  22761. * @author mrdoob / http://mrdoob.com/
  22762. */
  22763. function BoxHelper( object, color ) {
  22764. if ( color === undefined ) color = 0xffff00;
  22765. 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 ] );
  22766. var positions = new Float32Array( 8 * 3 );
  22767. var geometry = new BufferGeometry();
  22768. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  22769. geometry.addAttribute( 'position', new BufferAttribute( positions, 3 ) );
  22770. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  22771. if ( object !== undefined ) {
  22772. this.update( object );
  22773. }
  22774. }
  22775. BoxHelper.prototype = Object.create( LineSegments.prototype );
  22776. BoxHelper.prototype.constructor = BoxHelper;
  22777. BoxHelper.prototype.update = ( function () {
  22778. var box = new Box3();
  22779. return function update( object ) {
  22780. if ( (object && object.isBox3) ) {
  22781. box.copy( object );
  22782. } else {
  22783. box.setFromObject( object );
  22784. }
  22785. if ( box.isEmpty() ) return;
  22786. var min = box.min;
  22787. var max = box.max;
  22788. /*
  22789. 5____4
  22790. 1/___0/|
  22791. | 6__|_7
  22792. 2/___3/
  22793. 0: max.x, max.y, max.z
  22794. 1: min.x, max.y, max.z
  22795. 2: min.x, min.y, max.z
  22796. 3: max.x, min.y, max.z
  22797. 4: max.x, max.y, min.z
  22798. 5: min.x, max.y, min.z
  22799. 6: min.x, min.y, min.z
  22800. 7: max.x, min.y, min.z
  22801. */
  22802. var position = this.geometry.attributes.position;
  22803. var array = position.array;
  22804. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  22805. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  22806. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  22807. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  22808. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  22809. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  22810. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  22811. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  22812. position.needsUpdate = true;
  22813. this.geometry.computeBoundingSphere();
  22814. };
  22815. } )();
  22816. /**
  22817. * @author Mugen87 / https://github.com/Mugen87
  22818. */
  22819. function CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  22820. BufferGeometry.call( this );
  22821. this.type = 'CylinderBufferGeometry';
  22822. this.parameters = {
  22823. radiusTop: radiusTop,
  22824. radiusBottom: radiusBottom,
  22825. height: height,
  22826. radialSegments: radialSegments,
  22827. heightSegments: heightSegments,
  22828. openEnded: openEnded,
  22829. thetaStart: thetaStart,
  22830. thetaLength: thetaLength
  22831. };
  22832. var scope = this;
  22833. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  22834. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  22835. height = height !== undefined ? height : 100;
  22836. radialSegments = Math.floor( radialSegments ) || 8;
  22837. heightSegments = Math.floor( heightSegments ) || 1;
  22838. openEnded = openEnded !== undefined ? openEnded : false;
  22839. thetaStart = thetaStart !== undefined ? thetaStart : 0.0;
  22840. thetaLength = thetaLength !== undefined ? thetaLength : 2.0 * Math.PI;
  22841. // used to calculate buffer length
  22842. var nbCap = 0;
  22843. if ( openEnded === false ) {
  22844. if ( radiusTop > 0 ) nbCap ++;
  22845. if ( radiusBottom > 0 ) nbCap ++;
  22846. }
  22847. var vertexCount = calculateVertexCount();
  22848. var indexCount = calculateIndexCount();
  22849. // buffers
  22850. var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ), 1 );
  22851. var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  22852. var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  22853. var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  22854. // helper variables
  22855. var index = 0,
  22856. indexOffset = 0,
  22857. indexArray = [],
  22858. halfHeight = height / 2;
  22859. // group variables
  22860. var groupStart = 0;
  22861. // generate geometry
  22862. generateTorso();
  22863. if ( openEnded === false ) {
  22864. if ( radiusTop > 0 ) generateCap( true );
  22865. if ( radiusBottom > 0 ) generateCap( false );
  22866. }
  22867. // build geometry
  22868. this.setIndex( indices );
  22869. this.addAttribute( 'position', vertices );
  22870. this.addAttribute( 'normal', normals );
  22871. this.addAttribute( 'uv', uvs );
  22872. // helper functions
  22873. function calculateVertexCount() {
  22874. var count = ( radialSegments + 1 ) * ( heightSegments + 1 );
  22875. if ( openEnded === false ) {
  22876. count += ( ( radialSegments + 1 ) * nbCap ) + ( radialSegments * nbCap );
  22877. }
  22878. return count;
  22879. }
  22880. function calculateIndexCount() {
  22881. var count = radialSegments * heightSegments * 2 * 3;
  22882. if ( openEnded === false ) {
  22883. count += radialSegments * nbCap * 3;
  22884. }
  22885. return count;
  22886. }
  22887. function generateTorso() {
  22888. var x, y;
  22889. var normal = new Vector3();
  22890. var vertex = new Vector3();
  22891. var groupCount = 0;
  22892. // this will be used to calculate the normal
  22893. var tanTheta = ( radiusBottom - radiusTop ) / height;
  22894. // generate vertices, normals and uvs
  22895. for ( y = 0; y <= heightSegments; y ++ ) {
  22896. var indexRow = [];
  22897. var v = y / heightSegments;
  22898. // calculate the radius of the current row
  22899. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  22900. for ( x = 0; x <= radialSegments; x ++ ) {
  22901. var u = x / radialSegments;
  22902. // vertex
  22903. vertex.x = radius * Math.sin( u * thetaLength + thetaStart );
  22904. vertex.y = - v * height + halfHeight;
  22905. vertex.z = radius * Math.cos( u * thetaLength + thetaStart );
  22906. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  22907. // normal
  22908. normal.copy( vertex );
  22909. // handle special case if radiusTop/radiusBottom is zero
  22910. if ( ( radiusTop === 0 && y === 0 ) || ( radiusBottom === 0 && y === heightSegments ) ) {
  22911. normal.x = Math.sin( u * thetaLength + thetaStart );
  22912. normal.z = Math.cos( u * thetaLength + thetaStart );
  22913. }
  22914. normal.setY( Math.sqrt( normal.x * normal.x + normal.z * normal.z ) * tanTheta ).normalize();
  22915. normals.setXYZ( index, normal.x, normal.y, normal.z );
  22916. // uv
  22917. uvs.setXY( index, u, 1 - v );
  22918. // save index of vertex in respective row
  22919. indexRow.push( index );
  22920. // increase index
  22921. index ++;
  22922. }
  22923. // now save vertices of the row in our index array
  22924. indexArray.push( indexRow );
  22925. }
  22926. // generate indices
  22927. for ( x = 0; x < radialSegments; x ++ ) {
  22928. for ( y = 0; y < heightSegments; y ++ ) {
  22929. // we use the index array to access the correct indices
  22930. var i1 = indexArray[ y ][ x ];
  22931. var i2 = indexArray[ y + 1 ][ x ];
  22932. var i3 = indexArray[ y + 1 ][ x + 1 ];
  22933. var i4 = indexArray[ y ][ x + 1 ];
  22934. // face one
  22935. indices.setX( indexOffset, i1 ); indexOffset ++;
  22936. indices.setX( indexOffset, i2 ); indexOffset ++;
  22937. indices.setX( indexOffset, i4 ); indexOffset ++;
  22938. // face two
  22939. indices.setX( indexOffset, i2 ); indexOffset ++;
  22940. indices.setX( indexOffset, i3 ); indexOffset ++;
  22941. indices.setX( indexOffset, i4 ); indexOffset ++;
  22942. // update counters
  22943. groupCount += 6;
  22944. }
  22945. }
  22946. // add a group to the geometry. this will ensure multi material support
  22947. scope.addGroup( groupStart, groupCount, 0 );
  22948. // calculate new start value for groups
  22949. groupStart += groupCount;
  22950. }
  22951. function generateCap( top ) {
  22952. var x, centerIndexStart, centerIndexEnd;
  22953. var uv = new Vector2();
  22954. var vertex = new Vector3();
  22955. var groupCount = 0;
  22956. var radius = ( top === true ) ? radiusTop : radiusBottom;
  22957. var sign = ( top === true ) ? 1 : - 1;
  22958. // save the index of the first center vertex
  22959. centerIndexStart = index;
  22960. // first we generate the center vertex data of the cap.
  22961. // because the geometry needs one set of uvs per face,
  22962. // we must generate a center vertex per face/segment
  22963. for ( x = 1; x <= radialSegments; x ++ ) {
  22964. // vertex
  22965. vertices.setXYZ( index, 0, halfHeight * sign, 0 );
  22966. // normal
  22967. normals.setXYZ( index, 0, sign, 0 );
  22968. // uv
  22969. uv.x = 0.5;
  22970. uv.y = 0.5;
  22971. uvs.setXY( index, uv.x, uv.y );
  22972. // increase index
  22973. index ++;
  22974. }
  22975. // save the index of the last center vertex
  22976. centerIndexEnd = index;
  22977. // now we generate the surrounding vertices, normals and uvs
  22978. for ( x = 0; x <= radialSegments; x ++ ) {
  22979. var u = x / radialSegments;
  22980. var theta = u * thetaLength + thetaStart;
  22981. var cosTheta = Math.cos( theta );
  22982. var sinTheta = Math.sin( theta );
  22983. // vertex
  22984. vertex.x = radius * sinTheta;
  22985. vertex.y = halfHeight * sign;
  22986. vertex.z = radius * cosTheta;
  22987. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  22988. // normal
  22989. normals.setXYZ( index, 0, sign, 0 );
  22990. // uv
  22991. uv.x = ( cosTheta * 0.5 ) + 0.5;
  22992. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  22993. uvs.setXY( index, uv.x, uv.y );
  22994. // increase index
  22995. index ++;
  22996. }
  22997. // generate indices
  22998. for ( x = 0; x < radialSegments; x ++ ) {
  22999. var c = centerIndexStart + x;
  23000. var i = centerIndexEnd + x;
  23001. if ( top === true ) {
  23002. // face top
  23003. indices.setX( indexOffset, i ); indexOffset ++;
  23004. indices.setX( indexOffset, i + 1 ); indexOffset ++;
  23005. indices.setX( indexOffset, c ); indexOffset ++;
  23006. } else {
  23007. // face bottom
  23008. indices.setX( indexOffset, i + 1 ); indexOffset ++;
  23009. indices.setX( indexOffset, i ); indexOffset ++;
  23010. indices.setX( indexOffset, c ); indexOffset ++;
  23011. }
  23012. // update counters
  23013. groupCount += 3;
  23014. }
  23015. // add a group to the geometry. this will ensure multi material support
  23016. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  23017. // calculate new start value for groups
  23018. groupStart += groupCount;
  23019. }
  23020. }
  23021. CylinderBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  23022. CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry;
  23023. /**
  23024. * @author WestLangley / http://github.com/WestLangley
  23025. * @author zz85 / http://github.com/zz85
  23026. * @author bhouston / http://clara.io
  23027. *
  23028. * Creates an arrow for visualizing directions
  23029. *
  23030. * Parameters:
  23031. * dir - Vector3
  23032. * origin - Vector3
  23033. * length - Number
  23034. * color - color in hex value
  23035. * headLength - Number
  23036. * headWidth - Number
  23037. */
  23038. exports.ArrowHelper = ( function () {
  23039. var lineGeometry = new BufferGeometry();
  23040. lineGeometry.addAttribute( 'position', new Float32Attribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  23041. var coneGeometry = new CylinderBufferGeometry( 0, 0.5, 1, 5, 1 );
  23042. coneGeometry.translate( 0, - 0.5, 0 );
  23043. return function ArrowHelper( dir, origin, length, color, headLength, headWidth ) {
  23044. // dir is assumed to be normalized
  23045. Object3D.call( this );
  23046. if ( color === undefined ) color = 0xffff00;
  23047. if ( length === undefined ) length = 1;
  23048. if ( headLength === undefined ) headLength = 0.2 * length;
  23049. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  23050. this.position.copy( origin );
  23051. this.line = new Line( lineGeometry, new LineBasicMaterial( { color: color } ) );
  23052. this.line.matrixAutoUpdate = false;
  23053. this.add( this.line );
  23054. this.cone = new Mesh( coneGeometry, new MeshBasicMaterial( { color: color } ) );
  23055. this.cone.matrixAutoUpdate = false;
  23056. this.add( this.cone );
  23057. this.setDirection( dir );
  23058. this.setLength( length, headLength, headWidth );
  23059. };
  23060. }() );
  23061. exports.ArrowHelper.prototype = Object.create( Object3D.prototype );
  23062. exports.ArrowHelper.prototype.constructor = exports.ArrowHelper;
  23063. exports.ArrowHelper.prototype.setDirection = ( function () {
  23064. var axis = new Vector3();
  23065. var radians;
  23066. return function setDirection( dir ) {
  23067. // dir is assumed to be normalized
  23068. if ( dir.y > 0.99999 ) {
  23069. this.quaternion.set( 0, 0, 0, 1 );
  23070. } else if ( dir.y < - 0.99999 ) {
  23071. this.quaternion.set( 1, 0, 0, 0 );
  23072. } else {
  23073. axis.set( dir.z, 0, - dir.x ).normalize();
  23074. radians = Math.acos( dir.y );
  23075. this.quaternion.setFromAxisAngle( axis, radians );
  23076. }
  23077. };
  23078. }() );
  23079. exports.ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  23080. if ( headLength === undefined ) headLength = 0.2 * length;
  23081. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  23082. this.line.scale.set( 1, Math.max( 0, length - headLength ), 1 );
  23083. this.line.updateMatrix();
  23084. this.cone.scale.set( headWidth, headLength, headWidth );
  23085. this.cone.position.y = length;
  23086. this.cone.updateMatrix();
  23087. };
  23088. exports.ArrowHelper.prototype.setColor = function ( color ) {
  23089. this.line.material.color.copy( color );
  23090. this.cone.material.color.copy( color );
  23091. };
  23092. /**
  23093. * @author sroucheray / http://sroucheray.org/
  23094. * @author mrdoob / http://mrdoob.com/
  23095. */
  23096. function AxisHelper( size ) {
  23097. size = size || 1;
  23098. var vertices = new Float32Array( [
  23099. 0, 0, 0, size, 0, 0,
  23100. 0, 0, 0, 0, size, 0,
  23101. 0, 0, 0, 0, 0, size
  23102. ] );
  23103. var colors = new Float32Array( [
  23104. 1, 0, 0, 1, 0.6, 0,
  23105. 0, 1, 0, 0.6, 1, 0,
  23106. 0, 0, 1, 0, 0.6, 1
  23107. ] );
  23108. var geometry = new BufferGeometry();
  23109. geometry.addAttribute( 'position', new BufferAttribute( vertices, 3 ) );
  23110. geometry.addAttribute( 'color', new BufferAttribute( colors, 3 ) );
  23111. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  23112. LineSegments.call( this, geometry, material );
  23113. }
  23114. AxisHelper.prototype = Object.create( LineSegments.prototype );
  23115. AxisHelper.prototype.constructor = AxisHelper;
  23116. /**
  23117. * @author zz85 / https://github.com/zz85
  23118. * Parametric Surfaces Geometry
  23119. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  23120. *
  23121. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements );
  23122. *
  23123. */
  23124. function ParametricGeometry( func, slices, stacks ) {
  23125. Geometry.call( this );
  23126. this.type = 'ParametricGeometry';
  23127. this.parameters = {
  23128. func: func,
  23129. slices: slices,
  23130. stacks: stacks
  23131. };
  23132. var verts = this.vertices;
  23133. var faces = this.faces;
  23134. var uvs = this.faceVertexUvs[ 0 ];
  23135. var i, j, p;
  23136. var u, v;
  23137. var sliceCount = slices + 1;
  23138. for ( i = 0; i <= stacks; i ++ ) {
  23139. v = i / stacks;
  23140. for ( j = 0; j <= slices; j ++ ) {
  23141. u = j / slices;
  23142. p = func( u, v );
  23143. verts.push( p );
  23144. }
  23145. }
  23146. var a, b, c, d;
  23147. var uva, uvb, uvc, uvd;
  23148. for ( i = 0; i < stacks; i ++ ) {
  23149. for ( j = 0; j < slices; j ++ ) {
  23150. a = i * sliceCount + j;
  23151. b = i * sliceCount + j + 1;
  23152. c = ( i + 1 ) * sliceCount + j + 1;
  23153. d = ( i + 1 ) * sliceCount + j;
  23154. uva = new Vector2( j / slices, i / stacks );
  23155. uvb = new Vector2( ( j + 1 ) / slices, i / stacks );
  23156. uvc = new Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  23157. uvd = new Vector2( j / slices, ( i + 1 ) / stacks );
  23158. faces.push( new Face3( a, b, d ) );
  23159. uvs.push( [ uva, uvb, uvd ] );
  23160. faces.push( new Face3( b, c, d ) );
  23161. uvs.push( [ uvb.clone(), uvc, uvd.clone() ] );
  23162. }
  23163. }
  23164. // console.log(this);
  23165. // magic bullet
  23166. // var diff = this.mergeVertices();
  23167. // console.log('removed ', diff, ' vertices by merging');
  23168. this.computeFaceNormals();
  23169. this.computeVertexNormals();
  23170. }
  23171. ParametricGeometry.prototype = Object.create( Geometry.prototype );
  23172. ParametricGeometry.prototype.constructor = ParametricGeometry;
  23173. /**
  23174. * @author clockworkgeek / https://github.com/clockworkgeek
  23175. * @author timothypratley / https://github.com/timothypratley
  23176. * @author WestLangley / http://github.com/WestLangley
  23177. */
  23178. function PolyhedronGeometry( vertices, indices, radius, detail ) {
  23179. Geometry.call( this );
  23180. this.type = 'PolyhedronGeometry';
  23181. this.parameters = {
  23182. vertices: vertices,
  23183. indices: indices,
  23184. radius: radius,
  23185. detail: detail
  23186. };
  23187. radius = radius || 1;
  23188. detail = detail || 0;
  23189. var that = this;
  23190. for ( var i = 0, l = vertices.length; i < l; i += 3 ) {
  23191. prepare( new Vector3( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] ) );
  23192. }
  23193. var p = this.vertices;
  23194. var faces = [];
  23195. for ( var i = 0, j = 0, l = indices.length; i < l; i += 3, j ++ ) {
  23196. var v1 = p[ indices[ i ] ];
  23197. var v2 = p[ indices[ i + 1 ] ];
  23198. var v3 = p[ indices[ i + 2 ] ];
  23199. faces[ j ] = new Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  23200. }
  23201. var centroid = new Vector3();
  23202. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  23203. subdivide( faces[ i ], detail );
  23204. }
  23205. // Handle case when face straddles the seam
  23206. for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) {
  23207. var uvs = this.faceVertexUvs[ 0 ][ i ];
  23208. var x0 = uvs[ 0 ].x;
  23209. var x1 = uvs[ 1 ].x;
  23210. var x2 = uvs[ 2 ].x;
  23211. var max = Math.max( x0, x1, x2 );
  23212. var min = Math.min( x0, x1, x2 );
  23213. if ( max > 0.9 && min < 0.1 ) {
  23214. // 0.9 is somewhat arbitrary
  23215. if ( x0 < 0.2 ) uvs[ 0 ].x += 1;
  23216. if ( x1 < 0.2 ) uvs[ 1 ].x += 1;
  23217. if ( x2 < 0.2 ) uvs[ 2 ].x += 1;
  23218. }
  23219. }
  23220. // Apply radius
  23221. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  23222. this.vertices[ i ].multiplyScalar( radius );
  23223. }
  23224. // Merge vertices
  23225. this.mergeVertices();
  23226. this.computeFaceNormals();
  23227. this.boundingSphere = new Sphere( new Vector3(), radius );
  23228. // Project vector onto sphere's surface
  23229. function prepare( vector ) {
  23230. var vertex = vector.normalize().clone();
  23231. vertex.index = that.vertices.push( vertex ) - 1;
  23232. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  23233. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  23234. var v = inclination( vector ) / Math.PI + 0.5;
  23235. vertex.uv = new Vector2( u, 1 - v );
  23236. return vertex;
  23237. }
  23238. // Approximate a curved face with recursively sub-divided triangles.
  23239. function make( v1, v2, v3 ) {
  23240. var face = new Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  23241. that.faces.push( face );
  23242. centroid.copy( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  23243. var azi = azimuth( centroid );
  23244. that.faceVertexUvs[ 0 ].push( [
  23245. correctUV( v1.uv, v1, azi ),
  23246. correctUV( v2.uv, v2, azi ),
  23247. correctUV( v3.uv, v3, azi )
  23248. ] );
  23249. }
  23250. // Analytically subdivide a face to the required detail level.
  23251. function subdivide( face, detail ) {
  23252. var cols = Math.pow( 2, detail );
  23253. var a = prepare( that.vertices[ face.a ] );
  23254. var b = prepare( that.vertices[ face.b ] );
  23255. var c = prepare( that.vertices[ face.c ] );
  23256. var v = [];
  23257. // Construct all of the vertices for this subdivision.
  23258. for ( var i = 0 ; i <= cols; i ++ ) {
  23259. v[ i ] = [];
  23260. var aj = prepare( a.clone().lerp( c, i / cols ) );
  23261. var bj = prepare( b.clone().lerp( c, i / cols ) );
  23262. var rows = cols - i;
  23263. for ( var j = 0; j <= rows; j ++ ) {
  23264. if ( j === 0 && i === cols ) {
  23265. v[ i ][ j ] = aj;
  23266. } else {
  23267. v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) );
  23268. }
  23269. }
  23270. }
  23271. // Construct all of the faces.
  23272. for ( var i = 0; i < cols ; i ++ ) {
  23273. for ( var j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  23274. var k = Math.floor( j / 2 );
  23275. if ( j % 2 === 0 ) {
  23276. make(
  23277. v[ i ][ k + 1 ],
  23278. v[ i + 1 ][ k ],
  23279. v[ i ][ k ]
  23280. );
  23281. } else {
  23282. make(
  23283. v[ i ][ k + 1 ],
  23284. v[ i + 1 ][ k + 1 ],
  23285. v[ i + 1 ][ k ]
  23286. );
  23287. }
  23288. }
  23289. }
  23290. }
  23291. // Angle around the Y axis, counter-clockwise when looking from above.
  23292. function azimuth( vector ) {
  23293. return Math.atan2( vector.z, - vector.x );
  23294. }
  23295. // Angle above the XZ plane.
  23296. function inclination( vector ) {
  23297. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  23298. }
  23299. // Texture fixing helper. Spheres have some odd behaviours.
  23300. function correctUV( uv, vector, azimuth ) {
  23301. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new Vector2( uv.x - 1, uv.y );
  23302. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  23303. return uv.clone();
  23304. }
  23305. }
  23306. PolyhedronGeometry.prototype = Object.create( Geometry.prototype );
  23307. PolyhedronGeometry.prototype.constructor = PolyhedronGeometry;
  23308. /**
  23309. * @author timothypratley / https://github.com/timothypratley
  23310. */
  23311. function TetrahedronGeometry( radius, detail ) {
  23312. var vertices = [
  23313. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  23314. ];
  23315. var indices = [
  23316. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  23317. ];
  23318. PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  23319. this.type = 'TetrahedronGeometry';
  23320. this.parameters = {
  23321. radius: radius,
  23322. detail: detail
  23323. };
  23324. }
  23325. TetrahedronGeometry.prototype = Object.create( PolyhedronGeometry.prototype );
  23326. TetrahedronGeometry.prototype.constructor = TetrahedronGeometry;
  23327. /**
  23328. * @author timothypratley / https://github.com/timothypratley
  23329. */
  23330. function OctahedronGeometry( radius, detail ) {
  23331. var vertices = [
  23332. 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  23333. ];
  23334. var indices = [
  23335. 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2
  23336. ];
  23337. PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  23338. this.type = 'OctahedronGeometry';
  23339. this.parameters = {
  23340. radius: radius,
  23341. detail: detail
  23342. };
  23343. }
  23344. OctahedronGeometry.prototype = Object.create( PolyhedronGeometry.prototype );
  23345. OctahedronGeometry.prototype.constructor = OctahedronGeometry;
  23346. /**
  23347. * @author timothypratley / https://github.com/timothypratley
  23348. */
  23349. function IcosahedronGeometry( radius, detail ) {
  23350. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  23351. var vertices = [
  23352. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  23353. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  23354. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  23355. ];
  23356. var indices = [
  23357. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  23358. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  23359. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  23360. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  23361. ];
  23362. PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  23363. this.type = 'IcosahedronGeometry';
  23364. this.parameters = {
  23365. radius: radius,
  23366. detail: detail
  23367. };
  23368. }
  23369. IcosahedronGeometry.prototype = Object.create( PolyhedronGeometry.prototype );
  23370. IcosahedronGeometry.prototype.constructor = IcosahedronGeometry;
  23371. /**
  23372. * @author Abe Pazos / https://hamoid.com
  23373. */
  23374. function DodecahedronGeometry( radius, detail ) {
  23375. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  23376. var r = 1 / t;
  23377. var vertices = [
  23378. // (±1, ±1, ±1)
  23379. - 1, - 1, - 1, - 1, - 1, 1,
  23380. - 1, 1, - 1, - 1, 1, 1,
  23381. 1, - 1, - 1, 1, - 1, 1,
  23382. 1, 1, - 1, 1, 1, 1,
  23383. // (0, ±1/φ, ±φ)
  23384. 0, - r, - t, 0, - r, t,
  23385. 0, r, - t, 0, r, t,
  23386. // (±1/φ, ±φ, 0)
  23387. - r, - t, 0, - r, t, 0,
  23388. r, - t, 0, r, t, 0,
  23389. // (±φ, 0, ±1/φ)
  23390. - t, 0, - r, t, 0, - r,
  23391. - t, 0, r, t, 0, r
  23392. ];
  23393. var indices = [
  23394. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  23395. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  23396. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  23397. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  23398. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  23399. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  23400. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  23401. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  23402. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  23403. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  23404. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  23405. 1, 12, 14, 1, 14, 5, 1, 5, 9
  23406. ];
  23407. PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  23408. this.type = 'DodecahedronGeometry';
  23409. this.parameters = {
  23410. radius: radius,
  23411. detail: detail
  23412. };
  23413. }
  23414. DodecahedronGeometry.prototype = Object.create( PolyhedronGeometry.prototype );
  23415. DodecahedronGeometry.prototype.constructor = DodecahedronGeometry;
  23416. /**
  23417. * @author Mugen87 / https://github.com/Mugen87
  23418. *
  23419. * see: http://www.blackpawn.com/texts/pqtorus/
  23420. */
  23421. function TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) {
  23422. BufferGeometry.call( this );
  23423. this.type = 'TorusKnotBufferGeometry';
  23424. this.parameters = {
  23425. radius: radius,
  23426. tube: tube,
  23427. tubularSegments: tubularSegments,
  23428. radialSegments: radialSegments,
  23429. p: p,
  23430. q: q
  23431. };
  23432. radius = radius || 100;
  23433. tube = tube || 40;
  23434. tubularSegments = Math.floor( tubularSegments ) || 64;
  23435. radialSegments = Math.floor( radialSegments ) || 8;
  23436. p = p || 2;
  23437. q = q || 3;
  23438. // used to calculate buffer length
  23439. var vertexCount = ( ( radialSegments + 1 ) * ( tubularSegments + 1 ) );
  23440. var indexCount = radialSegments * tubularSegments * 2 * 3;
  23441. // buffers
  23442. var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 );
  23443. var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  23444. var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  23445. var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  23446. // helper variables
  23447. var i, j, index = 0, indexOffset = 0;
  23448. var vertex = new Vector3();
  23449. var normal = new Vector3();
  23450. var uv = new Vector2();
  23451. var P1 = new Vector3();
  23452. var P2 = new Vector3();
  23453. var B = new Vector3();
  23454. var T = new Vector3();
  23455. var N = new Vector3();
  23456. // generate vertices, normals and uvs
  23457. for ( i = 0; i <= tubularSegments; ++ i ) {
  23458. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  23459. var u = i / tubularSegments * p * Math.PI * 2;
  23460. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  23461. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  23462. calculatePositionOnCurve( u, p, q, radius, P1 );
  23463. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  23464. // calculate orthonormal basis
  23465. T.subVectors( P2, P1 );
  23466. N.addVectors( P2, P1 );
  23467. B.crossVectors( T, N );
  23468. N.crossVectors( B, T );
  23469. // normalize B, N. T can be ignored, we don't use it
  23470. B.normalize();
  23471. N.normalize();
  23472. for ( j = 0; j <= radialSegments; ++ j ) {
  23473. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  23474. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  23475. var v = j / radialSegments * Math.PI * 2;
  23476. var cx = - tube * Math.cos( v );
  23477. var cy = tube * Math.sin( v );
  23478. // now calculate the final vertex position.
  23479. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  23480. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  23481. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  23482. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  23483. // vertex
  23484. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  23485. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  23486. normal.subVectors( vertex, P1 ).normalize();
  23487. normals.setXYZ( index, normal.x, normal.y, normal.z );
  23488. // uv
  23489. uv.x = i / tubularSegments;
  23490. uv.y = j / radialSegments;
  23491. uvs.setXY( index, uv.x, uv.y );
  23492. // increase index
  23493. index ++;
  23494. }
  23495. }
  23496. // generate indices
  23497. for ( j = 1; j <= tubularSegments; j ++ ) {
  23498. for ( i = 1; i <= radialSegments; i ++ ) {
  23499. // indices
  23500. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  23501. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  23502. var c = ( radialSegments + 1 ) * j + i;
  23503. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  23504. // face one
  23505. indices.setX( indexOffset, a ); indexOffset++;
  23506. indices.setX( indexOffset, b ); indexOffset++;
  23507. indices.setX( indexOffset, d ); indexOffset++;
  23508. // face two
  23509. indices.setX( indexOffset, b ); indexOffset++;
  23510. indices.setX( indexOffset, c ); indexOffset++;
  23511. indices.setX( indexOffset, d ); indexOffset++;
  23512. }
  23513. }
  23514. // build geometry
  23515. this.setIndex( indices );
  23516. this.addAttribute( 'position', vertices );
  23517. this.addAttribute( 'normal', normals );
  23518. this.addAttribute( 'uv', uvs );
  23519. // this function calculates the current position on the torus curve
  23520. function calculatePositionOnCurve( u, p, q, radius, position ) {
  23521. var cu = Math.cos( u );
  23522. var su = Math.sin( u );
  23523. var quOverP = q / p * u;
  23524. var cs = Math.cos( quOverP );
  23525. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  23526. position.y = radius * ( 2 + cs ) * su * 0.5;
  23527. position.z = radius * Math.sin( quOverP ) * 0.5;
  23528. }
  23529. }
  23530. TorusKnotBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  23531. TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry;
  23532. /**
  23533. * @author oosmoxiecode
  23534. */
  23535. function TorusKnotGeometry( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) {
  23536. Geometry.call( this );
  23537. this.type = 'TorusKnotGeometry';
  23538. this.parameters = {
  23539. radius: radius,
  23540. tube: tube,
  23541. tubularSegments: tubularSegments,
  23542. radialSegments: radialSegments,
  23543. p: p,
  23544. q: q
  23545. };
  23546. if( heightScale !== undefined ) console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' );
  23547. this.fromBufferGeometry( new TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) );
  23548. this.mergeVertices();
  23549. }
  23550. TorusKnotGeometry.prototype = Object.create( Geometry.prototype );
  23551. TorusKnotGeometry.prototype.constructor = TorusKnotGeometry;
  23552. /**
  23553. * @author Mugen87 / https://github.com/Mugen87
  23554. */
  23555. function TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  23556. BufferGeometry.call( this );
  23557. this.type = 'TorusBufferGeometry';
  23558. this.parameters = {
  23559. radius: radius,
  23560. tube: tube,
  23561. radialSegments: radialSegments,
  23562. tubularSegments: tubularSegments,
  23563. arc: arc
  23564. };
  23565. radius = radius || 100;
  23566. tube = tube || 40;
  23567. radialSegments = Math.floor( radialSegments ) || 8;
  23568. tubularSegments = Math.floor( tubularSegments ) || 6;
  23569. arc = arc || Math.PI * 2;
  23570. // used to calculate buffer length
  23571. var vertexCount = ( ( radialSegments + 1 ) * ( tubularSegments + 1 ) );
  23572. var indexCount = radialSegments * tubularSegments * 2 * 3;
  23573. // buffers
  23574. var indices = new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount );
  23575. var vertices = new Float32Array( vertexCount * 3 );
  23576. var normals = new Float32Array( vertexCount * 3 );
  23577. var uvs = new Float32Array( vertexCount * 2 );
  23578. // offset variables
  23579. var vertexBufferOffset = 0;
  23580. var uvBufferOffset = 0;
  23581. var indexBufferOffset = 0;
  23582. // helper variables
  23583. var center = new Vector3();
  23584. var vertex = new Vector3();
  23585. var normal = new Vector3();
  23586. var j, i;
  23587. // generate vertices, normals and uvs
  23588. for ( j = 0; j <= radialSegments; j ++ ) {
  23589. for ( i = 0; i <= tubularSegments; i ++ ) {
  23590. var u = i / tubularSegments * arc;
  23591. var v = j / radialSegments * Math.PI * 2;
  23592. // vertex
  23593. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  23594. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  23595. vertex.z = tube * Math.sin( v );
  23596. vertices[ vertexBufferOffset ] = vertex.x;
  23597. vertices[ vertexBufferOffset + 1 ] = vertex.y;
  23598. vertices[ vertexBufferOffset + 2 ] = vertex.z;
  23599. // this vector is used to calculate the normal
  23600. center.x = radius * Math.cos( u );
  23601. center.y = radius * Math.sin( u );
  23602. // normal
  23603. normal.subVectors( vertex, center ).normalize();
  23604. normals[ vertexBufferOffset ] = normal.x;
  23605. normals[ vertexBufferOffset + 1 ] = normal.y;
  23606. normals[ vertexBufferOffset + 2 ] = normal.z;
  23607. // uv
  23608. uvs[ uvBufferOffset ] = i / tubularSegments;
  23609. uvs[ uvBufferOffset + 1 ] = j / radialSegments;
  23610. // update offsets
  23611. vertexBufferOffset += 3;
  23612. uvBufferOffset += 2;
  23613. }
  23614. }
  23615. // generate indices
  23616. for ( j = 1; j <= radialSegments; j ++ ) {
  23617. for ( i = 1; i <= tubularSegments; i ++ ) {
  23618. // indices
  23619. var a = ( tubularSegments + 1 ) * j + i - 1;
  23620. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  23621. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  23622. var d = ( tubularSegments + 1 ) * j + i;
  23623. // face one
  23624. indices[ indexBufferOffset ] = a;
  23625. indices[ indexBufferOffset + 1 ] = b;
  23626. indices[ indexBufferOffset + 2 ] = d;
  23627. // face two
  23628. indices[ indexBufferOffset + 3 ] = b;
  23629. indices[ indexBufferOffset + 4 ] = c;
  23630. indices[ indexBufferOffset + 5 ] = d;
  23631. // update offset
  23632. indexBufferOffset += 6;
  23633. }
  23634. }
  23635. // build geometry
  23636. this.setIndex( new BufferAttribute( indices, 1 ) );
  23637. this.addAttribute( 'position', new BufferAttribute( vertices, 3 ) );
  23638. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) );
  23639. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) );
  23640. }
  23641. TorusBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  23642. TorusBufferGeometry.prototype.constructor = TorusBufferGeometry;
  23643. /**
  23644. * @author oosmoxiecode
  23645. * @author mrdoob / http://mrdoob.com/
  23646. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  23647. */
  23648. function TorusGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  23649. Geometry.call( this );
  23650. this.type = 'TorusGeometry';
  23651. this.parameters = {
  23652. radius: radius,
  23653. tube: tube,
  23654. radialSegments: radialSegments,
  23655. tubularSegments: tubularSegments,
  23656. arc: arc
  23657. };
  23658. this.fromBufferGeometry( new TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) );
  23659. }
  23660. TorusGeometry.prototype = Object.create( Geometry.prototype );
  23661. TorusGeometry.prototype.constructor = TorusGeometry;
  23662. /**
  23663. * @author zz85 / http://www.lab4games.net/zz85/blog
  23664. * @author alteredq / http://alteredqualia.com/
  23665. *
  23666. * Text = 3D Text
  23667. *
  23668. * parameters = {
  23669. * font: <THREE.Font>, // font
  23670. *
  23671. * size: <float>, // size of the text
  23672. * height: <float>, // thickness to extrude text
  23673. * curveSegments: <int>, // number of points on the curves
  23674. *
  23675. * bevelEnabled: <bool>, // turn on bevel
  23676. * bevelThickness: <float>, // how deep into text bevel goes
  23677. * bevelSize: <float> // how far from text outline is bevel
  23678. * }
  23679. */
  23680. function TextGeometry( text, parameters ) {
  23681. parameters = parameters || {};
  23682. var font = parameters.font;
  23683. if ( (font && font.isFont) === false ) {
  23684. console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' );
  23685. return new Geometry();
  23686. }
  23687. var shapes = font.generateShapes( text, parameters.size, parameters.curveSegments );
  23688. // translate parameters to ExtrudeGeometry API
  23689. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  23690. // defaults
  23691. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  23692. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  23693. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  23694. ExtrudeGeometry.call( this, shapes, parameters );
  23695. this.type = 'TextGeometry';
  23696. }
  23697. TextGeometry.prototype = Object.create( ExtrudeGeometry.prototype );
  23698. TextGeometry.prototype.constructor = TextGeometry;
  23699. /**
  23700. * @author Mugen87 / https://github.com/Mugen87
  23701. */
  23702. function RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  23703. BufferGeometry.call( this );
  23704. this.type = 'RingBufferGeometry';
  23705. this.parameters = {
  23706. innerRadius: innerRadius,
  23707. outerRadius: outerRadius,
  23708. thetaSegments: thetaSegments,
  23709. phiSegments: phiSegments,
  23710. thetaStart: thetaStart,
  23711. thetaLength: thetaLength
  23712. };
  23713. innerRadius = innerRadius || 20;
  23714. outerRadius = outerRadius || 50;
  23715. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  23716. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  23717. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  23718. phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 1;
  23719. // these are used to calculate buffer length
  23720. var vertexCount = ( thetaSegments + 1 ) * ( phiSegments + 1 );
  23721. var indexCount = thetaSegments * phiSegments * 2 * 3;
  23722. // buffers
  23723. var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 );
  23724. var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  23725. var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  23726. var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  23727. // some helper variables
  23728. var index = 0, indexOffset = 0, segment;
  23729. var radius = innerRadius;
  23730. var radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  23731. var vertex = new Vector3();
  23732. var uv = new Vector2();
  23733. var j, i;
  23734. // generate vertices, normals and uvs
  23735. // values are generate from the inside of the ring to the outside
  23736. for ( j = 0; j <= phiSegments; j ++ ) {
  23737. for ( i = 0; i <= thetaSegments; i ++ ) {
  23738. segment = thetaStart + i / thetaSegments * thetaLength;
  23739. // vertex
  23740. vertex.x = radius * Math.cos( segment );
  23741. vertex.y = radius * Math.sin( segment );
  23742. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  23743. // normal
  23744. normals.setXYZ( index, 0, 0, 1 );
  23745. // uv
  23746. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  23747. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  23748. uvs.setXY( index, uv.x, uv.y );
  23749. // increase index
  23750. index++;
  23751. }
  23752. // increase the radius for next row of vertices
  23753. radius += radiusStep;
  23754. }
  23755. // generate indices
  23756. for ( j = 0; j < phiSegments; j ++ ) {
  23757. var thetaSegmentLevel = j * ( thetaSegments + 1 );
  23758. for ( i = 0; i < thetaSegments; i ++ ) {
  23759. segment = i + thetaSegmentLevel;
  23760. // indices
  23761. var a = segment;
  23762. var b = segment + thetaSegments + 1;
  23763. var c = segment + thetaSegments + 2;
  23764. var d = segment + 1;
  23765. // face one
  23766. indices.setX( indexOffset, a ); indexOffset++;
  23767. indices.setX( indexOffset, b ); indexOffset++;
  23768. indices.setX( indexOffset, c ); indexOffset++;
  23769. // face two
  23770. indices.setX( indexOffset, a ); indexOffset++;
  23771. indices.setX( indexOffset, c ); indexOffset++;
  23772. indices.setX( indexOffset, d ); indexOffset++;
  23773. }
  23774. }
  23775. // build geometry
  23776. this.setIndex( indices );
  23777. this.addAttribute( 'position', vertices );
  23778. this.addAttribute( 'normal', normals );
  23779. this.addAttribute( 'uv', uvs );
  23780. }
  23781. RingBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  23782. RingBufferGeometry.prototype.constructor = RingBufferGeometry;
  23783. /**
  23784. * @author Kaleb Murphy
  23785. */
  23786. function RingGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  23787. Geometry.call( this );
  23788. this.type = 'RingGeometry';
  23789. this.parameters = {
  23790. innerRadius: innerRadius,
  23791. outerRadius: outerRadius,
  23792. thetaSegments: thetaSegments,
  23793. phiSegments: phiSegments,
  23794. thetaStart: thetaStart,
  23795. thetaLength: thetaLength
  23796. };
  23797. this.fromBufferGeometry( new RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) );
  23798. }
  23799. RingGeometry.prototype = Object.create( Geometry.prototype );
  23800. RingGeometry.prototype.constructor = RingGeometry;
  23801. /**
  23802. * @author mrdoob / http://mrdoob.com/
  23803. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  23804. */
  23805. function PlaneGeometry( width, height, widthSegments, heightSegments ) {
  23806. Geometry.call( this );
  23807. this.type = 'PlaneGeometry';
  23808. this.parameters = {
  23809. width: width,
  23810. height: height,
  23811. widthSegments: widthSegments,
  23812. heightSegments: heightSegments
  23813. };
  23814. this.fromBufferGeometry( new PlaneBufferGeometry( width, height, widthSegments, heightSegments ) );
  23815. }
  23816. PlaneGeometry.prototype = Object.create( Geometry.prototype );
  23817. PlaneGeometry.prototype.constructor = PlaneGeometry;
  23818. /**
  23819. * @author Mugen87 / https://github.com/Mugen87
  23820. */
  23821. // points - to create a closed torus, one must use a set of points
  23822. // like so: [ a, b, c, d, a ], see first is the same as last.
  23823. // segments - the number of circumference segments to create
  23824. // phiStart - the starting radian
  23825. // phiLength - the radian (0 to 2PI) range of the lathed section
  23826. // 2PI is a closed lathe, less than 2PI is a portion.
  23827. function LatheBufferGeometry( points, segments, phiStart, phiLength ) {
  23828. BufferGeometry.call( this );
  23829. this.type = 'LatheBufferGeometry';
  23830. this.parameters = {
  23831. points: points,
  23832. segments: segments,
  23833. phiStart: phiStart,
  23834. phiLength: phiLength
  23835. };
  23836. segments = Math.floor( segments ) || 12;
  23837. phiStart = phiStart || 0;
  23838. phiLength = phiLength || Math.PI * 2;
  23839. // clamp phiLength so it's in range of [ 0, 2PI ]
  23840. phiLength = exports.Math.clamp( phiLength, 0, Math.PI * 2 );
  23841. // these are used to calculate buffer length
  23842. var vertexCount = ( segments + 1 ) * points.length;
  23843. var indexCount = segments * points.length * 2 * 3;
  23844. // buffers
  23845. var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 );
  23846. var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  23847. var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  23848. // helper variables
  23849. var index = 0, indexOffset = 0, base;
  23850. var inverseSegments = 1.0 / segments;
  23851. var vertex = new Vector3();
  23852. var uv = new Vector2();
  23853. var i, j;
  23854. // generate vertices and uvs
  23855. for ( i = 0; i <= segments; i ++ ) {
  23856. var phi = phiStart + i * inverseSegments * phiLength;
  23857. var sin = Math.sin( phi );
  23858. var cos = Math.cos( phi );
  23859. for ( j = 0; j <= ( points.length - 1 ); j ++ ) {
  23860. // vertex
  23861. vertex.x = points[ j ].x * sin;
  23862. vertex.y = points[ j ].y;
  23863. vertex.z = points[ j ].x * cos;
  23864. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  23865. // uv
  23866. uv.x = i / segments;
  23867. uv.y = j / ( points.length - 1 );
  23868. uvs.setXY( index, uv.x, uv.y );
  23869. // increase index
  23870. index ++;
  23871. }
  23872. }
  23873. // generate indices
  23874. for ( i = 0; i < segments; i ++ ) {
  23875. for ( j = 0; j < ( points.length - 1 ); j ++ ) {
  23876. base = j + i * points.length;
  23877. // indices
  23878. var a = base;
  23879. var b = base + points.length;
  23880. var c = base + points.length + 1;
  23881. var d = base + 1;
  23882. // face one
  23883. indices.setX( indexOffset, a ); indexOffset++;
  23884. indices.setX( indexOffset, b ); indexOffset++;
  23885. indices.setX( indexOffset, d ); indexOffset++;
  23886. // face two
  23887. indices.setX( indexOffset, b ); indexOffset++;
  23888. indices.setX( indexOffset, c ); indexOffset++;
  23889. indices.setX( indexOffset, d ); indexOffset++;
  23890. }
  23891. }
  23892. // build geometry
  23893. this.setIndex( indices );
  23894. this.addAttribute( 'position', vertices );
  23895. this.addAttribute( 'uv', uvs );
  23896. // generate normals
  23897. this.computeVertexNormals();
  23898. // if the geometry is closed, we need to average the normals along the seam.
  23899. // because the corresponding vertices are identical (but still have different UVs).
  23900. if( phiLength === Math.PI * 2 ) {
  23901. var normals = this.attributes.normal.array;
  23902. var n1 = new Vector3();
  23903. var n2 = new Vector3();
  23904. var n = new Vector3();
  23905. // this is the buffer offset for the last line of vertices
  23906. base = segments * points.length * 3;
  23907. for( i = 0, j = 0; i < points.length; i ++, j += 3 ) {
  23908. // select the normal of the vertex in the first line
  23909. n1.x = normals[ j + 0 ];
  23910. n1.y = normals[ j + 1 ];
  23911. n1.z = normals[ j + 2 ];
  23912. // select the normal of the vertex in the last line
  23913. n2.x = normals[ base + j + 0 ];
  23914. n2.y = normals[ base + j + 1 ];
  23915. n2.z = normals[ base + j + 2 ];
  23916. // average normals
  23917. n.addVectors( n1, n2 ).normalize();
  23918. // assign the new values to both normals
  23919. normals[ j + 0 ] = normals[ base + j + 0 ] = n.x;
  23920. normals[ j + 1 ] = normals[ base + j + 1 ] = n.y;
  23921. normals[ j + 2 ] = normals[ base + j + 2 ] = n.z;
  23922. } // next row
  23923. }
  23924. }
  23925. LatheBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  23926. LatheBufferGeometry.prototype.constructor = LatheBufferGeometry;
  23927. /**
  23928. * @author astrodud / http://astrodud.isgreat.org/
  23929. * @author zz85 / https://github.com/zz85
  23930. * @author bhouston / http://clara.io
  23931. */
  23932. // points - to create a closed torus, one must use a set of points
  23933. // like so: [ a, b, c, d, a ], see first is the same as last.
  23934. // segments - the number of circumference segments to create
  23935. // phiStart - the starting radian
  23936. // phiLength - the radian (0 to 2PI) range of the lathed section
  23937. // 2PI is a closed lathe, less than 2PI is a portion.
  23938. function LatheGeometry( points, segments, phiStart, phiLength ) {
  23939. Geometry.call( this );
  23940. this.type = 'LatheGeometry';
  23941. this.parameters = {
  23942. points: points,
  23943. segments: segments,
  23944. phiStart: phiStart,
  23945. phiLength: phiLength
  23946. };
  23947. this.fromBufferGeometry( new LatheBufferGeometry( points, segments, phiStart, phiLength ) );
  23948. this.mergeVertices();
  23949. }
  23950. LatheGeometry.prototype = Object.create( Geometry.prototype );
  23951. LatheGeometry.prototype.constructor = LatheGeometry;
  23952. /**
  23953. * @author mrdoob / http://mrdoob.com/
  23954. */
  23955. function CylinderGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  23956. Geometry.call( this );
  23957. this.type = 'CylinderGeometry';
  23958. this.parameters = {
  23959. radiusTop: radiusTop,
  23960. radiusBottom: radiusBottom,
  23961. height: height,
  23962. radialSegments: radialSegments,
  23963. heightSegments: heightSegments,
  23964. openEnded: openEnded,
  23965. thetaStart: thetaStart,
  23966. thetaLength: thetaLength
  23967. };
  23968. this.fromBufferGeometry( new CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) );
  23969. this.mergeVertices();
  23970. }
  23971. CylinderGeometry.prototype = Object.create( Geometry.prototype );
  23972. CylinderGeometry.prototype.constructor = CylinderGeometry;
  23973. /**
  23974. * @author abelnation / http://github.com/abelnation
  23975. */
  23976. function ConeGeometry(
  23977. radius, height,
  23978. radialSegments, heightSegments,
  23979. openEnded, thetaStart, thetaLength ) {
  23980. CylinderGeometry.call( this,
  23981. 0, radius, height,
  23982. radialSegments, heightSegments,
  23983. openEnded, thetaStart, thetaLength );
  23984. this.type = 'ConeGeometry';
  23985. this.parameters = {
  23986. radius: radius,
  23987. height: height,
  23988. radialSegments: radialSegments,
  23989. heightSegments: heightSegments,
  23990. openEnded: openEnded,
  23991. thetaStart: thetaStart,
  23992. thetaLength: thetaLength
  23993. };
  23994. }
  23995. ConeGeometry.prototype = Object.create( CylinderGeometry.prototype );
  23996. ConeGeometry.prototype.constructor = ConeGeometry;
  23997. /*
  23998. * @author: abelnation / http://github.com/abelnation
  23999. */
  24000. function ConeBufferGeometry(
  24001. radius, height,
  24002. radialSegments, heightSegments,
  24003. openEnded, thetaStart, thetaLength ) {
  24004. CylinderBufferGeometry.call( this,
  24005. 0, radius, height,
  24006. radialSegments, heightSegments,
  24007. openEnded, thetaStart, thetaLength );
  24008. this.type = 'ConeBufferGeometry';
  24009. this.parameters = {
  24010. radius: radius,
  24011. height: height,
  24012. radialSegments: radialSegments,
  24013. heightSegments: heightSegments,
  24014. thetaStart: thetaStart,
  24015. thetaLength: thetaLength
  24016. };
  24017. }
  24018. ConeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  24019. ConeBufferGeometry.prototype.constructor = ConeBufferGeometry;
  24020. /**
  24021. * @author benaadams / https://twitter.com/ben_a_adams
  24022. */
  24023. function CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) {
  24024. BufferGeometry.call( this );
  24025. this.type = 'CircleBufferGeometry';
  24026. this.parameters = {
  24027. radius: radius,
  24028. segments: segments,
  24029. thetaStart: thetaStart,
  24030. thetaLength: thetaLength
  24031. };
  24032. radius = radius || 50;
  24033. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  24034. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  24035. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  24036. var vertices = segments + 2;
  24037. var positions = new Float32Array( vertices * 3 );
  24038. var normals = new Float32Array( vertices * 3 );
  24039. var uvs = new Float32Array( vertices * 2 );
  24040. // center data is already zero, but need to set a few extras
  24041. normals[ 2 ] = 1.0;
  24042. uvs[ 0 ] = 0.5;
  24043. uvs[ 1 ] = 0.5;
  24044. for ( var s = 0, i = 3, ii = 2 ; s <= segments; s ++, i += 3, ii += 2 ) {
  24045. var segment = thetaStart + s / segments * thetaLength;
  24046. positions[ i ] = radius * Math.cos( segment );
  24047. positions[ i + 1 ] = radius * Math.sin( segment );
  24048. normals[ i + 2 ] = 1; // normal z
  24049. uvs[ ii ] = ( positions[ i ] / radius + 1 ) / 2;
  24050. uvs[ ii + 1 ] = ( positions[ i + 1 ] / radius + 1 ) / 2;
  24051. }
  24052. var indices = [];
  24053. for ( var i = 1; i <= segments; i ++ ) {
  24054. indices.push( i, i + 1, 0 );
  24055. }
  24056. this.setIndex( new BufferAttribute( new Uint16Array( indices ), 1 ) );
  24057. this.addAttribute( 'position', new BufferAttribute( positions, 3 ) );
  24058. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) );
  24059. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) );
  24060. this.boundingSphere = new Sphere( new Vector3(), radius );
  24061. }
  24062. CircleBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  24063. CircleBufferGeometry.prototype.constructor = CircleBufferGeometry;
  24064. /**
  24065. * @author hughes
  24066. */
  24067. function CircleGeometry( radius, segments, thetaStart, thetaLength ) {
  24068. Geometry.call( this );
  24069. this.type = 'CircleGeometry';
  24070. this.parameters = {
  24071. radius: radius,
  24072. segments: segments,
  24073. thetaStart: thetaStart,
  24074. thetaLength: thetaLength
  24075. };
  24076. this.fromBufferGeometry( new CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) );
  24077. }
  24078. CircleGeometry.prototype = Object.create( Geometry.prototype );
  24079. CircleGeometry.prototype.constructor = CircleGeometry;
  24080. /**
  24081. * @author zz85 https://github.com/zz85
  24082. *
  24083. * Centripetal CatmullRom Curve - which is useful for avoiding
  24084. * cusps and self-intersections in non-uniform catmull rom curves.
  24085. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  24086. *
  24087. * curve.type accepts centripetal(default), chordal and catmullrom
  24088. * curve.tension is used for catmullrom which defaults to 0.5
  24089. */
  24090. exports.CatmullRomCurve3 = ( function() {
  24091. var
  24092. tmp = new Vector3(),
  24093. px = new CubicPoly(),
  24094. py = new CubicPoly(),
  24095. pz = new CubicPoly();
  24096. /*
  24097. Based on an optimized c++ solution in
  24098. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  24099. - http://ideone.com/NoEbVM
  24100. This CubicPoly class could be used for reusing some variables and calculations,
  24101. but for three.js curve use, it could be possible inlined and flatten into a single function call
  24102. which can be placed in CurveUtils.
  24103. */
  24104. function CubicPoly() {
  24105. }
  24106. /*
  24107. * Compute coefficients for a cubic polynomial
  24108. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  24109. * such that
  24110. * p(0) = x0, p(1) = x1
  24111. * and
  24112. * p'(0) = t0, p'(1) = t1.
  24113. */
  24114. CubicPoly.prototype.init = function( x0, x1, t0, t1 ) {
  24115. this.c0 = x0;
  24116. this.c1 = t0;
  24117. this.c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  24118. this.c3 = 2 * x0 - 2 * x1 + t0 + t1;
  24119. };
  24120. CubicPoly.prototype.initNonuniformCatmullRom = function( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  24121. // compute tangents when parameterized in [t1,t2]
  24122. var t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  24123. var t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  24124. // rescale tangents for parametrization in [0,1]
  24125. t1 *= dt1;
  24126. t2 *= dt1;
  24127. // initCubicPoly
  24128. this.init( x1, x2, t1, t2 );
  24129. };
  24130. // standard Catmull-Rom spline: interpolate between x1 and x2 with previous/following points x1/x4
  24131. CubicPoly.prototype.initCatmullRom = function( x0, x1, x2, x3, tension ) {
  24132. this.init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  24133. };
  24134. CubicPoly.prototype.calc = function( t ) {
  24135. var t2 = t * t;
  24136. var t3 = t2 * t;
  24137. return this.c0 + this.c1 * t + this.c2 * t2 + this.c3 * t3;
  24138. };
  24139. // Subclass Three.js curve
  24140. return Curve.create(
  24141. function ( p /* array of Vector3 */ ) {
  24142. this.points = p || [];
  24143. this.closed = false;
  24144. },
  24145. function ( t ) {
  24146. var points = this.points,
  24147. point, intPoint, weight, l;
  24148. l = points.length;
  24149. if ( l < 2 ) console.log( 'duh, you need at least 2 points' );
  24150. point = ( l - ( this.closed ? 0 : 1 ) ) * t;
  24151. intPoint = Math.floor( point );
  24152. weight = point - intPoint;
  24153. if ( this.closed ) {
  24154. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  24155. } else if ( weight === 0 && intPoint === l - 1 ) {
  24156. intPoint = l - 2;
  24157. weight = 1;
  24158. }
  24159. var p0, p1, p2, p3; // 4 points
  24160. if ( this.closed || intPoint > 0 ) {
  24161. p0 = points[ ( intPoint - 1 ) % l ];
  24162. } else {
  24163. // extrapolate first point
  24164. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  24165. p0 = tmp;
  24166. }
  24167. p1 = points[ intPoint % l ];
  24168. p2 = points[ ( intPoint + 1 ) % l ];
  24169. if ( this.closed || intPoint + 2 < l ) {
  24170. p3 = points[ ( intPoint + 2 ) % l ];
  24171. } else {
  24172. // extrapolate last point
  24173. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  24174. p3 = tmp;
  24175. }
  24176. if ( this.type === undefined || this.type === 'centripetal' || this.type === 'chordal' ) {
  24177. // init Centripetal / Chordal Catmull-Rom
  24178. var pow = this.type === 'chordal' ? 0.5 : 0.25;
  24179. var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  24180. var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  24181. var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  24182. // safety check for repeated points
  24183. if ( dt1 < 1e-4 ) dt1 = 1.0;
  24184. if ( dt0 < 1e-4 ) dt0 = dt1;
  24185. if ( dt2 < 1e-4 ) dt2 = dt1;
  24186. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  24187. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  24188. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  24189. } else if ( this.type === 'catmullrom' ) {
  24190. var tension = this.tension !== undefined ? this.tension : 0.5;
  24191. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, tension );
  24192. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, tension );
  24193. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, tension );
  24194. }
  24195. var v = new Vector3(
  24196. px.calc( weight ),
  24197. py.calc( weight ),
  24198. pz.calc( weight )
  24199. );
  24200. return v;
  24201. }
  24202. );
  24203. } )();
  24204. /**************************************************************
  24205. * Closed Spline 3D curve
  24206. **************************************************************/
  24207. function ClosedSplineCurve3( points ) {
  24208. console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Please use THREE.CatmullRomCurve3.' );
  24209. exports.CatmullRomCurve3.call( this, points );
  24210. this.type = 'catmullrom';
  24211. this.closed = true;
  24212. }
  24213. ClosedSplineCurve3.prototype = Object.create( exports.CatmullRomCurve3.prototype );
  24214. /**************************************************************
  24215. * Spline 3D curve
  24216. **************************************************************/
  24217. var SplineCurve3 = Curve.create(
  24218. function ( points /* array of Vector3 */ ) {
  24219. console.warn( 'THREE.SplineCurve3 will be deprecated. Please use THREE.CatmullRomCurve3' );
  24220. this.points = ( points === undefined ) ? [] : points;
  24221. },
  24222. function ( t ) {
  24223. var points = this.points;
  24224. var point = ( points.length - 1 ) * t;
  24225. var intPoint = Math.floor( point );
  24226. var weight = point - intPoint;
  24227. var point0 = points[ intPoint == 0 ? intPoint : intPoint - 1 ];
  24228. var point1 = points[ intPoint ];
  24229. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  24230. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  24231. var interpolate = exports.CurveUtils.interpolate;
  24232. return new Vector3(
  24233. interpolate( point0.x, point1.x, point2.x, point3.x, weight ),
  24234. interpolate( point0.y, point1.y, point2.y, point3.y, weight ),
  24235. interpolate( point0.z, point1.z, point2.z, point3.z, weight )
  24236. );
  24237. }
  24238. );
  24239. /**************************************************************
  24240. * Cubic Bezier 3D curve
  24241. **************************************************************/
  24242. exports.CubicBezierCurve3 = Curve.create(
  24243. function ( v0, v1, v2, v3 ) {
  24244. this.v0 = v0;
  24245. this.v1 = v1;
  24246. this.v2 = v2;
  24247. this.v3 = v3;
  24248. },
  24249. function ( t ) {
  24250. var b3 = exports.ShapeUtils.b3;
  24251. return new Vector3(
  24252. b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ),
  24253. b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ),
  24254. b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z )
  24255. );
  24256. }
  24257. );
  24258. /**************************************************************
  24259. * Quadratic Bezier 3D curve
  24260. **************************************************************/
  24261. exports.QuadraticBezierCurve3 = Curve.create(
  24262. function ( v0, v1, v2 ) {
  24263. this.v0 = v0;
  24264. this.v1 = v1;
  24265. this.v2 = v2;
  24266. },
  24267. function ( t ) {
  24268. var b2 = exports.ShapeUtils.b2;
  24269. return new Vector3(
  24270. b2( t, this.v0.x, this.v1.x, this.v2.x ),
  24271. b2( t, this.v0.y, this.v1.y, this.v2.y ),
  24272. b2( t, this.v0.z, this.v1.z, this.v2.z )
  24273. );
  24274. }
  24275. );
  24276. /**************************************************************
  24277. * Line3D
  24278. **************************************************************/
  24279. exports.LineCurve3 = Curve.create(
  24280. function ( v1, v2 ) {
  24281. this.v1 = v1;
  24282. this.v2 = v2;
  24283. },
  24284. function ( t ) {
  24285. if ( t === 1 ) {
  24286. return this.v2.clone();
  24287. }
  24288. var vector = new Vector3();
  24289. vector.subVectors( this.v2, this.v1 ); // diff
  24290. vector.multiplyScalar( t );
  24291. vector.add( this.v1 );
  24292. return vector;
  24293. }
  24294. );
  24295. /**************************************************************
  24296. * Arc curve
  24297. **************************************************************/
  24298. function ArcCurve( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24299. EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  24300. }
  24301. ArcCurve.prototype = Object.create( EllipseCurve.prototype );
  24302. ArcCurve.prototype.constructor = ArcCurve;
  24303. /**
  24304. * @author alteredq / http://alteredqualia.com/
  24305. */
  24306. exports.SceneUtils = {
  24307. createMultiMaterialObject: function ( geometry, materials ) {
  24308. var group = new Group();
  24309. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  24310. group.add( new Mesh( geometry, materials[ i ] ) );
  24311. }
  24312. return group;
  24313. },
  24314. detach: function ( child, parent, scene ) {
  24315. child.applyMatrix( parent.matrixWorld );
  24316. parent.remove( child );
  24317. scene.add( child );
  24318. },
  24319. attach: function ( child, scene, parent ) {
  24320. var matrixWorldInverse = new Matrix4();
  24321. matrixWorldInverse.getInverse( parent.matrixWorld );
  24322. child.applyMatrix( matrixWorldInverse );
  24323. scene.remove( child );
  24324. parent.add( child );
  24325. }
  24326. };
  24327. Object.defineProperty( exports, 'AudioContext', {
  24328. get: function () {
  24329. return exports.getAudioContext();
  24330. }
  24331. });
  24332. exports.SpritePlugin = SpritePlugin;
  24333. exports.LensFlarePlugin = LensFlarePlugin;
  24334. exports.WebGLTextures = WebGLTextures;
  24335. exports.WebGLStencilBuffer = WebGLStencilBuffer;
  24336. exports.WebGLDepthBuffer = WebGLDepthBuffer;
  24337. exports.WebGLColorBuffer = WebGLColorBuffer;
  24338. exports.WebGLState = WebGLState;
  24339. exports.WebGLShadowMap = WebGLShadowMap;
  24340. exports.WebGLProperties = WebGLProperties;
  24341. exports.WebGLPrograms = WebGLPrograms;
  24342. exports.WebGLObjects = WebGLObjects;
  24343. exports.WebGLLights = WebGLLights;
  24344. exports.WebGLGeometries = WebGLGeometries;
  24345. exports.WebGLCapabilities = WebGLCapabilities;
  24346. exports.WebGLExtensions = WebGLExtensions;
  24347. exports.WebGLIndexedBufferRenderer = WebGLIndexedBufferRenderer;
  24348. exports.WebGLClipping = WebGLClipping;
  24349. exports.WebGLBufferRenderer = WebGLBufferRenderer;
  24350. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  24351. exports.WebGLRenderTarget = WebGLRenderTarget;
  24352. exports.WebGLRenderer = WebGLRenderer;
  24353. exports.ShaderChunk = ShaderChunk;
  24354. exports.FogExp2 = FogExp2;
  24355. exports.Fog = Fog;
  24356. exports.Scene = Scene;
  24357. exports.LensFlare = LensFlare;
  24358. exports.Sprite = Sprite;
  24359. exports.LOD = LOD;
  24360. exports.SkinnedMesh = SkinnedMesh;
  24361. exports.Skeleton = Skeleton;
  24362. exports.Bone = Bone;
  24363. exports.Mesh = Mesh;
  24364. exports.LineSegments = LineSegments;
  24365. exports.Line = Line;
  24366. exports.Points = Points;
  24367. exports.Group = Group;
  24368. exports.VideoTexture = VideoTexture;
  24369. exports.DataTexture = DataTexture;
  24370. exports.CompressedTexture = CompressedTexture;
  24371. exports.CubeTexture = CubeTexture;
  24372. exports.CanvasTexture = CanvasTexture;
  24373. exports.DepthTexture = DepthTexture;
  24374. exports.TextureIdCount = TextureIdCount;
  24375. exports.Texture = Texture;
  24376. exports.ShadowMaterial = ShadowMaterial;
  24377. exports.SpriteMaterial = SpriteMaterial;
  24378. exports.RawShaderMaterial = RawShaderMaterial;
  24379. exports.ShaderMaterial = ShaderMaterial;
  24380. exports.PointsMaterial = PointsMaterial;
  24381. exports.MultiMaterial = MultiMaterial;
  24382. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  24383. exports.MeshStandardMaterial = MeshStandardMaterial;
  24384. exports.MeshPhongMaterial = MeshPhongMaterial;
  24385. exports.MeshNormalMaterial = MeshNormalMaterial;
  24386. exports.MeshLambertMaterial = MeshLambertMaterial;
  24387. exports.MeshDepthMaterial = MeshDepthMaterial;
  24388. exports.MeshBasicMaterial = MeshBasicMaterial;
  24389. exports.LineDashedMaterial = LineDashedMaterial;
  24390. exports.LineBasicMaterial = LineBasicMaterial;
  24391. exports.MaterialIdCount = MaterialIdCount;
  24392. exports.Material = Material;
  24393. exports.CompressedTextureLoader = CompressedTextureLoader;
  24394. exports.BinaryTextureLoader = BinaryTextureLoader;
  24395. exports.DataTextureLoader = DataTextureLoader;
  24396. exports.CubeTextureLoader = CubeTextureLoader;
  24397. exports.TextureLoader = TextureLoader;
  24398. exports.ObjectLoader = ObjectLoader;
  24399. exports.MaterialLoader = MaterialLoader;
  24400. exports.BufferGeometryLoader = BufferGeometryLoader;
  24401. exports.LoadingManager = LoadingManager;
  24402. exports.JSONLoader = JSONLoader;
  24403. exports.ImageLoader = ImageLoader;
  24404. exports.FontLoader = FontLoader;
  24405. exports.XHRLoader = XHRLoader;
  24406. exports.Loader = Loader;
  24407. exports.AudioLoader = AudioLoader;
  24408. exports.SpotLightShadow = SpotLightShadow;
  24409. exports.SpotLight = SpotLight;
  24410. exports.PointLight = PointLight;
  24411. exports.HemisphereLight = HemisphereLight;
  24412. exports.DirectionalLightShadow = DirectionalLightShadow;
  24413. exports.DirectionalLight = DirectionalLight;
  24414. exports.AmbientLight = AmbientLight;
  24415. exports.LightShadow = LightShadow;
  24416. exports.Light = Light;
  24417. exports.StereoCamera = StereoCamera;
  24418. exports.PerspectiveCamera = PerspectiveCamera;
  24419. exports.OrthographicCamera = OrthographicCamera;
  24420. exports.CubeCamera = CubeCamera;
  24421. exports.Camera = Camera;
  24422. exports.AudioListener = AudioListener;
  24423. exports.PositionalAudio = PositionalAudio;
  24424. exports.getAudioContext = getAudioContext;
  24425. exports.AudioAnalyser = AudioAnalyser;
  24426. exports.Audio = Audio;
  24427. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  24428. exports.StringKeyframeTrack = StringKeyframeTrack;
  24429. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  24430. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  24431. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  24432. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  24433. exports.PropertyMixer = PropertyMixer;
  24434. exports.PropertyBinding = PropertyBinding;
  24435. exports.KeyframeTrack = KeyframeTrack;
  24436. exports.AnimationObjectGroup = AnimationObjectGroup;
  24437. exports.AnimationMixer = AnimationMixer;
  24438. exports.AnimationClip = AnimationClip;
  24439. exports.AnimationAction = AnimationAction;
  24440. exports.Uniform = Uniform;
  24441. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  24442. exports.BufferGeometry = BufferGeometry;
  24443. exports.DirectGeometry = DirectGeometry;
  24444. exports.GeometryIdCount = GeometryIdCount;
  24445. exports.Geometry = Geometry;
  24446. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  24447. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  24448. exports.InterleavedBuffer = InterleavedBuffer;
  24449. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  24450. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  24451. exports.Float64Attribute = Float64Attribute;
  24452. exports.Float32Attribute = Float32Attribute;
  24453. exports.Uint32Attribute = Uint32Attribute;
  24454. exports.Int32Attribute = Int32Attribute;
  24455. exports.Uint16Attribute = Uint16Attribute;
  24456. exports.Int16Attribute = Int16Attribute;
  24457. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  24458. exports.Uint8Attribute = Uint8Attribute;
  24459. exports.Int8Attribute = Int8Attribute;
  24460. exports.BufferAttribute = BufferAttribute;
  24461. exports.Face3 = Face3;
  24462. exports.Object3DIdCount = Object3DIdCount;
  24463. exports.Object3D = Object3D;
  24464. exports.Raycaster = Raycaster;
  24465. exports.Layers = Layers;
  24466. exports.EventDispatcher = EventDispatcher;
  24467. exports.Clock = Clock;
  24468. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  24469. exports.LinearInterpolant = LinearInterpolant;
  24470. exports.DiscreteInterpolant = DiscreteInterpolant;
  24471. exports.CubicInterpolant = CubicInterpolant;
  24472. exports.Interpolant = Interpolant;
  24473. exports.Triangle = Triangle;
  24474. exports.Spline = Spline;
  24475. exports.Spherical = Spherical;
  24476. exports.Plane = Plane;
  24477. exports.Frustum = Frustum;
  24478. exports.Sphere = Sphere;
  24479. exports.Ray = Ray;
  24480. exports.Matrix4 = Matrix4;
  24481. exports.Matrix3 = Matrix3;
  24482. exports.Box3 = Box3;
  24483. exports.Box2 = Box2;
  24484. exports.Line3 = Line3;
  24485. exports.Euler = Euler;
  24486. exports.Vector4 = Vector4;
  24487. exports.Vector3 = Vector3;
  24488. exports.Vector2 = Vector2;
  24489. exports.Quaternion = Quaternion;
  24490. exports.Color = Color;
  24491. exports.MorphBlendMesh = MorphBlendMesh;
  24492. exports.ImmediateRenderObject = ImmediateRenderObject;
  24493. exports.WireframeHelper = WireframeHelper;
  24494. exports.VertexNormalsHelper = VertexNormalsHelper;
  24495. exports.SpotLightHelper = SpotLightHelper;
  24496. exports.SkeletonHelper = SkeletonHelper;
  24497. exports.PointLightHelper = PointLightHelper;
  24498. exports.HemisphereLightHelper = HemisphereLightHelper;
  24499. exports.GridHelper = GridHelper;
  24500. exports.FaceNormalsHelper = FaceNormalsHelper;
  24501. exports.EdgesHelper = EdgesHelper;
  24502. exports.DirectionalLightHelper = DirectionalLightHelper;
  24503. exports.CameraHelper = CameraHelper;
  24504. exports.BoundingBoxHelper = BoundingBoxHelper;
  24505. exports.BoxHelper = BoxHelper;
  24506. exports.AxisHelper = AxisHelper;
  24507. exports.WireframeGeometry = WireframeGeometry;
  24508. exports.ParametricGeometry = ParametricGeometry;
  24509. exports.TetrahedronGeometry = TetrahedronGeometry;
  24510. exports.OctahedronGeometry = OctahedronGeometry;
  24511. exports.IcosahedronGeometry = IcosahedronGeometry;
  24512. exports.DodecahedronGeometry = DodecahedronGeometry;
  24513. exports.PolyhedronGeometry = PolyhedronGeometry;
  24514. exports.TubeGeometry = TubeGeometry;
  24515. exports.TorusKnotGeometry = TorusKnotGeometry;
  24516. exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry;
  24517. exports.TorusGeometry = TorusGeometry;
  24518. exports.TorusBufferGeometry = TorusBufferGeometry;
  24519. exports.TextGeometry = TextGeometry;
  24520. exports.SphereBufferGeometry = SphereBufferGeometry;
  24521. exports.SphereGeometry = SphereGeometry;
  24522. exports.RingGeometry = RingGeometry;
  24523. exports.RingBufferGeometry = RingBufferGeometry;
  24524. exports.PlaneBufferGeometry = PlaneBufferGeometry;
  24525. exports.PlaneGeometry = PlaneGeometry;
  24526. exports.LatheGeometry = LatheGeometry;
  24527. exports.LatheBufferGeometry = LatheBufferGeometry;
  24528. exports.ShapeGeometry = ShapeGeometry;
  24529. exports.ExtrudeGeometry = ExtrudeGeometry;
  24530. exports.EdgesGeometry = EdgesGeometry;
  24531. exports.ConeGeometry = ConeGeometry;
  24532. exports.ConeBufferGeometry = ConeBufferGeometry;
  24533. exports.CylinderGeometry = CylinderGeometry;
  24534. exports.CylinderBufferGeometry = CylinderBufferGeometry;
  24535. exports.CircleBufferGeometry = CircleBufferGeometry;
  24536. exports.CircleGeometry = CircleGeometry;
  24537. exports.BoxBufferGeometry = BoxBufferGeometry;
  24538. exports.BoxGeometry = BoxGeometry;
  24539. exports.ClosedSplineCurve3 = ClosedSplineCurve3;
  24540. exports.SplineCurve3 = SplineCurve3;
  24541. exports.ArcCurve = ArcCurve;
  24542. exports.EllipseCurve = EllipseCurve;
  24543. exports.SplineCurve = SplineCurve;
  24544. exports.CubicBezierCurve = CubicBezierCurve;
  24545. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  24546. exports.LineCurve = LineCurve;
  24547. exports.Shape = Shape;
  24548. exports.ShapePath = ShapePath;
  24549. exports.Path = Path;
  24550. exports.Font = Font;
  24551. exports.CurvePath = CurvePath;
  24552. exports.Curve = Curve;
  24553. exports.REVISION = REVISION;
  24554. exports.MOUSE = MOUSE;
  24555. exports.CullFaceNone = CullFaceNone;
  24556. exports.CullFaceBack = CullFaceBack;
  24557. exports.CullFaceFront = CullFaceFront;
  24558. exports.CullFaceFrontBack = CullFaceFrontBack;
  24559. exports.FrontFaceDirectionCW = FrontFaceDirectionCW;
  24560. exports.FrontFaceDirectionCCW = FrontFaceDirectionCCW;
  24561. exports.BasicShadowMap = BasicShadowMap;
  24562. exports.PCFShadowMap = PCFShadowMap;
  24563. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  24564. exports.FrontSide = FrontSide;
  24565. exports.BackSide = BackSide;
  24566. exports.DoubleSide = DoubleSide;
  24567. exports.FlatShading = FlatShading;
  24568. exports.SmoothShading = SmoothShading;
  24569. exports.NoColors = NoColors;
  24570. exports.FaceColors = FaceColors;
  24571. exports.VertexColors = VertexColors;
  24572. exports.NoBlending = NoBlending;
  24573. exports.NormalBlending = NormalBlending;
  24574. exports.AdditiveBlending = AdditiveBlending;
  24575. exports.SubtractiveBlending = SubtractiveBlending;
  24576. exports.MultiplyBlending = MultiplyBlending;
  24577. exports.CustomBlending = CustomBlending;
  24578. exports.AddEquation = AddEquation;
  24579. exports.SubtractEquation = SubtractEquation;
  24580. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  24581. exports.MinEquation = MinEquation;
  24582. exports.MaxEquation = MaxEquation;
  24583. exports.ZeroFactor = ZeroFactor;
  24584. exports.OneFactor = OneFactor;
  24585. exports.SrcColorFactor = SrcColorFactor;
  24586. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  24587. exports.SrcAlphaFactor = SrcAlphaFactor;
  24588. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  24589. exports.DstAlphaFactor = DstAlphaFactor;
  24590. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  24591. exports.DstColorFactor = DstColorFactor;
  24592. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  24593. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  24594. exports.NeverDepth = NeverDepth;
  24595. exports.AlwaysDepth = AlwaysDepth;
  24596. exports.LessDepth = LessDepth;
  24597. exports.LessEqualDepth = LessEqualDepth;
  24598. exports.EqualDepth = EqualDepth;
  24599. exports.GreaterEqualDepth = GreaterEqualDepth;
  24600. exports.GreaterDepth = GreaterDepth;
  24601. exports.NotEqualDepth = NotEqualDepth;
  24602. exports.MultiplyOperation = MultiplyOperation;
  24603. exports.MixOperation = MixOperation;
  24604. exports.AddOperation = AddOperation;
  24605. exports.NoToneMapping = NoToneMapping;
  24606. exports.LinearToneMapping = LinearToneMapping;
  24607. exports.ReinhardToneMapping = ReinhardToneMapping;
  24608. exports.Uncharted2ToneMapping = Uncharted2ToneMapping;
  24609. exports.CineonToneMapping = CineonToneMapping;
  24610. exports.UVMapping = UVMapping;
  24611. exports.CubeReflectionMapping = CubeReflectionMapping;
  24612. exports.CubeRefractionMapping = CubeRefractionMapping;
  24613. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  24614. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  24615. exports.SphericalReflectionMapping = SphericalReflectionMapping;
  24616. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  24617. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  24618. exports.RepeatWrapping = RepeatWrapping;
  24619. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  24620. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  24621. exports.NearestFilter = NearestFilter;
  24622. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  24623. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  24624. exports.LinearFilter = LinearFilter;
  24625. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  24626. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  24627. exports.UnsignedByteType = UnsignedByteType;
  24628. exports.ByteType = ByteType;
  24629. exports.ShortType = ShortType;
  24630. exports.UnsignedShortType = UnsignedShortType;
  24631. exports.IntType = IntType;
  24632. exports.UnsignedIntType = UnsignedIntType;
  24633. exports.FloatType = FloatType;
  24634. exports.HalfFloatType = HalfFloatType;
  24635. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  24636. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  24637. exports.UnsignedShort565Type = UnsignedShort565Type;
  24638. exports.UnsignedInt248Type = UnsignedInt248Type;
  24639. exports.AlphaFormat = AlphaFormat;
  24640. exports.RGBFormat = RGBFormat;
  24641. exports.RGBAFormat = RGBAFormat;
  24642. exports.LuminanceFormat = LuminanceFormat;
  24643. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  24644. exports.RGBEFormat = RGBEFormat;
  24645. exports.DepthFormat = DepthFormat;
  24646. exports.DepthStencilFormat = DepthStencilFormat;
  24647. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  24648. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  24649. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  24650. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  24651. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  24652. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  24653. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  24654. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  24655. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  24656. exports.LoopOnce = LoopOnce;
  24657. exports.LoopRepeat = LoopRepeat;
  24658. exports.LoopPingPong = LoopPingPong;
  24659. exports.InterpolateDiscrete = InterpolateDiscrete;
  24660. exports.InterpolateLinear = InterpolateLinear;
  24661. exports.InterpolateSmooth = InterpolateSmooth;
  24662. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  24663. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  24664. exports.WrapAroundEnding = WrapAroundEnding;
  24665. exports.TrianglesDrawMode = TrianglesDrawMode;
  24666. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  24667. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  24668. exports.LinearEncoding = LinearEncoding;
  24669. exports.sRGBEncoding = sRGBEncoding;
  24670. exports.GammaEncoding = GammaEncoding;
  24671. exports.RGBEEncoding = RGBEEncoding;
  24672. exports.LogLuvEncoding = LogLuvEncoding;
  24673. exports.RGBM7Encoding = RGBM7Encoding;
  24674. exports.RGBM16Encoding = RGBM16Encoding;
  24675. exports.RGBDEncoding = RGBDEncoding;
  24676. exports.BasicDepthPacking = BasicDepthPacking;
  24677. exports.RGBADepthPacking = RGBADepthPacking;
  24678. Object.defineProperty(exports, '__esModule', { value: true });
  24679. }));
  24680. /**
  24681. * @author mrdoob / http://mrdoob.com/
  24682. */
  24683. Object.assign( THREE, {
  24684. CubeGeometry: THREE.BoxGeometry,
  24685. Face4: function ( a, b, c, d, normal, color, materialIndex ) {
  24686. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' );
  24687. return new THREE.Face3( a, b, c, normal, color, materialIndex );
  24688. },
  24689. LineStrip: 0,
  24690. LinePieces: 1,
  24691. MeshFaceMaterial: THREE.MultiMaterial,
  24692. PointCloud: function ( geometry, material ) {
  24693. console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
  24694. return new THREE.Points( geometry, material );
  24695. },
  24696. Particle: THREE.Sprite,
  24697. ParticleSystem: function ( geometry, material ) {
  24698. console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
  24699. return new THREE.Points( geometry, material );
  24700. },
  24701. PointCloudMaterial: function ( parameters ) {
  24702. console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
  24703. return new THREE.PointsMaterial( parameters );
  24704. },
  24705. ParticleBasicMaterial: function ( parameters ) {
  24706. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
  24707. return new THREE.PointsMaterial( parameters );
  24708. },
  24709. ParticleSystemMaterial: function ( parameters ) {
  24710. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
  24711. return new THREE.PointsMaterial( parameters );
  24712. },
  24713. Vertex: function ( x, y, z ) {
  24714. console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' );
  24715. return new THREE.Vector3( x, y, z );
  24716. }
  24717. } );
  24718. //
  24719. Object.assign( THREE.Box2.prototype, {
  24720. empty: function () {
  24721. console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' );
  24722. return this.isEmpty();
  24723. },
  24724. isIntersectionBox: function ( box ) {
  24725. console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
  24726. return this.intersectsBox( box );
  24727. }
  24728. } );
  24729. Object.assign( THREE.Box3.prototype, {
  24730. empty: function () {
  24731. console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' );
  24732. return this.isEmpty();
  24733. },
  24734. isIntersectionBox: function ( box ) {
  24735. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  24736. return this.intersectsBox( box );
  24737. },
  24738. isIntersectionSphere: function ( sphere ) {
  24739. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  24740. return this.intersectsSphere( sphere );
  24741. }
  24742. } );
  24743. Object.assign( THREE.Matrix3.prototype, {
  24744. multiplyVector3: function ( vector ) {
  24745. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  24746. return vector.applyMatrix3( this );
  24747. },
  24748. multiplyVector3Array: function ( a ) {
  24749. console.warn( 'THREE.Matrix3: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  24750. return this.applyToVector3Array( a );
  24751. }
  24752. } );
  24753. Object.assign( THREE.Matrix4.prototype, {
  24754. extractPosition: function ( m ) {
  24755. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  24756. return this.copyPosition( m );
  24757. },
  24758. setRotationFromQuaternion: function ( q ) {
  24759. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  24760. return this.makeRotationFromQuaternion( q );
  24761. },
  24762. multiplyVector3: function ( vector ) {
  24763. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  24764. return vector.applyProjection( this );
  24765. },
  24766. multiplyVector4: function ( vector ) {
  24767. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  24768. return vector.applyMatrix4( this );
  24769. },
  24770. multiplyVector3Array: function ( a ) {
  24771. console.warn( 'THREE.Matrix4: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  24772. return this.applyToVector3Array( a );
  24773. },
  24774. rotateAxis: function ( v ) {
  24775. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  24776. v.transformDirection( this );
  24777. },
  24778. crossVector: function ( vector ) {
  24779. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  24780. return vector.applyMatrix4( this );
  24781. },
  24782. translate: function ( v ) {
  24783. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  24784. },
  24785. rotateX: function ( angle ) {
  24786. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  24787. },
  24788. rotateY: function ( angle ) {
  24789. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  24790. },
  24791. rotateZ: function ( angle ) {
  24792. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  24793. },
  24794. rotateByAxis: function ( axis, angle ) {
  24795. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  24796. }
  24797. } );
  24798. Object.assign( THREE.Plane.prototype, {
  24799. isIntersectionLine: function ( line ) {
  24800. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  24801. return this.intersectsLine( line );
  24802. }
  24803. } );
  24804. Object.assign( THREE.Quaternion.prototype, {
  24805. multiplyVector3: function ( vector ) {
  24806. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  24807. return vector.applyQuaternion( this );
  24808. }
  24809. } );
  24810. Object.assign( THREE.Ray.prototype, {
  24811. isIntersectionBox: function ( box ) {
  24812. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  24813. return this.intersectsBox( box );
  24814. },
  24815. isIntersectionPlane: function ( plane ) {
  24816. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  24817. return this.intersectsPlane( plane );
  24818. },
  24819. isIntersectionSphere: function ( sphere ) {
  24820. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  24821. return this.intersectsSphere( sphere );
  24822. }
  24823. } );
  24824. Object.assign( THREE.Vector3.prototype, {
  24825. setEulerFromRotationMatrix: function () {
  24826. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  24827. },
  24828. setEulerFromQuaternion: function () {
  24829. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  24830. },
  24831. getPositionFromMatrix: function ( m ) {
  24832. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  24833. return this.setFromMatrixPosition( m );
  24834. },
  24835. getScaleFromMatrix: function ( m ) {
  24836. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  24837. return this.setFromMatrixScale( m );
  24838. },
  24839. getColumnFromMatrix: function ( index, matrix ) {
  24840. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  24841. return this.setFromMatrixColumn( matrix, index );
  24842. }
  24843. } );
  24844. //
  24845. Object.assign( THREE.Object3D.prototype, {
  24846. getChildByName: function ( name ) {
  24847. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  24848. return this.getObjectByName( name );
  24849. },
  24850. renderDepth: function ( value ) {
  24851. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  24852. },
  24853. translate: function ( distance, axis ) {
  24854. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  24855. return this.translateOnAxis( axis, distance );
  24856. }
  24857. } );
  24858. Object.defineProperties( THREE.Object3D.prototype, {
  24859. eulerOrder: {
  24860. get: function () {
  24861. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  24862. return this.rotation.order;
  24863. },
  24864. set: function ( value ) {
  24865. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  24866. this.rotation.order = value;
  24867. }
  24868. },
  24869. useQuaternion: {
  24870. get: function () {
  24871. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  24872. },
  24873. set: function ( value ) {
  24874. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  24875. }
  24876. }
  24877. } );
  24878. Object.defineProperties( THREE.LOD.prototype, {
  24879. objects: {
  24880. get: function () {
  24881. console.warn( 'THREE.LOD: .objects has been renamed to .levels.' );
  24882. return this.levels;
  24883. }
  24884. }
  24885. } );
  24886. //
  24887. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) {
  24888. console.warn( "THREE.PerspectiveCamera.setLens is deprecated. " +
  24889. "Use .setFocalLength and .filmGauge for a photographic setup." );
  24890. if ( filmGauge !== undefined ) this.filmGauge = filmGauge;
  24891. this.setFocalLength( focalLength );
  24892. };
  24893. //
  24894. Object.defineProperties( THREE.Light.prototype, {
  24895. onlyShadow: {
  24896. set: function ( value ) {
  24897. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  24898. }
  24899. },
  24900. shadowCameraFov: {
  24901. set: function ( value ) {
  24902. console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' );
  24903. this.shadow.camera.fov = value;
  24904. }
  24905. },
  24906. shadowCameraLeft: {
  24907. set: function ( value ) {
  24908. console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' );
  24909. this.shadow.camera.left = value;
  24910. }
  24911. },
  24912. shadowCameraRight: {
  24913. set: function ( value ) {
  24914. console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' );
  24915. this.shadow.camera.right = value;
  24916. }
  24917. },
  24918. shadowCameraTop: {
  24919. set: function ( value ) {
  24920. console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' );
  24921. this.shadow.camera.top = value;
  24922. }
  24923. },
  24924. shadowCameraBottom: {
  24925. set: function ( value ) {
  24926. console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' );
  24927. this.shadow.camera.bottom = value;
  24928. }
  24929. },
  24930. shadowCameraNear: {
  24931. set: function ( value ) {
  24932. console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' );
  24933. this.shadow.camera.near = value;
  24934. }
  24935. },
  24936. shadowCameraFar: {
  24937. set: function ( value ) {
  24938. console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' );
  24939. this.shadow.camera.far = value;
  24940. }
  24941. },
  24942. shadowCameraVisible: {
  24943. set: function ( value ) {
  24944. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );
  24945. }
  24946. },
  24947. shadowBias: {
  24948. set: function ( value ) {
  24949. console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' );
  24950. this.shadow.bias = value;
  24951. }
  24952. },
  24953. shadowDarkness: {
  24954. set: function ( value ) {
  24955. console.warn( 'THREE.Light: .shadowDarkness has been removed.' );
  24956. }
  24957. },
  24958. shadowMapWidth: {
  24959. set: function ( value ) {
  24960. console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' );
  24961. this.shadow.mapSize.width = value;
  24962. }
  24963. },
  24964. shadowMapHeight: {
  24965. set: function ( value ) {
  24966. console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' );
  24967. this.shadow.mapSize.height = value;
  24968. }
  24969. }
  24970. } );
  24971. //
  24972. Object.defineProperties( THREE.BufferAttribute.prototype, {
  24973. length: {
  24974. get: function () {
  24975. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Please use .count.' );
  24976. return this.array.length;
  24977. }
  24978. }
  24979. } );
  24980. Object.assign( THREE.BufferGeometry.prototype, {
  24981. addIndex: function ( index ) {
  24982. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  24983. this.setIndex( index );
  24984. },
  24985. addDrawCall: function ( start, count, indexOffset ) {
  24986. if ( indexOffset !== undefined ) {
  24987. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  24988. }
  24989. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  24990. this.addGroup( start, count );
  24991. },
  24992. clearDrawCalls: function () {
  24993. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  24994. this.clearGroups();
  24995. },
  24996. computeTangents: function () {
  24997. console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' );
  24998. },
  24999. computeOffsets: function () {
  25000. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );
  25001. }
  25002. } );
  25003. Object.defineProperties( THREE.BufferGeometry.prototype, {
  25004. drawcalls: {
  25005. get: function () {
  25006. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  25007. return this.groups;
  25008. }
  25009. },
  25010. offsets: {
  25011. get: function () {
  25012. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  25013. return this.groups;
  25014. }
  25015. }
  25016. } );
  25017. //
  25018. Object.defineProperties( THREE.Material.prototype, {
  25019. wrapAround: {
  25020. get: function () {
  25021. console.warn( 'THREE.' + this.type + ': .wrapAround has been removed.' );
  25022. },
  25023. set: function ( value ) {
  25024. console.warn( 'THREE.' + this.type + ': .wrapAround has been removed.' );
  25025. }
  25026. },
  25027. wrapRGB: {
  25028. get: function () {
  25029. console.warn( 'THREE.' + this.type + ': .wrapRGB has been removed.' );
  25030. return new THREE.Color();
  25031. }
  25032. }
  25033. } );
  25034. Object.defineProperties( THREE.MeshPhongMaterial.prototype, {
  25035. metal: {
  25036. get: function () {
  25037. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' );
  25038. return false;
  25039. },
  25040. set: function ( value ) {
  25041. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' );
  25042. }
  25043. }
  25044. } );
  25045. Object.defineProperties( THREE.ShaderMaterial.prototype, {
  25046. derivatives: {
  25047. get: function () {
  25048. console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  25049. return this.extensions.derivatives;
  25050. },
  25051. set: function ( value ) {
  25052. console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  25053. this.extensions.derivatives = value;
  25054. }
  25055. }
  25056. } );
  25057. //
  25058. THREE.EventDispatcher.prototype = Object.assign( Object.create( {
  25059. // Note: Extra base ensures these properties are not 'assign'ed.
  25060. constructor: THREE.EventDispatcher,
  25061. apply: function ( target ) {
  25062. console.warn( "THREE.EventDispatcher: .apply is deprecated, " +
  25063. "just inherit or Object.assign the prototype to mix-in." );
  25064. Object.assign( target, this );
  25065. }
  25066. } ), THREE.EventDispatcher.prototype );
  25067. //
  25068. Object.assign( THREE.WebGLRenderer.prototype, {
  25069. supportsFloatTextures: function () {
  25070. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  25071. return this.extensions.get( 'OES_texture_float' );
  25072. },
  25073. supportsHalfFloatTextures: function () {
  25074. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  25075. return this.extensions.get( 'OES_texture_half_float' );
  25076. },
  25077. supportsStandardDerivatives: function () {
  25078. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  25079. return this.extensions.get( 'OES_standard_derivatives' );
  25080. },
  25081. supportsCompressedTextureS3TC: function () {
  25082. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  25083. return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  25084. },
  25085. supportsCompressedTexturePVRTC: function () {
  25086. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  25087. return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  25088. },
  25089. supportsBlendMinMax: function () {
  25090. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  25091. return this.extensions.get( 'EXT_blend_minmax' );
  25092. },
  25093. supportsVertexTextures: function () {
  25094. return this.capabilities.vertexTextures;
  25095. },
  25096. supportsInstancedArrays: function () {
  25097. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  25098. return this.extensions.get( 'ANGLE_instanced_arrays' );
  25099. },
  25100. enableScissorTest: function ( boolean ) {
  25101. console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' );
  25102. this.setScissorTest( boolean );
  25103. },
  25104. initMaterial: function () {
  25105. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  25106. },
  25107. addPrePlugin: function () {
  25108. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  25109. },
  25110. addPostPlugin: function () {
  25111. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  25112. },
  25113. updateShadowMap: function () {
  25114. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  25115. }
  25116. } );
  25117. Object.defineProperties( THREE.WebGLRenderer.prototype, {
  25118. shadowMapEnabled: {
  25119. get: function () {
  25120. return this.shadowMap.enabled;
  25121. },
  25122. set: function ( value ) {
  25123. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  25124. this.shadowMap.enabled = value;
  25125. }
  25126. },
  25127. shadowMapType: {
  25128. get: function () {
  25129. return this.shadowMap.type;
  25130. },
  25131. set: function ( value ) {
  25132. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  25133. this.shadowMap.type = value;
  25134. }
  25135. },
  25136. shadowMapCullFace: {
  25137. get: function () {
  25138. return this.shadowMap.cullFace;
  25139. },
  25140. set: function ( value ) {
  25141. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace is now .shadowMap.cullFace.' );
  25142. this.shadowMap.cullFace = value;
  25143. }
  25144. }
  25145. } );
  25146. Object.defineProperties( THREE.WebGLShadowMap.prototype, {
  25147. cullFace: {
  25148. get: function () {
  25149. return this.renderReverseSided ? THREE.CullFaceFront : THREE.CullFaceBack;
  25150. },
  25151. set: function ( cullFace ) {
  25152. var value = ( cullFace !== THREE.CullFaceBack );
  25153. console.warn( "WebGLRenderer: .shadowMap.cullFace is deprecated. Set .shadowMap.renderReverseSided to " + value + "." );
  25154. this.renderReverseSided = value;
  25155. }
  25156. }
  25157. } );
  25158. //
  25159. Object.defineProperties( THREE.WebGLRenderTarget.prototype, {
  25160. wrapS: {
  25161. get: function () {
  25162. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  25163. return this.texture.wrapS;
  25164. },
  25165. set: function ( value ) {
  25166. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  25167. this.texture.wrapS = value;
  25168. }
  25169. },
  25170. wrapT: {
  25171. get: function () {
  25172. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  25173. return this.texture.wrapT;
  25174. },
  25175. set: function ( value ) {
  25176. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  25177. this.texture.wrapT = value;
  25178. }
  25179. },
  25180. magFilter: {
  25181. get: function () {
  25182. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  25183. return this.texture.magFilter;
  25184. },
  25185. set: function ( value ) {
  25186. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  25187. this.texture.magFilter = value;
  25188. }
  25189. },
  25190. minFilter: {
  25191. get: function () {
  25192. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  25193. return this.texture.minFilter;
  25194. },
  25195. set: function ( value ) {
  25196. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  25197. this.texture.minFilter = value;
  25198. }
  25199. },
  25200. anisotropy: {
  25201. get: function () {
  25202. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  25203. return this.texture.anisotropy;
  25204. },
  25205. set: function ( value ) {
  25206. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  25207. this.texture.anisotropy = value;
  25208. }
  25209. },
  25210. offset: {
  25211. get: function () {
  25212. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  25213. return this.texture.offset;
  25214. },
  25215. set: function ( value ) {
  25216. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  25217. this.texture.offset = value;
  25218. }
  25219. },
  25220. repeat: {
  25221. get: function () {
  25222. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  25223. return this.texture.repeat;
  25224. },
  25225. set: function ( value ) {
  25226. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  25227. this.texture.repeat = value;
  25228. }
  25229. },
  25230. format: {
  25231. get: function () {
  25232. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  25233. return this.texture.format;
  25234. },
  25235. set: function ( value ) {
  25236. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  25237. this.texture.format = value;
  25238. }
  25239. },
  25240. type: {
  25241. get: function () {
  25242. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  25243. return this.texture.type;
  25244. },
  25245. set: function ( value ) {
  25246. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  25247. this.texture.type = value;
  25248. }
  25249. },
  25250. generateMipmaps: {
  25251. get: function () {
  25252. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  25253. return this.texture.generateMipmaps;
  25254. },
  25255. set: function ( value ) {
  25256. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  25257. this.texture.generateMipmaps = value;
  25258. }
  25259. }
  25260. } );
  25261. //
  25262. Object.assign( THREE.Audio.prototype, {
  25263. load: function ( file ) {
  25264. console.warn( 'THREE.Audio: .load has been deprecated. Please use THREE.AudioLoader.' );
  25265. var scope = this;
  25266. var audioLoader = new THREE.AudioLoader();
  25267. audioLoader.load( file, function ( buffer ) {
  25268. scope.setBuffer( buffer );
  25269. } );
  25270. return this;
  25271. }
  25272. } );
  25273. Object.assign( THREE.AudioAnalyser.prototype, {
  25274. getData: function ( file ) {
  25275. console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' );
  25276. return this.getFrequencyData();
  25277. }
  25278. } );
  25279. //
  25280. THREE.GeometryUtils = {
  25281. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  25282. console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  25283. var matrix;
  25284. if ( geometry2 instanceof THREE.Mesh ) {
  25285. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  25286. matrix = geometry2.matrix;
  25287. geometry2 = geometry2.geometry;
  25288. }
  25289. geometry1.merge( geometry2, matrix, materialIndexOffset );
  25290. },
  25291. center: function ( geometry ) {
  25292. console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
  25293. return geometry.center();
  25294. }
  25295. };
  25296. THREE.ImageUtils = {
  25297. crossOrigin: undefined,
  25298. loadTexture: function ( url, mapping, onLoad, onError ) {
  25299. console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
  25300. var loader = new THREE.TextureLoader();
  25301. loader.setCrossOrigin( this.crossOrigin );
  25302. var texture = loader.load( url, onLoad, undefined, onError );
  25303. if ( mapping ) texture.mapping = mapping;
  25304. return texture;
  25305. },
  25306. loadTextureCube: function ( urls, mapping, onLoad, onError ) {
  25307. console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
  25308. var loader = new THREE.CubeTextureLoader();
  25309. loader.setCrossOrigin( this.crossOrigin );
  25310. var texture = loader.load( urls, onLoad, undefined, onError );
  25311. if ( mapping ) texture.mapping = mapping;
  25312. return texture;
  25313. },
  25314. loadCompressedTexture: function () {
  25315. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' );
  25316. },
  25317. loadCompressedTextureCube: function () {
  25318. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' );
  25319. }
  25320. };
  25321. //
  25322. THREE.Projector = function () {
  25323. console.error( 'THREE.Projector has been moved to /examples/js/renderers/Projector.js.' );
  25324. this.projectVector = function ( vector, camera ) {
  25325. console.warn( 'THREE.Projector: .projectVector() is now vector.project().' );
  25326. vector.project( camera );
  25327. };
  25328. this.unprojectVector = function ( vector, camera ) {
  25329. console.warn( 'THREE.Projector: .unprojectVector() is now vector.unproject().' );
  25330. vector.unproject( camera );
  25331. };
  25332. this.pickingRay = function ( vector, camera ) {
  25333. console.error( 'THREE.Projector: .pickingRay() is now raycaster.setFromCamera().' );
  25334. };
  25335. };
  25336. //
  25337. THREE.CanvasRenderer = function () {
  25338. console.error( 'THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js' );
  25339. this.domElement = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  25340. this.clear = function () {};
  25341. this.render = function () {};
  25342. this.setClearColor = function () {};
  25343. this.setSize = function () {};
  25344. };
粤ICP备19079148号