three.js 1.0 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848
  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 = '81dev';
  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 BlendingMode = {
  127. NoBlending: NoBlending,
  128. NormalBlending: NormalBlending,
  129. AdditiveBlending: AdditiveBlending,
  130. SubtractiveBlending: SubtractiveBlending,
  131. MultiplyBlending: MultiplyBlending,
  132. CustomBlending: CustomBlending
  133. };
  134. var AddEquation = 100;
  135. var SubtractEquation = 101;
  136. var ReverseSubtractEquation = 102;
  137. var MinEquation = 103;
  138. var MaxEquation = 104;
  139. var ZeroFactor = 200;
  140. var OneFactor = 201;
  141. var SrcColorFactor = 202;
  142. var OneMinusSrcColorFactor = 203;
  143. var SrcAlphaFactor = 204;
  144. var OneMinusSrcAlphaFactor = 205;
  145. var DstAlphaFactor = 206;
  146. var OneMinusDstAlphaFactor = 207;
  147. var DstColorFactor = 208;
  148. var OneMinusDstColorFactor = 209;
  149. var SrcAlphaSaturateFactor = 210;
  150. var NeverDepth = 0;
  151. var AlwaysDepth = 1;
  152. var LessDepth = 2;
  153. var LessEqualDepth = 3;
  154. var EqualDepth = 4;
  155. var GreaterEqualDepth = 5;
  156. var GreaterDepth = 6;
  157. var NotEqualDepth = 7;
  158. var MultiplyOperation = 0;
  159. var MixOperation = 1;
  160. var AddOperation = 2;
  161. var NoToneMapping = 0;
  162. var LinearToneMapping = 1;
  163. var ReinhardToneMapping = 2;
  164. var Uncharted2ToneMapping = 3;
  165. var CineonToneMapping = 4;
  166. var UVMapping = 300;
  167. var CubeReflectionMapping = 301;
  168. var CubeRefractionMapping = 302;
  169. var EquirectangularReflectionMapping = 303;
  170. var EquirectangularRefractionMapping = 304;
  171. var SphericalReflectionMapping = 305;
  172. var CubeUVReflectionMapping = 306;
  173. var CubeUVRefractionMapping = 307;
  174. var TextureMapping = {
  175. UVMapping: UVMapping,
  176. CubeReflectionMapping: CubeReflectionMapping,
  177. CubeRefractionMapping: CubeRefractionMapping,
  178. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  179. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  180. SphericalReflectionMapping: SphericalReflectionMapping,
  181. CubeUVReflectionMapping: CubeUVReflectionMapping,
  182. CubeUVRefractionMapping: CubeUVRefractionMapping
  183. };
  184. var RepeatWrapping = 1000;
  185. var ClampToEdgeWrapping = 1001;
  186. var MirroredRepeatWrapping = 1002;
  187. var TextureWrapping = {
  188. RepeatWrapping: RepeatWrapping,
  189. ClampToEdgeWrapping: ClampToEdgeWrapping,
  190. MirroredRepeatWrapping: MirroredRepeatWrapping
  191. };
  192. var NearestFilter = 1003;
  193. var NearestMipMapNearestFilter = 1004;
  194. var NearestMipMapLinearFilter = 1005;
  195. var LinearFilter = 1006;
  196. var LinearMipMapNearestFilter = 1007;
  197. var LinearMipMapLinearFilter = 1008;
  198. var TextureFilter = {
  199. NearestFilter: NearestFilter,
  200. NearestMipMapNearestFilter: NearestMipMapNearestFilter,
  201. NearestMipMapLinearFilter: NearestMipMapLinearFilter,
  202. LinearFilter: LinearFilter,
  203. LinearMipMapNearestFilter: LinearMipMapNearestFilter,
  204. LinearMipMapLinearFilter: LinearMipMapLinearFilter
  205. };
  206. var UnsignedByteType = 1009;
  207. var ByteType = 1010;
  208. var ShortType = 1011;
  209. var UnsignedShortType = 1012;
  210. var IntType = 1013;
  211. var UnsignedIntType = 1014;
  212. var FloatType = 1015;
  213. var HalfFloatType = 1016;
  214. var UnsignedShort4444Type = 1017;
  215. var UnsignedShort5551Type = 1018;
  216. var UnsignedShort565Type = 1019;
  217. var UnsignedInt248Type = 1020;
  218. var AlphaFormat = 1021;
  219. var RGBFormat = 1022;
  220. var RGBAFormat = 1023;
  221. var LuminanceFormat = 1024;
  222. var LuminanceAlphaFormat = 1025;
  223. var RGBEFormat = RGBAFormat;
  224. var DepthFormat = 1026;
  225. var DepthStencilFormat = 1027;
  226. var RGB_S3TC_DXT1_Format = 2001;
  227. var RGBA_S3TC_DXT1_Format = 2002;
  228. var RGBA_S3TC_DXT3_Format = 2003;
  229. var RGBA_S3TC_DXT5_Format = 2004;
  230. var RGB_PVRTC_4BPPV1_Format = 2100;
  231. var RGB_PVRTC_2BPPV1_Format = 2101;
  232. var RGBA_PVRTC_4BPPV1_Format = 2102;
  233. var RGBA_PVRTC_2BPPV1_Format = 2103;
  234. var RGB_ETC1_Format = 2151;
  235. var LoopOnce = 2200;
  236. var LoopRepeat = 2201;
  237. var LoopPingPong = 2202;
  238. var InterpolateDiscrete = 2300;
  239. var InterpolateLinear = 2301;
  240. var InterpolateSmooth = 2302;
  241. var ZeroCurvatureEnding = 2400;
  242. var ZeroSlopeEnding = 2401;
  243. var WrapAroundEnding = 2402;
  244. var TrianglesDrawMode = 0;
  245. var TriangleStripDrawMode = 1;
  246. var TriangleFanDrawMode = 2;
  247. var LinearEncoding = 3000;
  248. var sRGBEncoding = 3001;
  249. var GammaEncoding = 3007;
  250. var RGBEEncoding = 3002;
  251. var LogLuvEncoding = 3003;
  252. var RGBM7Encoding = 3004;
  253. var RGBM16Encoding = 3005;
  254. var RGBDEncoding = 3006;
  255. var BasicDepthPacking = 3200;
  256. var RGBADepthPacking = 3201;
  257. /**
  258. * @author alteredq / http://alteredqualia.com/
  259. * @author mrdoob / http://mrdoob.com/
  260. */
  261. exports.Math = {
  262. DEG2RAD: Math.PI / 180,
  263. RAD2DEG: 180 / Math.PI,
  264. generateUUID: function () {
  265. // http://www.broofa.com/Tools/Math.uuid.htm
  266. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split( '' );
  267. var uuid = new Array( 36 );
  268. var rnd = 0, r;
  269. return function generateUUID() {
  270. for ( var i = 0; i < 36; i ++ ) {
  271. if ( i === 8 || i === 13 || i === 18 || i === 23 ) {
  272. uuid[ i ] = '-';
  273. } else if ( i === 14 ) {
  274. uuid[ i ] = '4';
  275. } else {
  276. if ( rnd <= 0x02 ) rnd = 0x2000000 + ( Math.random() * 0x1000000 ) | 0;
  277. r = rnd & 0xf;
  278. rnd = rnd >> 4;
  279. uuid[ i ] = chars[ ( i === 19 ) ? ( r & 0x3 ) | 0x8 : r ];
  280. }
  281. }
  282. return uuid.join( '' );
  283. };
  284. }(),
  285. clamp: function ( value, min, max ) {
  286. return Math.max( min, Math.min( max, value ) );
  287. },
  288. // compute euclidian modulo of m % n
  289. // https://en.wikipedia.org/wiki/Modulo_operation
  290. euclideanModulo: function ( n, m ) {
  291. return ( ( n % m ) + m ) % m;
  292. },
  293. // Linear mapping from range <a1, a2> to range <b1, b2>
  294. mapLinear: function ( x, a1, a2, b1, b2 ) {
  295. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  296. },
  297. // http://en.wikipedia.org/wiki/Smoothstep
  298. smoothstep: function ( x, min, max ) {
  299. if ( x <= min ) return 0;
  300. if ( x >= max ) return 1;
  301. x = ( x - min ) / ( max - min );
  302. return x * x * ( 3 - 2 * x );
  303. },
  304. smootherstep: function ( x, min, max ) {
  305. if ( x <= min ) return 0;
  306. if ( x >= max ) return 1;
  307. x = ( x - min ) / ( max - min );
  308. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  309. },
  310. random16: function () {
  311. console.warn( 'THREE.Math.random16() has been deprecated. Use Math.random() instead.' );
  312. return Math.random();
  313. },
  314. // Random integer from <low, high> interval
  315. randInt: function ( low, high ) {
  316. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  317. },
  318. // Random float from <low, high> interval
  319. randFloat: function ( low, high ) {
  320. return low + Math.random() * ( high - low );
  321. },
  322. // Random float from <-range/2, range/2> interval
  323. randFloatSpread: function ( range ) {
  324. return range * ( 0.5 - Math.random() );
  325. },
  326. degToRad: function ( degrees ) {
  327. return degrees * exports.Math.DEG2RAD;
  328. },
  329. radToDeg: function ( radians ) {
  330. return radians * exports.Math.RAD2DEG;
  331. },
  332. isPowerOfTwo: function ( value ) {
  333. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  334. },
  335. nearestPowerOfTwo: function ( value ) {
  336. return Math.pow( 2, Math.round( Math.log( value ) / Math.LN2 ) );
  337. },
  338. nextPowerOfTwo: function ( value ) {
  339. value --;
  340. value |= value >> 1;
  341. value |= value >> 2;
  342. value |= value >> 4;
  343. value |= value >> 8;
  344. value |= value >> 16;
  345. value ++;
  346. return value;
  347. }
  348. };
  349. /**
  350. * @author mrdoob / http://mrdoob.com/
  351. * @author philogb / http://blog.thejit.org/
  352. * @author egraether / http://egraether.com/
  353. * @author zz85 / http://www.lab4games.net/zz85/blog
  354. */
  355. function Vector2( x, y ) {
  356. this.x = x || 0;
  357. this.y = y || 0;
  358. }
  359. Vector2.prototype = {
  360. constructor: Vector2,
  361. isVector2: true,
  362. get width() {
  363. return this.x;
  364. },
  365. set width( value ) {
  366. this.x = value;
  367. },
  368. get height() {
  369. return this.y;
  370. },
  371. set height( value ) {
  372. this.y = value;
  373. },
  374. //
  375. set: function ( x, y ) {
  376. this.x = x;
  377. this.y = y;
  378. return this;
  379. },
  380. setScalar: function ( scalar ) {
  381. this.x = scalar;
  382. this.y = scalar;
  383. return this;
  384. },
  385. setX: function ( x ) {
  386. this.x = x;
  387. return this;
  388. },
  389. setY: function ( y ) {
  390. this.y = y;
  391. return this;
  392. },
  393. setComponent: function ( index, value ) {
  394. switch ( index ) {
  395. case 0: this.x = value; break;
  396. case 1: this.y = value; break;
  397. default: throw new Error( 'index is out of range: ' + index );
  398. }
  399. },
  400. getComponent: function ( index ) {
  401. switch ( index ) {
  402. case 0: return this.x;
  403. case 1: return this.y;
  404. default: throw new Error( 'index is out of range: ' + index );
  405. }
  406. },
  407. clone: function () {
  408. return new this.constructor( this.x, this.y );
  409. },
  410. copy: function ( v ) {
  411. this.x = v.x;
  412. this.y = v.y;
  413. return this;
  414. },
  415. add: function ( v, w ) {
  416. if ( w !== undefined ) {
  417. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  418. return this.addVectors( v, w );
  419. }
  420. this.x += v.x;
  421. this.y += v.y;
  422. return this;
  423. },
  424. addScalar: function ( s ) {
  425. this.x += s;
  426. this.y += s;
  427. return this;
  428. },
  429. addVectors: function ( a, b ) {
  430. this.x = a.x + b.x;
  431. this.y = a.y + b.y;
  432. return this;
  433. },
  434. addScaledVector: function ( v, s ) {
  435. this.x += v.x * s;
  436. this.y += v.y * s;
  437. return this;
  438. },
  439. sub: function ( v, w ) {
  440. if ( w !== undefined ) {
  441. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  442. return this.subVectors( v, w );
  443. }
  444. this.x -= v.x;
  445. this.y -= v.y;
  446. return this;
  447. },
  448. subScalar: function ( s ) {
  449. this.x -= s;
  450. this.y -= s;
  451. return this;
  452. },
  453. subVectors: function ( a, b ) {
  454. this.x = a.x - b.x;
  455. this.y = a.y - b.y;
  456. return this;
  457. },
  458. multiply: function ( v ) {
  459. this.x *= v.x;
  460. this.y *= v.y;
  461. return this;
  462. },
  463. multiplyScalar: function ( scalar ) {
  464. if ( isFinite( scalar ) ) {
  465. this.x *= scalar;
  466. this.y *= scalar;
  467. } else {
  468. this.x = 0;
  469. this.y = 0;
  470. }
  471. return this;
  472. },
  473. divide: function ( v ) {
  474. this.x /= v.x;
  475. this.y /= v.y;
  476. return this;
  477. },
  478. divideScalar: function ( scalar ) {
  479. return this.multiplyScalar( 1 / scalar );
  480. },
  481. min: function ( v ) {
  482. this.x = Math.min( this.x, v.x );
  483. this.y = Math.min( this.y, v.y );
  484. return this;
  485. },
  486. max: function ( v ) {
  487. this.x = Math.max( this.x, v.x );
  488. this.y = Math.max( this.y, v.y );
  489. return this;
  490. },
  491. clamp: function ( min, max ) {
  492. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  493. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  494. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  495. return this;
  496. },
  497. clampScalar: function () {
  498. var min, max;
  499. return function clampScalar( minVal, maxVal ) {
  500. if ( min === undefined ) {
  501. min = new Vector2();
  502. max = new Vector2();
  503. }
  504. min.set( minVal, minVal );
  505. max.set( maxVal, maxVal );
  506. return this.clamp( min, max );
  507. };
  508. }(),
  509. clampLength: function ( min, max ) {
  510. var length = this.length();
  511. return this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length );
  512. },
  513. floor: function () {
  514. this.x = Math.floor( this.x );
  515. this.y = Math.floor( this.y );
  516. return this;
  517. },
  518. ceil: function () {
  519. this.x = Math.ceil( this.x );
  520. this.y = Math.ceil( this.y );
  521. return this;
  522. },
  523. round: function () {
  524. this.x = Math.round( this.x );
  525. this.y = Math.round( this.y );
  526. return this;
  527. },
  528. roundToZero: function () {
  529. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  530. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  531. return this;
  532. },
  533. negate: function () {
  534. this.x = - this.x;
  535. this.y = - this.y;
  536. return this;
  537. },
  538. dot: function ( v ) {
  539. return this.x * v.x + this.y * v.y;
  540. },
  541. lengthSq: function () {
  542. return this.x * this.x + this.y * this.y;
  543. },
  544. length: function () {
  545. return Math.sqrt( this.x * this.x + this.y * this.y );
  546. },
  547. lengthManhattan: function() {
  548. return Math.abs( this.x ) + Math.abs( this.y );
  549. },
  550. normalize: function () {
  551. return this.divideScalar( this.length() );
  552. },
  553. angle: function () {
  554. // computes the angle in radians with respect to the positive x-axis
  555. var angle = Math.atan2( this.y, this.x );
  556. if ( angle < 0 ) angle += 2 * Math.PI;
  557. return angle;
  558. },
  559. distanceTo: function ( v ) {
  560. return Math.sqrt( this.distanceToSquared( v ) );
  561. },
  562. distanceToSquared: function ( v ) {
  563. var dx = this.x - v.x, dy = this.y - v.y;
  564. return dx * dx + dy * dy;
  565. },
  566. distanceToManhattan: function ( v ) {
  567. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  568. },
  569. setLength: function ( length ) {
  570. return this.multiplyScalar( length / this.length() );
  571. },
  572. lerp: function ( v, alpha ) {
  573. this.x += ( v.x - this.x ) * alpha;
  574. this.y += ( v.y - this.y ) * alpha;
  575. return this;
  576. },
  577. lerpVectors: function ( v1, v2, alpha ) {
  578. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  579. },
  580. equals: function ( v ) {
  581. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  582. },
  583. fromArray: function ( array, offset ) {
  584. if ( offset === undefined ) offset = 0;
  585. this.x = array[ offset ];
  586. this.y = array[ offset + 1 ];
  587. return this;
  588. },
  589. toArray: function ( array, offset ) {
  590. if ( array === undefined ) array = [];
  591. if ( offset === undefined ) offset = 0;
  592. array[ offset ] = this.x;
  593. array[ offset + 1 ] = this.y;
  594. return array;
  595. },
  596. fromAttribute: function ( attribute, index, offset ) {
  597. if ( offset === undefined ) offset = 0;
  598. index = index * attribute.itemSize + offset;
  599. this.x = attribute.array[ index ];
  600. this.y = attribute.array[ index + 1 ];
  601. return this;
  602. },
  603. rotateAround: function ( center, angle ) {
  604. var c = Math.cos( angle ), s = Math.sin( angle );
  605. var x = this.x - center.x;
  606. var y = this.y - center.y;
  607. this.x = x * c - y * s + center.x;
  608. this.y = x * s + y * c + center.y;
  609. return this;
  610. }
  611. };
  612. /**
  613. * @author mrdoob / http://mrdoob.com/
  614. * @author alteredq / http://alteredqualia.com/
  615. * @author szimek / https://github.com/szimek/
  616. */
  617. function Texture( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  618. Object.defineProperty( this, 'id', { value: TextureIdCount() } );
  619. this.uuid = exports.Math.generateUUID();
  620. this.name = '';
  621. this.sourceFile = '';
  622. this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE;
  623. this.mipmaps = [];
  624. this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING;
  625. this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping;
  626. this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping;
  627. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  628. this.minFilter = minFilter !== undefined ? minFilter : LinearMipMapLinearFilter;
  629. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  630. this.format = format !== undefined ? format : RGBAFormat;
  631. this.type = type !== undefined ? type : UnsignedByteType;
  632. this.offset = new Vector2( 0, 0 );
  633. this.repeat = new Vector2( 1, 1 );
  634. this.generateMipmaps = true;
  635. this.premultiplyAlpha = false;
  636. this.flipY = true;
  637. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  638. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  639. //
  640. // Also changing the encoding after already used by a Material will not automatically make the Material
  641. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  642. this.encoding = encoding !== undefined ? encoding : LinearEncoding;
  643. this.version = 0;
  644. this.onUpdate = null;
  645. }
  646. Texture.DEFAULT_IMAGE = undefined;
  647. Texture.DEFAULT_MAPPING = UVMapping;
  648. Texture.prototype = {
  649. constructor: Texture,
  650. isTexture: true,
  651. set needsUpdate( value ) {
  652. if ( value === true ) this.version ++;
  653. },
  654. clone: function () {
  655. return new this.constructor().copy( this );
  656. },
  657. copy: function ( source ) {
  658. this.image = source.image;
  659. this.mipmaps = source.mipmaps.slice( 0 );
  660. this.mapping = source.mapping;
  661. this.wrapS = source.wrapS;
  662. this.wrapT = source.wrapT;
  663. this.magFilter = source.magFilter;
  664. this.minFilter = source.minFilter;
  665. this.anisotropy = source.anisotropy;
  666. this.format = source.format;
  667. this.type = source.type;
  668. this.offset.copy( source.offset );
  669. this.repeat.copy( source.repeat );
  670. this.generateMipmaps = source.generateMipmaps;
  671. this.premultiplyAlpha = source.premultiplyAlpha;
  672. this.flipY = source.flipY;
  673. this.unpackAlignment = source.unpackAlignment;
  674. this.encoding = source.encoding;
  675. return this;
  676. },
  677. toJSON: function ( meta ) {
  678. if ( meta.textures[ this.uuid ] !== undefined ) {
  679. return meta.textures[ this.uuid ];
  680. }
  681. function getDataURL( image ) {
  682. var canvas;
  683. if ( image.toDataURL !== undefined ) {
  684. canvas = image;
  685. } else {
  686. canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  687. canvas.width = image.width;
  688. canvas.height = image.height;
  689. canvas.getContext( '2d' ).drawImage( image, 0, 0, image.width, image.height );
  690. }
  691. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  692. return canvas.toDataURL( 'image/jpeg', 0.6 );
  693. } else {
  694. return canvas.toDataURL( 'image/png' );
  695. }
  696. }
  697. var output = {
  698. metadata: {
  699. version: 4.4,
  700. type: 'Texture',
  701. generator: 'Texture.toJSON'
  702. },
  703. uuid: this.uuid,
  704. name: this.name,
  705. mapping: this.mapping,
  706. repeat: [ this.repeat.x, this.repeat.y ],
  707. offset: [ this.offset.x, this.offset.y ],
  708. wrap: [ this.wrapS, this.wrapT ],
  709. minFilter: this.minFilter,
  710. magFilter: this.magFilter,
  711. anisotropy: this.anisotropy,
  712. flipY: this.flipY
  713. };
  714. if ( this.image !== undefined ) {
  715. // TODO: Move to THREE.Image
  716. var image = this.image;
  717. if ( image.uuid === undefined ) {
  718. image.uuid = exports.Math.generateUUID(); // UGH
  719. }
  720. if ( meta.images[ image.uuid ] === undefined ) {
  721. meta.images[ image.uuid ] = {
  722. uuid: image.uuid,
  723. url: getDataURL( image )
  724. };
  725. }
  726. output.image = image.uuid;
  727. }
  728. meta.textures[ this.uuid ] = output;
  729. return output;
  730. },
  731. dispose: function () {
  732. this.dispatchEvent( { type: 'dispose' } );
  733. },
  734. transformUv: function ( uv ) {
  735. if ( this.mapping !== UVMapping ) return;
  736. uv.multiply( this.repeat );
  737. uv.add( this.offset );
  738. if ( uv.x < 0 || uv.x > 1 ) {
  739. switch ( this.wrapS ) {
  740. case RepeatWrapping:
  741. uv.x = uv.x - Math.floor( uv.x );
  742. break;
  743. case ClampToEdgeWrapping:
  744. uv.x = uv.x < 0 ? 0 : 1;
  745. break;
  746. case MirroredRepeatWrapping:
  747. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  748. uv.x = Math.ceil( uv.x ) - uv.x;
  749. } else {
  750. uv.x = uv.x - Math.floor( uv.x );
  751. }
  752. break;
  753. }
  754. }
  755. if ( uv.y < 0 || uv.y > 1 ) {
  756. switch ( this.wrapT ) {
  757. case RepeatWrapping:
  758. uv.y = uv.y - Math.floor( uv.y );
  759. break;
  760. case ClampToEdgeWrapping:
  761. uv.y = uv.y < 0 ? 0 : 1;
  762. break;
  763. case MirroredRepeatWrapping:
  764. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  765. uv.y = Math.ceil( uv.y ) - uv.y;
  766. } else {
  767. uv.y = uv.y - Math.floor( uv.y );
  768. }
  769. break;
  770. }
  771. }
  772. if ( this.flipY ) {
  773. uv.y = 1 - uv.y;
  774. }
  775. }
  776. };
  777. Object.assign( Texture.prototype, EventDispatcher.prototype );
  778. var count = 0;
  779. function TextureIdCount() { return count++; };
  780. /**
  781. * @author supereggbert / http://www.paulbrunt.co.uk/
  782. * @author philogb / http://blog.thejit.org/
  783. * @author mikael emtinger / http://gomo.se/
  784. * @author egraether / http://egraether.com/
  785. * @author WestLangley / http://github.com/WestLangley
  786. */
  787. function Vector4( x, y, z, w ) {
  788. this.x = x || 0;
  789. this.y = y || 0;
  790. this.z = z || 0;
  791. this.w = ( w !== undefined ) ? w : 1;
  792. }
  793. Vector4.prototype = {
  794. constructor: Vector4,
  795. isVector4: true,
  796. set: function ( x, y, z, w ) {
  797. this.x = x;
  798. this.y = y;
  799. this.z = z;
  800. this.w = w;
  801. return this;
  802. },
  803. setScalar: function ( scalar ) {
  804. this.x = scalar;
  805. this.y = scalar;
  806. this.z = scalar;
  807. this.w = scalar;
  808. return this;
  809. },
  810. setX: function ( x ) {
  811. this.x = x;
  812. return this;
  813. },
  814. setY: function ( y ) {
  815. this.y = y;
  816. return this;
  817. },
  818. setZ: function ( z ) {
  819. this.z = z;
  820. return this;
  821. },
  822. setW: function ( w ) {
  823. this.w = w;
  824. return this;
  825. },
  826. setComponent: function ( index, value ) {
  827. switch ( index ) {
  828. case 0: this.x = value; break;
  829. case 1: this.y = value; break;
  830. case 2: this.z = value; break;
  831. case 3: this.w = value; break;
  832. default: throw new Error( 'index is out of range: ' + index );
  833. }
  834. },
  835. getComponent: function ( index ) {
  836. switch ( index ) {
  837. case 0: return this.x;
  838. case 1: return this.y;
  839. case 2: return this.z;
  840. case 3: return this.w;
  841. default: throw new Error( 'index is out of range: ' + index );
  842. }
  843. },
  844. clone: function () {
  845. return new this.constructor( this.x, this.y, this.z, this.w );
  846. },
  847. copy: function ( v ) {
  848. this.x = v.x;
  849. this.y = v.y;
  850. this.z = v.z;
  851. this.w = ( v.w !== undefined ) ? v.w : 1;
  852. return this;
  853. },
  854. add: function ( v, w ) {
  855. if ( w !== undefined ) {
  856. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  857. return this.addVectors( v, w );
  858. }
  859. this.x += v.x;
  860. this.y += v.y;
  861. this.z += v.z;
  862. this.w += v.w;
  863. return this;
  864. },
  865. addScalar: function ( s ) {
  866. this.x += s;
  867. this.y += s;
  868. this.z += s;
  869. this.w += s;
  870. return this;
  871. },
  872. addVectors: function ( a, b ) {
  873. this.x = a.x + b.x;
  874. this.y = a.y + b.y;
  875. this.z = a.z + b.z;
  876. this.w = a.w + b.w;
  877. return this;
  878. },
  879. addScaledVector: function ( v, s ) {
  880. this.x += v.x * s;
  881. this.y += v.y * s;
  882. this.z += v.z * s;
  883. this.w += v.w * s;
  884. return this;
  885. },
  886. sub: function ( v, w ) {
  887. if ( w !== undefined ) {
  888. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  889. return this.subVectors( v, w );
  890. }
  891. this.x -= v.x;
  892. this.y -= v.y;
  893. this.z -= v.z;
  894. this.w -= v.w;
  895. return this;
  896. },
  897. subScalar: function ( s ) {
  898. this.x -= s;
  899. this.y -= s;
  900. this.z -= s;
  901. this.w -= s;
  902. return this;
  903. },
  904. subVectors: function ( a, b ) {
  905. this.x = a.x - b.x;
  906. this.y = a.y - b.y;
  907. this.z = a.z - b.z;
  908. this.w = a.w - b.w;
  909. return this;
  910. },
  911. multiplyScalar: function ( scalar ) {
  912. if ( isFinite( scalar ) ) {
  913. this.x *= scalar;
  914. this.y *= scalar;
  915. this.z *= scalar;
  916. this.w *= scalar;
  917. } else {
  918. this.x = 0;
  919. this.y = 0;
  920. this.z = 0;
  921. this.w = 0;
  922. }
  923. return this;
  924. },
  925. applyMatrix4: function ( m ) {
  926. var x = this.x, y = this.y, z = this.z, w = this.w;
  927. var e = m.elements;
  928. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  929. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  930. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  931. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  932. return this;
  933. },
  934. divideScalar: function ( scalar ) {
  935. return this.multiplyScalar( 1 / scalar );
  936. },
  937. setAxisAngleFromQuaternion: function ( q ) {
  938. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  939. // q is assumed to be normalized
  940. this.w = 2 * Math.acos( q.w );
  941. var s = Math.sqrt( 1 - q.w * q.w );
  942. if ( s < 0.0001 ) {
  943. this.x = 1;
  944. this.y = 0;
  945. this.z = 0;
  946. } else {
  947. this.x = q.x / s;
  948. this.y = q.y / s;
  949. this.z = q.z / s;
  950. }
  951. return this;
  952. },
  953. setAxisAngleFromRotationMatrix: function ( m ) {
  954. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  955. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  956. var angle, x, y, z, // variables for result
  957. epsilon = 0.01, // margin to allow for rounding errors
  958. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  959. te = m.elements,
  960. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  961. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  962. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  963. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  964. ( Math.abs( m13 - m31 ) < epsilon ) &&
  965. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  966. // singularity found
  967. // first check for identity matrix which must have +1 for all terms
  968. // in leading diagonal and zero in other terms
  969. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  970. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  971. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  972. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  973. // this singularity is identity matrix so angle = 0
  974. this.set( 1, 0, 0, 0 );
  975. return this; // zero angle, arbitrary axis
  976. }
  977. // otherwise this singularity is angle = 180
  978. angle = Math.PI;
  979. var xx = ( m11 + 1 ) / 2;
  980. var yy = ( m22 + 1 ) / 2;
  981. var zz = ( m33 + 1 ) / 2;
  982. var xy = ( m12 + m21 ) / 4;
  983. var xz = ( m13 + m31 ) / 4;
  984. var yz = ( m23 + m32 ) / 4;
  985. if ( ( xx > yy ) && ( xx > zz ) ) {
  986. // m11 is the largest diagonal term
  987. if ( xx < epsilon ) {
  988. x = 0;
  989. y = 0.707106781;
  990. z = 0.707106781;
  991. } else {
  992. x = Math.sqrt( xx );
  993. y = xy / x;
  994. z = xz / x;
  995. }
  996. } else if ( yy > zz ) {
  997. // m22 is the largest diagonal term
  998. if ( yy < epsilon ) {
  999. x = 0.707106781;
  1000. y = 0;
  1001. z = 0.707106781;
  1002. } else {
  1003. y = Math.sqrt( yy );
  1004. x = xy / y;
  1005. z = yz / y;
  1006. }
  1007. } else {
  1008. // m33 is the largest diagonal term so base result on this
  1009. if ( zz < epsilon ) {
  1010. x = 0.707106781;
  1011. y = 0.707106781;
  1012. z = 0;
  1013. } else {
  1014. z = Math.sqrt( zz );
  1015. x = xz / z;
  1016. y = yz / z;
  1017. }
  1018. }
  1019. this.set( x, y, z, angle );
  1020. return this; // return 180 deg rotation
  1021. }
  1022. // as we have reached here there are no singularities so we can handle normally
  1023. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  1024. ( m13 - m31 ) * ( m13 - m31 ) +
  1025. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1026. if ( Math.abs( s ) < 0.001 ) s = 1;
  1027. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1028. // caught by singularity test above, but I've left it in just in case
  1029. this.x = ( m32 - m23 ) / s;
  1030. this.y = ( m13 - m31 ) / s;
  1031. this.z = ( m21 - m12 ) / s;
  1032. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1033. return this;
  1034. },
  1035. min: function ( v ) {
  1036. this.x = Math.min( this.x, v.x );
  1037. this.y = Math.min( this.y, v.y );
  1038. this.z = Math.min( this.z, v.z );
  1039. this.w = Math.min( this.w, v.w );
  1040. return this;
  1041. },
  1042. max: function ( v ) {
  1043. this.x = Math.max( this.x, v.x );
  1044. this.y = Math.max( this.y, v.y );
  1045. this.z = Math.max( this.z, v.z );
  1046. this.w = Math.max( this.w, v.w );
  1047. return this;
  1048. },
  1049. clamp: function ( min, max ) {
  1050. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1051. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1052. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1053. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1054. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1055. return this;
  1056. },
  1057. clampScalar: function () {
  1058. var min, max;
  1059. return function clampScalar( minVal, maxVal ) {
  1060. if ( min === undefined ) {
  1061. min = new Vector4();
  1062. max = new Vector4();
  1063. }
  1064. min.set( minVal, minVal, minVal, minVal );
  1065. max.set( maxVal, maxVal, maxVal, maxVal );
  1066. return this.clamp( min, max );
  1067. };
  1068. }(),
  1069. floor: function () {
  1070. this.x = Math.floor( this.x );
  1071. this.y = Math.floor( this.y );
  1072. this.z = Math.floor( this.z );
  1073. this.w = Math.floor( this.w );
  1074. return this;
  1075. },
  1076. ceil: function () {
  1077. this.x = Math.ceil( this.x );
  1078. this.y = Math.ceil( this.y );
  1079. this.z = Math.ceil( this.z );
  1080. this.w = Math.ceil( this.w );
  1081. return this;
  1082. },
  1083. round: function () {
  1084. this.x = Math.round( this.x );
  1085. this.y = Math.round( this.y );
  1086. this.z = Math.round( this.z );
  1087. this.w = Math.round( this.w );
  1088. return this;
  1089. },
  1090. roundToZero: function () {
  1091. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1092. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1093. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1094. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1095. return this;
  1096. },
  1097. negate: function () {
  1098. this.x = - this.x;
  1099. this.y = - this.y;
  1100. this.z = - this.z;
  1101. this.w = - this.w;
  1102. return this;
  1103. },
  1104. dot: function ( v ) {
  1105. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1106. },
  1107. lengthSq: function () {
  1108. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1109. },
  1110. length: function () {
  1111. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1112. },
  1113. lengthManhattan: function () {
  1114. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1115. },
  1116. normalize: function () {
  1117. return this.divideScalar( this.length() );
  1118. },
  1119. setLength: function ( length ) {
  1120. return this.multiplyScalar( length / this.length() );
  1121. },
  1122. lerp: function ( v, alpha ) {
  1123. this.x += ( v.x - this.x ) * alpha;
  1124. this.y += ( v.y - this.y ) * alpha;
  1125. this.z += ( v.z - this.z ) * alpha;
  1126. this.w += ( v.w - this.w ) * alpha;
  1127. return this;
  1128. },
  1129. lerpVectors: function ( v1, v2, alpha ) {
  1130. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1131. },
  1132. equals: function ( v ) {
  1133. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1134. },
  1135. fromArray: function ( array, offset ) {
  1136. if ( offset === undefined ) offset = 0;
  1137. this.x = array[ offset ];
  1138. this.y = array[ offset + 1 ];
  1139. this.z = array[ offset + 2 ];
  1140. this.w = array[ offset + 3 ];
  1141. return this;
  1142. },
  1143. toArray: function ( array, offset ) {
  1144. if ( array === undefined ) array = [];
  1145. if ( offset === undefined ) offset = 0;
  1146. array[ offset ] = this.x;
  1147. array[ offset + 1 ] = this.y;
  1148. array[ offset + 2 ] = this.z;
  1149. array[ offset + 3 ] = this.w;
  1150. return array;
  1151. },
  1152. fromAttribute: function ( attribute, index, offset ) {
  1153. if ( offset === undefined ) offset = 0;
  1154. index = index * attribute.itemSize + offset;
  1155. this.x = attribute.array[ index ];
  1156. this.y = attribute.array[ index + 1 ];
  1157. this.z = attribute.array[ index + 2 ];
  1158. this.w = attribute.array[ index + 3 ];
  1159. return this;
  1160. }
  1161. };
  1162. /**
  1163. * @author szimek / https://github.com/szimek/
  1164. * @author alteredq / http://alteredqualia.com/
  1165. * @author Marius Kintel / https://github.com/kintel
  1166. */
  1167. /*
  1168. In options, we can specify:
  1169. * Texture parameters for an auto-generated target texture
  1170. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1171. */
  1172. function WebGLRenderTarget( width, height, options ) {
  1173. this.uuid = exports.Math.generateUUID();
  1174. this.width = width;
  1175. this.height = height;
  1176. this.scissor = new Vector4( 0, 0, width, height );
  1177. this.scissorTest = false;
  1178. this.viewport = new Vector4( 0, 0, width, height );
  1179. options = options || {};
  1180. if ( options.minFilter === undefined ) options.minFilter = LinearFilter;
  1181. this.texture = new Texture( undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  1182. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  1183. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  1184. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  1185. }
  1186. Object.assign( WebGLRenderTarget.prototype, EventDispatcher.prototype, {
  1187. isWebGLRenderTarget: true,
  1188. setSize: function ( width, height ) {
  1189. if ( this.width !== width || this.height !== height ) {
  1190. this.width = width;
  1191. this.height = height;
  1192. this.dispose();
  1193. }
  1194. this.viewport.set( 0, 0, width, height );
  1195. this.scissor.set( 0, 0, width, height );
  1196. },
  1197. clone: function () {
  1198. return new this.constructor().copy( this );
  1199. },
  1200. copy: function ( source ) {
  1201. this.width = source.width;
  1202. this.height = source.height;
  1203. this.viewport.copy( source.viewport );
  1204. this.texture = source.texture.clone();
  1205. this.depthBuffer = source.depthBuffer;
  1206. this.stencilBuffer = source.stencilBuffer;
  1207. this.depthTexture = source.depthTexture;
  1208. return this;
  1209. },
  1210. dispose: function () {
  1211. this.dispatchEvent( { type: 'dispose' } );
  1212. }
  1213. } );
  1214. /**
  1215. * @author alteredq / http://alteredqualia.com
  1216. */
  1217. function WebGLRenderTargetCube( width, height, options ) {
  1218. WebGLRenderTarget.call( this, width, height, options );
  1219. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  1220. this.activeMipMapLevel = 0;
  1221. }
  1222. WebGLRenderTargetCube.prototype = Object.create( WebGLRenderTarget.prototype );
  1223. WebGLRenderTargetCube.prototype.constructor = WebGLRenderTargetCube;
  1224. WebGLRenderTargetCube.prototype.isWebGLRenderTargetCube = true;
  1225. /**
  1226. * @author mikael emtinger / http://gomo.se/
  1227. * @author alteredq / http://alteredqualia.com/
  1228. * @author WestLangley / http://github.com/WestLangley
  1229. * @author bhouston / http://clara.io
  1230. */
  1231. function Quaternion( x, y, z, w ) {
  1232. this._x = x || 0;
  1233. this._y = y || 0;
  1234. this._z = z || 0;
  1235. this._w = ( w !== undefined ) ? w : 1;
  1236. }
  1237. Quaternion.prototype = {
  1238. constructor: Quaternion,
  1239. get x () {
  1240. return this._x;
  1241. },
  1242. set x ( value ) {
  1243. this._x = value;
  1244. this.onChangeCallback();
  1245. },
  1246. get y () {
  1247. return this._y;
  1248. },
  1249. set y ( value ) {
  1250. this._y = value;
  1251. this.onChangeCallback();
  1252. },
  1253. get z () {
  1254. return this._z;
  1255. },
  1256. set z ( value ) {
  1257. this._z = value;
  1258. this.onChangeCallback();
  1259. },
  1260. get w () {
  1261. return this._w;
  1262. },
  1263. set w ( value ) {
  1264. this._w = value;
  1265. this.onChangeCallback();
  1266. },
  1267. set: function ( x, y, z, w ) {
  1268. this._x = x;
  1269. this._y = y;
  1270. this._z = z;
  1271. this._w = w;
  1272. this.onChangeCallback();
  1273. return this;
  1274. },
  1275. clone: function () {
  1276. return new this.constructor( this._x, this._y, this._z, this._w );
  1277. },
  1278. copy: function ( quaternion ) {
  1279. this._x = quaternion.x;
  1280. this._y = quaternion.y;
  1281. this._z = quaternion.z;
  1282. this._w = quaternion.w;
  1283. this.onChangeCallback();
  1284. return this;
  1285. },
  1286. setFromEuler: function ( euler, update ) {
  1287. if ( (euler && euler.isEuler) === false ) {
  1288. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  1289. }
  1290. // http://www.mathworks.com/matlabcentral/fileexchange/
  1291. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  1292. // content/SpinCalc.m
  1293. var c1 = Math.cos( euler._x / 2 );
  1294. var c2 = Math.cos( euler._y / 2 );
  1295. var c3 = Math.cos( euler._z / 2 );
  1296. var s1 = Math.sin( euler._x / 2 );
  1297. var s2 = Math.sin( euler._y / 2 );
  1298. var s3 = Math.sin( euler._z / 2 );
  1299. var order = euler.order;
  1300. if ( order === 'XYZ' ) {
  1301. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1302. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1303. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1304. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1305. } else if ( order === 'YXZ' ) {
  1306. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1307. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1308. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1309. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1310. } else if ( order === 'ZXY' ) {
  1311. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1312. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1313. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1314. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1315. } else if ( order === 'ZYX' ) {
  1316. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1317. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1318. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1319. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1320. } else if ( order === 'YZX' ) {
  1321. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1322. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1323. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1324. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1325. } else if ( order === 'XZY' ) {
  1326. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1327. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1328. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1329. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1330. }
  1331. if ( update !== false ) this.onChangeCallback();
  1332. return this;
  1333. },
  1334. setFromAxisAngle: function ( axis, angle ) {
  1335. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  1336. // assumes axis is normalized
  1337. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  1338. this._x = axis.x * s;
  1339. this._y = axis.y * s;
  1340. this._z = axis.z * s;
  1341. this._w = Math.cos( halfAngle );
  1342. this.onChangeCallback();
  1343. return this;
  1344. },
  1345. setFromRotationMatrix: function ( m ) {
  1346. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  1347. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1348. var te = m.elements,
  1349. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1350. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1351. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  1352. trace = m11 + m22 + m33,
  1353. s;
  1354. if ( trace > 0 ) {
  1355. s = 0.5 / Math.sqrt( trace + 1.0 );
  1356. this._w = 0.25 / s;
  1357. this._x = ( m32 - m23 ) * s;
  1358. this._y = ( m13 - m31 ) * s;
  1359. this._z = ( m21 - m12 ) * s;
  1360. } else if ( m11 > m22 && m11 > m33 ) {
  1361. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  1362. this._w = ( m32 - m23 ) / s;
  1363. this._x = 0.25 * s;
  1364. this._y = ( m12 + m21 ) / s;
  1365. this._z = ( m13 + m31 ) / s;
  1366. } else if ( m22 > m33 ) {
  1367. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  1368. this._w = ( m13 - m31 ) / s;
  1369. this._x = ( m12 + m21 ) / s;
  1370. this._y = 0.25 * s;
  1371. this._z = ( m23 + m32 ) / s;
  1372. } else {
  1373. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  1374. this._w = ( m21 - m12 ) / s;
  1375. this._x = ( m13 + m31 ) / s;
  1376. this._y = ( m23 + m32 ) / s;
  1377. this._z = 0.25 * s;
  1378. }
  1379. this.onChangeCallback();
  1380. return this;
  1381. },
  1382. setFromUnitVectors: function () {
  1383. // http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final
  1384. // assumes direction vectors vFrom and vTo are normalized
  1385. var v1, r;
  1386. var EPS = 0.000001;
  1387. return function setFromUnitVectors( vFrom, vTo ) {
  1388. if ( v1 === undefined ) v1 = new Vector3();
  1389. r = vFrom.dot( vTo ) + 1;
  1390. if ( r < EPS ) {
  1391. r = 0;
  1392. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  1393. v1.set( - vFrom.y, vFrom.x, 0 );
  1394. } else {
  1395. v1.set( 0, - vFrom.z, vFrom.y );
  1396. }
  1397. } else {
  1398. v1.crossVectors( vFrom, vTo );
  1399. }
  1400. this._x = v1.x;
  1401. this._y = v1.y;
  1402. this._z = v1.z;
  1403. this._w = r;
  1404. return this.normalize();
  1405. };
  1406. }(),
  1407. inverse: function () {
  1408. return this.conjugate().normalize();
  1409. },
  1410. conjugate: function () {
  1411. this._x *= - 1;
  1412. this._y *= - 1;
  1413. this._z *= - 1;
  1414. this.onChangeCallback();
  1415. return this;
  1416. },
  1417. dot: function ( v ) {
  1418. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  1419. },
  1420. lengthSq: function () {
  1421. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  1422. },
  1423. length: function () {
  1424. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  1425. },
  1426. normalize: function () {
  1427. var l = this.length();
  1428. if ( l === 0 ) {
  1429. this._x = 0;
  1430. this._y = 0;
  1431. this._z = 0;
  1432. this._w = 1;
  1433. } else {
  1434. l = 1 / l;
  1435. this._x = this._x * l;
  1436. this._y = this._y * l;
  1437. this._z = this._z * l;
  1438. this._w = this._w * l;
  1439. }
  1440. this.onChangeCallback();
  1441. return this;
  1442. },
  1443. multiply: function ( q, p ) {
  1444. if ( p !== undefined ) {
  1445. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  1446. return this.multiplyQuaternions( q, p );
  1447. }
  1448. return this.multiplyQuaternions( this, q );
  1449. },
  1450. premultiply: function ( q ) {
  1451. return this.multiplyQuaternions( q, this );
  1452. },
  1453. multiplyQuaternions: function ( a, b ) {
  1454. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  1455. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  1456. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  1457. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  1458. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  1459. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  1460. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  1461. this.onChangeCallback();
  1462. return this;
  1463. },
  1464. slerp: function ( qb, t ) {
  1465. if ( t === 0 ) return this;
  1466. if ( t === 1 ) return this.copy( qb );
  1467. var x = this._x, y = this._y, z = this._z, w = this._w;
  1468. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  1469. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  1470. if ( cosHalfTheta < 0 ) {
  1471. this._w = - qb._w;
  1472. this._x = - qb._x;
  1473. this._y = - qb._y;
  1474. this._z = - qb._z;
  1475. cosHalfTheta = - cosHalfTheta;
  1476. } else {
  1477. this.copy( qb );
  1478. }
  1479. if ( cosHalfTheta >= 1.0 ) {
  1480. this._w = w;
  1481. this._x = x;
  1482. this._y = y;
  1483. this._z = z;
  1484. return this;
  1485. }
  1486. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  1487. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  1488. this._w = 0.5 * ( w + this._w );
  1489. this._x = 0.5 * ( x + this._x );
  1490. this._y = 0.5 * ( y + this._y );
  1491. this._z = 0.5 * ( z + this._z );
  1492. return this;
  1493. }
  1494. var halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  1495. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  1496. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  1497. this._w = ( w * ratioA + this._w * ratioB );
  1498. this._x = ( x * ratioA + this._x * ratioB );
  1499. this._y = ( y * ratioA + this._y * ratioB );
  1500. this._z = ( z * ratioA + this._z * ratioB );
  1501. this.onChangeCallback();
  1502. return this;
  1503. },
  1504. equals: function ( quaternion ) {
  1505. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  1506. },
  1507. fromArray: function ( array, offset ) {
  1508. if ( offset === undefined ) offset = 0;
  1509. this._x = array[ offset ];
  1510. this._y = array[ offset + 1 ];
  1511. this._z = array[ offset + 2 ];
  1512. this._w = array[ offset + 3 ];
  1513. this.onChangeCallback();
  1514. return this;
  1515. },
  1516. toArray: function ( array, offset ) {
  1517. if ( array === undefined ) array = [];
  1518. if ( offset === undefined ) offset = 0;
  1519. array[ offset ] = this._x;
  1520. array[ offset + 1 ] = this._y;
  1521. array[ offset + 2 ] = this._z;
  1522. array[ offset + 3 ] = this._w;
  1523. return array;
  1524. },
  1525. onChange: function ( callback ) {
  1526. this.onChangeCallback = callback;
  1527. return this;
  1528. },
  1529. onChangeCallback: function () {}
  1530. };
  1531. Object.assign( Quaternion, {
  1532. slerp: function( qa, qb, qm, t ) {
  1533. return qm.copy( qa ).slerp( qb, t );
  1534. },
  1535. slerpFlat: function(
  1536. dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  1537. // fuzz-free, array-based Quaternion SLERP operation
  1538. var x0 = src0[ srcOffset0 + 0 ],
  1539. y0 = src0[ srcOffset0 + 1 ],
  1540. z0 = src0[ srcOffset0 + 2 ],
  1541. w0 = src0[ srcOffset0 + 3 ],
  1542. x1 = src1[ srcOffset1 + 0 ],
  1543. y1 = src1[ srcOffset1 + 1 ],
  1544. z1 = src1[ srcOffset1 + 2 ],
  1545. w1 = src1[ srcOffset1 + 3 ];
  1546. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  1547. var s = 1 - t,
  1548. cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1549. dir = ( cos >= 0 ? 1 : - 1 ),
  1550. sqrSin = 1 - cos * cos;
  1551. // Skip the Slerp for tiny steps to avoid numeric problems:
  1552. if ( sqrSin > Number.EPSILON ) {
  1553. var sin = Math.sqrt( sqrSin ),
  1554. len = Math.atan2( sin, cos * dir );
  1555. s = Math.sin( s * len ) / sin;
  1556. t = Math.sin( t * len ) / sin;
  1557. }
  1558. var tDir = t * dir;
  1559. x0 = x0 * s + x1 * tDir;
  1560. y0 = y0 * s + y1 * tDir;
  1561. z0 = z0 * s + z1 * tDir;
  1562. w0 = w0 * s + w1 * tDir;
  1563. // Normalize in case we just did a lerp:
  1564. if ( s === 1 - t ) {
  1565. var f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  1566. x0 *= f;
  1567. y0 *= f;
  1568. z0 *= f;
  1569. w0 *= f;
  1570. }
  1571. }
  1572. dst[ dstOffset ] = x0;
  1573. dst[ dstOffset + 1 ] = y0;
  1574. dst[ dstOffset + 2 ] = z0;
  1575. dst[ dstOffset + 3 ] = w0;
  1576. }
  1577. } );
  1578. /**
  1579. * @author mrdoob / http://mrdoob.com/
  1580. * @author *kile / http://kile.stravaganza.org/
  1581. * @author philogb / http://blog.thejit.org/
  1582. * @author mikael emtinger / http://gomo.se/
  1583. * @author egraether / http://egraether.com/
  1584. * @author WestLangley / http://github.com/WestLangley
  1585. */
  1586. function Vector3( x, y, z ) {
  1587. this.x = x || 0;
  1588. this.y = y || 0;
  1589. this.z = z || 0;
  1590. }
  1591. Vector3.prototype = {
  1592. constructor: Vector3,
  1593. isVector3: true,
  1594. set: function ( x, y, z ) {
  1595. this.x = x;
  1596. this.y = y;
  1597. this.z = z;
  1598. return this;
  1599. },
  1600. setScalar: function ( scalar ) {
  1601. this.x = scalar;
  1602. this.y = scalar;
  1603. this.z = scalar;
  1604. return this;
  1605. },
  1606. setX: function ( x ) {
  1607. this.x = x;
  1608. return this;
  1609. },
  1610. setY: function ( y ) {
  1611. this.y = y;
  1612. return this;
  1613. },
  1614. setZ: function ( z ) {
  1615. this.z = z;
  1616. return this;
  1617. },
  1618. setComponent: function ( index, value ) {
  1619. switch ( index ) {
  1620. case 0: this.x = value; break;
  1621. case 1: this.y = value; break;
  1622. case 2: this.z = value; break;
  1623. default: throw new Error( 'index is out of range: ' + index );
  1624. }
  1625. },
  1626. getComponent: function ( index ) {
  1627. switch ( index ) {
  1628. case 0: return this.x;
  1629. case 1: return this.y;
  1630. case 2: return this.z;
  1631. default: throw new Error( 'index is out of range: ' + index );
  1632. }
  1633. },
  1634. clone: function () {
  1635. return new this.constructor( this.x, this.y, this.z );
  1636. },
  1637. copy: function ( v ) {
  1638. this.x = v.x;
  1639. this.y = v.y;
  1640. this.z = v.z;
  1641. return this;
  1642. },
  1643. add: function ( v, w ) {
  1644. if ( w !== undefined ) {
  1645. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1646. return this.addVectors( v, w );
  1647. }
  1648. this.x += v.x;
  1649. this.y += v.y;
  1650. this.z += v.z;
  1651. return this;
  1652. },
  1653. addScalar: function ( s ) {
  1654. this.x += s;
  1655. this.y += s;
  1656. this.z += s;
  1657. return this;
  1658. },
  1659. addVectors: function ( a, b ) {
  1660. this.x = a.x + b.x;
  1661. this.y = a.y + b.y;
  1662. this.z = a.z + b.z;
  1663. return this;
  1664. },
  1665. addScaledVector: function ( v, s ) {
  1666. this.x += v.x * s;
  1667. this.y += v.y * s;
  1668. this.z += v.z * s;
  1669. return this;
  1670. },
  1671. sub: function ( v, w ) {
  1672. if ( w !== undefined ) {
  1673. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1674. return this.subVectors( v, w );
  1675. }
  1676. this.x -= v.x;
  1677. this.y -= v.y;
  1678. this.z -= v.z;
  1679. return this;
  1680. },
  1681. subScalar: function ( s ) {
  1682. this.x -= s;
  1683. this.y -= s;
  1684. this.z -= s;
  1685. return this;
  1686. },
  1687. subVectors: function ( a, b ) {
  1688. this.x = a.x - b.x;
  1689. this.y = a.y - b.y;
  1690. this.z = a.z - b.z;
  1691. return this;
  1692. },
  1693. multiply: function ( v, w ) {
  1694. if ( w !== undefined ) {
  1695. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  1696. return this.multiplyVectors( v, w );
  1697. }
  1698. this.x *= v.x;
  1699. this.y *= v.y;
  1700. this.z *= v.z;
  1701. return this;
  1702. },
  1703. multiplyScalar: function ( scalar ) {
  1704. if ( isFinite( scalar ) ) {
  1705. this.x *= scalar;
  1706. this.y *= scalar;
  1707. this.z *= scalar;
  1708. } else {
  1709. this.x = 0;
  1710. this.y = 0;
  1711. this.z = 0;
  1712. }
  1713. return this;
  1714. },
  1715. multiplyVectors: function ( a, b ) {
  1716. this.x = a.x * b.x;
  1717. this.y = a.y * b.y;
  1718. this.z = a.z * b.z;
  1719. return this;
  1720. },
  1721. applyEuler: function () {
  1722. var quaternion;
  1723. return function applyEuler( euler ) {
  1724. if ( (euler && euler.isEuler) === false ) {
  1725. console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  1726. }
  1727. if ( quaternion === undefined ) quaternion = new Quaternion();
  1728. return this.applyQuaternion( quaternion.setFromEuler( euler ) );
  1729. };
  1730. }(),
  1731. applyAxisAngle: function () {
  1732. var quaternion;
  1733. return function applyAxisAngle( axis, angle ) {
  1734. if ( quaternion === undefined ) quaternion = new Quaternion();
  1735. return this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  1736. };
  1737. }(),
  1738. applyMatrix3: function ( m ) {
  1739. var x = this.x, y = this.y, z = this.z;
  1740. var e = m.elements;
  1741. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  1742. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  1743. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  1744. return this;
  1745. },
  1746. applyMatrix4: function ( m ) {
  1747. // input: THREE.Matrix4 affine matrix
  1748. var x = this.x, y = this.y, z = this.z;
  1749. var e = m.elements;
  1750. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ];
  1751. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ];
  1752. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ];
  1753. return this;
  1754. },
  1755. applyProjection: function ( m ) {
  1756. // input: THREE.Matrix4 projection matrix
  1757. var x = this.x, y = this.y, z = this.z;
  1758. var e = m.elements;
  1759. var d = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] ); // perspective divide
  1760. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * d;
  1761. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * d;
  1762. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * d;
  1763. return this;
  1764. },
  1765. applyQuaternion: function ( q ) {
  1766. var x = this.x, y = this.y, z = this.z;
  1767. var qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  1768. // calculate quat * vector
  1769. var ix = qw * x + qy * z - qz * y;
  1770. var iy = qw * y + qz * x - qx * z;
  1771. var iz = qw * z + qx * y - qy * x;
  1772. var iw = - qx * x - qy * y - qz * z;
  1773. // calculate result * inverse quat
  1774. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  1775. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  1776. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  1777. return this;
  1778. },
  1779. project: function () {
  1780. var matrix;
  1781. return function project( camera ) {
  1782. if ( matrix === undefined ) matrix = new Matrix4();
  1783. matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) );
  1784. return this.applyProjection( matrix );
  1785. };
  1786. }(),
  1787. unproject: function () {
  1788. var matrix;
  1789. return function unproject( camera ) {
  1790. if ( matrix === undefined ) matrix = new Matrix4();
  1791. matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) );
  1792. return this.applyProjection( matrix );
  1793. };
  1794. }(),
  1795. transformDirection: function ( m ) {
  1796. // input: THREE.Matrix4 affine matrix
  1797. // vector interpreted as a direction
  1798. var x = this.x, y = this.y, z = this.z;
  1799. var e = m.elements;
  1800. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  1801. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  1802. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  1803. return this.normalize();
  1804. },
  1805. divide: function ( v ) {
  1806. this.x /= v.x;
  1807. this.y /= v.y;
  1808. this.z /= v.z;
  1809. return this;
  1810. },
  1811. divideScalar: function ( scalar ) {
  1812. return this.multiplyScalar( 1 / scalar );
  1813. },
  1814. min: function ( v ) {
  1815. this.x = Math.min( this.x, v.x );
  1816. this.y = Math.min( this.y, v.y );
  1817. this.z = Math.min( this.z, v.z );
  1818. return this;
  1819. },
  1820. max: function ( v ) {
  1821. this.x = Math.max( this.x, v.x );
  1822. this.y = Math.max( this.y, v.y );
  1823. this.z = Math.max( this.z, v.z );
  1824. return this;
  1825. },
  1826. clamp: function ( min, max ) {
  1827. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1828. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1829. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1830. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1831. return this;
  1832. },
  1833. clampScalar: function () {
  1834. var min, max;
  1835. return function clampScalar( minVal, maxVal ) {
  1836. if ( min === undefined ) {
  1837. min = new Vector3();
  1838. max = new Vector3();
  1839. }
  1840. min.set( minVal, minVal, minVal );
  1841. max.set( maxVal, maxVal, maxVal );
  1842. return this.clamp( min, max );
  1843. };
  1844. }(),
  1845. clampLength: function ( min, max ) {
  1846. var length = this.length();
  1847. return this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length );
  1848. },
  1849. floor: function () {
  1850. this.x = Math.floor( this.x );
  1851. this.y = Math.floor( this.y );
  1852. this.z = Math.floor( this.z );
  1853. return this;
  1854. },
  1855. ceil: function () {
  1856. this.x = Math.ceil( this.x );
  1857. this.y = Math.ceil( this.y );
  1858. this.z = Math.ceil( this.z );
  1859. return this;
  1860. },
  1861. round: function () {
  1862. this.x = Math.round( this.x );
  1863. this.y = Math.round( this.y );
  1864. this.z = Math.round( this.z );
  1865. return this;
  1866. },
  1867. roundToZero: function () {
  1868. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1869. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1870. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1871. return this;
  1872. },
  1873. negate: function () {
  1874. this.x = - this.x;
  1875. this.y = - this.y;
  1876. this.z = - this.z;
  1877. return this;
  1878. },
  1879. dot: function ( v ) {
  1880. return this.x * v.x + this.y * v.y + this.z * v.z;
  1881. },
  1882. lengthSq: function () {
  1883. return this.x * this.x + this.y * this.y + this.z * this.z;
  1884. },
  1885. length: function () {
  1886. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1887. },
  1888. lengthManhattan: function () {
  1889. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1890. },
  1891. normalize: function () {
  1892. return this.divideScalar( this.length() );
  1893. },
  1894. setLength: function ( length ) {
  1895. return this.multiplyScalar( length / this.length() );
  1896. },
  1897. lerp: function ( v, alpha ) {
  1898. this.x += ( v.x - this.x ) * alpha;
  1899. this.y += ( v.y - this.y ) * alpha;
  1900. this.z += ( v.z - this.z ) * alpha;
  1901. return this;
  1902. },
  1903. lerpVectors: function ( v1, v2, alpha ) {
  1904. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1905. },
  1906. cross: function ( v, w ) {
  1907. if ( w !== undefined ) {
  1908. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1909. return this.crossVectors( v, w );
  1910. }
  1911. var x = this.x, y = this.y, z = this.z;
  1912. this.x = y * v.z - z * v.y;
  1913. this.y = z * v.x - x * v.z;
  1914. this.z = x * v.y - y * v.x;
  1915. return this;
  1916. },
  1917. crossVectors: function ( a, b ) {
  1918. var ax = a.x, ay = a.y, az = a.z;
  1919. var bx = b.x, by = b.y, bz = b.z;
  1920. this.x = ay * bz - az * by;
  1921. this.y = az * bx - ax * bz;
  1922. this.z = ax * by - ay * bx;
  1923. return this;
  1924. },
  1925. projectOnVector: function ( vector ) {
  1926. var scalar = vector.dot( this ) / vector.lengthSq();
  1927. return this.copy( vector ).multiplyScalar( scalar );
  1928. },
  1929. projectOnPlane: function () {
  1930. var v1;
  1931. return function projectOnPlane( planeNormal ) {
  1932. if ( v1 === undefined ) v1 = new Vector3();
  1933. v1.copy( this ).projectOnVector( planeNormal );
  1934. return this.sub( v1 );
  1935. };
  1936. }(),
  1937. reflect: function () {
  1938. // reflect incident vector off plane orthogonal to normal
  1939. // normal is assumed to have unit length
  1940. var v1;
  1941. return function reflect( normal ) {
  1942. if ( v1 === undefined ) v1 = new Vector3();
  1943. return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  1944. };
  1945. }(),
  1946. angleTo: function ( v ) {
  1947. var theta = this.dot( v ) / ( Math.sqrt( this.lengthSq() * v.lengthSq() ) );
  1948. // clamp, to handle numerical problems
  1949. return Math.acos( exports.Math.clamp( theta, - 1, 1 ) );
  1950. },
  1951. distanceTo: function ( v ) {
  1952. return Math.sqrt( this.distanceToSquared( v ) );
  1953. },
  1954. distanceToSquared: function ( v ) {
  1955. var dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  1956. return dx * dx + dy * dy + dz * dz;
  1957. },
  1958. distanceToManhattan: function ( v ) {
  1959. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  1960. },
  1961. setFromSpherical: function( s ) {
  1962. var sinPhiRadius = Math.sin( s.phi ) * s.radius;
  1963. this.x = sinPhiRadius * Math.sin( s.theta );
  1964. this.y = Math.cos( s.phi ) * s.radius;
  1965. this.z = sinPhiRadius * Math.cos( s.theta );
  1966. return this;
  1967. },
  1968. setFromMatrixPosition: function ( m ) {
  1969. return this.setFromMatrixColumn( m, 3 );
  1970. },
  1971. setFromMatrixScale: function ( m ) {
  1972. var sx = this.setFromMatrixColumn( m, 0 ).length();
  1973. var sy = this.setFromMatrixColumn( m, 1 ).length();
  1974. var sz = this.setFromMatrixColumn( m, 2 ).length();
  1975. this.x = sx;
  1976. this.y = sy;
  1977. this.z = sz;
  1978. return this;
  1979. },
  1980. setFromMatrixColumn: function ( m, index ) {
  1981. if ( typeof m === 'number' ) {
  1982. console.warn( 'THREE.Vector3: setFromMatrixColumn now expects ( matrix, index ).' );
  1983. var temp = m
  1984. m = index;
  1985. index = temp;
  1986. }
  1987. return this.fromArray( m.elements, index * 4 );
  1988. },
  1989. equals: function ( v ) {
  1990. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1991. },
  1992. fromArray: function ( array, offset ) {
  1993. if ( offset === undefined ) offset = 0;
  1994. this.x = array[ offset ];
  1995. this.y = array[ offset + 1 ];
  1996. this.z = array[ offset + 2 ];
  1997. return this;
  1998. },
  1999. toArray: function ( array, offset ) {
  2000. if ( array === undefined ) array = [];
  2001. if ( offset === undefined ) offset = 0;
  2002. array[ offset ] = this.x;
  2003. array[ offset + 1 ] = this.y;
  2004. array[ offset + 2 ] = this.z;
  2005. return array;
  2006. },
  2007. fromAttribute: function ( attribute, index, offset ) {
  2008. if ( offset === undefined ) offset = 0;
  2009. index = index * attribute.itemSize + offset;
  2010. this.x = attribute.array[ index ];
  2011. this.y = attribute.array[ index + 1 ];
  2012. this.z = attribute.array[ index + 2 ];
  2013. return this;
  2014. }
  2015. };
  2016. /**
  2017. * @author mrdoob / http://mrdoob.com/
  2018. * @author supereggbert / http://www.paulbrunt.co.uk/
  2019. * @author philogb / http://blog.thejit.org/
  2020. * @author jordi_ros / http://plattsoft.com
  2021. * @author D1plo1d / http://github.com/D1plo1d
  2022. * @author alteredq / http://alteredqualia.com/
  2023. * @author mikael emtinger / http://gomo.se/
  2024. * @author timknip / http://www.floorplanner.com/
  2025. * @author bhouston / http://clara.io
  2026. * @author WestLangley / http://github.com/WestLangley
  2027. */
  2028. function Matrix4() {
  2029. this.elements = new Float32Array( [
  2030. 1, 0, 0, 0,
  2031. 0, 1, 0, 0,
  2032. 0, 0, 1, 0,
  2033. 0, 0, 0, 1
  2034. ] );
  2035. if ( arguments.length > 0 ) {
  2036. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  2037. }
  2038. }
  2039. Matrix4.prototype = {
  2040. constructor: Matrix4,
  2041. isMatrix4: true,
  2042. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2043. var te = this.elements;
  2044. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  2045. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  2046. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  2047. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  2048. return this;
  2049. },
  2050. identity: function () {
  2051. this.set(
  2052. 1, 0, 0, 0,
  2053. 0, 1, 0, 0,
  2054. 0, 0, 1, 0,
  2055. 0, 0, 0, 1
  2056. );
  2057. return this;
  2058. },
  2059. clone: function () {
  2060. return new Matrix4().fromArray( this.elements );
  2061. },
  2062. copy: function ( m ) {
  2063. this.elements.set( m.elements );
  2064. return this;
  2065. },
  2066. copyPosition: function ( m ) {
  2067. var te = this.elements;
  2068. var me = m.elements;
  2069. te[ 12 ] = me[ 12 ];
  2070. te[ 13 ] = me[ 13 ];
  2071. te[ 14 ] = me[ 14 ];
  2072. return this;
  2073. },
  2074. extractBasis: function ( xAxis, yAxis, zAxis ) {
  2075. xAxis.setFromMatrixColumn( this, 0 );
  2076. yAxis.setFromMatrixColumn( this, 1 );
  2077. zAxis.setFromMatrixColumn( this, 2 );
  2078. return this;
  2079. },
  2080. makeBasis: function ( xAxis, yAxis, zAxis ) {
  2081. this.set(
  2082. xAxis.x, yAxis.x, zAxis.x, 0,
  2083. xAxis.y, yAxis.y, zAxis.y, 0,
  2084. xAxis.z, yAxis.z, zAxis.z, 0,
  2085. 0, 0, 0, 1
  2086. );
  2087. return this;
  2088. },
  2089. extractRotation: function () {
  2090. var v1;
  2091. return function extractRotation( m ) {
  2092. if ( v1 === undefined ) v1 = new Vector3();
  2093. var te = this.elements;
  2094. var me = m.elements;
  2095. var scaleX = 1 / v1.setFromMatrixColumn( m, 0 ).length();
  2096. var scaleY = 1 / v1.setFromMatrixColumn( m, 1 ).length();
  2097. var scaleZ = 1 / v1.setFromMatrixColumn( m, 2 ).length();
  2098. te[ 0 ] = me[ 0 ] * scaleX;
  2099. te[ 1 ] = me[ 1 ] * scaleX;
  2100. te[ 2 ] = me[ 2 ] * scaleX;
  2101. te[ 4 ] = me[ 4 ] * scaleY;
  2102. te[ 5 ] = me[ 5 ] * scaleY;
  2103. te[ 6 ] = me[ 6 ] * scaleY;
  2104. te[ 8 ] = me[ 8 ] * scaleZ;
  2105. te[ 9 ] = me[ 9 ] * scaleZ;
  2106. te[ 10 ] = me[ 10 ] * scaleZ;
  2107. return this;
  2108. };
  2109. }(),
  2110. makeRotationFromEuler: function ( euler ) {
  2111. if ( (euler && euler.isEuler) === false ) {
  2112. console.error( 'THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  2113. }
  2114. var te = this.elements;
  2115. var x = euler.x, y = euler.y, z = euler.z;
  2116. var a = Math.cos( x ), b = Math.sin( x );
  2117. var c = Math.cos( y ), d = Math.sin( y );
  2118. var e = Math.cos( z ), f = Math.sin( z );
  2119. if ( euler.order === 'XYZ' ) {
  2120. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2121. te[ 0 ] = c * e;
  2122. te[ 4 ] = - c * f;
  2123. te[ 8 ] = d;
  2124. te[ 1 ] = af + be * d;
  2125. te[ 5 ] = ae - bf * d;
  2126. te[ 9 ] = - b * c;
  2127. te[ 2 ] = bf - ae * d;
  2128. te[ 6 ] = be + af * d;
  2129. te[ 10 ] = a * c;
  2130. } else if ( euler.order === 'YXZ' ) {
  2131. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2132. te[ 0 ] = ce + df * b;
  2133. te[ 4 ] = de * b - cf;
  2134. te[ 8 ] = a * d;
  2135. te[ 1 ] = a * f;
  2136. te[ 5 ] = a * e;
  2137. te[ 9 ] = - b;
  2138. te[ 2 ] = cf * b - de;
  2139. te[ 6 ] = df + ce * b;
  2140. te[ 10 ] = a * c;
  2141. } else if ( euler.order === 'ZXY' ) {
  2142. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2143. te[ 0 ] = ce - df * b;
  2144. te[ 4 ] = - a * f;
  2145. te[ 8 ] = de + cf * b;
  2146. te[ 1 ] = cf + de * b;
  2147. te[ 5 ] = a * e;
  2148. te[ 9 ] = df - ce * b;
  2149. te[ 2 ] = - a * d;
  2150. te[ 6 ] = b;
  2151. te[ 10 ] = a * c;
  2152. } else if ( euler.order === 'ZYX' ) {
  2153. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2154. te[ 0 ] = c * e;
  2155. te[ 4 ] = be * d - af;
  2156. te[ 8 ] = ae * d + bf;
  2157. te[ 1 ] = c * f;
  2158. te[ 5 ] = bf * d + ae;
  2159. te[ 9 ] = af * d - be;
  2160. te[ 2 ] = - d;
  2161. te[ 6 ] = b * c;
  2162. te[ 10 ] = a * c;
  2163. } else if ( euler.order === 'YZX' ) {
  2164. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2165. te[ 0 ] = c * e;
  2166. te[ 4 ] = bd - ac * f;
  2167. te[ 8 ] = bc * f + ad;
  2168. te[ 1 ] = f;
  2169. te[ 5 ] = a * e;
  2170. te[ 9 ] = - b * e;
  2171. te[ 2 ] = - d * e;
  2172. te[ 6 ] = ad * f + bc;
  2173. te[ 10 ] = ac - bd * f;
  2174. } else if ( euler.order === 'XZY' ) {
  2175. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2176. te[ 0 ] = c * e;
  2177. te[ 4 ] = - f;
  2178. te[ 8 ] = d * e;
  2179. te[ 1 ] = ac * f + bd;
  2180. te[ 5 ] = a * e;
  2181. te[ 9 ] = ad * f - bc;
  2182. te[ 2 ] = bc * f - ad;
  2183. te[ 6 ] = b * e;
  2184. te[ 10 ] = bd * f + ac;
  2185. }
  2186. // last column
  2187. te[ 3 ] = 0;
  2188. te[ 7 ] = 0;
  2189. te[ 11 ] = 0;
  2190. // bottom row
  2191. te[ 12 ] = 0;
  2192. te[ 13 ] = 0;
  2193. te[ 14 ] = 0;
  2194. te[ 15 ] = 1;
  2195. return this;
  2196. },
  2197. makeRotationFromQuaternion: function ( q ) {
  2198. var te = this.elements;
  2199. var x = q.x, y = q.y, z = q.z, w = q.w;
  2200. var x2 = x + x, y2 = y + y, z2 = z + z;
  2201. var xx = x * x2, xy = x * y2, xz = x * z2;
  2202. var yy = y * y2, yz = y * z2, zz = z * z2;
  2203. var wx = w * x2, wy = w * y2, wz = w * z2;
  2204. te[ 0 ] = 1 - ( yy + zz );
  2205. te[ 4 ] = xy - wz;
  2206. te[ 8 ] = xz + wy;
  2207. te[ 1 ] = xy + wz;
  2208. te[ 5 ] = 1 - ( xx + zz );
  2209. te[ 9 ] = yz - wx;
  2210. te[ 2 ] = xz - wy;
  2211. te[ 6 ] = yz + wx;
  2212. te[ 10 ] = 1 - ( xx + yy );
  2213. // last column
  2214. te[ 3 ] = 0;
  2215. te[ 7 ] = 0;
  2216. te[ 11 ] = 0;
  2217. // bottom row
  2218. te[ 12 ] = 0;
  2219. te[ 13 ] = 0;
  2220. te[ 14 ] = 0;
  2221. te[ 15 ] = 1;
  2222. return this;
  2223. },
  2224. lookAt: function () {
  2225. var x, y, z;
  2226. return function lookAt( eye, target, up ) {
  2227. if ( x === undefined ) {
  2228. x = new Vector3();
  2229. y = new Vector3();
  2230. z = new Vector3();
  2231. }
  2232. var te = this.elements;
  2233. z.subVectors( eye, target ).normalize();
  2234. if ( z.lengthSq() === 0 ) {
  2235. z.z = 1;
  2236. }
  2237. x.crossVectors( up, z ).normalize();
  2238. if ( x.lengthSq() === 0 ) {
  2239. z.z += 0.0001;
  2240. x.crossVectors( up, z ).normalize();
  2241. }
  2242. y.crossVectors( z, x );
  2243. te[ 0 ] = x.x; te[ 4 ] = y.x; te[ 8 ] = z.x;
  2244. te[ 1 ] = x.y; te[ 5 ] = y.y; te[ 9 ] = z.y;
  2245. te[ 2 ] = x.z; te[ 6 ] = y.z; te[ 10 ] = z.z;
  2246. return this;
  2247. };
  2248. }(),
  2249. multiply: function ( m, n ) {
  2250. if ( n !== undefined ) {
  2251. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2252. return this.multiplyMatrices( m, n );
  2253. }
  2254. return this.multiplyMatrices( this, m );
  2255. },
  2256. premultiply: function ( m ) {
  2257. return this.multiplyMatrices( m, this );
  2258. },
  2259. multiplyMatrices: function ( a, b ) {
  2260. var ae = a.elements;
  2261. var be = b.elements;
  2262. var te = this.elements;
  2263. var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  2264. var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  2265. var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  2266. var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  2267. var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  2268. var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  2269. var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  2270. var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  2271. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2272. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2273. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2274. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2275. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2276. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2277. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2278. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2279. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2280. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2281. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2282. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2283. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2284. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2285. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2286. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2287. return this;
  2288. },
  2289. multiplyToArray: function ( a, b, r ) {
  2290. var te = this.elements;
  2291. this.multiplyMatrices( a, b );
  2292. r[ 0 ] = te[ 0 ]; r[ 1 ] = te[ 1 ]; r[ 2 ] = te[ 2 ]; r[ 3 ] = te[ 3 ];
  2293. r[ 4 ] = te[ 4 ]; r[ 5 ] = te[ 5 ]; r[ 6 ] = te[ 6 ]; r[ 7 ] = te[ 7 ];
  2294. r[ 8 ] = te[ 8 ]; r[ 9 ] = te[ 9 ]; r[ 10 ] = te[ 10 ]; r[ 11 ] = te[ 11 ];
  2295. r[ 12 ] = te[ 12 ]; r[ 13 ] = te[ 13 ]; r[ 14 ] = te[ 14 ]; r[ 15 ] = te[ 15 ];
  2296. return this;
  2297. },
  2298. multiplyScalar: function ( s ) {
  2299. var te = this.elements;
  2300. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  2301. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  2302. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  2303. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  2304. return this;
  2305. },
  2306. applyToVector3Array: function () {
  2307. var v1;
  2308. return function applyToVector3Array( array, offset, length ) {
  2309. if ( v1 === undefined ) v1 = new Vector3();
  2310. if ( offset === undefined ) offset = 0;
  2311. if ( length === undefined ) length = array.length;
  2312. for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) {
  2313. v1.fromArray( array, j );
  2314. v1.applyMatrix4( this );
  2315. v1.toArray( array, j );
  2316. }
  2317. return array;
  2318. };
  2319. }(),
  2320. applyToBuffer: function () {
  2321. var v1;
  2322. return function applyToBuffer( buffer, offset, length ) {
  2323. if ( v1 === undefined ) v1 = new Vector3();
  2324. if ( offset === undefined ) offset = 0;
  2325. if ( length === undefined ) length = buffer.length / buffer.itemSize;
  2326. for ( var i = 0, j = offset; i < length; i ++, j ++ ) {
  2327. v1.x = buffer.getX( j );
  2328. v1.y = buffer.getY( j );
  2329. v1.z = buffer.getZ( j );
  2330. v1.applyMatrix4( this );
  2331. buffer.setXYZ( v1.x, v1.y, v1.z );
  2332. }
  2333. return buffer;
  2334. };
  2335. }(),
  2336. determinant: function () {
  2337. var te = this.elements;
  2338. var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  2339. var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  2340. var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  2341. var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  2342. //TODO: make this more efficient
  2343. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2344. return (
  2345. n41 * (
  2346. + n14 * n23 * n32
  2347. - n13 * n24 * n32
  2348. - n14 * n22 * n33
  2349. + n12 * n24 * n33
  2350. + n13 * n22 * n34
  2351. - n12 * n23 * n34
  2352. ) +
  2353. n42 * (
  2354. + n11 * n23 * n34
  2355. - n11 * n24 * n33
  2356. + n14 * n21 * n33
  2357. - n13 * n21 * n34
  2358. + n13 * n24 * n31
  2359. - n14 * n23 * n31
  2360. ) +
  2361. n43 * (
  2362. + n11 * n24 * n32
  2363. - n11 * n22 * n34
  2364. - n14 * n21 * n32
  2365. + n12 * n21 * n34
  2366. + n14 * n22 * n31
  2367. - n12 * n24 * n31
  2368. ) +
  2369. n44 * (
  2370. - n13 * n22 * n31
  2371. - n11 * n23 * n32
  2372. + n11 * n22 * n33
  2373. + n13 * n21 * n32
  2374. - n12 * n21 * n33
  2375. + n12 * n23 * n31
  2376. )
  2377. );
  2378. },
  2379. transpose: function () {
  2380. var te = this.elements;
  2381. var tmp;
  2382. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  2383. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  2384. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  2385. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  2386. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  2387. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  2388. return this;
  2389. },
  2390. flattenToArrayOffset: function ( array, offset ) {
  2391. console.warn( "THREE.Matrix3: .flattenToArrayOffset is deprecated " +
  2392. "- just use .toArray instead." );
  2393. return this.toArray( array, offset );
  2394. },
  2395. getPosition: function () {
  2396. var v1;
  2397. return function getPosition() {
  2398. if ( v1 === undefined ) v1 = new Vector3();
  2399. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  2400. return v1.setFromMatrixColumn( this, 3 );
  2401. };
  2402. }(),
  2403. setPosition: function ( v ) {
  2404. var te = this.elements;
  2405. te[ 12 ] = v.x;
  2406. te[ 13 ] = v.y;
  2407. te[ 14 ] = v.z;
  2408. return this;
  2409. },
  2410. getInverse: function ( m, throwOnDegenerate ) {
  2411. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  2412. var te = this.elements,
  2413. me = m.elements,
  2414. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], n41 = me[ 3 ],
  2415. n12 = me[ 4 ], n22 = me[ 5 ], n32 = me[ 6 ], n42 = me[ 7 ],
  2416. n13 = me[ 8 ], n23 = me[ 9 ], n33 = me[ 10 ], n43 = me[ 11 ],
  2417. n14 = me[ 12 ], n24 = me[ 13 ], n34 = me[ 14 ], n44 = me[ 15 ],
  2418. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  2419. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  2420. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  2421. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  2422. var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  2423. if ( det === 0 ) {
  2424. var msg = "THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0";
  2425. if ( throwOnDegenerate === true ) {
  2426. throw new Error( msg );
  2427. } else {
  2428. console.warn( msg );
  2429. }
  2430. return this.identity();
  2431. }
  2432. var detInv = 1 / det;
  2433. te[ 0 ] = t11 * detInv;
  2434. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  2435. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  2436. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  2437. te[ 4 ] = t12 * detInv;
  2438. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  2439. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  2440. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  2441. te[ 8 ] = t13 * detInv;
  2442. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  2443. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  2444. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  2445. te[ 12 ] = t14 * detInv;
  2446. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  2447. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  2448. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  2449. return this;
  2450. },
  2451. scale: function ( v ) {
  2452. var te = this.elements;
  2453. var x = v.x, y = v.y, z = v.z;
  2454. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  2455. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  2456. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  2457. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  2458. return this;
  2459. },
  2460. getMaxScaleOnAxis: function () {
  2461. var te = this.elements;
  2462. var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  2463. var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  2464. var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  2465. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  2466. },
  2467. makeTranslation: function ( x, y, z ) {
  2468. this.set(
  2469. 1, 0, 0, x,
  2470. 0, 1, 0, y,
  2471. 0, 0, 1, z,
  2472. 0, 0, 0, 1
  2473. );
  2474. return this;
  2475. },
  2476. makeRotationX: function ( theta ) {
  2477. var c = Math.cos( theta ), s = Math.sin( theta );
  2478. this.set(
  2479. 1, 0, 0, 0,
  2480. 0, c, - s, 0,
  2481. 0, s, c, 0,
  2482. 0, 0, 0, 1
  2483. );
  2484. return this;
  2485. },
  2486. makeRotationY: function ( theta ) {
  2487. var c = Math.cos( theta ), s = Math.sin( theta );
  2488. this.set(
  2489. c, 0, s, 0,
  2490. 0, 1, 0, 0,
  2491. - s, 0, c, 0,
  2492. 0, 0, 0, 1
  2493. );
  2494. return this;
  2495. },
  2496. makeRotationZ: function ( theta ) {
  2497. var c = Math.cos( theta ), s = Math.sin( theta );
  2498. this.set(
  2499. c, - s, 0, 0,
  2500. s, c, 0, 0,
  2501. 0, 0, 1, 0,
  2502. 0, 0, 0, 1
  2503. );
  2504. return this;
  2505. },
  2506. makeRotationAxis: function ( axis, angle ) {
  2507. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  2508. var c = Math.cos( angle );
  2509. var s = Math.sin( angle );
  2510. var t = 1 - c;
  2511. var x = axis.x, y = axis.y, z = axis.z;
  2512. var tx = t * x, ty = t * y;
  2513. this.set(
  2514. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  2515. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  2516. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  2517. 0, 0, 0, 1
  2518. );
  2519. return this;
  2520. },
  2521. makeScale: function ( x, y, z ) {
  2522. this.set(
  2523. x, 0, 0, 0,
  2524. 0, y, 0, 0,
  2525. 0, 0, z, 0,
  2526. 0, 0, 0, 1
  2527. );
  2528. return this;
  2529. },
  2530. compose: function ( position, quaternion, scale ) {
  2531. this.makeRotationFromQuaternion( quaternion );
  2532. this.scale( scale );
  2533. this.setPosition( position );
  2534. return this;
  2535. },
  2536. decompose: function () {
  2537. var vector, matrix;
  2538. return function decompose( position, quaternion, scale ) {
  2539. if ( vector === undefined ) {
  2540. vector = new Vector3();
  2541. matrix = new Matrix4();
  2542. }
  2543. var te = this.elements;
  2544. var sx = vector.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  2545. var sy = vector.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  2546. var sz = vector.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  2547. // if determine is negative, we need to invert one scale
  2548. var det = this.determinant();
  2549. if ( det < 0 ) {
  2550. sx = - sx;
  2551. }
  2552. position.x = te[ 12 ];
  2553. position.y = te[ 13 ];
  2554. position.z = te[ 14 ];
  2555. // scale the rotation part
  2556. matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy()
  2557. var invSX = 1 / sx;
  2558. var invSY = 1 / sy;
  2559. var invSZ = 1 / sz;
  2560. matrix.elements[ 0 ] *= invSX;
  2561. matrix.elements[ 1 ] *= invSX;
  2562. matrix.elements[ 2 ] *= invSX;
  2563. matrix.elements[ 4 ] *= invSY;
  2564. matrix.elements[ 5 ] *= invSY;
  2565. matrix.elements[ 6 ] *= invSY;
  2566. matrix.elements[ 8 ] *= invSZ;
  2567. matrix.elements[ 9 ] *= invSZ;
  2568. matrix.elements[ 10 ] *= invSZ;
  2569. quaternion.setFromRotationMatrix( matrix );
  2570. scale.x = sx;
  2571. scale.y = sy;
  2572. scale.z = sz;
  2573. return this;
  2574. };
  2575. }(),
  2576. makeFrustum: function ( left, right, bottom, top, near, far ) {
  2577. var te = this.elements;
  2578. var x = 2 * near / ( right - left );
  2579. var y = 2 * near / ( top - bottom );
  2580. var a = ( right + left ) / ( right - left );
  2581. var b = ( top + bottom ) / ( top - bottom );
  2582. var c = - ( far + near ) / ( far - near );
  2583. var d = - 2 * far * near / ( far - near );
  2584. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  2585. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  2586. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  2587. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  2588. return this;
  2589. },
  2590. makePerspective: function ( fov, aspect, near, far ) {
  2591. var ymax = near * Math.tan( exports.Math.DEG2RAD * fov * 0.5 );
  2592. var ymin = - ymax;
  2593. var xmin = ymin * aspect;
  2594. var xmax = ymax * aspect;
  2595. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  2596. },
  2597. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  2598. var te = this.elements;
  2599. var w = 1.0 / ( right - left );
  2600. var h = 1.0 / ( top - bottom );
  2601. var p = 1.0 / ( far - near );
  2602. var x = ( right + left ) * w;
  2603. var y = ( top + bottom ) * h;
  2604. var z = ( far + near ) * p;
  2605. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  2606. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  2607. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  2608. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  2609. return this;
  2610. },
  2611. equals: function ( matrix ) {
  2612. var te = this.elements;
  2613. var me = matrix.elements;
  2614. for ( var i = 0; i < 16; i ++ ) {
  2615. if ( te[ i ] !== me[ i ] ) return false;
  2616. }
  2617. return true;
  2618. },
  2619. fromArray: function ( array, offset ) {
  2620. if ( offset === undefined ) offset = 0;
  2621. for( var i = 0; i < 16; i ++ ) {
  2622. this.elements[ i ] = array[ i + offset ];
  2623. }
  2624. return this;
  2625. },
  2626. toArray: function ( array, offset ) {
  2627. if ( array === undefined ) array = [];
  2628. if ( offset === undefined ) offset = 0;
  2629. var te = this.elements;
  2630. array[ offset ] = te[ 0 ];
  2631. array[ offset + 1 ] = te[ 1 ];
  2632. array[ offset + 2 ] = te[ 2 ];
  2633. array[ offset + 3 ] = te[ 3 ];
  2634. array[ offset + 4 ] = te[ 4 ];
  2635. array[ offset + 5 ] = te[ 5 ];
  2636. array[ offset + 6 ] = te[ 6 ];
  2637. array[ offset + 7 ] = te[ 7 ];
  2638. array[ offset + 8 ] = te[ 8 ];
  2639. array[ offset + 9 ] = te[ 9 ];
  2640. array[ offset + 10 ] = te[ 10 ];
  2641. array[ offset + 11 ] = te[ 11 ];
  2642. array[ offset + 12 ] = te[ 12 ];
  2643. array[ offset + 13 ] = te[ 13 ];
  2644. array[ offset + 14 ] = te[ 14 ];
  2645. array[ offset + 15 ] = te[ 15 ];
  2646. return array;
  2647. }
  2648. };
  2649. /**
  2650. * @author mrdoob / http://mrdoob.com/
  2651. */
  2652. function CubeTexture( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  2653. images = images !== undefined ? images : [];
  2654. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  2655. Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  2656. this.flipY = false;
  2657. }
  2658. CubeTexture.prototype = Object.create( Texture.prototype );
  2659. CubeTexture.prototype.constructor = CubeTexture;
  2660. CubeTexture.prototype.isCubeTexture = true;
  2661. Object.defineProperty( CubeTexture.prototype, 'images', {
  2662. get: function () {
  2663. return this.image;
  2664. },
  2665. set: function ( value ) {
  2666. this.image = value;
  2667. }
  2668. } );
  2669. var emptyTexture = new Texture();
  2670. var emptyCubeTexture = new CubeTexture();
  2671. // --- Base for inner nodes (including the root) ---
  2672. function UniformContainer() {
  2673. this.seq = [];
  2674. this.map = {};
  2675. }
  2676. // --- Utilities ---
  2677. // Array Caches (provide typed arrays for temporary by size)
  2678. var arrayCacheF32 = [];
  2679. var arrayCacheI32 = [];
  2680. // Flattening for arrays of vectors and matrices
  2681. function flatten( array, nBlocks, blockSize ) {
  2682. var firstElem = array[ 0 ];
  2683. if ( firstElem <= 0 || firstElem > 0 ) return array;
  2684. // unoptimized: ! isNaN( firstElem )
  2685. // see http://jacksondunstan.com/articles/983
  2686. var n = nBlocks * blockSize,
  2687. r = arrayCacheF32[ n ];
  2688. if ( r === undefined ) {
  2689. r = new Float32Array( n );
  2690. arrayCacheF32[ n ] = r;
  2691. }
  2692. if ( nBlocks !== 0 ) {
  2693. firstElem.toArray( r, 0 );
  2694. for ( var i = 1, offset = 0; i !== nBlocks; ++ i ) {
  2695. offset += blockSize;
  2696. array[ i ].toArray( r, offset );
  2697. }
  2698. }
  2699. return r;
  2700. }
  2701. // Texture unit allocation
  2702. function allocTexUnits( renderer, n ) {
  2703. var r = arrayCacheI32[ n ];
  2704. if ( r === undefined ) {
  2705. r = new Int32Array( n );
  2706. arrayCacheI32[ n ] = r;
  2707. }
  2708. for ( var i = 0; i !== n; ++ i )
  2709. r[ i ] = renderer.allocTextureUnit();
  2710. return r;
  2711. }
  2712. // --- Setters ---
  2713. // Note: Defining these methods externally, because they come in a bunch
  2714. // and this way their names minify.
  2715. // Single scalar
  2716. function setValue1f( gl, v ) { gl.uniform1f( this.addr, v ); }
  2717. function setValue1i( gl, v ) { gl.uniform1i( this.addr, v ); }
  2718. // Single float vector (from flat array or THREE.VectorN)
  2719. function setValue2fv( gl, v ) {
  2720. if ( v.x === undefined ) gl.uniform2fv( this.addr, v );
  2721. else gl.uniform2f( this.addr, v.x, v.y );
  2722. }
  2723. function setValue3fv( gl, v ) {
  2724. if ( v.x !== undefined )
  2725. gl.uniform3f( this.addr, v.x, v.y, v.z );
  2726. else if ( v.r !== undefined )
  2727. gl.uniform3f( this.addr, v.r, v.g, v.b );
  2728. else
  2729. gl.uniform3fv( this.addr, v );
  2730. }
  2731. function setValue4fv( gl, v ) {
  2732. if ( v.x === undefined ) gl.uniform4fv( this.addr, v );
  2733. else gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  2734. }
  2735. // Single matrix (from flat array or MatrixN)
  2736. function setValue2fm( gl, v ) {
  2737. gl.uniformMatrix2fv( this.addr, false, v.elements || v );
  2738. }
  2739. function setValue3fm( gl, v ) {
  2740. gl.uniformMatrix3fv( this.addr, false, v.elements || v );
  2741. }
  2742. function setValue4fm( gl, v ) {
  2743. gl.uniformMatrix4fv( this.addr, false, v.elements || v );
  2744. }
  2745. // Single texture (2D / Cube)
  2746. function setValueT1( gl, v, renderer ) {
  2747. var unit = renderer.allocTextureUnit();
  2748. gl.uniform1i( this.addr, unit );
  2749. renderer.setTexture2D( v || emptyTexture, unit );
  2750. }
  2751. function setValueT6( gl, v, renderer ) {
  2752. var unit = renderer.allocTextureUnit();
  2753. gl.uniform1i( this.addr, unit );
  2754. renderer.setTextureCube( v || emptyCubeTexture, unit );
  2755. }
  2756. // Integer / Boolean vectors or arrays thereof (always flat arrays)
  2757. function setValue2iv( gl, v ) { gl.uniform2iv( this.addr, v ); }
  2758. function setValue3iv( gl, v ) { gl.uniform3iv( this.addr, v ); }
  2759. function setValue4iv( gl, v ) { gl.uniform4iv( this.addr, v ); }
  2760. // Helper to pick the right setter for the singular case
  2761. function getSingularSetter( type ) {
  2762. switch ( type ) {
  2763. case 0x1406: return setValue1f; // FLOAT
  2764. case 0x8b50: return setValue2fv; // _VEC2
  2765. case 0x8b51: return setValue3fv; // _VEC3
  2766. case 0x8b52: return setValue4fv; // _VEC4
  2767. case 0x8b5a: return setValue2fm; // _MAT2
  2768. case 0x8b5b: return setValue3fm; // _MAT3
  2769. case 0x8b5c: return setValue4fm; // _MAT4
  2770. case 0x8b5e: return setValueT1; // SAMPLER_2D
  2771. case 0x8b60: return setValueT6; // SAMPLER_CUBE
  2772. case 0x1404: case 0x8b56: return setValue1i; // INT, BOOL
  2773. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  2774. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  2775. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  2776. }
  2777. }
  2778. // Array of scalars
  2779. function setValue1fv( gl, v ) { gl.uniform1fv( this.addr, v ); }
  2780. function setValue1iv( gl, v ) { gl.uniform1iv( this.addr, v ); }
  2781. // Array of vectors (flat or from THREE classes)
  2782. function setValueV2a( gl, v ) {
  2783. gl.uniform2fv( this.addr, flatten( v, this.size, 2 ) );
  2784. }
  2785. function setValueV3a( gl, v ) {
  2786. gl.uniform3fv( this.addr, flatten( v, this.size, 3 ) );
  2787. }
  2788. function setValueV4a( gl, v ) {
  2789. gl.uniform4fv( this.addr, flatten( v, this.size, 4 ) );
  2790. }
  2791. // Array of matrices (flat or from THREE clases)
  2792. function setValueM2a( gl, v ) {
  2793. gl.uniformMatrix2fv( this.addr, false, flatten( v, this.size, 4 ) );
  2794. }
  2795. function setValueM3a( gl, v ) {
  2796. gl.uniformMatrix3fv( this.addr, false, flatten( v, this.size, 9 ) );
  2797. }
  2798. function setValueM4a( gl, v ) {
  2799. gl.uniformMatrix4fv( this.addr, false, flatten( v, this.size, 16 ) );
  2800. }
  2801. // Array of textures (2D / Cube)
  2802. function setValueT1a( gl, v, renderer ) {
  2803. var n = v.length,
  2804. units = allocTexUnits( renderer, n );
  2805. gl.uniform1iv( this.addr, units );
  2806. for ( var i = 0; i !== n; ++ i ) {
  2807. renderer.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  2808. }
  2809. }
  2810. function setValueT6a( gl, v, renderer ) {
  2811. var n = v.length,
  2812. units = allocTexUnits( renderer, n );
  2813. gl.uniform1iv( this.addr, units );
  2814. for ( var i = 0; i !== n; ++ i ) {
  2815. renderer.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  2816. }
  2817. }
  2818. // Helper to pick the right setter for a pure (bottom-level) array
  2819. function getPureArraySetter( type ) {
  2820. switch ( type ) {
  2821. case 0x1406: return setValue1fv; // FLOAT
  2822. case 0x8b50: return setValueV2a; // _VEC2
  2823. case 0x8b51: return setValueV3a; // _VEC3
  2824. case 0x8b52: return setValueV4a; // _VEC4
  2825. case 0x8b5a: return setValueM2a; // _MAT2
  2826. case 0x8b5b: return setValueM3a; // _MAT3
  2827. case 0x8b5c: return setValueM4a; // _MAT4
  2828. case 0x8b5e: return setValueT1a; // SAMPLER_2D
  2829. case 0x8b60: return setValueT6a; // SAMPLER_CUBE
  2830. case 0x1404: case 0x8b56: return setValue1iv; // INT, BOOL
  2831. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  2832. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  2833. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  2834. }
  2835. }
  2836. // --- Uniform Classes ---
  2837. function SingleUniform( id, activeInfo, addr ) {
  2838. this.id = id;
  2839. this.addr = addr;
  2840. this.setValue = getSingularSetter( activeInfo.type );
  2841. // this.path = activeInfo.name; // DEBUG
  2842. }
  2843. function PureArrayUniform( id, activeInfo, addr ) {
  2844. this.id = id;
  2845. this.addr = addr;
  2846. this.size = activeInfo.size;
  2847. this.setValue = getPureArraySetter( activeInfo.type );
  2848. // this.path = activeInfo.name; // DEBUG
  2849. }
  2850. function StructuredUniform( id ) {
  2851. this.id = id;
  2852. UniformContainer.call( this ); // mix-in
  2853. }
  2854. StructuredUniform.prototype.setValue = function( gl, value ) {
  2855. // Note: Don't need an extra 'renderer' parameter, since samplers
  2856. // are not allowed in structured uniforms.
  2857. var seq = this.seq;
  2858. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  2859. var u = seq[ i ];
  2860. u.setValue( gl, value[ u.id ] );
  2861. }
  2862. };
  2863. // --- Top-level ---
  2864. // Parser - builds up the property tree from the path strings
  2865. var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g;
  2866. // extracts
  2867. // - the identifier (member name or array index)
  2868. // - followed by an optional right bracket (found when array index)
  2869. // - followed by an optional left bracket or dot (type of subscript)
  2870. //
  2871. // Note: These portions can be read in a non-overlapping fashion and
  2872. // allow straightforward parsing of the hierarchy that WebGL encodes
  2873. // in the uniform names.
  2874. function addUniform( container, uniformObject ) {
  2875. container.seq.push( uniformObject );
  2876. container.map[ uniformObject.id ] = uniformObject;
  2877. }
  2878. function parseUniform( activeInfo, addr, container ) {
  2879. var path = activeInfo.name,
  2880. pathLength = path.length;
  2881. // reset RegExp object, because of the early exit of a previous run
  2882. RePathPart.lastIndex = 0;
  2883. for (; ;) {
  2884. var match = RePathPart.exec( path ),
  2885. matchEnd = RePathPart.lastIndex,
  2886. id = match[ 1 ],
  2887. idIsIndex = match[ 2 ] === ']',
  2888. subscript = match[ 3 ];
  2889. if ( idIsIndex ) id = id | 0; // convert to integer
  2890. if ( subscript === undefined ||
  2891. subscript === '[' && matchEnd + 2 === pathLength ) {
  2892. // bare name or "pure" bottom-level array "[0]" suffix
  2893. addUniform( container, subscript === undefined ?
  2894. new SingleUniform( id, activeInfo, addr ) :
  2895. new PureArrayUniform( id, activeInfo, addr ) );
  2896. break;
  2897. } else {
  2898. // step into inner node / create it in case it doesn't exist
  2899. var map = container.map,
  2900. next = map[ id ];
  2901. if ( next === undefined ) {
  2902. next = new StructuredUniform( id );
  2903. addUniform( container, next );
  2904. }
  2905. container = next;
  2906. }
  2907. }
  2908. }
  2909. // Root Container
  2910. function WebGLUniforms( gl, program, renderer ) {
  2911. UniformContainer.call( this );
  2912. this.renderer = renderer;
  2913. var n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  2914. for ( var i = 0; i !== n; ++ i ) {
  2915. var info = gl.getActiveUniform( program, i ),
  2916. path = info.name,
  2917. addr = gl.getUniformLocation( program, path );
  2918. parseUniform( info, addr, this );
  2919. }
  2920. }
  2921. WebGLUniforms.prototype.setValue = function( gl, name, value ) {
  2922. var u = this.map[ name ];
  2923. if ( u !== undefined ) u.setValue( gl, value, this.renderer );
  2924. };
  2925. WebGLUniforms.prototype.set = function( gl, object, name ) {
  2926. var u = this.map[ name ];
  2927. if ( u !== undefined ) u.setValue( gl, object[ name ], this.renderer );
  2928. };
  2929. WebGLUniforms.prototype.setOptional = function( gl, object, name ) {
  2930. var v = object[ name ];
  2931. if ( v !== undefined ) this.setValue( gl, name, v );
  2932. };
  2933. // Static interface
  2934. WebGLUniforms.upload = function( gl, seq, values, renderer ) {
  2935. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  2936. var u = seq[ i ],
  2937. v = values[ u.id ];
  2938. if ( v.needsUpdate !== false ) {
  2939. // note: always updating when .needsUpdate is undefined
  2940. u.setValue( gl, v.value, renderer );
  2941. }
  2942. }
  2943. };
  2944. WebGLUniforms.seqWithValue = function( seq, values ) {
  2945. var r = [];
  2946. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  2947. var u = seq[ i ];
  2948. if ( u.id in values ) r.push( u );
  2949. }
  2950. return r;
  2951. };
  2952. WebGLUniforms.splitDynamic = function( seq, values ) {
  2953. var r = null,
  2954. n = seq.length,
  2955. w = 0;
  2956. for ( var i = 0; i !== n; ++ i ) {
  2957. var u = seq[ i ],
  2958. v = values[ u.id ];
  2959. if ( v && v.dynamic === true ) {
  2960. if ( r === null ) r = [];
  2961. r.push( u );
  2962. } else {
  2963. // in-place compact 'seq', removing the matches
  2964. if ( w < i ) seq[ w ] = u;
  2965. ++ w;
  2966. }
  2967. }
  2968. if ( w < n ) seq.length = w;
  2969. return r;
  2970. };
  2971. WebGLUniforms.evalDynamic = function( seq, values, object, camera ) {
  2972. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  2973. var v = values[ seq[ i ].id ],
  2974. f = v.onUpdateCallback;
  2975. if ( f !== undefined ) f.call( v, object, camera );
  2976. }
  2977. };
  2978. /**
  2979. * Uniform Utilities
  2980. */
  2981. exports.UniformsUtils = {
  2982. merge: function ( uniforms ) {
  2983. var merged = {};
  2984. for ( var u = 0; u < uniforms.length; u ++ ) {
  2985. var tmp = this.clone( uniforms[ u ] );
  2986. for ( var p in tmp ) {
  2987. merged[ p ] = tmp[ p ];
  2988. }
  2989. }
  2990. return merged;
  2991. },
  2992. clone: function ( uniforms_src ) {
  2993. var uniforms_dst = {};
  2994. for ( var u in uniforms_src ) {
  2995. uniforms_dst[ u ] = {};
  2996. for ( var p in uniforms_src[ u ] ) {
  2997. var parameter_src = uniforms_src[ u ][ p ];
  2998. if ( (parameter_src && parameter_src.isColor) ||
  2999. (parameter_src && parameter_src.isVector2) ||
  3000. (parameter_src && parameter_src.isVector3) ||
  3001. (parameter_src && parameter_src.isVector4) ||
  3002. (parameter_src && parameter_src.isMatrix3) ||
  3003. (parameter_src && parameter_src.isMatrix4) ||
  3004. (parameter_src && parameter_src.isTexture) ) {
  3005. uniforms_dst[ u ][ p ] = parameter_src.clone();
  3006. } else if ( Array.isArray( parameter_src ) ) {
  3007. uniforms_dst[ u ][ p ] = parameter_src.slice();
  3008. } else {
  3009. uniforms_dst[ u ][ p ] = parameter_src;
  3010. }
  3011. }
  3012. }
  3013. return uniforms_dst;
  3014. }
  3015. };
  3016. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif\n";
  3017. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif\n";
  3018. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif\n";
  3019. 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";
  3020. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  3021. var begin_vertex = "\nvec3 transformed = vec3( position );\n";
  3022. var beginnormal_vertex = "\nvec3 objectNormal = vec3( normal );\n";
  3023. 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";
  3024. 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";
  3025. 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";
  3026. 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";
  3027. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvarying vec3 vViewPosition;\n#endif\n";
  3028. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n";
  3029. var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";
  3030. var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif\n";
  3031. var color_pars_vertex = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  3032. var color_vertex = "#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif";
  3033. 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";
  3034. 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";
  3035. var defaultnormal_vertex = "#ifdef FLIP_SIDED\n\tobjectNormal = -objectNormal;\n#endif\nvec3 transformedNormal = normalMatrix * objectNormal;\n";
  3036. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif\n";
  3037. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normal * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n#endif\n";
  3038. 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";
  3039. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif\n";
  3040. var encodings_fragment = " gl_FragColor = linearToOutputTexel( gl_FragColor );\n";
  3041. 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";
  3042. 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#else\n\t\tvec4 envColor = vec4( 0.0 );\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";
  3043. 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";
  3044. 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";
  3045. 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";
  3046. 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";
  3047. 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";
  3048. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif\n";
  3049. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  3050. 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";
  3051. 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";
  3052. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n";
  3053. 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";
  3054. 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";
  3055. 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";
  3056. 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";
  3057. var logdepthbuf_fragment = "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n\tgl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n#endif";
  3058. 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";
  3059. 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";
  3060. 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";
  3061. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif\n";
  3062. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n";
  3063. 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";
  3064. var map_particle_pars_fragment = "#ifdef USE_MAP\n\tuniform vec4 offsetRepeat;\n\tuniform sampler2D map;\n#endif\n";
  3065. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.r;\n#endif\n";
  3066. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  3067. 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";
  3068. 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";
  3069. 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";
  3070. 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";
  3071. 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";
  3072. 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";
  3073. 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";
  3074. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif\n";
  3075. 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";
  3076. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.r;\n#endif\n";
  3077. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  3078. 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";
  3079. 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";
  3080. 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";
  3081. 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";
  3082. 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";
  3083. 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";
  3084. 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";
  3085. 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";
  3086. 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";
  3087. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  3088. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif\n";
  3089. 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";
  3090. 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";
  3091. 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";
  3092. 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";
  3093. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  3094. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif";
  3095. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif";
  3096. 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";
  3097. 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";
  3098. 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";
  3099. 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";
  3100. 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";
  3101. 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";
  3102. 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";
  3103. 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";
  3104. 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";
  3105. 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";
  3106. 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";
  3107. 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";
  3108. 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";
  3109. 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";
  3110. 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";
  3111. 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";
  3112. 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";
  3113. 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";
  3114. 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";
  3115. 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";
  3116. 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";
  3117. 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";
  3118. 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";
  3119. 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";
  3120. 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";
  3121. var ShaderChunk = {
  3122. alphamap_fragment: alphamap_fragment,
  3123. alphamap_pars_fragment: alphamap_pars_fragment,
  3124. alphatest_fragment: alphatest_fragment,
  3125. aomap_fragment: aomap_fragment,
  3126. aomap_pars_fragment: aomap_pars_fragment,
  3127. begin_vertex: begin_vertex,
  3128. beginnormal_vertex: beginnormal_vertex,
  3129. bsdfs: bsdfs,
  3130. bumpmap_pars_fragment: bumpmap_pars_fragment,
  3131. clipping_planes_fragment: clipping_planes_fragment,
  3132. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  3133. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  3134. clipping_planes_vertex: clipping_planes_vertex,
  3135. color_fragment: color_fragment,
  3136. color_pars_fragment: color_pars_fragment,
  3137. color_pars_vertex: color_pars_vertex,
  3138. color_vertex: color_vertex,
  3139. common: common,
  3140. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  3141. defaultnormal_vertex: defaultnormal_vertex,
  3142. displacementmap_pars_vertex: displacementmap_pars_vertex,
  3143. displacementmap_vertex: displacementmap_vertex,
  3144. emissivemap_fragment: emissivemap_fragment,
  3145. emissivemap_pars_fragment: emissivemap_pars_fragment,
  3146. encodings_fragment: encodings_fragment,
  3147. encodings_pars_fragment: encodings_pars_fragment,
  3148. envmap_fragment: envmap_fragment,
  3149. envmap_pars_fragment: envmap_pars_fragment,
  3150. envmap_pars_vertex: envmap_pars_vertex,
  3151. envmap_vertex: envmap_vertex,
  3152. fog_fragment: fog_fragment,
  3153. fog_pars_fragment: fog_pars_fragment,
  3154. lightmap_fragment: lightmap_fragment,
  3155. lightmap_pars_fragment: lightmap_pars_fragment,
  3156. lights_lambert_vertex: lights_lambert_vertex,
  3157. lights_pars: lights_pars,
  3158. lights_phong_fragment: lights_phong_fragment,
  3159. lights_phong_pars_fragment: lights_phong_pars_fragment,
  3160. lights_physical_fragment: lights_physical_fragment,
  3161. lights_physical_pars_fragment: lights_physical_pars_fragment,
  3162. lights_template: lights_template,
  3163. logdepthbuf_fragment: logdepthbuf_fragment,
  3164. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  3165. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  3166. logdepthbuf_vertex: logdepthbuf_vertex,
  3167. map_fragment: map_fragment,
  3168. map_pars_fragment: map_pars_fragment,
  3169. map_particle_fragment: map_particle_fragment,
  3170. map_particle_pars_fragment: map_particle_pars_fragment,
  3171. metalnessmap_fragment: metalnessmap_fragment,
  3172. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  3173. morphnormal_vertex: morphnormal_vertex,
  3174. morphtarget_pars_vertex: morphtarget_pars_vertex,
  3175. morphtarget_vertex: morphtarget_vertex,
  3176. normal_flip: normal_flip,
  3177. normal_fragment: normal_fragment,
  3178. normalmap_pars_fragment: normalmap_pars_fragment,
  3179. packing: packing,
  3180. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  3181. project_vertex: project_vertex,
  3182. roughnessmap_fragment: roughnessmap_fragment,
  3183. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  3184. shadowmap_pars_fragment: shadowmap_pars_fragment,
  3185. shadowmap_pars_vertex: shadowmap_pars_vertex,
  3186. shadowmap_vertex: shadowmap_vertex,
  3187. shadowmask_pars_fragment: shadowmask_pars_fragment,
  3188. skinbase_vertex: skinbase_vertex,
  3189. skinning_pars_vertex: skinning_pars_vertex,
  3190. skinning_vertex: skinning_vertex,
  3191. skinnormal_vertex: skinnormal_vertex,
  3192. specularmap_fragment: specularmap_fragment,
  3193. specularmap_pars_fragment: specularmap_pars_fragment,
  3194. tonemapping_fragment: tonemapping_fragment,
  3195. tonemapping_pars_fragment: tonemapping_pars_fragment,
  3196. uv_pars_fragment: uv_pars_fragment,
  3197. uv_pars_vertex: uv_pars_vertex,
  3198. uv_vertex: uv_vertex,
  3199. uv2_pars_fragment: uv2_pars_fragment,
  3200. uv2_pars_vertex: uv2_pars_vertex,
  3201. uv2_vertex: uv2_vertex,
  3202. worldpos_vertex: worldpos_vertex,
  3203. cube_frag: cube_frag,
  3204. cube_vert: cube_vert,
  3205. depth_frag: depth_frag,
  3206. depth_vert: depth_vert,
  3207. distanceRGBA_frag: distanceRGBA_frag,
  3208. distanceRGBA_vert: distanceRGBA_vert,
  3209. equirect_frag: equirect_frag,
  3210. equirect_vert: equirect_vert,
  3211. linedashed_frag: linedashed_frag,
  3212. linedashed_vert: linedashed_vert,
  3213. meshbasic_frag: meshbasic_frag,
  3214. meshbasic_vert: meshbasic_vert,
  3215. meshlambert_frag: meshlambert_frag,
  3216. meshlambert_vert: meshlambert_vert,
  3217. meshphong_frag: meshphong_frag,
  3218. meshphong_vert: meshphong_vert,
  3219. meshphysical_frag: meshphysical_frag,
  3220. meshphysical_vert: meshphysical_vert,
  3221. normal_frag: normal_frag,
  3222. normal_vert: normal_vert,
  3223. points_frag: points_frag,
  3224. points_vert: points_vert,
  3225. shadow_frag: shadow_frag,
  3226. shadow_vert: shadow_vert
  3227. };
  3228. /**
  3229. * @author mrdoob / http://mrdoob.com/
  3230. */
  3231. function Color( r, g, b ) {
  3232. if ( g === undefined && b === undefined ) {
  3233. // r is THREE.Color, hex or string
  3234. return this.set( r );
  3235. }
  3236. return this.setRGB( r, g, b );
  3237. }
  3238. Color.prototype = {
  3239. constructor: Color,
  3240. isColor: true,
  3241. r: 1, g: 1, b: 1,
  3242. set: function ( value ) {
  3243. if ( (value && value.isColor) ) {
  3244. this.copy( value );
  3245. } else if ( typeof value === 'number' ) {
  3246. this.setHex( value );
  3247. } else if ( typeof value === 'string' ) {
  3248. this.setStyle( value );
  3249. }
  3250. return this;
  3251. },
  3252. setScalar: function ( scalar ) {
  3253. this.r = scalar;
  3254. this.g = scalar;
  3255. this.b = scalar;
  3256. },
  3257. setHex: function ( hex ) {
  3258. hex = Math.floor( hex );
  3259. this.r = ( hex >> 16 & 255 ) / 255;
  3260. this.g = ( hex >> 8 & 255 ) / 255;
  3261. this.b = ( hex & 255 ) / 255;
  3262. return this;
  3263. },
  3264. setRGB: function ( r, g, b ) {
  3265. this.r = r;
  3266. this.g = g;
  3267. this.b = b;
  3268. return this;
  3269. },
  3270. setHSL: function () {
  3271. function hue2rgb( p, q, t ) {
  3272. if ( t < 0 ) t += 1;
  3273. if ( t > 1 ) t -= 1;
  3274. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  3275. if ( t < 1 / 2 ) return q;
  3276. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  3277. return p;
  3278. }
  3279. return function setHSL( h, s, l ) {
  3280. // h,s,l ranges are in 0.0 - 1.0
  3281. h = exports.Math.euclideanModulo( h, 1 );
  3282. s = exports.Math.clamp( s, 0, 1 );
  3283. l = exports.Math.clamp( l, 0, 1 );
  3284. if ( s === 0 ) {
  3285. this.r = this.g = this.b = l;
  3286. } else {
  3287. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  3288. var q = ( 2 * l ) - p;
  3289. this.r = hue2rgb( q, p, h + 1 / 3 );
  3290. this.g = hue2rgb( q, p, h );
  3291. this.b = hue2rgb( q, p, h - 1 / 3 );
  3292. }
  3293. return this;
  3294. };
  3295. }(),
  3296. setStyle: function ( style ) {
  3297. function handleAlpha( string ) {
  3298. if ( string === undefined ) return;
  3299. if ( parseFloat( string ) < 1 ) {
  3300. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  3301. }
  3302. }
  3303. var m;
  3304. if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) {
  3305. // rgb / hsl
  3306. var color;
  3307. var name = m[ 1 ];
  3308. var components = m[ 2 ];
  3309. switch ( name ) {
  3310. case 'rgb':
  3311. case 'rgba':
  3312. if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  3313. // rgb(255,0,0) rgba(255,0,0,0.5)
  3314. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  3315. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  3316. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  3317. handleAlpha( color[ 5 ] );
  3318. return this;
  3319. }
  3320. if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  3321. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  3322. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  3323. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  3324. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  3325. handleAlpha( color[ 5 ] );
  3326. return this;
  3327. }
  3328. break;
  3329. case 'hsl':
  3330. case 'hsla':
  3331. if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  3332. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  3333. var h = parseFloat( color[ 1 ] ) / 360;
  3334. var s = parseInt( color[ 2 ], 10 ) / 100;
  3335. var l = parseInt( color[ 3 ], 10 ) / 100;
  3336. handleAlpha( color[ 5 ] );
  3337. return this.setHSL( h, s, l );
  3338. }
  3339. break;
  3340. }
  3341. } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) {
  3342. // hex color
  3343. var hex = m[ 1 ];
  3344. var size = hex.length;
  3345. if ( size === 3 ) {
  3346. // #ff0
  3347. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  3348. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  3349. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  3350. return this;
  3351. } else if ( size === 6 ) {
  3352. // #ff0000
  3353. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  3354. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  3355. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  3356. return this;
  3357. }
  3358. }
  3359. if ( style && style.length > 0 ) {
  3360. // color keywords
  3361. var hex = exports.ColorKeywords[ style ];
  3362. if ( hex !== undefined ) {
  3363. // red
  3364. this.setHex( hex );
  3365. } else {
  3366. // unknown color
  3367. console.warn( 'THREE.Color: Unknown color ' + style );
  3368. }
  3369. }
  3370. return this;
  3371. },
  3372. clone: function () {
  3373. return new this.constructor( this.r, this.g, this.b );
  3374. },
  3375. copy: function ( color ) {
  3376. this.r = color.r;
  3377. this.g = color.g;
  3378. this.b = color.b;
  3379. return this;
  3380. },
  3381. copyGammaToLinear: function ( color, gammaFactor ) {
  3382. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  3383. this.r = Math.pow( color.r, gammaFactor );
  3384. this.g = Math.pow( color.g, gammaFactor );
  3385. this.b = Math.pow( color.b, gammaFactor );
  3386. return this;
  3387. },
  3388. copyLinearToGamma: function ( color, gammaFactor ) {
  3389. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  3390. var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  3391. this.r = Math.pow( color.r, safeInverse );
  3392. this.g = Math.pow( color.g, safeInverse );
  3393. this.b = Math.pow( color.b, safeInverse );
  3394. return this;
  3395. },
  3396. convertGammaToLinear: function () {
  3397. var r = this.r, g = this.g, b = this.b;
  3398. this.r = r * r;
  3399. this.g = g * g;
  3400. this.b = b * b;
  3401. return this;
  3402. },
  3403. convertLinearToGamma: function () {
  3404. this.r = Math.sqrt( this.r );
  3405. this.g = Math.sqrt( this.g );
  3406. this.b = Math.sqrt( this.b );
  3407. return this;
  3408. },
  3409. getHex: function () {
  3410. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  3411. },
  3412. getHexString: function () {
  3413. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  3414. },
  3415. getHSL: function ( optionalTarget ) {
  3416. // h,s,l ranges are in 0.0 - 1.0
  3417. var hsl = optionalTarget || { h: 0, s: 0, l: 0 };
  3418. var r = this.r, g = this.g, b = this.b;
  3419. var max = Math.max( r, g, b );
  3420. var min = Math.min( r, g, b );
  3421. var hue, saturation;
  3422. var lightness = ( min + max ) / 2.0;
  3423. if ( min === max ) {
  3424. hue = 0;
  3425. saturation = 0;
  3426. } else {
  3427. var delta = max - min;
  3428. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  3429. switch ( max ) {
  3430. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  3431. case g: hue = ( b - r ) / delta + 2; break;
  3432. case b: hue = ( r - g ) / delta + 4; break;
  3433. }
  3434. hue /= 6;
  3435. }
  3436. hsl.h = hue;
  3437. hsl.s = saturation;
  3438. hsl.l = lightness;
  3439. return hsl;
  3440. },
  3441. getStyle: function () {
  3442. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  3443. },
  3444. offsetHSL: function ( h, s, l ) {
  3445. var hsl = this.getHSL();
  3446. hsl.h += h; hsl.s += s; hsl.l += l;
  3447. this.setHSL( hsl.h, hsl.s, hsl.l );
  3448. return this;
  3449. },
  3450. add: function ( color ) {
  3451. this.r += color.r;
  3452. this.g += color.g;
  3453. this.b += color.b;
  3454. return this;
  3455. },
  3456. addColors: function ( color1, color2 ) {
  3457. this.r = color1.r + color2.r;
  3458. this.g = color1.g + color2.g;
  3459. this.b = color1.b + color2.b;
  3460. return this;
  3461. },
  3462. addScalar: function ( s ) {
  3463. this.r += s;
  3464. this.g += s;
  3465. this.b += s;
  3466. return this;
  3467. },
  3468. sub: function( color ) {
  3469. this.r = Math.max( 0, this.r - color.r );
  3470. this.g = Math.max( 0, this.g - color.g );
  3471. this.b = Math.max( 0, this.b - color.b );
  3472. return this;
  3473. },
  3474. multiply: function ( color ) {
  3475. this.r *= color.r;
  3476. this.g *= color.g;
  3477. this.b *= color.b;
  3478. return this;
  3479. },
  3480. multiplyScalar: function ( s ) {
  3481. this.r *= s;
  3482. this.g *= s;
  3483. this.b *= s;
  3484. return this;
  3485. },
  3486. lerp: function ( color, alpha ) {
  3487. this.r += ( color.r - this.r ) * alpha;
  3488. this.g += ( color.g - this.g ) * alpha;
  3489. this.b += ( color.b - this.b ) * alpha;
  3490. return this;
  3491. },
  3492. equals: function ( c ) {
  3493. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  3494. },
  3495. fromArray: function ( array, offset ) {
  3496. if ( offset === undefined ) offset = 0;
  3497. this.r = array[ offset ];
  3498. this.g = array[ offset + 1 ];
  3499. this.b = array[ offset + 2 ];
  3500. return this;
  3501. },
  3502. toArray: function ( array, offset ) {
  3503. if ( array === undefined ) array = [];
  3504. if ( offset === undefined ) offset = 0;
  3505. array[ offset ] = this.r;
  3506. array[ offset + 1 ] = this.g;
  3507. array[ offset + 2 ] = this.b;
  3508. return array;
  3509. },
  3510. toJSON: function () {
  3511. return this.getHex();
  3512. }
  3513. };
  3514. exports.ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  3515. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  3516. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  3517. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  3518. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  3519. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  3520. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  3521. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  3522. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  3523. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  3524. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  3525. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  3526. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  3527. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  3528. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  3529. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  3530. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  3531. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  3532. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  3533. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  3534. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  3535. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  3536. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  3537. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  3538. /**
  3539. * Uniforms library for shared webgl shaders
  3540. */
  3541. var UniformsLib = {
  3542. common: {
  3543. diffuse: { value: new Color( 0xeeeeee ) },
  3544. opacity: { value: 1.0 },
  3545. map: { value: null },
  3546. offsetRepeat: { value: new Vector4( 0, 0, 1, 1 ) },
  3547. specularMap: { value: null },
  3548. alphaMap: { value: null },
  3549. envMap: { value: null },
  3550. flipEnvMap: { value: - 1 },
  3551. reflectivity: { value: 1.0 },
  3552. refractionRatio: { value: 0.98 }
  3553. },
  3554. aomap: {
  3555. aoMap: { value: null },
  3556. aoMapIntensity: { value: 1 }
  3557. },
  3558. lightmap: {
  3559. lightMap: { value: null },
  3560. lightMapIntensity: { value: 1 }
  3561. },
  3562. emissivemap: {
  3563. emissiveMap: { value: null }
  3564. },
  3565. bumpmap: {
  3566. bumpMap: { value: null },
  3567. bumpScale: { value: 1 }
  3568. },
  3569. normalmap: {
  3570. normalMap: { value: null },
  3571. normalScale: { value: new Vector2( 1, 1 ) }
  3572. },
  3573. displacementmap: {
  3574. displacementMap: { value: null },
  3575. displacementScale: { value: 1 },
  3576. displacementBias: { value: 0 }
  3577. },
  3578. roughnessmap: {
  3579. roughnessMap: { value: null }
  3580. },
  3581. metalnessmap: {
  3582. metalnessMap: { value: null }
  3583. },
  3584. fog: {
  3585. fogDensity: { value: 0.00025 },
  3586. fogNear: { value: 1 },
  3587. fogFar: { value: 2000 },
  3588. fogColor: { value: new Color( 0xffffff ) }
  3589. },
  3590. lights: {
  3591. ambientLightColor: { value: [] },
  3592. directionalLights: { value: [], properties: {
  3593. direction: {},
  3594. color: {},
  3595. shadow: {},
  3596. shadowBias: {},
  3597. shadowRadius: {},
  3598. shadowMapSize: {}
  3599. } },
  3600. directionalShadowMap: { value: [] },
  3601. directionalShadowMatrix: { value: [] },
  3602. spotLights: { value: [], properties: {
  3603. color: {},
  3604. position: {},
  3605. direction: {},
  3606. distance: {},
  3607. coneCos: {},
  3608. penumbraCos: {},
  3609. decay: {},
  3610. shadow: {},
  3611. shadowBias: {},
  3612. shadowRadius: {},
  3613. shadowMapSize: {}
  3614. } },
  3615. spotShadowMap: { value: [] },
  3616. spotShadowMatrix: { value: [] },
  3617. pointLights: { value: [], properties: {
  3618. color: {},
  3619. position: {},
  3620. decay: {},
  3621. distance: {},
  3622. shadow: {},
  3623. shadowBias: {},
  3624. shadowRadius: {},
  3625. shadowMapSize: {}
  3626. } },
  3627. pointShadowMap: { value: [] },
  3628. pointShadowMatrix: { value: [] },
  3629. hemisphereLights: { value: [], properties: {
  3630. direction: {},
  3631. skyColor: {},
  3632. groundColor: {}
  3633. } }
  3634. },
  3635. points: {
  3636. diffuse: { value: new Color( 0xeeeeee ) },
  3637. opacity: { value: 1.0 },
  3638. size: { value: 1.0 },
  3639. scale: { value: 1.0 },
  3640. map: { value: null },
  3641. offsetRepeat: { value: new Vector4( 0, 0, 1, 1 ) }
  3642. }
  3643. };
  3644. /**
  3645. * @author alteredq / http://alteredqualia.com/
  3646. * @author mrdoob / http://mrdoob.com/
  3647. * @author mikael emtinger / http://gomo.se/
  3648. */
  3649. var ShaderLib = {
  3650. basic: {
  3651. uniforms: exports.UniformsUtils.merge( [
  3652. UniformsLib.common,
  3653. UniformsLib.aomap,
  3654. UniformsLib.fog
  3655. ] ),
  3656. vertexShader: ShaderChunk.meshbasic_vert,
  3657. fragmentShader: ShaderChunk.meshbasic_frag
  3658. },
  3659. lambert: {
  3660. uniforms: exports.UniformsUtils.merge( [
  3661. UniformsLib.common,
  3662. UniformsLib.aomap,
  3663. UniformsLib.lightmap,
  3664. UniformsLib.emissivemap,
  3665. UniformsLib.fog,
  3666. UniformsLib.lights,
  3667. {
  3668. emissive : { value: new Color( 0x000000 ) }
  3669. }
  3670. ] ),
  3671. vertexShader: ShaderChunk.meshlambert_vert,
  3672. fragmentShader: ShaderChunk.meshlambert_frag
  3673. },
  3674. phong: {
  3675. uniforms: exports.UniformsUtils.merge( [
  3676. UniformsLib.common,
  3677. UniformsLib.aomap,
  3678. UniformsLib.lightmap,
  3679. UniformsLib.emissivemap,
  3680. UniformsLib.bumpmap,
  3681. UniformsLib.normalmap,
  3682. UniformsLib.displacementmap,
  3683. UniformsLib.fog,
  3684. UniformsLib.lights,
  3685. {
  3686. emissive : { value: new Color( 0x000000 ) },
  3687. specular : { value: new Color( 0x111111 ) },
  3688. shininess: { value: 30 }
  3689. }
  3690. ] ),
  3691. vertexShader: ShaderChunk.meshphong_vert,
  3692. fragmentShader: ShaderChunk.meshphong_frag
  3693. },
  3694. standard: {
  3695. uniforms: exports.UniformsUtils.merge( [
  3696. UniformsLib.common,
  3697. UniformsLib.aomap,
  3698. UniformsLib.lightmap,
  3699. UniformsLib.emissivemap,
  3700. UniformsLib.bumpmap,
  3701. UniformsLib.normalmap,
  3702. UniformsLib.displacementmap,
  3703. UniformsLib.roughnessmap,
  3704. UniformsLib.metalnessmap,
  3705. UniformsLib.fog,
  3706. UniformsLib.lights,
  3707. {
  3708. emissive : { value: new Color( 0x000000 ) },
  3709. roughness: { value: 0.5 },
  3710. metalness: { value: 0 },
  3711. envMapIntensity : { value: 1 }, // temporary
  3712. }
  3713. ] ),
  3714. vertexShader: ShaderChunk.meshphysical_vert,
  3715. fragmentShader: ShaderChunk.meshphysical_frag
  3716. },
  3717. points: {
  3718. uniforms: exports.UniformsUtils.merge( [
  3719. UniformsLib.points,
  3720. UniformsLib.fog
  3721. ] ),
  3722. vertexShader: ShaderChunk.points_vert,
  3723. fragmentShader: ShaderChunk.points_frag
  3724. },
  3725. dashed: {
  3726. uniforms: exports.UniformsUtils.merge( [
  3727. UniformsLib.common,
  3728. UniformsLib.fog,
  3729. {
  3730. scale : { value: 1 },
  3731. dashSize : { value: 1 },
  3732. totalSize: { value: 2 }
  3733. }
  3734. ] ),
  3735. vertexShader: ShaderChunk.linedashed_vert,
  3736. fragmentShader: ShaderChunk.linedashed_frag
  3737. },
  3738. depth: {
  3739. uniforms: exports.UniformsUtils.merge( [
  3740. UniformsLib.common,
  3741. UniformsLib.displacementmap
  3742. ] ),
  3743. vertexShader: ShaderChunk.depth_vert,
  3744. fragmentShader: ShaderChunk.depth_frag
  3745. },
  3746. normal: {
  3747. uniforms: {
  3748. opacity : { value: 1.0 }
  3749. },
  3750. vertexShader: ShaderChunk.normal_vert,
  3751. fragmentShader: ShaderChunk.normal_frag
  3752. },
  3753. /* -------------------------------------------------------------------------
  3754. // Cube map shader
  3755. ------------------------------------------------------------------------- */
  3756. cube: {
  3757. uniforms: {
  3758. tCube: { value: null },
  3759. tFlip: { value: - 1 },
  3760. opacity: { value: 1.0 }
  3761. },
  3762. vertexShader: ShaderChunk.cube_vert,
  3763. fragmentShader: ShaderChunk.cube_frag
  3764. },
  3765. /* -------------------------------------------------------------------------
  3766. // Cube map shader
  3767. ------------------------------------------------------------------------- */
  3768. equirect: {
  3769. uniforms: {
  3770. tEquirect: { value: null },
  3771. tFlip: { value: - 1 }
  3772. },
  3773. vertexShader: ShaderChunk.equirect_vert,
  3774. fragmentShader: ShaderChunk.equirect_frag
  3775. },
  3776. distanceRGBA: {
  3777. uniforms: {
  3778. lightPos: { value: new Vector3() }
  3779. },
  3780. vertexShader: ShaderChunk.distanceRGBA_vert,
  3781. fragmentShader: ShaderChunk.distanceRGBA_frag
  3782. }
  3783. };
  3784. ShaderLib.physical = {
  3785. uniforms: exports.UniformsUtils.merge( [
  3786. ShaderLib.standard.uniforms,
  3787. {
  3788. clearCoat: { value: 0 },
  3789. clearCoatRoughness: { value: 0 }
  3790. }
  3791. ] ),
  3792. vertexShader: ShaderChunk.meshphysical_vert,
  3793. fragmentShader: ShaderChunk.meshphysical_frag
  3794. };
  3795. /**
  3796. * @author bhouston / http://clara.io
  3797. */
  3798. function Box2( min, max ) {
  3799. this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity );
  3800. this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity );
  3801. }
  3802. Box2.prototype = {
  3803. constructor: Box2,
  3804. set: function ( min, max ) {
  3805. this.min.copy( min );
  3806. this.max.copy( max );
  3807. return this;
  3808. },
  3809. setFromPoints: function ( points ) {
  3810. this.makeEmpty();
  3811. for ( var i = 0, il = points.length; i < il; i ++ ) {
  3812. this.expandByPoint( points[ i ] );
  3813. }
  3814. return this;
  3815. },
  3816. setFromCenterAndSize: function () {
  3817. var v1 = new Vector2();
  3818. return function setFromCenterAndSize( center, size ) {
  3819. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  3820. this.min.copy( center ).sub( halfSize );
  3821. this.max.copy( center ).add( halfSize );
  3822. return this;
  3823. };
  3824. }(),
  3825. clone: function () {
  3826. return new this.constructor().copy( this );
  3827. },
  3828. copy: function ( box ) {
  3829. this.min.copy( box.min );
  3830. this.max.copy( box.max );
  3831. return this;
  3832. },
  3833. makeEmpty: function () {
  3834. this.min.x = this.min.y = + Infinity;
  3835. this.max.x = this.max.y = - Infinity;
  3836. return this;
  3837. },
  3838. isEmpty: function () {
  3839. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  3840. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  3841. },
  3842. center: function ( optionalTarget ) {
  3843. var result = optionalTarget || new Vector2();
  3844. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  3845. },
  3846. size: function ( optionalTarget ) {
  3847. var result = optionalTarget || new Vector2();
  3848. return result.subVectors( this.max, this.min );
  3849. },
  3850. expandByPoint: function ( point ) {
  3851. this.min.min( point );
  3852. this.max.max( point );
  3853. return this;
  3854. },
  3855. expandByVector: function ( vector ) {
  3856. this.min.sub( vector );
  3857. this.max.add( vector );
  3858. return this;
  3859. },
  3860. expandByScalar: function ( scalar ) {
  3861. this.min.addScalar( - scalar );
  3862. this.max.addScalar( scalar );
  3863. return this;
  3864. },
  3865. containsPoint: function ( point ) {
  3866. if ( point.x < this.min.x || point.x > this.max.x ||
  3867. point.y < this.min.y || point.y > this.max.y ) {
  3868. return false;
  3869. }
  3870. return true;
  3871. },
  3872. containsBox: function ( box ) {
  3873. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  3874. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  3875. return true;
  3876. }
  3877. return false;
  3878. },
  3879. getParameter: function ( point, optionalTarget ) {
  3880. // This can potentially have a divide by zero if the box
  3881. // has a size dimension of 0.
  3882. var result = optionalTarget || new Vector2();
  3883. return result.set(
  3884. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  3885. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  3886. );
  3887. },
  3888. intersectsBox: function ( box ) {
  3889. // using 6 splitting planes to rule out intersections.
  3890. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  3891. box.max.y < this.min.y || box.min.y > this.max.y ) {
  3892. return false;
  3893. }
  3894. return true;
  3895. },
  3896. clampPoint: function ( point, optionalTarget ) {
  3897. var result = optionalTarget || new Vector2();
  3898. return result.copy( point ).clamp( this.min, this.max );
  3899. },
  3900. distanceToPoint: function () {
  3901. var v1 = new Vector2();
  3902. return function distanceToPoint( point ) {
  3903. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  3904. return clampedPoint.sub( point ).length();
  3905. };
  3906. }(),
  3907. intersect: function ( box ) {
  3908. this.min.max( box.min );
  3909. this.max.min( box.max );
  3910. return this;
  3911. },
  3912. union: function ( box ) {
  3913. this.min.min( box.min );
  3914. this.max.max( box.max );
  3915. return this;
  3916. },
  3917. translate: function ( offset ) {
  3918. this.min.add( offset );
  3919. this.max.add( offset );
  3920. return this;
  3921. },
  3922. equals: function ( box ) {
  3923. return box.min.equals( this.min ) && box.max.equals( this.max );
  3924. }
  3925. };
  3926. /**
  3927. * @author mikael emtinger / http://gomo.se/
  3928. * @author alteredq / http://alteredqualia.com/
  3929. */
  3930. function LensFlarePlugin( renderer, flares ) {
  3931. var gl = renderer.context;
  3932. var state = renderer.state;
  3933. var vertexBuffer, elementBuffer;
  3934. var shader, program, attributes, uniforms;
  3935. var tempTexture, occlusionTexture;
  3936. function init() {
  3937. var vertices = new Float32Array( [
  3938. - 1, - 1, 0, 0,
  3939. 1, - 1, 1, 0,
  3940. 1, 1, 1, 1,
  3941. - 1, 1, 0, 1
  3942. ] );
  3943. var faces = new Uint16Array( [
  3944. 0, 1, 2,
  3945. 0, 2, 3
  3946. ] );
  3947. // buffers
  3948. vertexBuffer = gl.createBuffer();
  3949. elementBuffer = gl.createBuffer();
  3950. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  3951. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  3952. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  3953. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  3954. // textures
  3955. tempTexture = gl.createTexture();
  3956. occlusionTexture = gl.createTexture();
  3957. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  3958. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB, 16, 16, 0, gl.RGB, gl.UNSIGNED_BYTE, null );
  3959. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  3960. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  3961. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  3962. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  3963. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  3964. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, 16, 16, 0, gl.RGBA, gl.UNSIGNED_BYTE, null );
  3965. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  3966. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  3967. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  3968. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  3969. shader = {
  3970. vertexShader: [
  3971. "uniform lowp int renderType;",
  3972. "uniform vec3 screenPosition;",
  3973. "uniform vec2 scale;",
  3974. "uniform float rotation;",
  3975. "uniform sampler2D occlusionMap;",
  3976. "attribute vec2 position;",
  3977. "attribute vec2 uv;",
  3978. "varying vec2 vUV;",
  3979. "varying float vVisibility;",
  3980. "void main() {",
  3981. "vUV = uv;",
  3982. "vec2 pos = position;",
  3983. "if ( renderType == 2 ) {",
  3984. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  3985. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  3986. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  3987. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  3988. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  3989. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  3990. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  3991. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  3992. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  3993. "vVisibility = visibility.r / 9.0;",
  3994. "vVisibility *= 1.0 - visibility.g / 9.0;",
  3995. "vVisibility *= visibility.b / 9.0;",
  3996. "vVisibility *= 1.0 - visibility.a / 9.0;",
  3997. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  3998. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  3999. "}",
  4000. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  4001. "}"
  4002. ].join( "\n" ),
  4003. fragmentShader: [
  4004. "uniform lowp int renderType;",
  4005. "uniform sampler2D map;",
  4006. "uniform float opacity;",
  4007. "uniform vec3 color;",
  4008. "varying vec2 vUV;",
  4009. "varying float vVisibility;",
  4010. "void main() {",
  4011. // pink square
  4012. "if ( renderType == 0 ) {",
  4013. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  4014. // restore
  4015. "} else if ( renderType == 1 ) {",
  4016. "gl_FragColor = texture2D( map, vUV );",
  4017. // flare
  4018. "} else {",
  4019. "vec4 texture = texture2D( map, vUV );",
  4020. "texture.a *= opacity * vVisibility;",
  4021. "gl_FragColor = texture;",
  4022. "gl_FragColor.rgb *= color;",
  4023. "}",
  4024. "}"
  4025. ].join( "\n" )
  4026. };
  4027. program = createProgram( shader );
  4028. attributes = {
  4029. vertex: gl.getAttribLocation ( program, "position" ),
  4030. uv: gl.getAttribLocation ( program, "uv" )
  4031. };
  4032. uniforms = {
  4033. renderType: gl.getUniformLocation( program, "renderType" ),
  4034. map: gl.getUniformLocation( program, "map" ),
  4035. occlusionMap: gl.getUniformLocation( program, "occlusionMap" ),
  4036. opacity: gl.getUniformLocation( program, "opacity" ),
  4037. color: gl.getUniformLocation( program, "color" ),
  4038. scale: gl.getUniformLocation( program, "scale" ),
  4039. rotation: gl.getUniformLocation( program, "rotation" ),
  4040. screenPosition: gl.getUniformLocation( program, "screenPosition" )
  4041. };
  4042. }
  4043. /*
  4044. * Render lens flares
  4045. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  4046. * reads these back and calculates occlusion.
  4047. */
  4048. this.render = function ( scene, camera, viewport ) {
  4049. if ( flares.length === 0 ) return;
  4050. var tempPosition = new Vector3();
  4051. var invAspect = viewport.w / viewport.z,
  4052. halfViewportWidth = viewport.z * 0.5,
  4053. halfViewportHeight = viewport.w * 0.5;
  4054. var size = 16 / viewport.w,
  4055. scale = new Vector2( size * invAspect, size );
  4056. var screenPosition = new Vector3( 1, 1, 0 ),
  4057. screenPositionPixels = new Vector2( 1, 1 );
  4058. var validArea = new Box2();
  4059. validArea.min.set( 0, 0 );
  4060. validArea.max.set( viewport.z - 16, viewport.w - 16 );
  4061. if ( program === undefined ) {
  4062. init();
  4063. }
  4064. gl.useProgram( program );
  4065. state.initAttributes();
  4066. state.enableAttribute( attributes.vertex );
  4067. state.enableAttribute( attributes.uv );
  4068. state.disableUnusedAttributes();
  4069. // loop through all lens flares to update their occlusion and positions
  4070. // setup gl and common used attribs/uniforms
  4071. gl.uniform1i( uniforms.occlusionMap, 0 );
  4072. gl.uniform1i( uniforms.map, 1 );
  4073. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  4074. gl.vertexAttribPointer( attributes.vertex, 2, gl.FLOAT, false, 2 * 8, 0 );
  4075. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  4076. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  4077. state.disable( gl.CULL_FACE );
  4078. state.setDepthWrite( false );
  4079. for ( var i = 0, l = flares.length; i < l; i ++ ) {
  4080. size = 16 / viewport.w;
  4081. scale.set( size * invAspect, size );
  4082. // calc object screen position
  4083. var flare = flares[ i ];
  4084. tempPosition.set( flare.matrixWorld.elements[ 12 ], flare.matrixWorld.elements[ 13 ], flare.matrixWorld.elements[ 14 ] );
  4085. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  4086. tempPosition.applyProjection( camera.projectionMatrix );
  4087. // setup arrays for gl programs
  4088. screenPosition.copy( tempPosition );
  4089. // horizontal and vertical coordinate of the lower left corner of the pixels to copy
  4090. screenPositionPixels.x = viewport.x + ( screenPosition.x * halfViewportWidth ) + halfViewportWidth - 8;
  4091. screenPositionPixels.y = viewport.y + ( screenPosition.y * halfViewportHeight ) + halfViewportHeight - 8;
  4092. // screen cull
  4093. if ( validArea.containsPoint( screenPositionPixels ) === true ) {
  4094. // save current RGB to temp texture
  4095. state.activeTexture( gl.TEXTURE0 );
  4096. state.bindTexture( gl.TEXTURE_2D, null );
  4097. state.activeTexture( gl.TEXTURE1 );
  4098. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  4099. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGB, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 );
  4100. // render pink quad
  4101. gl.uniform1i( uniforms.renderType, 0 );
  4102. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  4103. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  4104. state.disable( gl.BLEND );
  4105. state.enable( gl.DEPTH_TEST );
  4106. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4107. // copy result to occlusionMap
  4108. state.activeTexture( gl.TEXTURE0 );
  4109. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  4110. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGBA, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 );
  4111. // restore graphics
  4112. gl.uniform1i( uniforms.renderType, 1 );
  4113. state.disable( gl.DEPTH_TEST );
  4114. state.activeTexture( gl.TEXTURE1 );
  4115. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  4116. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4117. // update object positions
  4118. flare.positionScreen.copy( screenPosition );
  4119. if ( flare.customUpdateCallback ) {
  4120. flare.customUpdateCallback( flare );
  4121. } else {
  4122. flare.updateLensFlares();
  4123. }
  4124. // render flares
  4125. gl.uniform1i( uniforms.renderType, 2 );
  4126. state.enable( gl.BLEND );
  4127. for ( var j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  4128. var sprite = flare.lensFlares[ j ];
  4129. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  4130. screenPosition.x = sprite.x;
  4131. screenPosition.y = sprite.y;
  4132. screenPosition.z = sprite.z;
  4133. size = sprite.size * sprite.scale / viewport.w;
  4134. scale.x = size * invAspect;
  4135. scale.y = size;
  4136. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  4137. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  4138. gl.uniform1f( uniforms.rotation, sprite.rotation );
  4139. gl.uniform1f( uniforms.opacity, sprite.opacity );
  4140. gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  4141. state.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  4142. renderer.setTexture2D( sprite.texture, 1 );
  4143. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4144. }
  4145. }
  4146. }
  4147. }
  4148. // restore gl
  4149. state.enable( gl.CULL_FACE );
  4150. state.enable( gl.DEPTH_TEST );
  4151. state.setDepthWrite( true );
  4152. renderer.resetGLState();
  4153. };
  4154. function createProgram( shader ) {
  4155. var program = gl.createProgram();
  4156. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  4157. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  4158. var prefix = "precision " + renderer.getPrecision() + " float;\n";
  4159. gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  4160. gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  4161. gl.compileShader( fragmentShader );
  4162. gl.compileShader( vertexShader );
  4163. gl.attachShader( program, fragmentShader );
  4164. gl.attachShader( program, vertexShader );
  4165. gl.linkProgram( program );
  4166. return program;
  4167. }
  4168. }
  4169. /**
  4170. * @author mikael emtinger / http://gomo.se/
  4171. * @author alteredq / http://alteredqualia.com/
  4172. */
  4173. function SpritePlugin( renderer, sprites ) {
  4174. var gl = renderer.context;
  4175. var state = renderer.state;
  4176. var vertexBuffer, elementBuffer;
  4177. var program, attributes, uniforms;
  4178. var texture;
  4179. // decompose matrixWorld
  4180. var spritePosition = new Vector3();
  4181. var spriteRotation = new Quaternion();
  4182. var spriteScale = new Vector3();
  4183. function init() {
  4184. var vertices = new Float32Array( [
  4185. - 0.5, - 0.5, 0, 0,
  4186. 0.5, - 0.5, 1, 0,
  4187. 0.5, 0.5, 1, 1,
  4188. - 0.5, 0.5, 0, 1
  4189. ] );
  4190. var faces = new Uint16Array( [
  4191. 0, 1, 2,
  4192. 0, 2, 3
  4193. ] );
  4194. vertexBuffer = gl.createBuffer();
  4195. elementBuffer = gl.createBuffer();
  4196. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  4197. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  4198. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  4199. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  4200. program = createProgram();
  4201. attributes = {
  4202. position: gl.getAttribLocation ( program, 'position' ),
  4203. uv: gl.getAttribLocation ( program, 'uv' )
  4204. };
  4205. uniforms = {
  4206. uvOffset: gl.getUniformLocation( program, 'uvOffset' ),
  4207. uvScale: gl.getUniformLocation( program, 'uvScale' ),
  4208. rotation: gl.getUniformLocation( program, 'rotation' ),
  4209. scale: gl.getUniformLocation( program, 'scale' ),
  4210. color: gl.getUniformLocation( program, 'color' ),
  4211. map: gl.getUniformLocation( program, 'map' ),
  4212. opacity: gl.getUniformLocation( program, 'opacity' ),
  4213. modelViewMatrix: gl.getUniformLocation( program, 'modelViewMatrix' ),
  4214. projectionMatrix: gl.getUniformLocation( program, 'projectionMatrix' ),
  4215. fogType: gl.getUniformLocation( program, 'fogType' ),
  4216. fogDensity: gl.getUniformLocation( program, 'fogDensity' ),
  4217. fogNear: gl.getUniformLocation( program, 'fogNear' ),
  4218. fogFar: gl.getUniformLocation( program, 'fogFar' ),
  4219. fogColor: gl.getUniformLocation( program, 'fogColor' ),
  4220. alphaTest: gl.getUniformLocation( program, 'alphaTest' )
  4221. };
  4222. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  4223. canvas.width = 8;
  4224. canvas.height = 8;
  4225. var context = canvas.getContext( '2d' );
  4226. context.fillStyle = 'white';
  4227. context.fillRect( 0, 0, 8, 8 );
  4228. texture = new Texture( canvas );
  4229. texture.needsUpdate = true;
  4230. }
  4231. this.render = function ( scene, camera ) {
  4232. if ( sprites.length === 0 ) return;
  4233. // setup gl
  4234. if ( program === undefined ) {
  4235. init();
  4236. }
  4237. gl.useProgram( program );
  4238. state.initAttributes();
  4239. state.enableAttribute( attributes.position );
  4240. state.enableAttribute( attributes.uv );
  4241. state.disableUnusedAttributes();
  4242. state.disable( gl.CULL_FACE );
  4243. state.enable( gl.BLEND );
  4244. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  4245. gl.vertexAttribPointer( attributes.position, 2, gl.FLOAT, false, 2 * 8, 0 );
  4246. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  4247. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  4248. gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  4249. state.activeTexture( gl.TEXTURE0 );
  4250. gl.uniform1i( uniforms.map, 0 );
  4251. var oldFogType = 0;
  4252. var sceneFogType = 0;
  4253. var fog = scene.fog;
  4254. if ( fog ) {
  4255. gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  4256. if ( (fog && fog.isFog) ) {
  4257. gl.uniform1f( uniforms.fogNear, fog.near );
  4258. gl.uniform1f( uniforms.fogFar, fog.far );
  4259. gl.uniform1i( uniforms.fogType, 1 );
  4260. oldFogType = 1;
  4261. sceneFogType = 1;
  4262. } else if ( (fog && fog.isFogExp2) ) {
  4263. gl.uniform1f( uniforms.fogDensity, fog.density );
  4264. gl.uniform1i( uniforms.fogType, 2 );
  4265. oldFogType = 2;
  4266. sceneFogType = 2;
  4267. }
  4268. } else {
  4269. gl.uniform1i( uniforms.fogType, 0 );
  4270. oldFogType = 0;
  4271. sceneFogType = 0;
  4272. }
  4273. // update positions and sort
  4274. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  4275. var sprite = sprites[ i ];
  4276. sprite.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  4277. sprite.z = - sprite.modelViewMatrix.elements[ 14 ];
  4278. }
  4279. sprites.sort( painterSortStable );
  4280. // render all sprites
  4281. var scale = [];
  4282. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  4283. var sprite = sprites[ i ];
  4284. var material = sprite.material;
  4285. if ( material.visible === false ) continue;
  4286. gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  4287. gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite.modelViewMatrix.elements );
  4288. sprite.matrixWorld.decompose( spritePosition, spriteRotation, spriteScale );
  4289. scale[ 0 ] = spriteScale.x;
  4290. scale[ 1 ] = spriteScale.y;
  4291. var fogType = 0;
  4292. if ( scene.fog && material.fog ) {
  4293. fogType = sceneFogType;
  4294. }
  4295. if ( oldFogType !== fogType ) {
  4296. gl.uniform1i( uniforms.fogType, fogType );
  4297. oldFogType = fogType;
  4298. }
  4299. if ( material.map !== null ) {
  4300. gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y );
  4301. gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y );
  4302. } else {
  4303. gl.uniform2f( uniforms.uvOffset, 0, 0 );
  4304. gl.uniform2f( uniforms.uvScale, 1, 1 );
  4305. }
  4306. gl.uniform1f( uniforms.opacity, material.opacity );
  4307. gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  4308. gl.uniform1f( uniforms.rotation, material.rotation );
  4309. gl.uniform2fv( uniforms.scale, scale );
  4310. state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  4311. state.setDepthTest( material.depthTest );
  4312. state.setDepthWrite( material.depthWrite );
  4313. if ( material.map ) {
  4314. renderer.setTexture2D( material.map, 0 );
  4315. } else {
  4316. renderer.setTexture2D( texture, 0 );
  4317. }
  4318. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4319. }
  4320. // restore gl
  4321. state.enable( gl.CULL_FACE );
  4322. renderer.resetGLState();
  4323. };
  4324. function createProgram() {
  4325. var program = gl.createProgram();
  4326. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  4327. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  4328. gl.shaderSource( vertexShader, [
  4329. 'precision ' + renderer.getPrecision() + ' float;',
  4330. 'uniform mat4 modelViewMatrix;',
  4331. 'uniform mat4 projectionMatrix;',
  4332. 'uniform float rotation;',
  4333. 'uniform vec2 scale;',
  4334. 'uniform vec2 uvOffset;',
  4335. 'uniform vec2 uvScale;',
  4336. 'attribute vec2 position;',
  4337. 'attribute vec2 uv;',
  4338. 'varying vec2 vUV;',
  4339. 'void main() {',
  4340. 'vUV = uvOffset + uv * uvScale;',
  4341. 'vec2 alignedPosition = position * scale;',
  4342. 'vec2 rotatedPosition;',
  4343. 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  4344. 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  4345. 'vec4 finalPosition;',
  4346. 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  4347. 'finalPosition.xy += rotatedPosition;',
  4348. 'finalPosition = projectionMatrix * finalPosition;',
  4349. 'gl_Position = finalPosition;',
  4350. '}'
  4351. ].join( '\n' ) );
  4352. gl.shaderSource( fragmentShader, [
  4353. 'precision ' + renderer.getPrecision() + ' float;',
  4354. 'uniform vec3 color;',
  4355. 'uniform sampler2D map;',
  4356. 'uniform float opacity;',
  4357. 'uniform int fogType;',
  4358. 'uniform vec3 fogColor;',
  4359. 'uniform float fogDensity;',
  4360. 'uniform float fogNear;',
  4361. 'uniform float fogFar;',
  4362. 'uniform float alphaTest;',
  4363. 'varying vec2 vUV;',
  4364. 'void main() {',
  4365. 'vec4 texture = texture2D( map, vUV );',
  4366. 'if ( texture.a < alphaTest ) discard;',
  4367. 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  4368. 'if ( fogType > 0 ) {',
  4369. 'float depth = gl_FragCoord.z / gl_FragCoord.w;',
  4370. 'float fogFactor = 0.0;',
  4371. 'if ( fogType == 1 ) {',
  4372. 'fogFactor = smoothstep( fogNear, fogFar, depth );',
  4373. '} else {',
  4374. 'const float LOG2 = 1.442695;',
  4375. 'fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );',
  4376. 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  4377. '}',
  4378. 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );',
  4379. '}',
  4380. '}'
  4381. ].join( '\n' ) );
  4382. gl.compileShader( vertexShader );
  4383. gl.compileShader( fragmentShader );
  4384. gl.attachShader( program, vertexShader );
  4385. gl.attachShader( program, fragmentShader );
  4386. gl.linkProgram( program );
  4387. return program;
  4388. }
  4389. function painterSortStable( a, b ) {
  4390. if ( a.renderOrder !== b.renderOrder ) {
  4391. return a.renderOrder - b.renderOrder;
  4392. } else if ( a.z !== b.z ) {
  4393. return b.z - a.z;
  4394. } else {
  4395. return b.id - a.id;
  4396. }
  4397. }
  4398. }
  4399. /**
  4400. * @author mrdoob / http://mrdoob.com/
  4401. * @author alteredq / http://alteredqualia.com/
  4402. */
  4403. function Material() {
  4404. Object.defineProperty( this, 'id', { value: MaterialIdCount() } );
  4405. this.uuid = exports.Math.generateUUID();
  4406. this.name = '';
  4407. this.type = 'Material';
  4408. this.fog = true;
  4409. this.lights = true;
  4410. this.blending = NormalBlending;
  4411. this.side = FrontSide;
  4412. this.shading = SmoothShading; // THREE.FlatShading, THREE.SmoothShading
  4413. this.vertexColors = NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors
  4414. this.opacity = 1;
  4415. this.transparent = false;
  4416. this.blendSrc = SrcAlphaFactor;
  4417. this.blendDst = OneMinusSrcAlphaFactor;
  4418. this.blendEquation = AddEquation;
  4419. this.blendSrcAlpha = null;
  4420. this.blendDstAlpha = null;
  4421. this.blendEquationAlpha = null;
  4422. this.depthFunc = LessEqualDepth;
  4423. this.depthTest = true;
  4424. this.depthWrite = true;
  4425. this.clippingPlanes = null;
  4426. this.clipShadows = false;
  4427. this.colorWrite = true;
  4428. this.precision = null; // override the renderer's default precision for this material
  4429. this.polygonOffset = false;
  4430. this.polygonOffsetFactor = 0;
  4431. this.polygonOffsetUnits = 0;
  4432. this.alphaTest = 0;
  4433. this.premultipliedAlpha = false;
  4434. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  4435. this.visible = true;
  4436. this._needsUpdate = true;
  4437. }
  4438. Material.prototype = {
  4439. constructor: Material,
  4440. isMaterial: true,
  4441. get needsUpdate() {
  4442. return this._needsUpdate;
  4443. },
  4444. set needsUpdate( value ) {
  4445. if ( value === true ) this.update();
  4446. this._needsUpdate = value;
  4447. },
  4448. setValues: function ( values ) {
  4449. if ( values === undefined ) return;
  4450. for ( var key in values ) {
  4451. var newValue = values[ key ];
  4452. if ( newValue === undefined ) {
  4453. console.warn( "THREE.Material: '" + key + "' parameter is undefined." );
  4454. continue;
  4455. }
  4456. var currentValue = this[ key ];
  4457. if ( currentValue === undefined ) {
  4458. console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." );
  4459. continue;
  4460. }
  4461. if ( (currentValue && currentValue.isColor) ) {
  4462. currentValue.set( newValue );
  4463. } else if ( (currentValue && currentValue.isVector3) && (newValue && newValue.isVector3) ) {
  4464. currentValue.copy( newValue );
  4465. } else if ( key === 'overdraw' ) {
  4466. // ensure overdraw is backwards-compatible with legacy boolean type
  4467. this[ key ] = Number( newValue );
  4468. } else {
  4469. this[ key ] = newValue;
  4470. }
  4471. }
  4472. },
  4473. toJSON: function ( meta ) {
  4474. var isRoot = meta === undefined;
  4475. if ( isRoot ) {
  4476. meta = {
  4477. textures: {},
  4478. images: {}
  4479. };
  4480. }
  4481. var data = {
  4482. metadata: {
  4483. version: 4.4,
  4484. type: 'Material',
  4485. generator: 'Material.toJSON'
  4486. }
  4487. };
  4488. // standard Material serialization
  4489. data.uuid = this.uuid;
  4490. data.type = this.type;
  4491. if ( this.name !== '' ) data.name = this.name;
  4492. if ( (this.color && this.color.isColor) ) data.color = this.color.getHex();
  4493. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  4494. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  4495. if ( (this.emissive && this.emissive.isColor) ) data.emissive = this.emissive.getHex();
  4496. if ( (this.specular && this.specular.isColor) ) data.specular = this.specular.getHex();
  4497. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  4498. if ( (this.map && this.map.isTexture) ) data.map = this.map.toJSON( meta ).uuid;
  4499. if ( (this.alphaMap && this.alphaMap.isTexture) ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  4500. if ( (this.lightMap && this.lightMap.isTexture) ) data.lightMap = this.lightMap.toJSON( meta ).uuid;
  4501. if ( (this.bumpMap && this.bumpMap.isTexture) ) {
  4502. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  4503. data.bumpScale = this.bumpScale;
  4504. }
  4505. if ( (this.normalMap && this.normalMap.isTexture) ) {
  4506. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  4507. data.normalScale = this.normalScale.toArray();
  4508. }
  4509. if ( (this.displacementMap && this.displacementMap.isTexture) ) {
  4510. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  4511. data.displacementScale = this.displacementScale;
  4512. data.displacementBias = this.displacementBias;
  4513. }
  4514. if ( (this.roughnessMap && this.roughnessMap.isTexture) ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  4515. if ( (this.metalnessMap && this.metalnessMap.isTexture) ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  4516. if ( (this.emissiveMap && this.emissiveMap.isTexture) ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  4517. if ( (this.specularMap && this.specularMap.isTexture) ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  4518. if ( (this.envMap && this.envMap.isTexture) ) {
  4519. data.envMap = this.envMap.toJSON( meta ).uuid;
  4520. data.reflectivity = this.reflectivity; // Scale behind envMap
  4521. }
  4522. if ( this.size !== undefined ) data.size = this.size;
  4523. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  4524. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  4525. if ( this.shading !== SmoothShading ) data.shading = this.shading;
  4526. if ( this.side !== FrontSide ) data.side = this.side;
  4527. if ( this.vertexColors !== NoColors ) data.vertexColors = this.vertexColors;
  4528. if ( this.opacity < 1 ) data.opacity = this.opacity;
  4529. if ( this.transparent === true ) data.transparent = this.transparent;
  4530. data.depthFunc = this.depthFunc;
  4531. data.depthTest = this.depthTest;
  4532. data.depthWrite = this.depthWrite;
  4533. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  4534. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  4535. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  4536. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  4537. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  4538. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  4539. data.skinning = this.skinning;
  4540. data.morphTargets = this.morphTargets;
  4541. // TODO: Copied from Object3D.toJSON
  4542. function extractFromCache( cache ) {
  4543. var values = [];
  4544. for ( var key in cache ) {
  4545. var data = cache[ key ];
  4546. delete data.metadata;
  4547. values.push( data );
  4548. }
  4549. return values;
  4550. }
  4551. if ( isRoot ) {
  4552. var textures = extractFromCache( meta.textures );
  4553. var images = extractFromCache( meta.images );
  4554. if ( textures.length > 0 ) data.textures = textures;
  4555. if ( images.length > 0 ) data.images = images;
  4556. }
  4557. return data;
  4558. },
  4559. clone: function () {
  4560. return new this.constructor().copy( this );
  4561. },
  4562. copy: function ( source ) {
  4563. this.name = source.name;
  4564. this.fog = source.fog;
  4565. this.lights = source.lights;
  4566. this.blending = source.blending;
  4567. this.side = source.side;
  4568. this.shading = source.shading;
  4569. this.vertexColors = source.vertexColors;
  4570. this.opacity = source.opacity;
  4571. this.transparent = source.transparent;
  4572. this.blendSrc = source.blendSrc;
  4573. this.blendDst = source.blendDst;
  4574. this.blendEquation = source.blendEquation;
  4575. this.blendSrcAlpha = source.blendSrcAlpha;
  4576. this.blendDstAlpha = source.blendDstAlpha;
  4577. this.blendEquationAlpha = source.blendEquationAlpha;
  4578. this.depthFunc = source.depthFunc;
  4579. this.depthTest = source.depthTest;
  4580. this.depthWrite = source.depthWrite;
  4581. this.colorWrite = source.colorWrite;
  4582. this.precision = source.precision;
  4583. this.polygonOffset = source.polygonOffset;
  4584. this.polygonOffsetFactor = source.polygonOffsetFactor;
  4585. this.polygonOffsetUnits = source.polygonOffsetUnits;
  4586. this.alphaTest = source.alphaTest;
  4587. this.premultipliedAlpha = source.premultipliedAlpha;
  4588. this.overdraw = source.overdraw;
  4589. this.visible = source.visible;
  4590. this.clipShadows = source.clipShadows;
  4591. var srcPlanes = source.clippingPlanes,
  4592. dstPlanes = null;
  4593. if ( srcPlanes !== null ) {
  4594. var n = srcPlanes.length;
  4595. dstPlanes = new Array( n );
  4596. for ( var i = 0; i !== n; ++ i )
  4597. dstPlanes[ i ] = srcPlanes[ i ].clone();
  4598. }
  4599. this.clippingPlanes = dstPlanes;
  4600. return this;
  4601. },
  4602. update: function () {
  4603. this.dispatchEvent( { type: 'update' } );
  4604. },
  4605. dispose: function () {
  4606. this.dispatchEvent( { type: 'dispose' } );
  4607. }
  4608. };
  4609. Object.assign( Material.prototype, EventDispatcher.prototype );
  4610. var count$1 = 0;
  4611. function MaterialIdCount() { return count$1++; };
  4612. /**
  4613. * @author alteredq / http://alteredqualia.com/
  4614. *
  4615. * parameters = {
  4616. * defines: { "label" : "value" },
  4617. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  4618. *
  4619. * fragmentShader: <string>,
  4620. * vertexShader: <string>,
  4621. *
  4622. * wireframe: <boolean>,
  4623. * wireframeLinewidth: <float>,
  4624. *
  4625. * lights: <bool>,
  4626. *
  4627. * skinning: <bool>,
  4628. * morphTargets: <bool>,
  4629. * morphNormals: <bool>
  4630. * }
  4631. */
  4632. function ShaderMaterial( parameters ) {
  4633. Material.call( this );
  4634. this.type = 'ShaderMaterial';
  4635. this.defines = {};
  4636. this.uniforms = {};
  4637. this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}';
  4638. this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}';
  4639. this.linewidth = 1;
  4640. this.wireframe = false;
  4641. this.wireframeLinewidth = 1;
  4642. this.fog = false; // set to use scene fog
  4643. this.lights = false; // set to use scene lights
  4644. this.clipping = false; // set to use user-defined clipping planes
  4645. this.skinning = false; // set to use skinning attribute streams
  4646. this.morphTargets = false; // set to use morph targets
  4647. this.morphNormals = false; // set to use morph normals
  4648. this.extensions = {
  4649. derivatives: false, // set to use derivatives
  4650. fragDepth: false, // set to use fragment depth values
  4651. drawBuffers: false, // set to use draw buffers
  4652. shaderTextureLOD: false // set to use shader texture LOD
  4653. };
  4654. // When rendered geometry doesn't include these attributes but the material does,
  4655. // use these default values in WebGL. This avoids errors when buffer data is missing.
  4656. this.defaultAttributeValues = {
  4657. 'color': [ 1, 1, 1 ],
  4658. 'uv': [ 0, 0 ],
  4659. 'uv2': [ 0, 0 ]
  4660. };
  4661. this.index0AttributeName = undefined;
  4662. if ( parameters !== undefined ) {
  4663. if ( parameters.attributes !== undefined ) {
  4664. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  4665. }
  4666. this.setValues( parameters );
  4667. }
  4668. }
  4669. ShaderMaterial.prototype = Object.create( Material.prototype );
  4670. ShaderMaterial.prototype.constructor = ShaderMaterial;
  4671. ShaderMaterial.prototype.isShaderMaterial = true;
  4672. ShaderMaterial.prototype.copy = function ( source ) {
  4673. Material.prototype.copy.call( this, source );
  4674. this.fragmentShader = source.fragmentShader;
  4675. this.vertexShader = source.vertexShader;
  4676. this.uniforms = exports.UniformsUtils.clone( source.uniforms );
  4677. this.defines = source.defines;
  4678. this.wireframe = source.wireframe;
  4679. this.wireframeLinewidth = source.wireframeLinewidth;
  4680. this.lights = source.lights;
  4681. this.clipping = source.clipping;
  4682. this.skinning = source.skinning;
  4683. this.morphTargets = source.morphTargets;
  4684. this.morphNormals = source.morphNormals;
  4685. this.extensions = source.extensions;
  4686. return this;
  4687. };
  4688. ShaderMaterial.prototype.toJSON = function ( meta ) {
  4689. var data = Material.prototype.toJSON.call( this, meta );
  4690. data.uniforms = this.uniforms;
  4691. data.vertexShader = this.vertexShader;
  4692. data.fragmentShader = this.fragmentShader;
  4693. return data;
  4694. };
  4695. /**
  4696. * @author mrdoob / http://mrdoob.com/
  4697. * @author alteredq / http://alteredqualia.com/
  4698. * @author bhouston / https://clara.io
  4699. * @author WestLangley / http://github.com/WestLangley
  4700. *
  4701. * parameters = {
  4702. *
  4703. * opacity: <float>,
  4704. *
  4705. * map: new THREE.Texture( <Image> ),
  4706. *
  4707. * alphaMap: new THREE.Texture( <Image> ),
  4708. *
  4709. * displacementMap: new THREE.Texture( <Image> ),
  4710. * displacementScale: <float>,
  4711. * displacementBias: <float>,
  4712. *
  4713. * wireframe: <boolean>,
  4714. * wireframeLinewidth: <float>
  4715. * }
  4716. */
  4717. function MeshDepthMaterial( parameters ) {
  4718. Material.call( this );
  4719. this.type = 'MeshDepthMaterial';
  4720. this.depthPacking = BasicDepthPacking;
  4721. this.skinning = false;
  4722. this.morphTargets = false;
  4723. this.map = null;
  4724. this.alphaMap = null;
  4725. this.displacementMap = null;
  4726. this.displacementScale = 1;
  4727. this.displacementBias = 0;
  4728. this.wireframe = false;
  4729. this.wireframeLinewidth = 1;
  4730. this.fog = false;
  4731. this.lights = false;
  4732. this.setValues( parameters );
  4733. }
  4734. MeshDepthMaterial.prototype = Object.create( Material.prototype );
  4735. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  4736. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  4737. MeshDepthMaterial.prototype.copy = function ( source ) {
  4738. Material.prototype.copy.call( this, source );
  4739. this.depthPacking = source.depthPacking;
  4740. this.skinning = source.skinning;
  4741. this.morphTargets = source.morphTargets;
  4742. this.map = source.map;
  4743. this.alphaMap = source.alphaMap;
  4744. this.displacementMap = source.displacementMap;
  4745. this.displacementScale = source.displacementScale;
  4746. this.displacementBias = source.displacementBias;
  4747. this.wireframe = source.wireframe;
  4748. this.wireframeLinewidth = source.wireframeLinewidth;
  4749. return this;
  4750. };
  4751. /**
  4752. * @author bhouston / http://clara.io
  4753. * @author WestLangley / http://github.com/WestLangley
  4754. */
  4755. function Box3( min, max ) {
  4756. this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity );
  4757. this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity );
  4758. }
  4759. Box3.prototype = {
  4760. constructor: Box3,
  4761. isBox3: true,
  4762. set: function ( min, max ) {
  4763. this.min.copy( min );
  4764. this.max.copy( max );
  4765. return this;
  4766. },
  4767. setFromArray: function ( array ) {
  4768. var minX = + Infinity;
  4769. var minY = + Infinity;
  4770. var minZ = + Infinity;
  4771. var maxX = - Infinity;
  4772. var maxY = - Infinity;
  4773. var maxZ = - Infinity;
  4774. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  4775. var x = array[ i ];
  4776. var y = array[ i + 1 ];
  4777. var z = array[ i + 2 ];
  4778. if ( x < minX ) minX = x;
  4779. if ( y < minY ) minY = y;
  4780. if ( z < minZ ) minZ = z;
  4781. if ( x > maxX ) maxX = x;
  4782. if ( y > maxY ) maxY = y;
  4783. if ( z > maxZ ) maxZ = z;
  4784. }
  4785. this.min.set( minX, minY, minZ );
  4786. this.max.set( maxX, maxY, maxZ );
  4787. },
  4788. setFromPoints: function ( points ) {
  4789. this.makeEmpty();
  4790. for ( var i = 0, il = points.length; i < il; i ++ ) {
  4791. this.expandByPoint( points[ i ] );
  4792. }
  4793. return this;
  4794. },
  4795. setFromCenterAndSize: function () {
  4796. var v1 = new Vector3();
  4797. return function setFromCenterAndSize( center, size ) {
  4798. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  4799. this.min.copy( center ).sub( halfSize );
  4800. this.max.copy( center ).add( halfSize );
  4801. return this;
  4802. };
  4803. }(),
  4804. setFromObject: function () {
  4805. // Computes the world-axis-aligned bounding box of an object (including its children),
  4806. // accounting for both the object's, and children's, world transforms
  4807. var v1 = new Vector3();
  4808. return function setFromObject( object ) {
  4809. var scope = this;
  4810. object.updateMatrixWorld( true );
  4811. this.makeEmpty();
  4812. object.traverse( function ( node ) {
  4813. var geometry = node.geometry;
  4814. if ( geometry !== undefined ) {
  4815. if ( (geometry && geometry.isGeometry) ) {
  4816. var vertices = geometry.vertices;
  4817. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  4818. v1.copy( vertices[ i ] );
  4819. v1.applyMatrix4( node.matrixWorld );
  4820. scope.expandByPoint( v1 );
  4821. }
  4822. } else if ( (geometry && geometry.isBufferGeometry) ) {
  4823. var attribute = geometry.attributes.position;
  4824. if ( attribute !== undefined ) {
  4825. var array, offset, stride;
  4826. if ( (attribute && attribute.isInterleavedBufferAttribute) ) {
  4827. array = attribute.data.array;
  4828. offset = attribute.offset;
  4829. stride = attribute.data.stride;
  4830. } else {
  4831. array = attribute.array;
  4832. offset = 0;
  4833. stride = 3;
  4834. }
  4835. for ( var i = offset, il = array.length; i < il; i += stride ) {
  4836. v1.fromArray( array, i );
  4837. v1.applyMatrix4( node.matrixWorld );
  4838. scope.expandByPoint( v1 );
  4839. }
  4840. }
  4841. }
  4842. }
  4843. } );
  4844. return this;
  4845. };
  4846. }(),
  4847. clone: function () {
  4848. return new this.constructor().copy( this );
  4849. },
  4850. copy: function ( box ) {
  4851. this.min.copy( box.min );
  4852. this.max.copy( box.max );
  4853. return this;
  4854. },
  4855. makeEmpty: function () {
  4856. this.min.x = this.min.y = this.min.z = + Infinity;
  4857. this.max.x = this.max.y = this.max.z = - Infinity;
  4858. return this;
  4859. },
  4860. isEmpty: function () {
  4861. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  4862. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  4863. },
  4864. center: function ( optionalTarget ) {
  4865. var result = optionalTarget || new Vector3();
  4866. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  4867. },
  4868. size: function ( optionalTarget ) {
  4869. var result = optionalTarget || new Vector3();
  4870. return result.subVectors( this.max, this.min );
  4871. },
  4872. expandByPoint: function ( point ) {
  4873. this.min.min( point );
  4874. this.max.max( point );
  4875. return this;
  4876. },
  4877. expandByVector: function ( vector ) {
  4878. this.min.sub( vector );
  4879. this.max.add( vector );
  4880. return this;
  4881. },
  4882. expandByScalar: function ( scalar ) {
  4883. this.min.addScalar( - scalar );
  4884. this.max.addScalar( scalar );
  4885. return this;
  4886. },
  4887. containsPoint: function ( point ) {
  4888. if ( point.x < this.min.x || point.x > this.max.x ||
  4889. point.y < this.min.y || point.y > this.max.y ||
  4890. point.z < this.min.z || point.z > this.max.z ) {
  4891. return false;
  4892. }
  4893. return true;
  4894. },
  4895. containsBox: function ( box ) {
  4896. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  4897. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  4898. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  4899. return true;
  4900. }
  4901. return false;
  4902. },
  4903. getParameter: function ( point, optionalTarget ) {
  4904. // This can potentially have a divide by zero if the box
  4905. // has a size dimension of 0.
  4906. var result = optionalTarget || new Vector3();
  4907. return result.set(
  4908. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  4909. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  4910. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  4911. );
  4912. },
  4913. intersectsBox: function ( box ) {
  4914. // using 6 splitting planes to rule out intersections.
  4915. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  4916. box.max.y < this.min.y || box.min.y > this.max.y ||
  4917. box.max.z < this.min.z || box.min.z > this.max.z ) {
  4918. return false;
  4919. }
  4920. return true;
  4921. },
  4922. intersectsSphere: ( function () {
  4923. var closestPoint;
  4924. return function intersectsSphere( sphere ) {
  4925. if ( closestPoint === undefined ) closestPoint = new Vector3();
  4926. // Find the point on the AABB closest to the sphere center.
  4927. this.clampPoint( sphere.center, closestPoint );
  4928. // If that point is inside the sphere, the AABB and sphere intersect.
  4929. return closestPoint.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  4930. };
  4931. } )(),
  4932. intersectsPlane: function ( plane ) {
  4933. // We compute the minimum and maximum dot product values. If those values
  4934. // are on the same side (back or front) of the plane, then there is no intersection.
  4935. var min, max;
  4936. if ( plane.normal.x > 0 ) {
  4937. min = plane.normal.x * this.min.x;
  4938. max = plane.normal.x * this.max.x;
  4939. } else {
  4940. min = plane.normal.x * this.max.x;
  4941. max = plane.normal.x * this.min.x;
  4942. }
  4943. if ( plane.normal.y > 0 ) {
  4944. min += plane.normal.y * this.min.y;
  4945. max += plane.normal.y * this.max.y;
  4946. } else {
  4947. min += plane.normal.y * this.max.y;
  4948. max += plane.normal.y * this.min.y;
  4949. }
  4950. if ( plane.normal.z > 0 ) {
  4951. min += plane.normal.z * this.min.z;
  4952. max += plane.normal.z * this.max.z;
  4953. } else {
  4954. min += plane.normal.z * this.max.z;
  4955. max += plane.normal.z * this.min.z;
  4956. }
  4957. return ( min <= plane.constant && max >= plane.constant );
  4958. },
  4959. clampPoint: function ( point, optionalTarget ) {
  4960. var result = optionalTarget || new Vector3();
  4961. return result.copy( point ).clamp( this.min, this.max );
  4962. },
  4963. distanceToPoint: function () {
  4964. var v1 = new Vector3();
  4965. return function distanceToPoint( point ) {
  4966. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  4967. return clampedPoint.sub( point ).length();
  4968. };
  4969. }(),
  4970. getBoundingSphere: function () {
  4971. var v1 = new Vector3();
  4972. return function getBoundingSphere( optionalTarget ) {
  4973. var result = optionalTarget || new Sphere();
  4974. result.center = this.center();
  4975. result.radius = this.size( v1 ).length() * 0.5;
  4976. return result;
  4977. };
  4978. }(),
  4979. intersect: function ( box ) {
  4980. this.min.max( box.min );
  4981. this.max.min( box.max );
  4982. // 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.
  4983. if( this.isEmpty() ) this.makeEmpty();
  4984. return this;
  4985. },
  4986. union: function ( box ) {
  4987. this.min.min( box.min );
  4988. this.max.max( box.max );
  4989. return this;
  4990. },
  4991. applyMatrix4: function () {
  4992. var points = [
  4993. new Vector3(),
  4994. new Vector3(),
  4995. new Vector3(),
  4996. new Vector3(),
  4997. new Vector3(),
  4998. new Vector3(),
  4999. new Vector3(),
  5000. new Vector3()
  5001. ];
  5002. return function applyMatrix4( matrix ) {
  5003. // transform of empty box is an empty box.
  5004. if( this.isEmpty() ) return this;
  5005. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  5006. points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  5007. points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  5008. points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  5009. points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  5010. points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  5011. points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  5012. points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  5013. points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  5014. this.setFromPoints( points );
  5015. return this;
  5016. };
  5017. }(),
  5018. translate: function ( offset ) {
  5019. this.min.add( offset );
  5020. this.max.add( offset );
  5021. return this;
  5022. },
  5023. equals: function ( box ) {
  5024. return box.min.equals( this.min ) && box.max.equals( this.max );
  5025. }
  5026. };
  5027. /**
  5028. * @author bhouston / http://clara.io
  5029. * @author mrdoob / http://mrdoob.com/
  5030. */
  5031. function Sphere( center, radius ) {
  5032. this.center = ( center !== undefined ) ? center : new Vector3();
  5033. this.radius = ( radius !== undefined ) ? radius : 0;
  5034. }
  5035. Sphere.prototype = {
  5036. constructor: Sphere,
  5037. set: function ( center, radius ) {
  5038. this.center.copy( center );
  5039. this.radius = radius;
  5040. return this;
  5041. },
  5042. setFromPoints: function () {
  5043. var box = new Box3();
  5044. return function setFromPoints( points, optionalCenter ) {
  5045. var center = this.center;
  5046. if ( optionalCenter !== undefined ) {
  5047. center.copy( optionalCenter );
  5048. } else {
  5049. box.setFromPoints( points ).center( center );
  5050. }
  5051. var maxRadiusSq = 0;
  5052. for ( var i = 0, il = points.length; i < il; i ++ ) {
  5053. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  5054. }
  5055. this.radius = Math.sqrt( maxRadiusSq );
  5056. return this;
  5057. };
  5058. }(),
  5059. clone: function () {
  5060. return new this.constructor().copy( this );
  5061. },
  5062. copy: function ( sphere ) {
  5063. this.center.copy( sphere.center );
  5064. this.radius = sphere.radius;
  5065. return this;
  5066. },
  5067. empty: function () {
  5068. return ( this.radius <= 0 );
  5069. },
  5070. containsPoint: function ( point ) {
  5071. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  5072. },
  5073. distanceToPoint: function ( point ) {
  5074. return ( point.distanceTo( this.center ) - this.radius );
  5075. },
  5076. intersectsSphere: function ( sphere ) {
  5077. var radiusSum = this.radius + sphere.radius;
  5078. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  5079. },
  5080. intersectsBox: function ( box ) {
  5081. return box.intersectsSphere( this );
  5082. },
  5083. intersectsPlane: function ( plane ) {
  5084. // We use the following equation to compute the signed distance from
  5085. // the center of the sphere to the plane.
  5086. //
  5087. // distance = q * n - d
  5088. //
  5089. // If this distance is greater than the radius of the sphere,
  5090. // then there is no intersection.
  5091. return Math.abs( this.center.dot( plane.normal ) - plane.constant ) <= this.radius;
  5092. },
  5093. clampPoint: function ( point, optionalTarget ) {
  5094. var deltaLengthSq = this.center.distanceToSquared( point );
  5095. var result = optionalTarget || new Vector3();
  5096. result.copy( point );
  5097. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  5098. result.sub( this.center ).normalize();
  5099. result.multiplyScalar( this.radius ).add( this.center );
  5100. }
  5101. return result;
  5102. },
  5103. getBoundingBox: function ( optionalTarget ) {
  5104. var box = optionalTarget || new Box3();
  5105. box.set( this.center, this.center );
  5106. box.expandByScalar( this.radius );
  5107. return box;
  5108. },
  5109. applyMatrix4: function ( matrix ) {
  5110. this.center.applyMatrix4( matrix );
  5111. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  5112. return this;
  5113. },
  5114. translate: function ( offset ) {
  5115. this.center.add( offset );
  5116. return this;
  5117. },
  5118. equals: function ( sphere ) {
  5119. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  5120. }
  5121. };
  5122. /**
  5123. * @author alteredq / http://alteredqualia.com/
  5124. * @author WestLangley / http://github.com/WestLangley
  5125. * @author bhouston / http://clara.io
  5126. * @author tschw
  5127. */
  5128. function Matrix3() {
  5129. this.elements = new Float32Array( [
  5130. 1, 0, 0,
  5131. 0, 1, 0,
  5132. 0, 0, 1
  5133. ] );
  5134. if ( arguments.length > 0 ) {
  5135. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  5136. }
  5137. }
  5138. Matrix3.prototype = {
  5139. constructor: Matrix3,
  5140. isMatrix3: true,
  5141. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  5142. var te = this.elements;
  5143. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  5144. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  5145. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  5146. return this;
  5147. },
  5148. identity: function () {
  5149. this.set(
  5150. 1, 0, 0,
  5151. 0, 1, 0,
  5152. 0, 0, 1
  5153. );
  5154. return this;
  5155. },
  5156. clone: function () {
  5157. return new this.constructor().fromArray( this.elements );
  5158. },
  5159. copy: function ( m ) {
  5160. var me = m.elements;
  5161. this.set(
  5162. me[ 0 ], me[ 3 ], me[ 6 ],
  5163. me[ 1 ], me[ 4 ], me[ 7 ],
  5164. me[ 2 ], me[ 5 ], me[ 8 ]
  5165. );
  5166. return this;
  5167. },
  5168. setFromMatrix4: function( m ) {
  5169. var me = m.elements;
  5170. this.set(
  5171. me[ 0 ], me[ 4 ], me[ 8 ],
  5172. me[ 1 ], me[ 5 ], me[ 9 ],
  5173. me[ 2 ], me[ 6 ], me[ 10 ]
  5174. );
  5175. return this;
  5176. },
  5177. applyToVector3Array: function () {
  5178. var v1;
  5179. return function applyToVector3Array( array, offset, length ) {
  5180. if ( v1 === undefined ) v1 = new Vector3();
  5181. if ( offset === undefined ) offset = 0;
  5182. if ( length === undefined ) length = array.length;
  5183. for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) {
  5184. v1.fromArray( array, j );
  5185. v1.applyMatrix3( this );
  5186. v1.toArray( array, j );
  5187. }
  5188. return array;
  5189. };
  5190. }(),
  5191. applyToBuffer: function () {
  5192. var v1;
  5193. return function applyToBuffer( buffer, offset, length ) {
  5194. if ( v1 === undefined ) v1 = new Vector3();
  5195. if ( offset === undefined ) offset = 0;
  5196. if ( length === undefined ) length = buffer.length / buffer.itemSize;
  5197. for ( var i = 0, j = offset; i < length; i ++, j ++ ) {
  5198. v1.x = buffer.getX( j );
  5199. v1.y = buffer.getY( j );
  5200. v1.z = buffer.getZ( j );
  5201. v1.applyMatrix3( this );
  5202. buffer.setXYZ( v1.x, v1.y, v1.z );
  5203. }
  5204. return buffer;
  5205. };
  5206. }(),
  5207. multiplyScalar: function ( s ) {
  5208. var te = this.elements;
  5209. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  5210. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  5211. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  5212. return this;
  5213. },
  5214. determinant: function () {
  5215. var te = this.elements;
  5216. var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  5217. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  5218. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  5219. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  5220. },
  5221. getInverse: function ( matrix, throwOnDegenerate ) {
  5222. if ( (matrix && matrix.isMatrix4) ) {
  5223. console.error( "THREE.Matrix3.getInverse no longer takes a Matrix4 argument." );
  5224. }
  5225. var me = matrix.elements,
  5226. te = this.elements,
  5227. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ],
  5228. n12 = me[ 3 ], n22 = me[ 4 ], n32 = me[ 5 ],
  5229. n13 = me[ 6 ], n23 = me[ 7 ], n33 = me[ 8 ],
  5230. t11 = n33 * n22 - n32 * n23,
  5231. t12 = n32 * n13 - n33 * n12,
  5232. t13 = n23 * n12 - n22 * n13,
  5233. det = n11 * t11 + n21 * t12 + n31 * t13;
  5234. if ( det === 0 ) {
  5235. var msg = "THREE.Matrix3.getInverse(): can't invert matrix, determinant is 0";
  5236. if ( throwOnDegenerate === true ) {
  5237. throw new Error( msg );
  5238. } else {
  5239. console.warn( msg );
  5240. }
  5241. return this.identity();
  5242. }
  5243. var detInv = 1 / det;
  5244. te[ 0 ] = t11 * detInv;
  5245. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  5246. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  5247. te[ 3 ] = t12 * detInv;
  5248. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  5249. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  5250. te[ 6 ] = t13 * detInv;
  5251. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  5252. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  5253. return this;
  5254. },
  5255. transpose: function () {
  5256. var tmp, m = this.elements;
  5257. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  5258. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  5259. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  5260. return this;
  5261. },
  5262. flattenToArrayOffset: function ( array, offset ) {
  5263. console.warn( "THREE.Matrix3: .flattenToArrayOffset is deprecated " +
  5264. "- just use .toArray instead." );
  5265. return this.toArray( array, offset );
  5266. },
  5267. getNormalMatrix: function ( matrix4 ) {
  5268. return this.setFromMatrix4( matrix4 ).getInverse( this ).transpose();
  5269. },
  5270. transposeIntoArray: function ( r ) {
  5271. var m = this.elements;
  5272. r[ 0 ] = m[ 0 ];
  5273. r[ 1 ] = m[ 3 ];
  5274. r[ 2 ] = m[ 6 ];
  5275. r[ 3 ] = m[ 1 ];
  5276. r[ 4 ] = m[ 4 ];
  5277. r[ 5 ] = m[ 7 ];
  5278. r[ 6 ] = m[ 2 ];
  5279. r[ 7 ] = m[ 5 ];
  5280. r[ 8 ] = m[ 8 ];
  5281. return this;
  5282. },
  5283. fromArray: function ( array, offset ) {
  5284. if ( offset === undefined ) offset = 0;
  5285. for( var i = 0; i < 9; i ++ ) {
  5286. this.elements[ i ] = array[ i + offset ];
  5287. }
  5288. return this;
  5289. },
  5290. toArray: function ( array, offset ) {
  5291. if ( array === undefined ) array = [];
  5292. if ( offset === undefined ) offset = 0;
  5293. var te = this.elements;
  5294. array[ offset ] = te[ 0 ];
  5295. array[ offset + 1 ] = te[ 1 ];
  5296. array[ offset + 2 ] = te[ 2 ];
  5297. array[ offset + 3 ] = te[ 3 ];
  5298. array[ offset + 4 ] = te[ 4 ];
  5299. array[ offset + 5 ] = te[ 5 ];
  5300. array[ offset + 6 ] = te[ 6 ];
  5301. array[ offset + 7 ] = te[ 7 ];
  5302. array[ offset + 8 ] = te[ 8 ];
  5303. return array;
  5304. }
  5305. };
  5306. /**
  5307. * @author bhouston / http://clara.io
  5308. */
  5309. function Plane( normal, constant ) {
  5310. this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 );
  5311. this.constant = ( constant !== undefined ) ? constant : 0;
  5312. }
  5313. Plane.prototype = {
  5314. constructor: Plane,
  5315. set: function ( normal, constant ) {
  5316. this.normal.copy( normal );
  5317. this.constant = constant;
  5318. return this;
  5319. },
  5320. setComponents: function ( x, y, z, w ) {
  5321. this.normal.set( x, y, z );
  5322. this.constant = w;
  5323. return this;
  5324. },
  5325. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  5326. this.normal.copy( normal );
  5327. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  5328. return this;
  5329. },
  5330. setFromCoplanarPoints: function () {
  5331. var v1 = new Vector3();
  5332. var v2 = new Vector3();
  5333. return function setFromCoplanarPoints( a, b, c ) {
  5334. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  5335. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  5336. this.setFromNormalAndCoplanarPoint( normal, a );
  5337. return this;
  5338. };
  5339. }(),
  5340. clone: function () {
  5341. return new this.constructor().copy( this );
  5342. },
  5343. copy: function ( plane ) {
  5344. this.normal.copy( plane.normal );
  5345. this.constant = plane.constant;
  5346. return this;
  5347. },
  5348. normalize: function () {
  5349. // Note: will lead to a divide by zero if the plane is invalid.
  5350. var inverseNormalLength = 1.0 / this.normal.length();
  5351. this.normal.multiplyScalar( inverseNormalLength );
  5352. this.constant *= inverseNormalLength;
  5353. return this;
  5354. },
  5355. negate: function () {
  5356. this.constant *= - 1;
  5357. this.normal.negate();
  5358. return this;
  5359. },
  5360. distanceToPoint: function ( point ) {
  5361. return this.normal.dot( point ) + this.constant;
  5362. },
  5363. distanceToSphere: function ( sphere ) {
  5364. return this.distanceToPoint( sphere.center ) - sphere.radius;
  5365. },
  5366. projectPoint: function ( point, optionalTarget ) {
  5367. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  5368. },
  5369. orthoPoint: function ( point, optionalTarget ) {
  5370. var perpendicularMagnitude = this.distanceToPoint( point );
  5371. var result = optionalTarget || new Vector3();
  5372. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  5373. },
  5374. intersectLine: function () {
  5375. var v1 = new Vector3();
  5376. return function intersectLine( line, optionalTarget ) {
  5377. var result = optionalTarget || new Vector3();
  5378. var direction = line.delta( v1 );
  5379. var denominator = this.normal.dot( direction );
  5380. if ( denominator === 0 ) {
  5381. // line is coplanar, return origin
  5382. if ( this.distanceToPoint( line.start ) === 0 ) {
  5383. return result.copy( line.start );
  5384. }
  5385. // Unsure if this is the correct method to handle this case.
  5386. return undefined;
  5387. }
  5388. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  5389. if ( t < 0 || t > 1 ) {
  5390. return undefined;
  5391. }
  5392. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  5393. };
  5394. }(),
  5395. intersectsLine: function ( line ) {
  5396. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  5397. var startSign = this.distanceToPoint( line.start );
  5398. var endSign = this.distanceToPoint( line.end );
  5399. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  5400. },
  5401. intersectsBox: function ( box ) {
  5402. return box.intersectsPlane( this );
  5403. },
  5404. intersectsSphere: function ( sphere ) {
  5405. return sphere.intersectsPlane( this );
  5406. },
  5407. coplanarPoint: function ( optionalTarget ) {
  5408. var result = optionalTarget || new Vector3();
  5409. return result.copy( this.normal ).multiplyScalar( - this.constant );
  5410. },
  5411. applyMatrix4: function () {
  5412. var v1 = new Vector3();
  5413. var m1 = new Matrix3();
  5414. return function applyMatrix4( matrix, optionalNormalMatrix ) {
  5415. var referencePoint = this.coplanarPoint( v1 ).applyMatrix4( matrix );
  5416. // transform normal based on theory here:
  5417. // http://www.songho.ca/opengl/gl_normaltransform.html
  5418. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  5419. var normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  5420. // recalculate constant (like in setFromNormalAndCoplanarPoint)
  5421. this.constant = - referencePoint.dot( normal );
  5422. return this;
  5423. };
  5424. }(),
  5425. translate: function ( offset ) {
  5426. this.constant = this.constant - offset.dot( this.normal );
  5427. return this;
  5428. },
  5429. equals: function ( plane ) {
  5430. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  5431. }
  5432. };
  5433. /**
  5434. * @author mrdoob / http://mrdoob.com/
  5435. * @author alteredq / http://alteredqualia.com/
  5436. * @author bhouston / http://clara.io
  5437. */
  5438. function Frustum( p0, p1, p2, p3, p4, p5 ) {
  5439. this.planes = [
  5440. ( p0 !== undefined ) ? p0 : new Plane(),
  5441. ( p1 !== undefined ) ? p1 : new Plane(),
  5442. ( p2 !== undefined ) ? p2 : new Plane(),
  5443. ( p3 !== undefined ) ? p3 : new Plane(),
  5444. ( p4 !== undefined ) ? p4 : new Plane(),
  5445. ( p5 !== undefined ) ? p5 : new Plane()
  5446. ];
  5447. }
  5448. Frustum.prototype = {
  5449. constructor: Frustum,
  5450. set: function ( p0, p1, p2, p3, p4, p5 ) {
  5451. var planes = this.planes;
  5452. planes[ 0 ].copy( p0 );
  5453. planes[ 1 ].copy( p1 );
  5454. planes[ 2 ].copy( p2 );
  5455. planes[ 3 ].copy( p3 );
  5456. planes[ 4 ].copy( p4 );
  5457. planes[ 5 ].copy( p5 );
  5458. return this;
  5459. },
  5460. clone: function () {
  5461. return new this.constructor().copy( this );
  5462. },
  5463. copy: function ( frustum ) {
  5464. var planes = this.planes;
  5465. for ( var i = 0; i < 6; i ++ ) {
  5466. planes[ i ].copy( frustum.planes[ i ] );
  5467. }
  5468. return this;
  5469. },
  5470. setFromMatrix: function ( m ) {
  5471. var planes = this.planes;
  5472. var me = m.elements;
  5473. var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  5474. var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  5475. var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  5476. var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  5477. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  5478. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  5479. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  5480. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  5481. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  5482. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  5483. return this;
  5484. },
  5485. intersectsObject: function () {
  5486. var sphere = new Sphere();
  5487. return function intersectsObject( object ) {
  5488. var geometry = object.geometry;
  5489. if ( geometry.boundingSphere === null )
  5490. geometry.computeBoundingSphere();
  5491. sphere.copy( geometry.boundingSphere )
  5492. .applyMatrix4( object.matrixWorld );
  5493. return this.intersectsSphere( sphere );
  5494. };
  5495. }(),
  5496. intersectsSprite: function () {
  5497. var sphere = new Sphere();
  5498. return function intersectsSprite( sprite ) {
  5499. sphere.center.set( 0, 0, 0 );
  5500. sphere.radius = 0.7071067811865476;
  5501. sphere.applyMatrix4( sprite.matrixWorld );
  5502. return this.intersectsSphere( sphere );
  5503. };
  5504. }(),
  5505. intersectsSphere: function ( sphere ) {
  5506. var planes = this.planes;
  5507. var center = sphere.center;
  5508. var negRadius = - sphere.radius;
  5509. for ( var i = 0; i < 6; i ++ ) {
  5510. var distance = planes[ i ].distanceToPoint( center );
  5511. if ( distance < negRadius ) {
  5512. return false;
  5513. }
  5514. }
  5515. return true;
  5516. },
  5517. intersectsBox: function () {
  5518. var p1 = new Vector3(),
  5519. p2 = new Vector3();
  5520. return function intersectsBox( box ) {
  5521. var planes = this.planes;
  5522. for ( var i = 0; i < 6 ; i ++ ) {
  5523. var plane = planes[ i ];
  5524. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  5525. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  5526. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  5527. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  5528. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  5529. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  5530. var d1 = plane.distanceToPoint( p1 );
  5531. var d2 = plane.distanceToPoint( p2 );
  5532. // if both outside plane, no intersection
  5533. if ( d1 < 0 && d2 < 0 ) {
  5534. return false;
  5535. }
  5536. }
  5537. return true;
  5538. };
  5539. }(),
  5540. containsPoint: function ( point ) {
  5541. var planes = this.planes;
  5542. for ( var i = 0; i < 6; i ++ ) {
  5543. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  5544. return false;
  5545. }
  5546. }
  5547. return true;
  5548. }
  5549. };
  5550. function WebGLShadowMap( _renderer, _lights, _objects, capabilities ) {
  5551. var _gl = _renderer.context,
  5552. _state = _renderer.state,
  5553. _frustum = new Frustum(),
  5554. _projScreenMatrix = new Matrix4(),
  5555. _lightShadows = _lights.shadows,
  5556. _shadowMapSize = new Vector2(),
  5557. _maxShadowMapSize = new Vector2( capabilities.maxTextureSize, capabilities.maxTextureSize ),
  5558. _lookTarget = new Vector3(),
  5559. _lightPositionWorld = new Vector3(),
  5560. _renderList = [],
  5561. _MorphingFlag = 1,
  5562. _SkinningFlag = 2,
  5563. _NumberOfMaterialVariants = ( _MorphingFlag | _SkinningFlag ) + 1,
  5564. _depthMaterials = new Array( _NumberOfMaterialVariants ),
  5565. _distanceMaterials = new Array( _NumberOfMaterialVariants ),
  5566. _materialCache = {};
  5567. var cubeDirections = [
  5568. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  5569. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  5570. ];
  5571. var cubeUps = [
  5572. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  5573. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  5574. ];
  5575. var cube2DViewPorts = [
  5576. new Vector4(), new Vector4(), new Vector4(),
  5577. new Vector4(), new Vector4(), new Vector4()
  5578. ];
  5579. // init
  5580. var depthMaterialTemplate = new MeshDepthMaterial();
  5581. depthMaterialTemplate.depthPacking = RGBADepthPacking;
  5582. depthMaterialTemplate.clipping = true;
  5583. var distanceShader = ShaderLib[ "distanceRGBA" ];
  5584. var distanceUniforms = exports.UniformsUtils.clone( distanceShader.uniforms );
  5585. for ( var i = 0; i !== _NumberOfMaterialVariants; ++ i ) {
  5586. var useMorphing = ( i & _MorphingFlag ) !== 0;
  5587. var useSkinning = ( i & _SkinningFlag ) !== 0;
  5588. var depthMaterial = depthMaterialTemplate.clone();
  5589. depthMaterial.morphTargets = useMorphing;
  5590. depthMaterial.skinning = useSkinning;
  5591. _depthMaterials[ i ] = depthMaterial;
  5592. var distanceMaterial = new ShaderMaterial( {
  5593. defines: {
  5594. 'USE_SHADOWMAP': ''
  5595. },
  5596. uniforms: distanceUniforms,
  5597. vertexShader: distanceShader.vertexShader,
  5598. fragmentShader: distanceShader.fragmentShader,
  5599. morphTargets: useMorphing,
  5600. skinning: useSkinning,
  5601. clipping: true
  5602. } );
  5603. _distanceMaterials[ i ] = distanceMaterial;
  5604. }
  5605. //
  5606. var scope = this;
  5607. this.enabled = false;
  5608. this.autoUpdate = true;
  5609. this.needsUpdate = false;
  5610. this.type = PCFShadowMap;
  5611. this.renderReverseSided = true;
  5612. this.renderSingleSided = true;
  5613. this.render = function ( scene, camera ) {
  5614. if ( scope.enabled === false ) return;
  5615. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  5616. if ( _lightShadows.length === 0 ) return;
  5617. // Set GL state for depth map.
  5618. _state.clearColor( 1, 1, 1, 1 );
  5619. _state.disable( _gl.BLEND );
  5620. _state.setDepthTest( true );
  5621. _state.setScissorTest( false );
  5622. // render depth map
  5623. var faceCount, isPointLight;
  5624. for ( var i = 0, il = _lightShadows.length; i < il; i ++ ) {
  5625. var light = _lightShadows[ i ];
  5626. var shadow = light.shadow;
  5627. if ( shadow === undefined ) {
  5628. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  5629. continue;
  5630. }
  5631. var shadowCamera = shadow.camera;
  5632. _shadowMapSize.copy( shadow.mapSize );
  5633. _shadowMapSize.min( _maxShadowMapSize );
  5634. if ( (light && light.isPointLight) ) {
  5635. faceCount = 6;
  5636. isPointLight = true;
  5637. var vpWidth = _shadowMapSize.x;
  5638. var vpHeight = _shadowMapSize.y;
  5639. // These viewports map a cube-map onto a 2D texture with the
  5640. // following orientation:
  5641. //
  5642. // xzXZ
  5643. // y Y
  5644. //
  5645. // X - Positive x direction
  5646. // x - Negative x direction
  5647. // Y - Positive y direction
  5648. // y - Negative y direction
  5649. // Z - Positive z direction
  5650. // z - Negative z direction
  5651. // positive X
  5652. cube2DViewPorts[ 0 ].set( vpWidth * 2, vpHeight, vpWidth, vpHeight );
  5653. // negative X
  5654. cube2DViewPorts[ 1 ].set( 0, vpHeight, vpWidth, vpHeight );
  5655. // positive Z
  5656. cube2DViewPorts[ 2 ].set( vpWidth * 3, vpHeight, vpWidth, vpHeight );
  5657. // negative Z
  5658. cube2DViewPorts[ 3 ].set( vpWidth, vpHeight, vpWidth, vpHeight );
  5659. // positive Y
  5660. cube2DViewPorts[ 4 ].set( vpWidth * 3, 0, vpWidth, vpHeight );
  5661. // negative Y
  5662. cube2DViewPorts[ 5 ].set( vpWidth, 0, vpWidth, vpHeight );
  5663. _shadowMapSize.x *= 4.0;
  5664. _shadowMapSize.y *= 2.0;
  5665. } else {
  5666. faceCount = 1;
  5667. isPointLight = false;
  5668. }
  5669. if ( shadow.map === null ) {
  5670. var pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat };
  5671. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  5672. shadowCamera.updateProjectionMatrix();
  5673. }
  5674. if ( (shadow && shadow.isSpotLightShadow) ) {
  5675. shadow.update( light );
  5676. }
  5677. var shadowMap = shadow.map;
  5678. var shadowMatrix = shadow.matrix;
  5679. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  5680. shadowCamera.position.copy( _lightPositionWorld );
  5681. _renderer.setRenderTarget( shadowMap );
  5682. _renderer.clear();
  5683. // render shadow map for each cube face (if omni-directional) or
  5684. // run a single pass if not
  5685. for ( var face = 0; face < faceCount; face ++ ) {
  5686. if ( isPointLight ) {
  5687. _lookTarget.copy( shadowCamera.position );
  5688. _lookTarget.add( cubeDirections[ face ] );
  5689. shadowCamera.up.copy( cubeUps[ face ] );
  5690. shadowCamera.lookAt( _lookTarget );
  5691. var vpDimensions = cube2DViewPorts[ face ];
  5692. _state.viewport( vpDimensions );
  5693. } else {
  5694. _lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  5695. shadowCamera.lookAt( _lookTarget );
  5696. }
  5697. shadowCamera.updateMatrixWorld();
  5698. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  5699. // compute shadow matrix
  5700. shadowMatrix.set(
  5701. 0.5, 0.0, 0.0, 0.5,
  5702. 0.0, 0.5, 0.0, 0.5,
  5703. 0.0, 0.0, 0.5, 0.5,
  5704. 0.0, 0.0, 0.0, 1.0
  5705. );
  5706. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  5707. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  5708. // update camera matrices and frustum
  5709. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  5710. _frustum.setFromMatrix( _projScreenMatrix );
  5711. // set object matrices & frustum culling
  5712. _renderList.length = 0;
  5713. projectObject( scene, camera, shadowCamera );
  5714. // render shadow map
  5715. // render regular objects
  5716. for ( var j = 0, jl = _renderList.length; j < jl; j ++ ) {
  5717. var object = _renderList[ j ];
  5718. var geometry = _objects.update( object );
  5719. var material = object.material;
  5720. if ( (material && material.isMultiMaterial) ) {
  5721. var groups = geometry.groups;
  5722. var materials = material.materials;
  5723. for ( var k = 0, kl = groups.length; k < kl; k ++ ) {
  5724. var group = groups[ k ];
  5725. var groupMaterial = materials[ group.materialIndex ];
  5726. if ( groupMaterial.visible === true ) {
  5727. var depthMaterial = getDepthMaterial( object, groupMaterial, isPointLight, _lightPositionWorld );
  5728. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  5729. }
  5730. }
  5731. } else {
  5732. var depthMaterial = getDepthMaterial( object, material, isPointLight, _lightPositionWorld );
  5733. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  5734. }
  5735. }
  5736. }
  5737. }
  5738. // Restore GL state.
  5739. var clearColor = _renderer.getClearColor(),
  5740. clearAlpha = _renderer.getClearAlpha();
  5741. _renderer.setClearColor( clearColor, clearAlpha );
  5742. scope.needsUpdate = false;
  5743. };
  5744. function getDepthMaterial( object, material, isPointLight, lightPositionWorld ) {
  5745. var geometry = object.geometry;
  5746. var result = null;
  5747. var materialVariants = _depthMaterials;
  5748. var customMaterial = object.customDepthMaterial;
  5749. if ( isPointLight ) {
  5750. materialVariants = _distanceMaterials;
  5751. customMaterial = object.customDistanceMaterial;
  5752. }
  5753. if ( ! customMaterial ) {
  5754. var useMorphing = false;
  5755. if ( material.morphTargets ) {
  5756. if ( (geometry && geometry.isBufferGeometry) ) {
  5757. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  5758. } else if ( (geometry && geometry.isGeometry) ) {
  5759. useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0;
  5760. }
  5761. }
  5762. var useSkinning = object.isSkinnedMesh && material.skinning;
  5763. var variantIndex = 0;
  5764. if ( useMorphing ) variantIndex |= _MorphingFlag;
  5765. if ( useSkinning ) variantIndex |= _SkinningFlag;
  5766. result = materialVariants[ variantIndex ];
  5767. } else {
  5768. result = customMaterial;
  5769. }
  5770. if ( _renderer.localClippingEnabled &&
  5771. material.clipShadows === true &&
  5772. material.clippingPlanes.length !== 0 ) {
  5773. // in this case we need a unique material instance reflecting the
  5774. // appropriate state
  5775. var keyA = result.uuid, keyB = material.uuid;
  5776. var materialsForVariant = _materialCache[ keyA ];
  5777. if ( materialsForVariant === undefined ) {
  5778. materialsForVariant = {};
  5779. _materialCache[ keyA ] = materialsForVariant;
  5780. }
  5781. var cachedMaterial = materialsForVariant[ keyB ];
  5782. if ( cachedMaterial === undefined ) {
  5783. cachedMaterial = result.clone();
  5784. materialsForVariant[ keyB ] = cachedMaterial;
  5785. }
  5786. result = cachedMaterial;
  5787. }
  5788. result.visible = material.visible;
  5789. result.wireframe = material.wireframe;
  5790. var side = material.side;
  5791. if ( scope.renderSingleSided && side == DoubleSide ) {
  5792. side = FrontSide;
  5793. }
  5794. if ( scope.renderReverseSided ) {
  5795. if ( side === FrontSide ) side = BackSide;
  5796. else if ( side === BackSide ) side = FrontSide;
  5797. }
  5798. result.side = side;
  5799. result.clipShadows = material.clipShadows;
  5800. result.clippingPlanes = material.clippingPlanes;
  5801. result.wireframeLinewidth = material.wireframeLinewidth;
  5802. result.linewidth = material.linewidth;
  5803. if ( isPointLight && result.uniforms.lightPos !== undefined ) {
  5804. result.uniforms.lightPos.value.copy( lightPositionWorld );
  5805. }
  5806. return result;
  5807. }
  5808. function projectObject( object, camera, shadowCamera ) {
  5809. if ( object.visible === false ) return;
  5810. var visible = ( object.layers.mask & camera.layers.mask ) !== 0;
  5811. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  5812. if ( object.castShadow && ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) ) {
  5813. var material = object.material;
  5814. if ( material.visible === true ) {
  5815. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  5816. _renderList.push( object );
  5817. }
  5818. }
  5819. }
  5820. var children = object.children;
  5821. for ( var i = 0, l = children.length; i < l; i ++ ) {
  5822. projectObject( children[ i ], camera, shadowCamera );
  5823. }
  5824. }
  5825. }
  5826. /**
  5827. * @author mrdoob / http://mrdoob.com/
  5828. */
  5829. function BufferAttribute( array, itemSize, normalized ) {
  5830. if ( Array.isArray( array ) ) {
  5831. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  5832. }
  5833. this.uuid = exports.Math.generateUUID();
  5834. this.array = array;
  5835. this.itemSize = itemSize;
  5836. this.normalized = normalized === true;
  5837. this.dynamic = false;
  5838. this.updateRange = { offset: 0, count: - 1 };
  5839. this.version = 0;
  5840. }
  5841. BufferAttribute.prototype = {
  5842. constructor: BufferAttribute,
  5843. isBufferAttribute: true,
  5844. get count() {
  5845. return this.array.length / this.itemSize;
  5846. },
  5847. set needsUpdate( value ) {
  5848. if ( value === true ) this.version ++;
  5849. },
  5850. setDynamic: function ( value ) {
  5851. this.dynamic = value;
  5852. return this;
  5853. },
  5854. copy: function ( source ) {
  5855. this.array = new source.array.constructor( source.array );
  5856. this.itemSize = source.itemSize;
  5857. this.normalized = source.normalized;
  5858. this.dynamic = source.dynamic;
  5859. return this;
  5860. },
  5861. copyAt: function ( index1, attribute, index2 ) {
  5862. index1 *= this.itemSize;
  5863. index2 *= attribute.itemSize;
  5864. for ( var i = 0, l = this.itemSize; i < l; i ++ ) {
  5865. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5866. }
  5867. return this;
  5868. },
  5869. copyArray: function ( array ) {
  5870. this.array.set( array );
  5871. return this;
  5872. },
  5873. copyColorsArray: function ( colors ) {
  5874. var array = this.array, offset = 0;
  5875. for ( var i = 0, l = colors.length; i < l; i ++ ) {
  5876. var color = colors[ i ];
  5877. if ( color === undefined ) {
  5878. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  5879. color = new Color();
  5880. }
  5881. array[ offset ++ ] = color.r;
  5882. array[ offset ++ ] = color.g;
  5883. array[ offset ++ ] = color.b;
  5884. }
  5885. return this;
  5886. },
  5887. copyIndicesArray: function ( indices ) {
  5888. var array = this.array, offset = 0;
  5889. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  5890. var index = indices[ i ];
  5891. array[ offset ++ ] = index.a;
  5892. array[ offset ++ ] = index.b;
  5893. array[ offset ++ ] = index.c;
  5894. }
  5895. return this;
  5896. },
  5897. copyVector2sArray: function ( vectors ) {
  5898. var array = this.array, offset = 0;
  5899. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  5900. var vector = vectors[ i ];
  5901. if ( vector === undefined ) {
  5902. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  5903. vector = new Vector2();
  5904. }
  5905. array[ offset ++ ] = vector.x;
  5906. array[ offset ++ ] = vector.y;
  5907. }
  5908. return this;
  5909. },
  5910. copyVector3sArray: function ( vectors ) {
  5911. var array = this.array, offset = 0;
  5912. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  5913. var vector = vectors[ i ];
  5914. if ( vector === undefined ) {
  5915. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  5916. vector = new Vector3();
  5917. }
  5918. array[ offset ++ ] = vector.x;
  5919. array[ offset ++ ] = vector.y;
  5920. array[ offset ++ ] = vector.z;
  5921. }
  5922. return this;
  5923. },
  5924. copyVector4sArray: function ( vectors ) {
  5925. var array = this.array, offset = 0;
  5926. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  5927. var vector = vectors[ i ];
  5928. if ( vector === undefined ) {
  5929. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  5930. vector = new Vector4();
  5931. }
  5932. array[ offset ++ ] = vector.x;
  5933. array[ offset ++ ] = vector.y;
  5934. array[ offset ++ ] = vector.z;
  5935. array[ offset ++ ] = vector.w;
  5936. }
  5937. return this;
  5938. },
  5939. set: function ( value, offset ) {
  5940. if ( offset === undefined ) offset = 0;
  5941. this.array.set( value, offset );
  5942. return this;
  5943. },
  5944. getX: function ( index ) {
  5945. return this.array[ index * this.itemSize ];
  5946. },
  5947. setX: function ( index, x ) {
  5948. this.array[ index * this.itemSize ] = x;
  5949. return this;
  5950. },
  5951. getY: function ( index ) {
  5952. return this.array[ index * this.itemSize + 1 ];
  5953. },
  5954. setY: function ( index, y ) {
  5955. this.array[ index * this.itemSize + 1 ] = y;
  5956. return this;
  5957. },
  5958. getZ: function ( index ) {
  5959. return this.array[ index * this.itemSize + 2 ];
  5960. },
  5961. setZ: function ( index, z ) {
  5962. this.array[ index * this.itemSize + 2 ] = z;
  5963. return this;
  5964. },
  5965. getW: function ( index ) {
  5966. return this.array[ index * this.itemSize + 3 ];
  5967. },
  5968. setW: function ( index, w ) {
  5969. this.array[ index * this.itemSize + 3 ] = w;
  5970. return this;
  5971. },
  5972. setXY: function ( index, x, y ) {
  5973. index *= this.itemSize;
  5974. this.array[ index + 0 ] = x;
  5975. this.array[ index + 1 ] = y;
  5976. return this;
  5977. },
  5978. setXYZ: function ( index, x, y, z ) {
  5979. index *= this.itemSize;
  5980. this.array[ index + 0 ] = x;
  5981. this.array[ index + 1 ] = y;
  5982. this.array[ index + 2 ] = z;
  5983. return this;
  5984. },
  5985. setXYZW: function ( index, x, y, z, w ) {
  5986. index *= this.itemSize;
  5987. this.array[ index + 0 ] = x;
  5988. this.array[ index + 1 ] = y;
  5989. this.array[ index + 2 ] = z;
  5990. this.array[ index + 3 ] = w;
  5991. return this;
  5992. },
  5993. clone: function () {
  5994. return new this.constructor().copy( this );
  5995. }
  5996. };
  5997. //
  5998. function Int8Attribute( array, itemSize ) {
  5999. return new BufferAttribute( new Int8Array( array ), itemSize );
  6000. }
  6001. function Uint8Attribute( array, itemSize ) {
  6002. return new BufferAttribute( new Uint8Array( array ), itemSize );
  6003. }
  6004. function Uint8ClampedAttribute( array, itemSize ) {
  6005. return new BufferAttribute( new Uint8ClampedArray( array ), itemSize );
  6006. }
  6007. function Int16Attribute( array, itemSize ) {
  6008. return new BufferAttribute( new Int16Array( array ), itemSize );
  6009. }
  6010. function Uint16Attribute( array, itemSize ) {
  6011. return new BufferAttribute( new Uint16Array( array ), itemSize );
  6012. }
  6013. function Int32Attribute( array, itemSize ) {
  6014. return new BufferAttribute( new Int32Array( array ), itemSize );
  6015. }
  6016. function Uint32Attribute( array, itemSize ) {
  6017. return new BufferAttribute( new Uint32Array( array ), itemSize );
  6018. }
  6019. function Float32Attribute( array, itemSize ) {
  6020. return new BufferAttribute( new Float32Array( array ), itemSize );
  6021. }
  6022. function Float64Attribute( array, itemSize ) {
  6023. return new BufferAttribute( new Float64Array( array ), itemSize );
  6024. }
  6025. // Deprecated
  6026. function DynamicBufferAttribute( array, itemSize ) {
  6027. console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.' );
  6028. return new BufferAttribute( array, itemSize ).setDynamic( true );
  6029. }
  6030. /**
  6031. * @author mrdoob / http://mrdoob.com/
  6032. * @author alteredq / http://alteredqualia.com/
  6033. */
  6034. function Face3( a, b, c, normal, color, materialIndex ) {
  6035. this.a = a;
  6036. this.b = b;
  6037. this.c = c;
  6038. this.normal = (normal && normal.isVector3) ? normal : new Vector3();
  6039. this.vertexNormals = Array.isArray( normal ) ? normal : [];
  6040. this.color = (color && color.isColor) ? color : new Color();
  6041. this.vertexColors = Array.isArray( color ) ? color : [];
  6042. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  6043. }
  6044. Face3.prototype = {
  6045. constructor: Face3,
  6046. clone: function () {
  6047. return new this.constructor().copy( this );
  6048. },
  6049. copy: function ( source ) {
  6050. this.a = source.a;
  6051. this.b = source.b;
  6052. this.c = source.c;
  6053. this.normal.copy( source.normal );
  6054. this.color.copy( source.color );
  6055. this.materialIndex = source.materialIndex;
  6056. for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) {
  6057. this.vertexNormals[ i ] = source.vertexNormals[ i ].clone();
  6058. }
  6059. for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) {
  6060. this.vertexColors[ i ] = source.vertexColors[ i ].clone();
  6061. }
  6062. return this;
  6063. }
  6064. };
  6065. /**
  6066. * @author mrdoob / http://mrdoob.com/
  6067. * @author WestLangley / http://github.com/WestLangley
  6068. * @author bhouston / http://clara.io
  6069. */
  6070. function Euler( x, y, z, order ) {
  6071. this._x = x || 0;
  6072. this._y = y || 0;
  6073. this._z = z || 0;
  6074. this._order = order || Euler.DefaultOrder;
  6075. }
  6076. Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  6077. Euler.DefaultOrder = 'XYZ';
  6078. Euler.prototype = {
  6079. constructor: Euler,
  6080. isEuler: true,
  6081. get x () {
  6082. return this._x;
  6083. },
  6084. set x ( value ) {
  6085. this._x = value;
  6086. this.onChangeCallback();
  6087. },
  6088. get y () {
  6089. return this._y;
  6090. },
  6091. set y ( value ) {
  6092. this._y = value;
  6093. this.onChangeCallback();
  6094. },
  6095. get z () {
  6096. return this._z;
  6097. },
  6098. set z ( value ) {
  6099. this._z = value;
  6100. this.onChangeCallback();
  6101. },
  6102. get order () {
  6103. return this._order;
  6104. },
  6105. set order ( value ) {
  6106. this._order = value;
  6107. this.onChangeCallback();
  6108. },
  6109. set: function ( x, y, z, order ) {
  6110. this._x = x;
  6111. this._y = y;
  6112. this._z = z;
  6113. this._order = order || this._order;
  6114. this.onChangeCallback();
  6115. return this;
  6116. },
  6117. clone: function () {
  6118. return new this.constructor( this._x, this._y, this._z, this._order );
  6119. },
  6120. copy: function ( euler ) {
  6121. this._x = euler._x;
  6122. this._y = euler._y;
  6123. this._z = euler._z;
  6124. this._order = euler._order;
  6125. this.onChangeCallback();
  6126. return this;
  6127. },
  6128. setFromRotationMatrix: function ( m, order, update ) {
  6129. var clamp = exports.Math.clamp;
  6130. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6131. var te = m.elements;
  6132. var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  6133. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  6134. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  6135. order = order || this._order;
  6136. if ( order === 'XYZ' ) {
  6137. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  6138. if ( Math.abs( m13 ) < 0.99999 ) {
  6139. this._x = Math.atan2( - m23, m33 );
  6140. this._z = Math.atan2( - m12, m11 );
  6141. } else {
  6142. this._x = Math.atan2( m32, m22 );
  6143. this._z = 0;
  6144. }
  6145. } else if ( order === 'YXZ' ) {
  6146. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  6147. if ( Math.abs( m23 ) < 0.99999 ) {
  6148. this._y = Math.atan2( m13, m33 );
  6149. this._z = Math.atan2( m21, m22 );
  6150. } else {
  6151. this._y = Math.atan2( - m31, m11 );
  6152. this._z = 0;
  6153. }
  6154. } else if ( order === 'ZXY' ) {
  6155. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  6156. if ( Math.abs( m32 ) < 0.99999 ) {
  6157. this._y = Math.atan2( - m31, m33 );
  6158. this._z = Math.atan2( - m12, m22 );
  6159. } else {
  6160. this._y = 0;
  6161. this._z = Math.atan2( m21, m11 );
  6162. }
  6163. } else if ( order === 'ZYX' ) {
  6164. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  6165. if ( Math.abs( m31 ) < 0.99999 ) {
  6166. this._x = Math.atan2( m32, m33 );
  6167. this._z = Math.atan2( m21, m11 );
  6168. } else {
  6169. this._x = 0;
  6170. this._z = Math.atan2( - m12, m22 );
  6171. }
  6172. } else if ( order === 'YZX' ) {
  6173. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  6174. if ( Math.abs( m21 ) < 0.99999 ) {
  6175. this._x = Math.atan2( - m23, m22 );
  6176. this._y = Math.atan2( - m31, m11 );
  6177. } else {
  6178. this._x = 0;
  6179. this._y = Math.atan2( m13, m33 );
  6180. }
  6181. } else if ( order === 'XZY' ) {
  6182. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  6183. if ( Math.abs( m12 ) < 0.99999 ) {
  6184. this._x = Math.atan2( m32, m22 );
  6185. this._y = Math.atan2( m13, m11 );
  6186. } else {
  6187. this._x = Math.atan2( - m23, m33 );
  6188. this._y = 0;
  6189. }
  6190. } else {
  6191. console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order );
  6192. }
  6193. this._order = order;
  6194. if ( update !== false ) this.onChangeCallback();
  6195. return this;
  6196. },
  6197. setFromQuaternion: function () {
  6198. var matrix;
  6199. return function setFromQuaternion( q, order, update ) {
  6200. if ( matrix === undefined ) matrix = new Matrix4();
  6201. matrix.makeRotationFromQuaternion( q );
  6202. return this.setFromRotationMatrix( matrix, order, update );
  6203. };
  6204. }(),
  6205. setFromVector3: function ( v, order ) {
  6206. return this.set( v.x, v.y, v.z, order || this._order );
  6207. },
  6208. reorder: function () {
  6209. // WARNING: this discards revolution information -bhouston
  6210. var q = new Quaternion();
  6211. return function reorder( newOrder ) {
  6212. q.setFromEuler( this );
  6213. return this.setFromQuaternion( q, newOrder );
  6214. };
  6215. }(),
  6216. equals: function ( euler ) {
  6217. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  6218. },
  6219. fromArray: function ( array ) {
  6220. this._x = array[ 0 ];
  6221. this._y = array[ 1 ];
  6222. this._z = array[ 2 ];
  6223. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  6224. this.onChangeCallback();
  6225. return this;
  6226. },
  6227. toArray: function ( array, offset ) {
  6228. if ( array === undefined ) array = [];
  6229. if ( offset === undefined ) offset = 0;
  6230. array[ offset ] = this._x;
  6231. array[ offset + 1 ] = this._y;
  6232. array[ offset + 2 ] = this._z;
  6233. array[ offset + 3 ] = this._order;
  6234. return array;
  6235. },
  6236. toVector3: function ( optionalResult ) {
  6237. if ( optionalResult ) {
  6238. return optionalResult.set( this._x, this._y, this._z );
  6239. } else {
  6240. return new Vector3( this._x, this._y, this._z );
  6241. }
  6242. },
  6243. onChange: function ( callback ) {
  6244. this.onChangeCallback = callback;
  6245. return this;
  6246. },
  6247. onChangeCallback: function () {}
  6248. };
  6249. /**
  6250. * @author mrdoob / http://mrdoob.com/
  6251. */
  6252. function Layers() {
  6253. this.mask = 1;
  6254. }
  6255. Layers.prototype = {
  6256. constructor: Layers,
  6257. set: function ( channel ) {
  6258. this.mask = 1 << channel;
  6259. },
  6260. enable: function ( channel ) {
  6261. this.mask |= 1 << channel;
  6262. },
  6263. toggle: function ( channel ) {
  6264. this.mask ^= 1 << channel;
  6265. },
  6266. disable: function ( channel ) {
  6267. this.mask &= ~ ( 1 << channel );
  6268. },
  6269. test: function ( layers ) {
  6270. return ( this.mask & layers.mask ) !== 0;
  6271. }
  6272. };
  6273. /**
  6274. * @author mrdoob / http://mrdoob.com/
  6275. * @author mikael emtinger / http://gomo.se/
  6276. * @author alteredq / http://alteredqualia.com/
  6277. * @author WestLangley / http://github.com/WestLangley
  6278. * @author elephantatwork / www.elephantatwork.ch
  6279. */
  6280. function Object3D() {
  6281. Object.defineProperty( this, 'id', { value: Object3DIdCount() } );
  6282. this.uuid = exports.Math.generateUUID();
  6283. this.name = '';
  6284. this.type = 'Object3D';
  6285. this.parent = null;
  6286. this.children = [];
  6287. this.up = Object3D.DefaultUp.clone();
  6288. var position = new Vector3();
  6289. var rotation = new Euler();
  6290. var quaternion = new Quaternion();
  6291. var scale = new Vector3( 1, 1, 1 );
  6292. function onRotationChange() {
  6293. quaternion.setFromEuler( rotation, false );
  6294. }
  6295. function onQuaternionChange() {
  6296. rotation.setFromQuaternion( quaternion, undefined, false );
  6297. }
  6298. rotation.onChange( onRotationChange );
  6299. quaternion.onChange( onQuaternionChange );
  6300. Object.defineProperties( this, {
  6301. position: {
  6302. enumerable: true,
  6303. value: position
  6304. },
  6305. rotation: {
  6306. enumerable: true,
  6307. value: rotation
  6308. },
  6309. quaternion: {
  6310. enumerable: true,
  6311. value: quaternion
  6312. },
  6313. scale: {
  6314. enumerable: true,
  6315. value: scale
  6316. },
  6317. modelViewMatrix: {
  6318. value: new Matrix4()
  6319. },
  6320. normalMatrix: {
  6321. value: new Matrix3()
  6322. }
  6323. } );
  6324. this.matrix = new Matrix4();
  6325. this.matrixWorld = new Matrix4();
  6326. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  6327. this.matrixWorldNeedsUpdate = false;
  6328. this.layers = new Layers();
  6329. this.visible = true;
  6330. this.castShadow = false;
  6331. this.receiveShadow = false;
  6332. this.frustumCulled = true;
  6333. this.renderOrder = 0;
  6334. this.userData = {};
  6335. }
  6336. Object3D.DefaultUp = new Vector3( 0, 1, 0 );
  6337. Object3D.DefaultMatrixAutoUpdate = true;
  6338. Object.assign( Object3D.prototype, EventDispatcher.prototype, {
  6339. isObject3D: true,
  6340. applyMatrix: function ( matrix ) {
  6341. this.matrix.multiplyMatrices( matrix, this.matrix );
  6342. this.matrix.decompose( this.position, this.quaternion, this.scale );
  6343. },
  6344. setRotationFromAxisAngle: function ( axis, angle ) {
  6345. // assumes axis is normalized
  6346. this.quaternion.setFromAxisAngle( axis, angle );
  6347. },
  6348. setRotationFromEuler: function ( euler ) {
  6349. this.quaternion.setFromEuler( euler, true );
  6350. },
  6351. setRotationFromMatrix: function ( m ) {
  6352. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6353. this.quaternion.setFromRotationMatrix( m );
  6354. },
  6355. setRotationFromQuaternion: function ( q ) {
  6356. // assumes q is normalized
  6357. this.quaternion.copy( q );
  6358. },
  6359. rotateOnAxis: function () {
  6360. // rotate object on axis in object space
  6361. // axis is assumed to be normalized
  6362. var q1 = new Quaternion();
  6363. return function rotateOnAxis( axis, angle ) {
  6364. q1.setFromAxisAngle( axis, angle );
  6365. this.quaternion.multiply( q1 );
  6366. return this;
  6367. };
  6368. }(),
  6369. rotateX: function () {
  6370. var v1 = new Vector3( 1, 0, 0 );
  6371. return function rotateX( angle ) {
  6372. return this.rotateOnAxis( v1, angle );
  6373. };
  6374. }(),
  6375. rotateY: function () {
  6376. var v1 = new Vector3( 0, 1, 0 );
  6377. return function rotateY( angle ) {
  6378. return this.rotateOnAxis( v1, angle );
  6379. };
  6380. }(),
  6381. rotateZ: function () {
  6382. var v1 = new Vector3( 0, 0, 1 );
  6383. return function rotateZ( angle ) {
  6384. return this.rotateOnAxis( v1, angle );
  6385. };
  6386. }(),
  6387. translateOnAxis: function () {
  6388. // translate object by distance along axis in object space
  6389. // axis is assumed to be normalized
  6390. var v1 = new Vector3();
  6391. return function translateOnAxis( axis, distance ) {
  6392. v1.copy( axis ).applyQuaternion( this.quaternion );
  6393. this.position.add( v1.multiplyScalar( distance ) );
  6394. return this;
  6395. };
  6396. }(),
  6397. translateX: function () {
  6398. var v1 = new Vector3( 1, 0, 0 );
  6399. return function translateX( distance ) {
  6400. return this.translateOnAxis( v1, distance );
  6401. };
  6402. }(),
  6403. translateY: function () {
  6404. var v1 = new Vector3( 0, 1, 0 );
  6405. return function translateY( distance ) {
  6406. return this.translateOnAxis( v1, distance );
  6407. };
  6408. }(),
  6409. translateZ: function () {
  6410. var v1 = new Vector3( 0, 0, 1 );
  6411. return function translateZ( distance ) {
  6412. return this.translateOnAxis( v1, distance );
  6413. };
  6414. }(),
  6415. localToWorld: function ( vector ) {
  6416. return vector.applyMatrix4( this.matrixWorld );
  6417. },
  6418. worldToLocal: function () {
  6419. var m1 = new Matrix4();
  6420. return function worldToLocal( vector ) {
  6421. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  6422. };
  6423. }(),
  6424. lookAt: function () {
  6425. // This routine does not support objects with rotated and/or translated parent(s)
  6426. var m1 = new Matrix4();
  6427. return function lookAt( vector ) {
  6428. m1.lookAt( vector, this.position, this.up );
  6429. this.quaternion.setFromRotationMatrix( m1 );
  6430. };
  6431. }(),
  6432. add: function ( object ) {
  6433. if ( arguments.length > 1 ) {
  6434. for ( var i = 0; i < arguments.length; i ++ ) {
  6435. this.add( arguments[ i ] );
  6436. }
  6437. return this;
  6438. }
  6439. if ( object === this ) {
  6440. console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object );
  6441. return this;
  6442. }
  6443. if ( (object && object.isObject3D) ) {
  6444. if ( object.parent !== null ) {
  6445. object.parent.remove( object );
  6446. }
  6447. object.parent = this;
  6448. object.dispatchEvent( { type: 'added' } );
  6449. this.children.push( object );
  6450. } else {
  6451. console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object );
  6452. }
  6453. return this;
  6454. },
  6455. remove: function ( object ) {
  6456. if ( arguments.length > 1 ) {
  6457. for ( var i = 0; i < arguments.length; i ++ ) {
  6458. this.remove( arguments[ i ] );
  6459. }
  6460. }
  6461. var index = this.children.indexOf( object );
  6462. if ( index !== - 1 ) {
  6463. object.parent = null;
  6464. object.dispatchEvent( { type: 'removed' } );
  6465. this.children.splice( index, 1 );
  6466. }
  6467. },
  6468. getObjectById: function ( id ) {
  6469. return this.getObjectByProperty( 'id', id );
  6470. },
  6471. getObjectByName: function ( name ) {
  6472. return this.getObjectByProperty( 'name', name );
  6473. },
  6474. getObjectByProperty: function ( name, value ) {
  6475. if ( this[ name ] === value ) return this;
  6476. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  6477. var child = this.children[ i ];
  6478. var object = child.getObjectByProperty( name, value );
  6479. if ( object !== undefined ) {
  6480. return object;
  6481. }
  6482. }
  6483. return undefined;
  6484. },
  6485. getWorldPosition: function ( optionalTarget ) {
  6486. var result = optionalTarget || new Vector3();
  6487. this.updateMatrixWorld( true );
  6488. return result.setFromMatrixPosition( this.matrixWorld );
  6489. },
  6490. getWorldQuaternion: function () {
  6491. var position = new Vector3();
  6492. var scale = new Vector3();
  6493. return function getWorldQuaternion( optionalTarget ) {
  6494. var result = optionalTarget || new Quaternion();
  6495. this.updateMatrixWorld( true );
  6496. this.matrixWorld.decompose( position, result, scale );
  6497. return result;
  6498. };
  6499. }(),
  6500. getWorldRotation: function () {
  6501. var quaternion = new Quaternion();
  6502. return function getWorldRotation( optionalTarget ) {
  6503. var result = optionalTarget || new Euler();
  6504. this.getWorldQuaternion( quaternion );
  6505. return result.setFromQuaternion( quaternion, this.rotation.order, false );
  6506. };
  6507. }(),
  6508. getWorldScale: function () {
  6509. var position = new Vector3();
  6510. var quaternion = new Quaternion();
  6511. return function getWorldScale( optionalTarget ) {
  6512. var result = optionalTarget || new Vector3();
  6513. this.updateMatrixWorld( true );
  6514. this.matrixWorld.decompose( position, quaternion, result );
  6515. return result;
  6516. };
  6517. }(),
  6518. getWorldDirection: function () {
  6519. var quaternion = new Quaternion();
  6520. return function getWorldDirection( optionalTarget ) {
  6521. var result = optionalTarget || new Vector3();
  6522. this.getWorldQuaternion( quaternion );
  6523. return result.set( 0, 0, 1 ).applyQuaternion( quaternion );
  6524. };
  6525. }(),
  6526. raycast: function () {},
  6527. traverse: function ( callback ) {
  6528. callback( this );
  6529. var children = this.children;
  6530. for ( var i = 0, l = children.length; i < l; i ++ ) {
  6531. children[ i ].traverse( callback );
  6532. }
  6533. },
  6534. traverseVisible: function ( callback ) {
  6535. if ( this.visible === false ) return;
  6536. callback( this );
  6537. var children = this.children;
  6538. for ( var i = 0, l = children.length; i < l; i ++ ) {
  6539. children[ i ].traverseVisible( callback );
  6540. }
  6541. },
  6542. traverseAncestors: function ( callback ) {
  6543. var parent = this.parent;
  6544. if ( parent !== null ) {
  6545. callback( parent );
  6546. parent.traverseAncestors( callback );
  6547. }
  6548. },
  6549. updateMatrix: function () {
  6550. this.matrix.compose( this.position, this.quaternion, this.scale );
  6551. this.matrixWorldNeedsUpdate = true;
  6552. },
  6553. updateMatrixWorld: function ( force ) {
  6554. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  6555. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  6556. if ( this.parent === null ) {
  6557. this.matrixWorld.copy( this.matrix );
  6558. } else {
  6559. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  6560. }
  6561. this.matrixWorldNeedsUpdate = false;
  6562. force = true;
  6563. }
  6564. // update children
  6565. var children = this.children;
  6566. for ( var i = 0, l = children.length; i < l; i ++ ) {
  6567. children[ i ].updateMatrixWorld( force );
  6568. }
  6569. },
  6570. toJSON: function ( meta ) {
  6571. // meta is '' when called from JSON.stringify
  6572. var isRootObject = ( meta === undefined || meta === '' );
  6573. var output = {};
  6574. // meta is a hash used to collect geometries, materials.
  6575. // not providing it implies that this is the root object
  6576. // being serialized.
  6577. if ( isRootObject ) {
  6578. // initialize meta obj
  6579. meta = {
  6580. geometries: {},
  6581. materials: {},
  6582. textures: {},
  6583. images: {}
  6584. };
  6585. output.metadata = {
  6586. version: 4.4,
  6587. type: 'Object',
  6588. generator: 'Object3D.toJSON'
  6589. };
  6590. }
  6591. // standard Object3D serialization
  6592. var object = {};
  6593. object.uuid = this.uuid;
  6594. object.type = this.type;
  6595. if ( this.name !== '' ) object.name = this.name;
  6596. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  6597. if ( this.castShadow === true ) object.castShadow = true;
  6598. if ( this.receiveShadow === true ) object.receiveShadow = true;
  6599. if ( this.visible === false ) object.visible = false;
  6600. object.matrix = this.matrix.toArray();
  6601. //
  6602. if ( this.geometry !== undefined ) {
  6603. if ( meta.geometries[ this.geometry.uuid ] === undefined ) {
  6604. meta.geometries[ this.geometry.uuid ] = this.geometry.toJSON( meta );
  6605. }
  6606. object.geometry = this.geometry.uuid;
  6607. }
  6608. if ( this.material !== undefined ) {
  6609. if ( meta.materials[ this.material.uuid ] === undefined ) {
  6610. meta.materials[ this.material.uuid ] = this.material.toJSON( meta );
  6611. }
  6612. object.material = this.material.uuid;
  6613. }
  6614. //
  6615. if ( this.children.length > 0 ) {
  6616. object.children = [];
  6617. for ( var i = 0; i < this.children.length; i ++ ) {
  6618. object.children.push( this.children[ i ].toJSON( meta ).object );
  6619. }
  6620. }
  6621. if ( isRootObject ) {
  6622. var geometries = extractFromCache( meta.geometries );
  6623. var materials = extractFromCache( meta.materials );
  6624. var textures = extractFromCache( meta.textures );
  6625. var images = extractFromCache( meta.images );
  6626. if ( geometries.length > 0 ) output.geometries = geometries;
  6627. if ( materials.length > 0 ) output.materials = materials;
  6628. if ( textures.length > 0 ) output.textures = textures;
  6629. if ( images.length > 0 ) output.images = images;
  6630. }
  6631. output.object = object;
  6632. return output;
  6633. // extract data from the cache hash
  6634. // remove metadata on each item
  6635. // and return as array
  6636. function extractFromCache( cache ) {
  6637. var values = [];
  6638. for ( var key in cache ) {
  6639. var data = cache[ key ];
  6640. delete data.metadata;
  6641. values.push( data );
  6642. }
  6643. return values;
  6644. }
  6645. },
  6646. clone: function ( recursive ) {
  6647. return new this.constructor().copy( this, recursive );
  6648. },
  6649. copy: function ( source, recursive ) {
  6650. if ( recursive === undefined ) recursive = true;
  6651. this.name = source.name;
  6652. this.up.copy( source.up );
  6653. this.position.copy( source.position );
  6654. this.quaternion.copy( source.quaternion );
  6655. this.scale.copy( source.scale );
  6656. this.matrix.copy( source.matrix );
  6657. this.matrixWorld.copy( source.matrixWorld );
  6658. this.matrixAutoUpdate = source.matrixAutoUpdate;
  6659. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  6660. this.visible = source.visible;
  6661. this.castShadow = source.castShadow;
  6662. this.receiveShadow = source.receiveShadow;
  6663. this.frustumCulled = source.frustumCulled;
  6664. this.renderOrder = source.renderOrder;
  6665. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  6666. if ( recursive === true ) {
  6667. for ( var i = 0; i < source.children.length; i ++ ) {
  6668. var child = source.children[ i ];
  6669. this.add( child.clone() );
  6670. }
  6671. }
  6672. return this;
  6673. }
  6674. } );
  6675. var count$3 = 0;
  6676. function Object3DIdCount() { return count$3++; };
  6677. /**
  6678. * @author mrdoob / http://mrdoob.com/
  6679. * @author kile / http://kile.stravaganza.org/
  6680. * @author alteredq / http://alteredqualia.com/
  6681. * @author mikael emtinger / http://gomo.se/
  6682. * @author zz85 / http://www.lab4games.net/zz85/blog
  6683. * @author bhouston / http://clara.io
  6684. */
  6685. function Geometry() {
  6686. Object.defineProperty( this, 'id', { value: GeometryIdCount() } );
  6687. this.uuid = exports.Math.generateUUID();
  6688. this.name = '';
  6689. this.type = 'Geometry';
  6690. this.vertices = [];
  6691. this.colors = [];
  6692. this.faces = [];
  6693. this.faceVertexUvs = [ [] ];
  6694. this.morphTargets = [];
  6695. this.morphNormals = [];
  6696. this.skinWeights = [];
  6697. this.skinIndices = [];
  6698. this.lineDistances = [];
  6699. this.boundingBox = null;
  6700. this.boundingSphere = null;
  6701. // update flags
  6702. this.elementsNeedUpdate = false;
  6703. this.verticesNeedUpdate = false;
  6704. this.uvsNeedUpdate = false;
  6705. this.normalsNeedUpdate = false;
  6706. this.colorsNeedUpdate = false;
  6707. this.lineDistancesNeedUpdate = false;
  6708. this.groupsNeedUpdate = false;
  6709. }
  6710. Object.assign( Geometry.prototype, EventDispatcher.prototype, {
  6711. isGeometry: true,
  6712. applyMatrix: function ( matrix ) {
  6713. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  6714. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  6715. var vertex = this.vertices[ i ];
  6716. vertex.applyMatrix4( matrix );
  6717. }
  6718. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  6719. var face = this.faces[ i ];
  6720. face.normal.applyMatrix3( normalMatrix ).normalize();
  6721. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  6722. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  6723. }
  6724. }
  6725. if ( this.boundingBox !== null ) {
  6726. this.computeBoundingBox();
  6727. }
  6728. if ( this.boundingSphere !== null ) {
  6729. this.computeBoundingSphere();
  6730. }
  6731. this.verticesNeedUpdate = true;
  6732. this.normalsNeedUpdate = true;
  6733. return this;
  6734. },
  6735. rotateX: function () {
  6736. // rotate geometry around world x-axis
  6737. var m1;
  6738. return function rotateX( angle ) {
  6739. if ( m1 === undefined ) m1 = new Matrix4();
  6740. m1.makeRotationX( angle );
  6741. this.applyMatrix( m1 );
  6742. return this;
  6743. };
  6744. }(),
  6745. rotateY: function () {
  6746. // rotate geometry around world y-axis
  6747. var m1;
  6748. return function rotateY( angle ) {
  6749. if ( m1 === undefined ) m1 = new Matrix4();
  6750. m1.makeRotationY( angle );
  6751. this.applyMatrix( m1 );
  6752. return this;
  6753. };
  6754. }(),
  6755. rotateZ: function () {
  6756. // rotate geometry around world z-axis
  6757. var m1;
  6758. return function rotateZ( angle ) {
  6759. if ( m1 === undefined ) m1 = new Matrix4();
  6760. m1.makeRotationZ( angle );
  6761. this.applyMatrix( m1 );
  6762. return this;
  6763. };
  6764. }(),
  6765. translate: function () {
  6766. // translate geometry
  6767. var m1;
  6768. return function translate( x, y, z ) {
  6769. if ( m1 === undefined ) m1 = new Matrix4();
  6770. m1.makeTranslation( x, y, z );
  6771. this.applyMatrix( m1 );
  6772. return this;
  6773. };
  6774. }(),
  6775. scale: function () {
  6776. // scale geometry
  6777. var m1;
  6778. return function scale( x, y, z ) {
  6779. if ( m1 === undefined ) m1 = new Matrix4();
  6780. m1.makeScale( x, y, z );
  6781. this.applyMatrix( m1 );
  6782. return this;
  6783. };
  6784. }(),
  6785. lookAt: function () {
  6786. var obj;
  6787. return function lookAt( vector ) {
  6788. if ( obj === undefined ) obj = new Object3D();
  6789. obj.lookAt( vector );
  6790. obj.updateMatrix();
  6791. this.applyMatrix( obj.matrix );
  6792. };
  6793. }(),
  6794. fromBufferGeometry: function ( geometry ) {
  6795. var scope = this;
  6796. var indices = geometry.index !== null ? geometry.index.array : undefined;
  6797. var attributes = geometry.attributes;
  6798. var positions = attributes.position.array;
  6799. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  6800. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  6801. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  6802. var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;
  6803. if ( uvs2 !== undefined ) this.faceVertexUvs[ 1 ] = [];
  6804. var tempNormals = [];
  6805. var tempUVs = [];
  6806. var tempUVs2 = [];
  6807. for ( var i = 0, j = 0; i < positions.length; i += 3, j += 2 ) {
  6808. scope.vertices.push( new Vector3( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ) );
  6809. if ( normals !== undefined ) {
  6810. tempNormals.push( new Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) );
  6811. }
  6812. if ( colors !== undefined ) {
  6813. scope.colors.push( new Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) );
  6814. }
  6815. if ( uvs !== undefined ) {
  6816. tempUVs.push( new Vector2( uvs[ j ], uvs[ j + 1 ] ) );
  6817. }
  6818. if ( uvs2 !== undefined ) {
  6819. tempUVs2.push( new Vector2( uvs2[ j ], uvs2[ j + 1 ] ) );
  6820. }
  6821. }
  6822. function addFace( a, b, c, materialIndex ) {
  6823. var vertexNormals = normals !== undefined ? [ tempNormals[ a ].clone(), tempNormals[ b ].clone(), tempNormals[ c ].clone() ] : [];
  6824. var vertexColors = colors !== undefined ? [ scope.colors[ a ].clone(), scope.colors[ b ].clone(), scope.colors[ c ].clone() ] : [];
  6825. var face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex );
  6826. scope.faces.push( face );
  6827. if ( uvs !== undefined ) {
  6828. scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] );
  6829. }
  6830. if ( uvs2 !== undefined ) {
  6831. scope.faceVertexUvs[ 1 ].push( [ tempUVs2[ a ].clone(), tempUVs2[ b ].clone(), tempUVs2[ c ].clone() ] );
  6832. }
  6833. }
  6834. if ( indices !== undefined ) {
  6835. var groups = geometry.groups;
  6836. if ( groups.length > 0 ) {
  6837. for ( var i = 0; i < groups.length; i ++ ) {
  6838. var group = groups[ i ];
  6839. var start = group.start;
  6840. var count = group.count;
  6841. for ( var j = start, jl = start + count; j < jl; j += 3 ) {
  6842. addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ], group.materialIndex );
  6843. }
  6844. }
  6845. } else {
  6846. for ( var i = 0; i < indices.length; i += 3 ) {
  6847. addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  6848. }
  6849. }
  6850. } else {
  6851. for ( var i = 0; i < positions.length / 3; i += 3 ) {
  6852. addFace( i, i + 1, i + 2 );
  6853. }
  6854. }
  6855. this.computeFaceNormals();
  6856. if ( geometry.boundingBox !== null ) {
  6857. this.boundingBox = geometry.boundingBox.clone();
  6858. }
  6859. if ( geometry.boundingSphere !== null ) {
  6860. this.boundingSphere = geometry.boundingSphere.clone();
  6861. }
  6862. return this;
  6863. },
  6864. center: function () {
  6865. this.computeBoundingBox();
  6866. var offset = this.boundingBox.center().negate();
  6867. this.translate( offset.x, offset.y, offset.z );
  6868. return offset;
  6869. },
  6870. normalize: function () {
  6871. this.computeBoundingSphere();
  6872. var center = this.boundingSphere.center;
  6873. var radius = this.boundingSphere.radius;
  6874. var s = radius === 0 ? 1 : 1.0 / radius;
  6875. var matrix = new Matrix4();
  6876. matrix.set(
  6877. s, 0, 0, - s * center.x,
  6878. 0, s, 0, - s * center.y,
  6879. 0, 0, s, - s * center.z,
  6880. 0, 0, 0, 1
  6881. );
  6882. this.applyMatrix( matrix );
  6883. return this;
  6884. },
  6885. computeFaceNormals: function () {
  6886. var cb = new Vector3(), ab = new Vector3();
  6887. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6888. var face = this.faces[ f ];
  6889. var vA = this.vertices[ face.a ];
  6890. var vB = this.vertices[ face.b ];
  6891. var vC = this.vertices[ face.c ];
  6892. cb.subVectors( vC, vB );
  6893. ab.subVectors( vA, vB );
  6894. cb.cross( ab );
  6895. cb.normalize();
  6896. face.normal.copy( cb );
  6897. }
  6898. },
  6899. computeVertexNormals: function ( areaWeighted ) {
  6900. if ( areaWeighted === undefined ) areaWeighted = true;
  6901. var v, vl, f, fl, face, vertices;
  6902. vertices = new Array( this.vertices.length );
  6903. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  6904. vertices[ v ] = new Vector3();
  6905. }
  6906. if ( areaWeighted ) {
  6907. // vertex normals weighted by triangle areas
  6908. // http://www.iquilezles.org/www/articles/normals/normals.htm
  6909. var vA, vB, vC;
  6910. var cb = new Vector3(), ab = new Vector3();
  6911. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6912. face = this.faces[ f ];
  6913. vA = this.vertices[ face.a ];
  6914. vB = this.vertices[ face.b ];
  6915. vC = this.vertices[ face.c ];
  6916. cb.subVectors( vC, vB );
  6917. ab.subVectors( vA, vB );
  6918. cb.cross( ab );
  6919. vertices[ face.a ].add( cb );
  6920. vertices[ face.b ].add( cb );
  6921. vertices[ face.c ].add( cb );
  6922. }
  6923. } else {
  6924. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6925. face = this.faces[ f ];
  6926. vertices[ face.a ].add( face.normal );
  6927. vertices[ face.b ].add( face.normal );
  6928. vertices[ face.c ].add( face.normal );
  6929. }
  6930. }
  6931. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  6932. vertices[ v ].normalize();
  6933. }
  6934. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6935. face = this.faces[ f ];
  6936. var vertexNormals = face.vertexNormals;
  6937. if ( vertexNormals.length === 3 ) {
  6938. vertexNormals[ 0 ].copy( vertices[ face.a ] );
  6939. vertexNormals[ 1 ].copy( vertices[ face.b ] );
  6940. vertexNormals[ 2 ].copy( vertices[ face.c ] );
  6941. } else {
  6942. vertexNormals[ 0 ] = vertices[ face.a ].clone();
  6943. vertexNormals[ 1 ] = vertices[ face.b ].clone();
  6944. vertexNormals[ 2 ] = vertices[ face.c ].clone();
  6945. }
  6946. }
  6947. if ( this.faces.length > 0 ) {
  6948. this.normalsNeedUpdate = true;
  6949. }
  6950. },
  6951. computeMorphNormals: function () {
  6952. var i, il, f, fl, face;
  6953. // save original normals
  6954. // - create temp variables on first access
  6955. // otherwise just copy (for faster repeated calls)
  6956. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6957. face = this.faces[ f ];
  6958. if ( ! face.__originalFaceNormal ) {
  6959. face.__originalFaceNormal = face.normal.clone();
  6960. } else {
  6961. face.__originalFaceNormal.copy( face.normal );
  6962. }
  6963. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  6964. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  6965. if ( ! face.__originalVertexNormals[ i ] ) {
  6966. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  6967. } else {
  6968. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  6969. }
  6970. }
  6971. }
  6972. // use temp geometry to compute face and vertex normals for each morph
  6973. var tmpGeo = new Geometry();
  6974. tmpGeo.faces = this.faces;
  6975. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  6976. // create on first access
  6977. if ( ! this.morphNormals[ i ] ) {
  6978. this.morphNormals[ i ] = {};
  6979. this.morphNormals[ i ].faceNormals = [];
  6980. this.morphNormals[ i ].vertexNormals = [];
  6981. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  6982. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  6983. var faceNormal, vertexNormals;
  6984. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6985. faceNormal = new Vector3();
  6986. vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() };
  6987. dstNormalsFace.push( faceNormal );
  6988. dstNormalsVertex.push( vertexNormals );
  6989. }
  6990. }
  6991. var morphNormals = this.morphNormals[ i ];
  6992. // set vertices to morph target
  6993. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  6994. // compute morph normals
  6995. tmpGeo.computeFaceNormals();
  6996. tmpGeo.computeVertexNormals();
  6997. // store morph normals
  6998. var faceNormal, vertexNormals;
  6999. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7000. face = this.faces[ f ];
  7001. faceNormal = morphNormals.faceNormals[ f ];
  7002. vertexNormals = morphNormals.vertexNormals[ f ];
  7003. faceNormal.copy( face.normal );
  7004. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  7005. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  7006. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  7007. }
  7008. }
  7009. // restore original normals
  7010. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7011. face = this.faces[ f ];
  7012. face.normal = face.__originalFaceNormal;
  7013. face.vertexNormals = face.__originalVertexNormals;
  7014. }
  7015. },
  7016. computeTangents: function () {
  7017. console.warn( 'THREE.Geometry: .computeTangents() has been removed.' );
  7018. },
  7019. computeLineDistances: function () {
  7020. var d = 0;
  7021. var vertices = this.vertices;
  7022. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  7023. if ( i > 0 ) {
  7024. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  7025. }
  7026. this.lineDistances[ i ] = d;
  7027. }
  7028. },
  7029. computeBoundingBox: function () {
  7030. if ( this.boundingBox === null ) {
  7031. this.boundingBox = new Box3();
  7032. }
  7033. this.boundingBox.setFromPoints( this.vertices );
  7034. },
  7035. computeBoundingSphere: function () {
  7036. if ( this.boundingSphere === null ) {
  7037. this.boundingSphere = new Sphere();
  7038. }
  7039. this.boundingSphere.setFromPoints( this.vertices );
  7040. },
  7041. merge: function ( geometry, matrix, materialIndexOffset ) {
  7042. if ( (geometry && geometry.isGeometry) === false ) {
  7043. console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  7044. return;
  7045. }
  7046. var normalMatrix,
  7047. vertexOffset = this.vertices.length,
  7048. vertices1 = this.vertices,
  7049. vertices2 = geometry.vertices,
  7050. faces1 = this.faces,
  7051. faces2 = geometry.faces,
  7052. uvs1 = this.faceVertexUvs[ 0 ],
  7053. uvs2 = geometry.faceVertexUvs[ 0 ],
  7054. colors1 = this.colors,
  7055. colors2 = geometry.colors;
  7056. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  7057. if ( matrix !== undefined ) {
  7058. normalMatrix = new Matrix3().getNormalMatrix( matrix );
  7059. }
  7060. // vertices
  7061. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  7062. var vertex = vertices2[ i ];
  7063. var vertexCopy = vertex.clone();
  7064. if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
  7065. vertices1.push( vertexCopy );
  7066. }
  7067. // colors
  7068. for ( var i = 0, il = colors2.length; i < il; i ++ ) {
  7069. colors1.push( colors2[ i ].clone() );
  7070. }
  7071. // faces
  7072. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  7073. var face = faces2[ i ], faceCopy, normal, color,
  7074. faceVertexNormals = face.vertexNormals,
  7075. faceVertexColors = face.vertexColors;
  7076. faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  7077. faceCopy.normal.copy( face.normal );
  7078. if ( normalMatrix !== undefined ) {
  7079. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  7080. }
  7081. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  7082. normal = faceVertexNormals[ j ].clone();
  7083. if ( normalMatrix !== undefined ) {
  7084. normal.applyMatrix3( normalMatrix ).normalize();
  7085. }
  7086. faceCopy.vertexNormals.push( normal );
  7087. }
  7088. faceCopy.color.copy( face.color );
  7089. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  7090. color = faceVertexColors[ j ];
  7091. faceCopy.vertexColors.push( color.clone() );
  7092. }
  7093. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  7094. faces1.push( faceCopy );
  7095. }
  7096. // uvs
  7097. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  7098. var uv = uvs2[ i ], uvCopy = [];
  7099. if ( uv === undefined ) {
  7100. continue;
  7101. }
  7102. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  7103. uvCopy.push( uv[ j ].clone() );
  7104. }
  7105. uvs1.push( uvCopy );
  7106. }
  7107. },
  7108. mergeMesh: function ( mesh ) {
  7109. if ( (mesh && mesh.isMesh) === false ) {
  7110. console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
  7111. return;
  7112. }
  7113. mesh.matrixAutoUpdate && mesh.updateMatrix();
  7114. this.merge( mesh.geometry, mesh.matrix );
  7115. },
  7116. /*
  7117. * Checks for duplicate vertices with hashmap.
  7118. * Duplicated vertices are removed
  7119. * and faces' vertices are updated.
  7120. */
  7121. mergeVertices: function () {
  7122. var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  7123. var unique = [], changes = [];
  7124. var v, key;
  7125. var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
  7126. var precision = Math.pow( 10, precisionPoints );
  7127. var i, il, face;
  7128. var indices, j, jl;
  7129. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  7130. v = this.vertices[ i ];
  7131. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  7132. if ( verticesMap[ key ] === undefined ) {
  7133. verticesMap[ key ] = i;
  7134. unique.push( this.vertices[ i ] );
  7135. changes[ i ] = unique.length - 1;
  7136. } else {
  7137. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  7138. changes[ i ] = changes[ verticesMap[ key ] ];
  7139. }
  7140. }
  7141. // if faces are completely degenerate after merging vertices, we
  7142. // have to remove them from the geometry.
  7143. var faceIndicesToRemove = [];
  7144. for ( i = 0, il = this.faces.length; i < il; i ++ ) {
  7145. face = this.faces[ i ];
  7146. face.a = changes[ face.a ];
  7147. face.b = changes[ face.b ];
  7148. face.c = changes[ face.c ];
  7149. indices = [ face.a, face.b, face.c ];
  7150. var dupIndex = - 1;
  7151. // if any duplicate vertices are found in a Face3
  7152. // we have to remove the face as nothing can be saved
  7153. for ( var n = 0; n < 3; n ++ ) {
  7154. if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) {
  7155. dupIndex = n;
  7156. faceIndicesToRemove.push( i );
  7157. break;
  7158. }
  7159. }
  7160. }
  7161. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  7162. var idx = faceIndicesToRemove[ i ];
  7163. this.faces.splice( idx, 1 );
  7164. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  7165. this.faceVertexUvs[ j ].splice( idx, 1 );
  7166. }
  7167. }
  7168. // Use unique set of vertices
  7169. var diff = this.vertices.length - unique.length;
  7170. this.vertices = unique;
  7171. return diff;
  7172. },
  7173. sortFacesByMaterialIndex: function () {
  7174. var faces = this.faces;
  7175. var length = faces.length;
  7176. // tag faces
  7177. for ( var i = 0; i < length; i ++ ) {
  7178. faces[ i ]._id = i;
  7179. }
  7180. // sort faces
  7181. function materialIndexSort( a, b ) {
  7182. return a.materialIndex - b.materialIndex;
  7183. }
  7184. faces.sort( materialIndexSort );
  7185. // sort uvs
  7186. var uvs1 = this.faceVertexUvs[ 0 ];
  7187. var uvs2 = this.faceVertexUvs[ 1 ];
  7188. var newUvs1, newUvs2;
  7189. if ( uvs1 && uvs1.length === length ) newUvs1 = [];
  7190. if ( uvs2 && uvs2.length === length ) newUvs2 = [];
  7191. for ( var i = 0; i < length; i ++ ) {
  7192. var id = faces[ i ]._id;
  7193. if ( newUvs1 ) newUvs1.push( uvs1[ id ] );
  7194. if ( newUvs2 ) newUvs2.push( uvs2[ id ] );
  7195. }
  7196. if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1;
  7197. if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2;
  7198. },
  7199. toJSON: function () {
  7200. var data = {
  7201. metadata: {
  7202. version: 4.4,
  7203. type: 'Geometry',
  7204. generator: 'Geometry.toJSON'
  7205. }
  7206. };
  7207. // standard Geometry serialization
  7208. data.uuid = this.uuid;
  7209. data.type = this.type;
  7210. if ( this.name !== '' ) data.name = this.name;
  7211. if ( this.parameters !== undefined ) {
  7212. var parameters = this.parameters;
  7213. for ( var key in parameters ) {
  7214. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  7215. }
  7216. return data;
  7217. }
  7218. var vertices = [];
  7219. for ( var i = 0; i < this.vertices.length; i ++ ) {
  7220. var vertex = this.vertices[ i ];
  7221. vertices.push( vertex.x, vertex.y, vertex.z );
  7222. }
  7223. var faces = [];
  7224. var normals = [];
  7225. var normalsHash = {};
  7226. var colors = [];
  7227. var colorsHash = {};
  7228. var uvs = [];
  7229. var uvsHash = {};
  7230. for ( var i = 0; i < this.faces.length; i ++ ) {
  7231. var face = this.faces[ i ];
  7232. var hasMaterial = true;
  7233. var hasFaceUv = false; // deprecated
  7234. var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined;
  7235. var hasFaceNormal = face.normal.length() > 0;
  7236. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  7237. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  7238. var hasFaceVertexColor = face.vertexColors.length > 0;
  7239. var faceType = 0;
  7240. faceType = setBit( faceType, 0, 0 ); // isQuad
  7241. faceType = setBit( faceType, 1, hasMaterial );
  7242. faceType = setBit( faceType, 2, hasFaceUv );
  7243. faceType = setBit( faceType, 3, hasFaceVertexUv );
  7244. faceType = setBit( faceType, 4, hasFaceNormal );
  7245. faceType = setBit( faceType, 5, hasFaceVertexNormal );
  7246. faceType = setBit( faceType, 6, hasFaceColor );
  7247. faceType = setBit( faceType, 7, hasFaceVertexColor );
  7248. faces.push( faceType );
  7249. faces.push( face.a, face.b, face.c );
  7250. faces.push( face.materialIndex );
  7251. if ( hasFaceVertexUv ) {
  7252. var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ];
  7253. faces.push(
  7254. getUvIndex( faceVertexUvs[ 0 ] ),
  7255. getUvIndex( faceVertexUvs[ 1 ] ),
  7256. getUvIndex( faceVertexUvs[ 2 ] )
  7257. );
  7258. }
  7259. if ( hasFaceNormal ) {
  7260. faces.push( getNormalIndex( face.normal ) );
  7261. }
  7262. if ( hasFaceVertexNormal ) {
  7263. var vertexNormals = face.vertexNormals;
  7264. faces.push(
  7265. getNormalIndex( vertexNormals[ 0 ] ),
  7266. getNormalIndex( vertexNormals[ 1 ] ),
  7267. getNormalIndex( vertexNormals[ 2 ] )
  7268. );
  7269. }
  7270. if ( hasFaceColor ) {
  7271. faces.push( getColorIndex( face.color ) );
  7272. }
  7273. if ( hasFaceVertexColor ) {
  7274. var vertexColors = face.vertexColors;
  7275. faces.push(
  7276. getColorIndex( vertexColors[ 0 ] ),
  7277. getColorIndex( vertexColors[ 1 ] ),
  7278. getColorIndex( vertexColors[ 2 ] )
  7279. );
  7280. }
  7281. }
  7282. function setBit( value, position, enabled ) {
  7283. return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) );
  7284. }
  7285. function getNormalIndex( normal ) {
  7286. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  7287. if ( normalsHash[ hash ] !== undefined ) {
  7288. return normalsHash[ hash ];
  7289. }
  7290. normalsHash[ hash ] = normals.length / 3;
  7291. normals.push( normal.x, normal.y, normal.z );
  7292. return normalsHash[ hash ];
  7293. }
  7294. function getColorIndex( color ) {
  7295. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  7296. if ( colorsHash[ hash ] !== undefined ) {
  7297. return colorsHash[ hash ];
  7298. }
  7299. colorsHash[ hash ] = colors.length;
  7300. colors.push( color.getHex() );
  7301. return colorsHash[ hash ];
  7302. }
  7303. function getUvIndex( uv ) {
  7304. var hash = uv.x.toString() + uv.y.toString();
  7305. if ( uvsHash[ hash ] !== undefined ) {
  7306. return uvsHash[ hash ];
  7307. }
  7308. uvsHash[ hash ] = uvs.length / 2;
  7309. uvs.push( uv.x, uv.y );
  7310. return uvsHash[ hash ];
  7311. }
  7312. data.data = {};
  7313. data.data.vertices = vertices;
  7314. data.data.normals = normals;
  7315. if ( colors.length > 0 ) data.data.colors = colors;
  7316. if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility
  7317. data.data.faces = faces;
  7318. return data;
  7319. },
  7320. clone: function () {
  7321. /*
  7322. // Handle primitives
  7323. var parameters = this.parameters;
  7324. if ( parameters !== undefined ) {
  7325. var values = [];
  7326. for ( var key in parameters ) {
  7327. values.push( parameters[ key ] );
  7328. }
  7329. var geometry = Object.create( this.constructor.prototype );
  7330. this.constructor.apply( geometry, values );
  7331. return geometry;
  7332. }
  7333. return new this.constructor().copy( this );
  7334. */
  7335. return new Geometry().copy( this );
  7336. },
  7337. copy: function ( source ) {
  7338. this.vertices = [];
  7339. this.faces = [];
  7340. this.faceVertexUvs = [ [] ];
  7341. this.colors = [];
  7342. var vertices = source.vertices;
  7343. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  7344. this.vertices.push( vertices[ i ].clone() );
  7345. }
  7346. var colors = source.colors;
  7347. for ( var i = 0, il = colors.length; i < il; i ++ ) {
  7348. this.colors.push( colors[ i ].clone() );
  7349. }
  7350. var faces = source.faces;
  7351. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  7352. this.faces.push( faces[ i ].clone() );
  7353. }
  7354. for ( var i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) {
  7355. var faceVertexUvs = source.faceVertexUvs[ i ];
  7356. if ( this.faceVertexUvs[ i ] === undefined ) {
  7357. this.faceVertexUvs[ i ] = [];
  7358. }
  7359. for ( var j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {
  7360. var uvs = faceVertexUvs[ j ], uvsCopy = [];
  7361. for ( var k = 0, kl = uvs.length; k < kl; k ++ ) {
  7362. var uv = uvs[ k ];
  7363. uvsCopy.push( uv.clone() );
  7364. }
  7365. this.faceVertexUvs[ i ].push( uvsCopy );
  7366. }
  7367. }
  7368. return this;
  7369. },
  7370. dispose: function () {
  7371. this.dispatchEvent( { type: 'dispose' } );
  7372. }
  7373. } );
  7374. var count$2 = 0;
  7375. function GeometryIdCount() { return count$2++; };
  7376. /**
  7377. * @author mrdoob / http://mrdoob.com/
  7378. */
  7379. function DirectGeometry() {
  7380. Object.defineProperty( this, 'id', { value: GeometryIdCount() } );
  7381. this.uuid = exports.Math.generateUUID();
  7382. this.name = '';
  7383. this.type = 'DirectGeometry';
  7384. this.indices = [];
  7385. this.vertices = [];
  7386. this.normals = [];
  7387. this.colors = [];
  7388. this.uvs = [];
  7389. this.uvs2 = [];
  7390. this.groups = [];
  7391. this.morphTargets = {};
  7392. this.skinWeights = [];
  7393. this.skinIndices = [];
  7394. // this.lineDistances = [];
  7395. this.boundingBox = null;
  7396. this.boundingSphere = null;
  7397. // update flags
  7398. this.verticesNeedUpdate = false;
  7399. this.normalsNeedUpdate = false;
  7400. this.colorsNeedUpdate = false;
  7401. this.uvsNeedUpdate = false;
  7402. this.groupsNeedUpdate = false;
  7403. }
  7404. Object.assign( DirectGeometry.prototype, EventDispatcher.prototype, {
  7405. computeBoundingBox: Geometry.prototype.computeBoundingBox,
  7406. computeBoundingSphere: Geometry.prototype.computeBoundingSphere,
  7407. computeFaceNormals: function () {
  7408. console.warn( 'THREE.DirectGeometry: computeFaceNormals() is not a method of this type of geometry.' );
  7409. },
  7410. computeVertexNormals: function () {
  7411. console.warn( 'THREE.DirectGeometry: computeVertexNormals() is not a method of this type of geometry.' );
  7412. },
  7413. computeGroups: function ( geometry ) {
  7414. var group;
  7415. var groups = [];
  7416. var materialIndex;
  7417. var faces = geometry.faces;
  7418. for ( var i = 0; i < faces.length; i ++ ) {
  7419. var face = faces[ i ];
  7420. // materials
  7421. if ( face.materialIndex !== materialIndex ) {
  7422. materialIndex = face.materialIndex;
  7423. if ( group !== undefined ) {
  7424. group.count = ( i * 3 ) - group.start;
  7425. groups.push( group );
  7426. }
  7427. group = {
  7428. start: i * 3,
  7429. materialIndex: materialIndex
  7430. };
  7431. }
  7432. }
  7433. if ( group !== undefined ) {
  7434. group.count = ( i * 3 ) - group.start;
  7435. groups.push( group );
  7436. }
  7437. this.groups = groups;
  7438. },
  7439. fromGeometry: function ( geometry ) {
  7440. var faces = geometry.faces;
  7441. var vertices = geometry.vertices;
  7442. var faceVertexUvs = geometry.faceVertexUvs;
  7443. var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0;
  7444. var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0;
  7445. // morphs
  7446. var morphTargets = geometry.morphTargets;
  7447. var morphTargetsLength = morphTargets.length;
  7448. var morphTargetsPosition;
  7449. if ( morphTargetsLength > 0 ) {
  7450. morphTargetsPosition = [];
  7451. for ( var i = 0; i < morphTargetsLength; i ++ ) {
  7452. morphTargetsPosition[ i ] = [];
  7453. }
  7454. this.morphTargets.position = morphTargetsPosition;
  7455. }
  7456. var morphNormals = geometry.morphNormals;
  7457. var morphNormalsLength = morphNormals.length;
  7458. var morphTargetsNormal;
  7459. if ( morphNormalsLength > 0 ) {
  7460. morphTargetsNormal = [];
  7461. for ( var i = 0; i < morphNormalsLength; i ++ ) {
  7462. morphTargetsNormal[ i ] = [];
  7463. }
  7464. this.morphTargets.normal = morphTargetsNormal;
  7465. }
  7466. // skins
  7467. var skinIndices = geometry.skinIndices;
  7468. var skinWeights = geometry.skinWeights;
  7469. var hasSkinIndices = skinIndices.length === vertices.length;
  7470. var hasSkinWeights = skinWeights.length === vertices.length;
  7471. //
  7472. for ( var i = 0; i < faces.length; i ++ ) {
  7473. var face = faces[ i ];
  7474. this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] );
  7475. var vertexNormals = face.vertexNormals;
  7476. if ( vertexNormals.length === 3 ) {
  7477. this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] );
  7478. } else {
  7479. var normal = face.normal;
  7480. this.normals.push( normal, normal, normal );
  7481. }
  7482. var vertexColors = face.vertexColors;
  7483. if ( vertexColors.length === 3 ) {
  7484. this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] );
  7485. } else {
  7486. var color = face.color;
  7487. this.colors.push( color, color, color );
  7488. }
  7489. if ( hasFaceVertexUv === true ) {
  7490. var vertexUvs = faceVertexUvs[ 0 ][ i ];
  7491. if ( vertexUvs !== undefined ) {
  7492. this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  7493. } else {
  7494. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i );
  7495. this.uvs.push( new Vector2(), new Vector2(), new Vector2() );
  7496. }
  7497. }
  7498. if ( hasFaceVertexUv2 === true ) {
  7499. var vertexUvs = faceVertexUvs[ 1 ][ i ];
  7500. if ( vertexUvs !== undefined ) {
  7501. this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  7502. } else {
  7503. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i );
  7504. this.uvs2.push( new Vector2(), new Vector2(), new Vector2() );
  7505. }
  7506. }
  7507. // morphs
  7508. for ( var j = 0; j < morphTargetsLength; j ++ ) {
  7509. var morphTarget = morphTargets[ j ].vertices;
  7510. morphTargetsPosition[ j ].push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] );
  7511. }
  7512. for ( var j = 0; j < morphNormalsLength; j ++ ) {
  7513. var morphNormal = morphNormals[ j ].vertexNormals[ i ];
  7514. morphTargetsNormal[ j ].push( morphNormal.a, morphNormal.b, morphNormal.c );
  7515. }
  7516. // skins
  7517. if ( hasSkinIndices ) {
  7518. this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] );
  7519. }
  7520. if ( hasSkinWeights ) {
  7521. this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] );
  7522. }
  7523. }
  7524. this.computeGroups( geometry );
  7525. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  7526. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  7527. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  7528. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  7529. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  7530. return this;
  7531. },
  7532. dispose: function () {
  7533. this.dispatchEvent( { type: 'dispose' } );
  7534. }
  7535. } );
  7536. /**
  7537. * @author alteredq / http://alteredqualia.com/
  7538. * @author mrdoob / http://mrdoob.com/
  7539. */
  7540. function BufferGeometry() {
  7541. Object.defineProperty( this, 'id', { value: GeometryIdCount() } );
  7542. this.uuid = exports.Math.generateUUID();
  7543. this.name = '';
  7544. this.type = 'BufferGeometry';
  7545. this.index = null;
  7546. this.attributes = {};
  7547. this.morphAttributes = {};
  7548. this.groups = [];
  7549. this.boundingBox = null;
  7550. this.boundingSphere = null;
  7551. this.drawRange = { start: 0, count: Infinity };
  7552. }
  7553. Object.assign( BufferGeometry.prototype, EventDispatcher.prototype, {
  7554. isBufferGeometry: true,
  7555. getIndex: function () {
  7556. return this.index;
  7557. },
  7558. setIndex: function ( index ) {
  7559. this.index = index;
  7560. },
  7561. addAttribute: function ( name, attribute ) {
  7562. if ( (attribute && attribute.isBufferAttribute) === false && (attribute && attribute.isInterleavedBufferAttribute) === false ) {
  7563. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  7564. this.addAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  7565. return;
  7566. }
  7567. if ( name === 'index' ) {
  7568. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  7569. this.setIndex( attribute );
  7570. return;
  7571. }
  7572. this.attributes[ name ] = attribute;
  7573. return this;
  7574. },
  7575. getAttribute: function ( name ) {
  7576. return this.attributes[ name ];
  7577. },
  7578. removeAttribute: function ( name ) {
  7579. delete this.attributes[ name ];
  7580. return this;
  7581. },
  7582. addGroup: function ( start, count, materialIndex ) {
  7583. this.groups.push( {
  7584. start: start,
  7585. count: count,
  7586. materialIndex: materialIndex !== undefined ? materialIndex : 0
  7587. } );
  7588. },
  7589. clearGroups: function () {
  7590. this.groups = [];
  7591. },
  7592. setDrawRange: function ( start, count ) {
  7593. this.drawRange.start = start;
  7594. this.drawRange.count = count;
  7595. },
  7596. applyMatrix: function ( matrix ) {
  7597. var position = this.attributes.position;
  7598. if ( position !== undefined ) {
  7599. matrix.applyToVector3Array( position.array );
  7600. position.needsUpdate = true;
  7601. }
  7602. var normal = this.attributes.normal;
  7603. if ( normal !== undefined ) {
  7604. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  7605. normalMatrix.applyToVector3Array( normal.array );
  7606. normal.needsUpdate = true;
  7607. }
  7608. if ( this.boundingBox !== null ) {
  7609. this.computeBoundingBox();
  7610. }
  7611. if ( this.boundingSphere !== null ) {
  7612. this.computeBoundingSphere();
  7613. }
  7614. return this;
  7615. },
  7616. rotateX: function () {
  7617. // rotate geometry around world x-axis
  7618. var m1;
  7619. return function rotateX( angle ) {
  7620. if ( m1 === undefined ) m1 = new Matrix4();
  7621. m1.makeRotationX( angle );
  7622. this.applyMatrix( m1 );
  7623. return this;
  7624. };
  7625. }(),
  7626. rotateY: function () {
  7627. // rotate geometry around world y-axis
  7628. var m1;
  7629. return function rotateY( angle ) {
  7630. if ( m1 === undefined ) m1 = new Matrix4();
  7631. m1.makeRotationY( angle );
  7632. this.applyMatrix( m1 );
  7633. return this;
  7634. };
  7635. }(),
  7636. rotateZ: function () {
  7637. // rotate geometry around world z-axis
  7638. var m1;
  7639. return function rotateZ( angle ) {
  7640. if ( m1 === undefined ) m1 = new Matrix4();
  7641. m1.makeRotationZ( angle );
  7642. this.applyMatrix( m1 );
  7643. return this;
  7644. };
  7645. }(),
  7646. translate: function () {
  7647. // translate geometry
  7648. var m1;
  7649. return function translate( x, y, z ) {
  7650. if ( m1 === undefined ) m1 = new Matrix4();
  7651. m1.makeTranslation( x, y, z );
  7652. this.applyMatrix( m1 );
  7653. return this;
  7654. };
  7655. }(),
  7656. scale: function () {
  7657. // scale geometry
  7658. var m1;
  7659. return function scale( x, y, z ) {
  7660. if ( m1 === undefined ) m1 = new Matrix4();
  7661. m1.makeScale( x, y, z );
  7662. this.applyMatrix( m1 );
  7663. return this;
  7664. };
  7665. }(),
  7666. lookAt: function () {
  7667. var obj;
  7668. return function lookAt( vector ) {
  7669. if ( obj === undefined ) obj = new Object3D();
  7670. obj.lookAt( vector );
  7671. obj.updateMatrix();
  7672. this.applyMatrix( obj.matrix );
  7673. };
  7674. }(),
  7675. center: function () {
  7676. this.computeBoundingBox();
  7677. var offset = this.boundingBox.center().negate();
  7678. this.translate( offset.x, offset.y, offset.z );
  7679. return offset;
  7680. },
  7681. setFromObject: function ( object ) {
  7682. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  7683. var geometry = object.geometry;
  7684. if ( (object && object.isPoints) || (object && object.isLine) ) {
  7685. var positions = new Float32Attribute( geometry.vertices.length * 3, 3 );
  7686. var colors = new Float32Attribute( geometry.colors.length * 3, 3 );
  7687. this.addAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) );
  7688. this.addAttribute( 'color', colors.copyColorsArray( geometry.colors ) );
  7689. if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) {
  7690. var lineDistances = new Float32Attribute( geometry.lineDistances.length, 1 );
  7691. this.addAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) );
  7692. }
  7693. if ( geometry.boundingSphere !== null ) {
  7694. this.boundingSphere = geometry.boundingSphere.clone();
  7695. }
  7696. if ( geometry.boundingBox !== null ) {
  7697. this.boundingBox = geometry.boundingBox.clone();
  7698. }
  7699. } else if ( (object && object.isMesh) ) {
  7700. if ( (geometry && geometry.isGeometry) ) {
  7701. this.fromGeometry( geometry );
  7702. }
  7703. }
  7704. return this;
  7705. },
  7706. updateFromObject: function ( object ) {
  7707. var geometry = object.geometry;
  7708. if ( (object && object.isMesh) ) {
  7709. var direct = geometry.__directGeometry;
  7710. if ( geometry.elementsNeedUpdate === true ) {
  7711. direct = undefined;
  7712. geometry.elementsNeedUpdate = false;
  7713. }
  7714. if ( direct === undefined ) {
  7715. return this.fromGeometry( geometry );
  7716. }
  7717. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  7718. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  7719. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  7720. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  7721. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  7722. geometry.verticesNeedUpdate = false;
  7723. geometry.normalsNeedUpdate = false;
  7724. geometry.colorsNeedUpdate = false;
  7725. geometry.uvsNeedUpdate = false;
  7726. geometry.groupsNeedUpdate = false;
  7727. geometry = direct;
  7728. }
  7729. var attribute;
  7730. if ( geometry.verticesNeedUpdate === true ) {
  7731. attribute = this.attributes.position;
  7732. if ( attribute !== undefined ) {
  7733. attribute.copyVector3sArray( geometry.vertices );
  7734. attribute.needsUpdate = true;
  7735. }
  7736. geometry.verticesNeedUpdate = false;
  7737. }
  7738. if ( geometry.normalsNeedUpdate === true ) {
  7739. attribute = this.attributes.normal;
  7740. if ( attribute !== undefined ) {
  7741. attribute.copyVector3sArray( geometry.normals );
  7742. attribute.needsUpdate = true;
  7743. }
  7744. geometry.normalsNeedUpdate = false;
  7745. }
  7746. if ( geometry.colorsNeedUpdate === true ) {
  7747. attribute = this.attributes.color;
  7748. if ( attribute !== undefined ) {
  7749. attribute.copyColorsArray( geometry.colors );
  7750. attribute.needsUpdate = true;
  7751. }
  7752. geometry.colorsNeedUpdate = false;
  7753. }
  7754. if ( geometry.uvsNeedUpdate ) {
  7755. attribute = this.attributes.uv;
  7756. if ( attribute !== undefined ) {
  7757. attribute.copyVector2sArray( geometry.uvs );
  7758. attribute.needsUpdate = true;
  7759. }
  7760. geometry.uvsNeedUpdate = false;
  7761. }
  7762. if ( geometry.lineDistancesNeedUpdate ) {
  7763. attribute = this.attributes.lineDistance;
  7764. if ( attribute !== undefined ) {
  7765. attribute.copyArray( geometry.lineDistances );
  7766. attribute.needsUpdate = true;
  7767. }
  7768. geometry.lineDistancesNeedUpdate = false;
  7769. }
  7770. if ( geometry.groupsNeedUpdate ) {
  7771. geometry.computeGroups( object.geometry );
  7772. this.groups = geometry.groups;
  7773. geometry.groupsNeedUpdate = false;
  7774. }
  7775. return this;
  7776. },
  7777. fromGeometry: function ( geometry ) {
  7778. geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry );
  7779. return this.fromDirectGeometry( geometry.__directGeometry );
  7780. },
  7781. fromDirectGeometry: function ( geometry ) {
  7782. var positions = new Float32Array( geometry.vertices.length * 3 );
  7783. this.addAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) );
  7784. if ( geometry.normals.length > 0 ) {
  7785. var normals = new Float32Array( geometry.normals.length * 3 );
  7786. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) );
  7787. }
  7788. if ( geometry.colors.length > 0 ) {
  7789. var colors = new Float32Array( geometry.colors.length * 3 );
  7790. this.addAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) );
  7791. }
  7792. if ( geometry.uvs.length > 0 ) {
  7793. var uvs = new Float32Array( geometry.uvs.length * 2 );
  7794. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) );
  7795. }
  7796. if ( geometry.uvs2.length > 0 ) {
  7797. var uvs2 = new Float32Array( geometry.uvs2.length * 2 );
  7798. this.addAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) );
  7799. }
  7800. if ( geometry.indices.length > 0 ) {
  7801. var TypeArray = geometry.vertices.length > 65535 ? Uint32Array : Uint16Array;
  7802. var indices = new TypeArray( geometry.indices.length * 3 );
  7803. this.setIndex( new BufferAttribute( indices, 1 ).copyIndicesArray( geometry.indices ) );
  7804. }
  7805. // groups
  7806. this.groups = geometry.groups;
  7807. // morphs
  7808. for ( var name in geometry.morphTargets ) {
  7809. var array = [];
  7810. var morphTargets = geometry.morphTargets[ name ];
  7811. for ( var i = 0, l = morphTargets.length; i < l; i ++ ) {
  7812. var morphTarget = morphTargets[ i ];
  7813. var attribute = new Float32Attribute( morphTarget.length * 3, 3 );
  7814. array.push( attribute.copyVector3sArray( morphTarget ) );
  7815. }
  7816. this.morphAttributes[ name ] = array;
  7817. }
  7818. // skinning
  7819. if ( geometry.skinIndices.length > 0 ) {
  7820. var skinIndices = new Float32Attribute( geometry.skinIndices.length * 4, 4 );
  7821. this.addAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) );
  7822. }
  7823. if ( geometry.skinWeights.length > 0 ) {
  7824. var skinWeights = new Float32Attribute( geometry.skinWeights.length * 4, 4 );
  7825. this.addAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) );
  7826. }
  7827. //
  7828. if ( geometry.boundingSphere !== null ) {
  7829. this.boundingSphere = geometry.boundingSphere.clone();
  7830. }
  7831. if ( geometry.boundingBox !== null ) {
  7832. this.boundingBox = geometry.boundingBox.clone();
  7833. }
  7834. return this;
  7835. },
  7836. computeBoundingBox: function () {
  7837. if ( this.boundingBox === null ) {
  7838. this.boundingBox = new Box3();
  7839. }
  7840. var positions = this.attributes.position.array;
  7841. if ( positions !== undefined ) {
  7842. this.boundingBox.setFromArray( positions );
  7843. } else {
  7844. this.boundingBox.makeEmpty();
  7845. }
  7846. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  7847. console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  7848. }
  7849. },
  7850. computeBoundingSphere: function () {
  7851. var box = new Box3();
  7852. var vector = new Vector3();
  7853. return function computeBoundingSphere() {
  7854. if ( this.boundingSphere === null ) {
  7855. this.boundingSphere = new Sphere();
  7856. }
  7857. var positions = this.attributes.position;
  7858. if ( positions ) {
  7859. var array = positions.array;
  7860. var center = this.boundingSphere.center;
  7861. box.setFromArray( array );
  7862. box.center( center );
  7863. // hoping to find a boundingSphere with a radius smaller than the
  7864. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  7865. var maxRadiusSq = 0;
  7866. for ( var i = 0, il = array.length; i < il; i += 3 ) {
  7867. vector.fromArray( array, i );
  7868. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  7869. }
  7870. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  7871. if ( isNaN( this.boundingSphere.radius ) ) {
  7872. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  7873. }
  7874. }
  7875. };
  7876. }(),
  7877. computeFaceNormals: function () {
  7878. // backwards compatibility
  7879. },
  7880. computeVertexNormals: function () {
  7881. var index = this.index;
  7882. var attributes = this.attributes;
  7883. var groups = this.groups;
  7884. if ( attributes.position ) {
  7885. var positions = attributes.position.array;
  7886. if ( attributes.normal === undefined ) {
  7887. this.addAttribute( 'normal', new BufferAttribute( new Float32Array( positions.length ), 3 ) );
  7888. } else {
  7889. // reset existing normals to zero
  7890. var array = attributes.normal.array;
  7891. for ( var i = 0, il = array.length; i < il; i ++ ) {
  7892. array[ i ] = 0;
  7893. }
  7894. }
  7895. var normals = attributes.normal.array;
  7896. var vA, vB, vC,
  7897. pA = new Vector3(),
  7898. pB = new Vector3(),
  7899. pC = new Vector3(),
  7900. cb = new Vector3(),
  7901. ab = new Vector3();
  7902. // indexed elements
  7903. if ( index ) {
  7904. var indices = index.array;
  7905. if ( groups.length === 0 ) {
  7906. this.addGroup( 0, indices.length );
  7907. }
  7908. for ( var j = 0, jl = groups.length; j < jl; ++ j ) {
  7909. var group = groups[ j ];
  7910. var start = group.start;
  7911. var count = group.count;
  7912. for ( var i = start, il = start + count; i < il; i += 3 ) {
  7913. vA = indices[ i + 0 ] * 3;
  7914. vB = indices[ i + 1 ] * 3;
  7915. vC = indices[ i + 2 ] * 3;
  7916. pA.fromArray( positions, vA );
  7917. pB.fromArray( positions, vB );
  7918. pC.fromArray( positions, vC );
  7919. cb.subVectors( pC, pB );
  7920. ab.subVectors( pA, pB );
  7921. cb.cross( ab );
  7922. normals[ vA ] += cb.x;
  7923. normals[ vA + 1 ] += cb.y;
  7924. normals[ vA + 2 ] += cb.z;
  7925. normals[ vB ] += cb.x;
  7926. normals[ vB + 1 ] += cb.y;
  7927. normals[ vB + 2 ] += cb.z;
  7928. normals[ vC ] += cb.x;
  7929. normals[ vC + 1 ] += cb.y;
  7930. normals[ vC + 2 ] += cb.z;
  7931. }
  7932. }
  7933. } else {
  7934. // non-indexed elements (unconnected triangle soup)
  7935. for ( var i = 0, il = positions.length; i < il; i += 9 ) {
  7936. pA.fromArray( positions, i );
  7937. pB.fromArray( positions, i + 3 );
  7938. pC.fromArray( positions, i + 6 );
  7939. cb.subVectors( pC, pB );
  7940. ab.subVectors( pA, pB );
  7941. cb.cross( ab );
  7942. normals[ i ] = cb.x;
  7943. normals[ i + 1 ] = cb.y;
  7944. normals[ i + 2 ] = cb.z;
  7945. normals[ i + 3 ] = cb.x;
  7946. normals[ i + 4 ] = cb.y;
  7947. normals[ i + 5 ] = cb.z;
  7948. normals[ i + 6 ] = cb.x;
  7949. normals[ i + 7 ] = cb.y;
  7950. normals[ i + 8 ] = cb.z;
  7951. }
  7952. }
  7953. this.normalizeNormals();
  7954. attributes.normal.needsUpdate = true;
  7955. }
  7956. },
  7957. merge: function ( geometry, offset ) {
  7958. if ( (geometry && geometry.isBufferGeometry) === false ) {
  7959. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  7960. return;
  7961. }
  7962. if ( offset === undefined ) offset = 0;
  7963. var attributes = this.attributes;
  7964. for ( var key in attributes ) {
  7965. if ( geometry.attributes[ key ] === undefined ) continue;
  7966. var attribute1 = attributes[ key ];
  7967. var attributeArray1 = attribute1.array;
  7968. var attribute2 = geometry.attributes[ key ];
  7969. var attributeArray2 = attribute2.array;
  7970. var attributeSize = attribute2.itemSize;
  7971. for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) {
  7972. attributeArray1[ j ] = attributeArray2[ i ];
  7973. }
  7974. }
  7975. return this;
  7976. },
  7977. normalizeNormals: function () {
  7978. var normals = this.attributes.normal.array;
  7979. var x, y, z, n;
  7980. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  7981. x = normals[ i ];
  7982. y = normals[ i + 1 ];
  7983. z = normals[ i + 2 ];
  7984. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  7985. normals[ i ] *= n;
  7986. normals[ i + 1 ] *= n;
  7987. normals[ i + 2 ] *= n;
  7988. }
  7989. },
  7990. toNonIndexed: function () {
  7991. if ( this.index === null ) {
  7992. console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' );
  7993. return this;
  7994. }
  7995. var geometry2 = new BufferGeometry();
  7996. var indices = this.index.array;
  7997. var attributes = this.attributes;
  7998. for ( var name in attributes ) {
  7999. var attribute = attributes[ name ];
  8000. var array = attribute.array;
  8001. var itemSize = attribute.itemSize;
  8002. var array2 = new array.constructor( indices.length * itemSize );
  8003. var index = 0, index2 = 0;
  8004. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  8005. index = indices[ i ] * itemSize;
  8006. for ( var j = 0; j < itemSize; j ++ ) {
  8007. array2[ index2 ++ ] = array[ index ++ ];
  8008. }
  8009. }
  8010. geometry2.addAttribute( name, new BufferAttribute( array2, itemSize ) );
  8011. }
  8012. return geometry2;
  8013. },
  8014. toJSON: function () {
  8015. var data = {
  8016. metadata: {
  8017. version: 4.4,
  8018. type: 'BufferGeometry',
  8019. generator: 'BufferGeometry.toJSON'
  8020. }
  8021. };
  8022. // standard BufferGeometry serialization
  8023. data.uuid = this.uuid;
  8024. data.type = this.type;
  8025. if ( this.name !== '' ) data.name = this.name;
  8026. if ( this.parameters !== undefined ) {
  8027. var parameters = this.parameters;
  8028. for ( var key in parameters ) {
  8029. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  8030. }
  8031. return data;
  8032. }
  8033. data.data = { attributes: {} };
  8034. var index = this.index;
  8035. if ( index !== null ) {
  8036. var array = Array.prototype.slice.call( index.array );
  8037. data.data.index = {
  8038. type: index.array.constructor.name,
  8039. array: array
  8040. };
  8041. }
  8042. var attributes = this.attributes;
  8043. for ( var key in attributes ) {
  8044. var attribute = attributes[ key ];
  8045. var array = Array.prototype.slice.call( attribute.array );
  8046. data.data.attributes[ key ] = {
  8047. itemSize: attribute.itemSize,
  8048. type: attribute.array.constructor.name,
  8049. array: array,
  8050. normalized: attribute.normalized
  8051. };
  8052. }
  8053. var groups = this.groups;
  8054. if ( groups.length > 0 ) {
  8055. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  8056. }
  8057. var boundingSphere = this.boundingSphere;
  8058. if ( boundingSphere !== null ) {
  8059. data.data.boundingSphere = {
  8060. center: boundingSphere.center.toArray(),
  8061. radius: boundingSphere.radius
  8062. };
  8063. }
  8064. return data;
  8065. },
  8066. clone: function () {
  8067. /*
  8068. // Handle primitives
  8069. var parameters = this.parameters;
  8070. if ( parameters !== undefined ) {
  8071. var values = [];
  8072. for ( var key in parameters ) {
  8073. values.push( parameters[ key ] );
  8074. }
  8075. var geometry = Object.create( this.constructor.prototype );
  8076. this.constructor.apply( geometry, values );
  8077. return geometry;
  8078. }
  8079. return new this.constructor().copy( this );
  8080. */
  8081. return new BufferGeometry().copy( this );
  8082. },
  8083. copy: function ( source ) {
  8084. var index = source.index;
  8085. if ( index !== null ) {
  8086. this.setIndex( index.clone() );
  8087. }
  8088. var attributes = source.attributes;
  8089. for ( var name in attributes ) {
  8090. var attribute = attributes[ name ];
  8091. this.addAttribute( name, attribute.clone() );
  8092. }
  8093. var groups = source.groups;
  8094. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  8095. var group = groups[ i ];
  8096. this.addGroup( group.start, group.count, group.materialIndex );
  8097. }
  8098. return this;
  8099. },
  8100. dispose: function () {
  8101. this.dispatchEvent( { type: 'dispose' } );
  8102. }
  8103. } );
  8104. BufferGeometry.MaxIndex = 65535;
  8105. /**
  8106. * @author Mugen87 / https://github.com/Mugen87
  8107. */
  8108. function BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  8109. BufferGeometry.call( this );
  8110. this.type = 'BoxBufferGeometry';
  8111. this.parameters = {
  8112. width: width,
  8113. height: height,
  8114. depth: depth,
  8115. widthSegments: widthSegments,
  8116. heightSegments: heightSegments,
  8117. depthSegments: depthSegments
  8118. };
  8119. var scope = this;
  8120. // segments
  8121. widthSegments = Math.floor( widthSegments ) || 1;
  8122. heightSegments = Math.floor( heightSegments ) || 1;
  8123. depthSegments = Math.floor( depthSegments ) || 1;
  8124. // these are used to calculate buffer length
  8125. var vertexCount = calculateVertexCount( widthSegments, heightSegments, depthSegments );
  8126. var indexCount = calculateIndexCount( widthSegments, heightSegments, depthSegments );
  8127. // buffers
  8128. var indices = new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount );
  8129. var vertices = new Float32Array( vertexCount * 3 );
  8130. var normals = new Float32Array( vertexCount * 3 );
  8131. var uvs = new Float32Array( vertexCount * 2 );
  8132. // offset variables
  8133. var vertexBufferOffset = 0;
  8134. var uvBufferOffset = 0;
  8135. var indexBufferOffset = 0;
  8136. var numberOfVertices = 0;
  8137. // group variables
  8138. var groupStart = 0;
  8139. // build each side of the box geometry
  8140. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  8141. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  8142. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  8143. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  8144. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  8145. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  8146. // build geometry
  8147. this.setIndex( new BufferAttribute( indices, 1 ) );
  8148. this.addAttribute( 'position', new BufferAttribute( vertices, 3 ) );
  8149. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) );
  8150. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) );
  8151. // helper functions
  8152. function calculateVertexCount( w, h, d ) {
  8153. var vertices = 0;
  8154. // calculate the amount of vertices for each side (plane)
  8155. vertices += (w + 1) * (h + 1) * 2; // xy
  8156. vertices += (w + 1) * (d + 1) * 2; // xz
  8157. vertices += (d + 1) * (h + 1) * 2; // zy
  8158. return vertices;
  8159. }
  8160. function calculateIndexCount( w, h, d ) {
  8161. var index = 0;
  8162. // calculate the amount of squares for each side
  8163. index += w * h * 2; // xy
  8164. index += w * d * 2; // xz
  8165. index += d * h * 2; // zy
  8166. return index * 6; // two triangles per square => six vertices per square
  8167. }
  8168. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  8169. var segmentWidth = width / gridX;
  8170. var segmentHeight = height / gridY;
  8171. var widthHalf = width / 2;
  8172. var heightHalf = height / 2;
  8173. var depthHalf = depth / 2;
  8174. var gridX1 = gridX + 1;
  8175. var gridY1 = gridY + 1;
  8176. var vertexCounter = 0;
  8177. var groupCount = 0;
  8178. var vector = new Vector3();
  8179. // generate vertices, normals and uvs
  8180. for ( var iy = 0; iy < gridY1; iy ++ ) {
  8181. var y = iy * segmentHeight - heightHalf;
  8182. for ( var ix = 0; ix < gridX1; ix ++ ) {
  8183. var x = ix * segmentWidth - widthHalf;
  8184. // set values to correct vector component
  8185. vector[ u ] = x * udir;
  8186. vector[ v ] = y * vdir;
  8187. vector[ w ] = depthHalf;
  8188. // now apply vector to vertex buffer
  8189. vertices[ vertexBufferOffset ] = vector.x;
  8190. vertices[ vertexBufferOffset + 1 ] = vector.y;
  8191. vertices[ vertexBufferOffset + 2 ] = vector.z;
  8192. // set values to correct vector component
  8193. vector[ u ] = 0;
  8194. vector[ v ] = 0;
  8195. vector[ w ] = depth > 0 ? 1 : - 1;
  8196. // now apply vector to normal buffer
  8197. normals[ vertexBufferOffset ] = vector.x;
  8198. normals[ vertexBufferOffset + 1 ] = vector.y;
  8199. normals[ vertexBufferOffset + 2 ] = vector.z;
  8200. // uvs
  8201. uvs[ uvBufferOffset ] = ix / gridX;
  8202. uvs[ uvBufferOffset + 1 ] = 1 - ( iy / gridY );
  8203. // update offsets and counters
  8204. vertexBufferOffset += 3;
  8205. uvBufferOffset += 2;
  8206. vertexCounter += 1;
  8207. }
  8208. }
  8209. // 1. you need three indices to draw a single face
  8210. // 2. a single segment consists of two faces
  8211. // 3. so we need to generate six (2*3) indices per segment
  8212. for ( iy = 0; iy < gridY; iy ++ ) {
  8213. for ( ix = 0; ix < gridX; ix ++ ) {
  8214. // indices
  8215. var a = numberOfVertices + ix + gridX1 * iy;
  8216. var b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  8217. var c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  8218. var d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  8219. // face one
  8220. indices[ indexBufferOffset ] = a;
  8221. indices[ indexBufferOffset + 1 ] = b;
  8222. indices[ indexBufferOffset + 2 ] = d;
  8223. // face two
  8224. indices[ indexBufferOffset + 3 ] = b;
  8225. indices[ indexBufferOffset + 4 ] = c;
  8226. indices[ indexBufferOffset + 5 ] = d;
  8227. // update offsets and counters
  8228. indexBufferOffset += 6;
  8229. groupCount += 6;
  8230. }
  8231. }
  8232. // add a group to the geometry. this will ensure multi material support
  8233. scope.addGroup( groupStart, groupCount, materialIndex );
  8234. // calculate new start value for groups
  8235. groupStart += groupCount;
  8236. // update total number of vertices
  8237. numberOfVertices += vertexCounter;
  8238. }
  8239. }
  8240. BoxBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  8241. BoxBufferGeometry.prototype.constructor = BoxBufferGeometry;
  8242. /**
  8243. * @author bhouston / http://clara.io
  8244. */
  8245. function Ray( origin, direction ) {
  8246. this.origin = ( origin !== undefined ) ? origin : new Vector3();
  8247. this.direction = ( direction !== undefined ) ? direction : new Vector3();
  8248. }
  8249. Ray.prototype = {
  8250. constructor: Ray,
  8251. set: function ( origin, direction ) {
  8252. this.origin.copy( origin );
  8253. this.direction.copy( direction );
  8254. return this;
  8255. },
  8256. clone: function () {
  8257. return new this.constructor().copy( this );
  8258. },
  8259. copy: function ( ray ) {
  8260. this.origin.copy( ray.origin );
  8261. this.direction.copy( ray.direction );
  8262. return this;
  8263. },
  8264. at: function ( t, optionalTarget ) {
  8265. var result = optionalTarget || new Vector3();
  8266. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  8267. },
  8268. lookAt: function ( v ) {
  8269. this.direction.copy( v ).sub( this.origin ).normalize();
  8270. return this;
  8271. },
  8272. recast: function () {
  8273. var v1 = new Vector3();
  8274. return function recast( t ) {
  8275. this.origin.copy( this.at( t, v1 ) );
  8276. return this;
  8277. };
  8278. }(),
  8279. closestPointToPoint: function ( point, optionalTarget ) {
  8280. var result = optionalTarget || new Vector3();
  8281. result.subVectors( point, this.origin );
  8282. var directionDistance = result.dot( this.direction );
  8283. if ( directionDistance < 0 ) {
  8284. return result.copy( this.origin );
  8285. }
  8286. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  8287. },
  8288. distanceToPoint: function ( point ) {
  8289. return Math.sqrt( this.distanceSqToPoint( point ) );
  8290. },
  8291. distanceSqToPoint: function () {
  8292. var v1 = new Vector3();
  8293. return function distanceSqToPoint( point ) {
  8294. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  8295. // point behind the ray
  8296. if ( directionDistance < 0 ) {
  8297. return this.origin.distanceToSquared( point );
  8298. }
  8299. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  8300. return v1.distanceToSquared( point );
  8301. };
  8302. }(),
  8303. distanceSqToSegment: function () {
  8304. var segCenter = new Vector3();
  8305. var segDir = new Vector3();
  8306. var diff = new Vector3();
  8307. return function distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  8308. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  8309. // It returns the min distance between the ray and the segment
  8310. // defined by v0 and v1
  8311. // It can also set two optional targets :
  8312. // - The closest point on the ray
  8313. // - The closest point on the segment
  8314. segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  8315. segDir.copy( v1 ).sub( v0 ).normalize();
  8316. diff.copy( this.origin ).sub( segCenter );
  8317. var segExtent = v0.distanceTo( v1 ) * 0.5;
  8318. var a01 = - this.direction.dot( segDir );
  8319. var b0 = diff.dot( this.direction );
  8320. var b1 = - diff.dot( segDir );
  8321. var c = diff.lengthSq();
  8322. var det = Math.abs( 1 - a01 * a01 );
  8323. var s0, s1, sqrDist, extDet;
  8324. if ( det > 0 ) {
  8325. // The ray and segment are not parallel.
  8326. s0 = a01 * b1 - b0;
  8327. s1 = a01 * b0 - b1;
  8328. extDet = segExtent * det;
  8329. if ( s0 >= 0 ) {
  8330. if ( s1 >= - extDet ) {
  8331. if ( s1 <= extDet ) {
  8332. // region 0
  8333. // Minimum at interior points of ray and segment.
  8334. var invDet = 1 / det;
  8335. s0 *= invDet;
  8336. s1 *= invDet;
  8337. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  8338. } else {
  8339. // region 1
  8340. s1 = segExtent;
  8341. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8342. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8343. }
  8344. } else {
  8345. // region 5
  8346. s1 = - segExtent;
  8347. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8348. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8349. }
  8350. } else {
  8351. if ( s1 <= - extDet ) {
  8352. // region 4
  8353. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  8354. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8355. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8356. } else if ( s1 <= extDet ) {
  8357. // region 3
  8358. s0 = 0;
  8359. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8360. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  8361. } else {
  8362. // region 2
  8363. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  8364. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8365. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8366. }
  8367. }
  8368. } else {
  8369. // Ray and segment are parallel.
  8370. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  8371. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8372. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8373. }
  8374. if ( optionalPointOnRay ) {
  8375. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  8376. }
  8377. if ( optionalPointOnSegment ) {
  8378. optionalPointOnSegment.copy( segDir ).multiplyScalar( s1 ).add( segCenter );
  8379. }
  8380. return sqrDist;
  8381. };
  8382. }(),
  8383. intersectSphere: function () {
  8384. var v1 = new Vector3();
  8385. return function intersectSphere( sphere, optionalTarget ) {
  8386. v1.subVectors( sphere.center, this.origin );
  8387. var tca = v1.dot( this.direction );
  8388. var d2 = v1.dot( v1 ) - tca * tca;
  8389. var radius2 = sphere.radius * sphere.radius;
  8390. if ( d2 > radius2 ) return null;
  8391. var thc = Math.sqrt( radius2 - d2 );
  8392. // t0 = first intersect point - entrance on front of sphere
  8393. var t0 = tca - thc;
  8394. // t1 = second intersect point - exit point on back of sphere
  8395. var t1 = tca + thc;
  8396. // test to see if both t0 and t1 are behind the ray - if so, return null
  8397. if ( t0 < 0 && t1 < 0 ) return null;
  8398. // test to see if t0 is behind the ray:
  8399. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  8400. // in order to always return an intersect point that is in front of the ray.
  8401. if ( t0 < 0 ) return this.at( t1, optionalTarget );
  8402. // else t0 is in front of the ray, so return the first collision point scaled by t0
  8403. return this.at( t0, optionalTarget );
  8404. };
  8405. }(),
  8406. intersectsSphere: function ( sphere ) {
  8407. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  8408. },
  8409. distanceToPlane: function ( plane ) {
  8410. var denominator = plane.normal.dot( this.direction );
  8411. if ( denominator === 0 ) {
  8412. // line is coplanar, return origin
  8413. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  8414. return 0;
  8415. }
  8416. // Null is preferable to undefined since undefined means.... it is undefined
  8417. return null;
  8418. }
  8419. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  8420. // Return if the ray never intersects the plane
  8421. return t >= 0 ? t : null;
  8422. },
  8423. intersectPlane: function ( plane, optionalTarget ) {
  8424. var t = this.distanceToPlane( plane );
  8425. if ( t === null ) {
  8426. return null;
  8427. }
  8428. return this.at( t, optionalTarget );
  8429. },
  8430. intersectsPlane: function ( plane ) {
  8431. // check if the ray lies on the plane first
  8432. var distToPoint = plane.distanceToPoint( this.origin );
  8433. if ( distToPoint === 0 ) {
  8434. return true;
  8435. }
  8436. var denominator = plane.normal.dot( this.direction );
  8437. if ( denominator * distToPoint < 0 ) {
  8438. return true;
  8439. }
  8440. // ray origin is behind the plane (and is pointing behind it)
  8441. return false;
  8442. },
  8443. intersectBox: function ( box, optionalTarget ) {
  8444. var tmin, tmax, tymin, tymax, tzmin, tzmax;
  8445. var invdirx = 1 / this.direction.x,
  8446. invdiry = 1 / this.direction.y,
  8447. invdirz = 1 / this.direction.z;
  8448. var origin = this.origin;
  8449. if ( invdirx >= 0 ) {
  8450. tmin = ( box.min.x - origin.x ) * invdirx;
  8451. tmax = ( box.max.x - origin.x ) * invdirx;
  8452. } else {
  8453. tmin = ( box.max.x - origin.x ) * invdirx;
  8454. tmax = ( box.min.x - origin.x ) * invdirx;
  8455. }
  8456. if ( invdiry >= 0 ) {
  8457. tymin = ( box.min.y - origin.y ) * invdiry;
  8458. tymax = ( box.max.y - origin.y ) * invdiry;
  8459. } else {
  8460. tymin = ( box.max.y - origin.y ) * invdiry;
  8461. tymax = ( box.min.y - origin.y ) * invdiry;
  8462. }
  8463. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  8464. // These lines also handle the case where tmin or tmax is NaN
  8465. // (result of 0 * Infinity). x !== x returns true if x is NaN
  8466. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  8467. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  8468. if ( invdirz >= 0 ) {
  8469. tzmin = ( box.min.z - origin.z ) * invdirz;
  8470. tzmax = ( box.max.z - origin.z ) * invdirz;
  8471. } else {
  8472. tzmin = ( box.max.z - origin.z ) * invdirz;
  8473. tzmax = ( box.min.z - origin.z ) * invdirz;
  8474. }
  8475. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  8476. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  8477. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  8478. //return point closest to the ray (positive side)
  8479. if ( tmax < 0 ) return null;
  8480. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  8481. },
  8482. intersectsBox: ( function () {
  8483. var v = new Vector3();
  8484. return function intersectsBox( box ) {
  8485. return this.intersectBox( box, v ) !== null;
  8486. };
  8487. } )(),
  8488. intersectTriangle: function () {
  8489. // Compute the offset origin, edges, and normal.
  8490. var diff = new Vector3();
  8491. var edge1 = new Vector3();
  8492. var edge2 = new Vector3();
  8493. var normal = new Vector3();
  8494. return function intersectTriangle( a, b, c, backfaceCulling, optionalTarget ) {
  8495. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  8496. edge1.subVectors( b, a );
  8497. edge2.subVectors( c, a );
  8498. normal.crossVectors( edge1, edge2 );
  8499. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  8500. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  8501. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  8502. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  8503. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  8504. var DdN = this.direction.dot( normal );
  8505. var sign;
  8506. if ( DdN > 0 ) {
  8507. if ( backfaceCulling ) return null;
  8508. sign = 1;
  8509. } else if ( DdN < 0 ) {
  8510. sign = - 1;
  8511. DdN = - DdN;
  8512. } else {
  8513. return null;
  8514. }
  8515. diff.subVectors( this.origin, a );
  8516. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  8517. // b1 < 0, no intersection
  8518. if ( DdQxE2 < 0 ) {
  8519. return null;
  8520. }
  8521. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  8522. // b2 < 0, no intersection
  8523. if ( DdE1xQ < 0 ) {
  8524. return null;
  8525. }
  8526. // b1+b2 > 1, no intersection
  8527. if ( DdQxE2 + DdE1xQ > DdN ) {
  8528. return null;
  8529. }
  8530. // Line intersects triangle, check if ray does.
  8531. var QdN = - sign * diff.dot( normal );
  8532. // t < 0, no intersection
  8533. if ( QdN < 0 ) {
  8534. return null;
  8535. }
  8536. // Ray intersects triangle.
  8537. return this.at( QdN / DdN, optionalTarget );
  8538. };
  8539. }(),
  8540. applyMatrix4: function ( matrix4 ) {
  8541. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  8542. this.origin.applyMatrix4( matrix4 );
  8543. this.direction.sub( this.origin );
  8544. this.direction.normalize();
  8545. return this;
  8546. },
  8547. equals: function ( ray ) {
  8548. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  8549. }
  8550. };
  8551. /**
  8552. * @author bhouston / http://clara.io
  8553. */
  8554. function Line3( start, end ) {
  8555. this.start = ( start !== undefined ) ? start : new Vector3();
  8556. this.end = ( end !== undefined ) ? end : new Vector3();
  8557. }
  8558. Line3.prototype = {
  8559. constructor: Line3,
  8560. set: function ( start, end ) {
  8561. this.start.copy( start );
  8562. this.end.copy( end );
  8563. return this;
  8564. },
  8565. clone: function () {
  8566. return new this.constructor().copy( this );
  8567. },
  8568. copy: function ( line ) {
  8569. this.start.copy( line.start );
  8570. this.end.copy( line.end );
  8571. return this;
  8572. },
  8573. center: function ( optionalTarget ) {
  8574. var result = optionalTarget || new Vector3();
  8575. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  8576. },
  8577. delta: function ( optionalTarget ) {
  8578. var result = optionalTarget || new Vector3();
  8579. return result.subVectors( this.end, this.start );
  8580. },
  8581. distanceSq: function () {
  8582. return this.start.distanceToSquared( this.end );
  8583. },
  8584. distance: function () {
  8585. return this.start.distanceTo( this.end );
  8586. },
  8587. at: function ( t, optionalTarget ) {
  8588. var result = optionalTarget || new Vector3();
  8589. return this.delta( result ).multiplyScalar( t ).add( this.start );
  8590. },
  8591. closestPointToPointParameter: function () {
  8592. var startP = new Vector3();
  8593. var startEnd = new Vector3();
  8594. return function closestPointToPointParameter( point, clampToLine ) {
  8595. startP.subVectors( point, this.start );
  8596. startEnd.subVectors( this.end, this.start );
  8597. var startEnd2 = startEnd.dot( startEnd );
  8598. var startEnd_startP = startEnd.dot( startP );
  8599. var t = startEnd_startP / startEnd2;
  8600. if ( clampToLine ) {
  8601. t = exports.Math.clamp( t, 0, 1 );
  8602. }
  8603. return t;
  8604. };
  8605. }(),
  8606. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  8607. var t = this.closestPointToPointParameter( point, clampToLine );
  8608. var result = optionalTarget || new Vector3();
  8609. return this.delta( result ).multiplyScalar( t ).add( this.start );
  8610. },
  8611. applyMatrix4: function ( matrix ) {
  8612. this.start.applyMatrix4( matrix );
  8613. this.end.applyMatrix4( matrix );
  8614. return this;
  8615. },
  8616. equals: function ( line ) {
  8617. return line.start.equals( this.start ) && line.end.equals( this.end );
  8618. }
  8619. };
  8620. /**
  8621. * @author bhouston / http://clara.io
  8622. * @author mrdoob / http://mrdoob.com/
  8623. */
  8624. function Triangle( a, b, c ) {
  8625. this.a = ( a !== undefined ) ? a : new Vector3();
  8626. this.b = ( b !== undefined ) ? b : new Vector3();
  8627. this.c = ( c !== undefined ) ? c : new Vector3();
  8628. }
  8629. Triangle.normal = function () {
  8630. var v0 = new Vector3();
  8631. return function normal( a, b, c, optionalTarget ) {
  8632. var result = optionalTarget || new Vector3();
  8633. result.subVectors( c, b );
  8634. v0.subVectors( a, b );
  8635. result.cross( v0 );
  8636. var resultLengthSq = result.lengthSq();
  8637. if ( resultLengthSq > 0 ) {
  8638. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  8639. }
  8640. return result.set( 0, 0, 0 );
  8641. };
  8642. }();
  8643. // static/instance method to calculate barycentric coordinates
  8644. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  8645. Triangle.barycoordFromPoint = function () {
  8646. var v0 = new Vector3();
  8647. var v1 = new Vector3();
  8648. var v2 = new Vector3();
  8649. return function barycoordFromPoint( point, a, b, c, optionalTarget ) {
  8650. v0.subVectors( c, a );
  8651. v1.subVectors( b, a );
  8652. v2.subVectors( point, a );
  8653. var dot00 = v0.dot( v0 );
  8654. var dot01 = v0.dot( v1 );
  8655. var dot02 = v0.dot( v2 );
  8656. var dot11 = v1.dot( v1 );
  8657. var dot12 = v1.dot( v2 );
  8658. var denom = ( dot00 * dot11 - dot01 * dot01 );
  8659. var result = optionalTarget || new Vector3();
  8660. // collinear or singular triangle
  8661. if ( denom === 0 ) {
  8662. // arbitrary location outside of triangle?
  8663. // not sure if this is the best idea, maybe should be returning undefined
  8664. return result.set( - 2, - 1, - 1 );
  8665. }
  8666. var invDenom = 1 / denom;
  8667. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  8668. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  8669. // barycentric coordinates must always sum to 1
  8670. return result.set( 1 - u - v, v, u );
  8671. };
  8672. }();
  8673. Triangle.containsPoint = function () {
  8674. var v1 = new Vector3();
  8675. return function containsPoint( point, a, b, c ) {
  8676. var result = Triangle.barycoordFromPoint( point, a, b, c, v1 );
  8677. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  8678. };
  8679. }();
  8680. Triangle.prototype = {
  8681. constructor: Triangle,
  8682. set: function ( a, b, c ) {
  8683. this.a.copy( a );
  8684. this.b.copy( b );
  8685. this.c.copy( c );
  8686. return this;
  8687. },
  8688. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  8689. this.a.copy( points[ i0 ] );
  8690. this.b.copy( points[ i1 ] );
  8691. this.c.copy( points[ i2 ] );
  8692. return this;
  8693. },
  8694. clone: function () {
  8695. return new this.constructor().copy( this );
  8696. },
  8697. copy: function ( triangle ) {
  8698. this.a.copy( triangle.a );
  8699. this.b.copy( triangle.b );
  8700. this.c.copy( triangle.c );
  8701. return this;
  8702. },
  8703. area: function () {
  8704. var v0 = new Vector3();
  8705. var v1 = new Vector3();
  8706. return function area() {
  8707. v0.subVectors( this.c, this.b );
  8708. v1.subVectors( this.a, this.b );
  8709. return v0.cross( v1 ).length() * 0.5;
  8710. };
  8711. }(),
  8712. midpoint: function ( optionalTarget ) {
  8713. var result = optionalTarget || new Vector3();
  8714. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  8715. },
  8716. normal: function ( optionalTarget ) {
  8717. return Triangle.normal( this.a, this.b, this.c, optionalTarget );
  8718. },
  8719. plane: function ( optionalTarget ) {
  8720. var result = optionalTarget || new Plane();
  8721. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  8722. },
  8723. barycoordFromPoint: function ( point, optionalTarget ) {
  8724. return Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  8725. },
  8726. containsPoint: function ( point ) {
  8727. return Triangle.containsPoint( point, this.a, this.b, this.c );
  8728. },
  8729. closestPointToPoint: function () {
  8730. var plane, edgeList, projectedPoint, closestPoint;
  8731. return function closestPointToPoint( point, optionalTarget ) {
  8732. if ( plane === undefined ) {
  8733. plane = new Plane();
  8734. edgeList = [ new Line3(), new Line3(), new Line3() ];
  8735. projectedPoint = new Vector3();
  8736. closestPoint = new Vector3();
  8737. }
  8738. var result = optionalTarget || new Vector3();
  8739. var minDistance = Infinity;
  8740. // project the point onto the plane of the triangle
  8741. plane.setFromCoplanarPoints( this.a, this.b, this.c );
  8742. plane.projectPoint( point, projectedPoint );
  8743. // check if the projection lies within the triangle
  8744. if( this.containsPoint( projectedPoint ) === true ) {
  8745. // if so, this is the closest point
  8746. result.copy( projectedPoint );
  8747. } else {
  8748. // if not, the point falls outside the triangle. the result is the closest point to the triangle's edges or vertices
  8749. edgeList[ 0 ].set( this.a, this.b );
  8750. edgeList[ 1 ].set( this.b, this.c );
  8751. edgeList[ 2 ].set( this.c, this.a );
  8752. for( var i = 0; i < edgeList.length; i ++ ) {
  8753. edgeList[ i ].closestPointToPoint( projectedPoint, true, closestPoint );
  8754. var distance = projectedPoint.distanceToSquared( closestPoint );
  8755. if( distance < minDistance ) {
  8756. minDistance = distance;
  8757. result.copy( closestPoint );
  8758. }
  8759. }
  8760. }
  8761. return result;
  8762. };
  8763. }(),
  8764. equals: function ( triangle ) {
  8765. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  8766. }
  8767. };
  8768. /**
  8769. * @author mrdoob / http://mrdoob.com/
  8770. * @author alteredq / http://alteredqualia.com/
  8771. *
  8772. * parameters = {
  8773. * color: <hex>,
  8774. * opacity: <float>,
  8775. * map: new THREE.Texture( <Image> ),
  8776. *
  8777. * aoMap: new THREE.Texture( <Image> ),
  8778. * aoMapIntensity: <float>
  8779. *
  8780. * specularMap: new THREE.Texture( <Image> ),
  8781. *
  8782. * alphaMap: new THREE.Texture( <Image> ),
  8783. *
  8784. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8785. * combine: THREE.Multiply,
  8786. * reflectivity: <float>,
  8787. * refractionRatio: <float>,
  8788. *
  8789. * shading: THREE.SmoothShading,
  8790. * depthTest: <bool>,
  8791. * depthWrite: <bool>,
  8792. *
  8793. * wireframe: <boolean>,
  8794. * wireframeLinewidth: <float>,
  8795. *
  8796. * skinning: <bool>,
  8797. * morphTargets: <bool>
  8798. * }
  8799. */
  8800. function MeshBasicMaterial( parameters ) {
  8801. Material.call( this );
  8802. this.type = 'MeshBasicMaterial';
  8803. this.color = new Color( 0xffffff ); // emissive
  8804. this.map = null;
  8805. this.aoMap = null;
  8806. this.aoMapIntensity = 1.0;
  8807. this.specularMap = null;
  8808. this.alphaMap = null;
  8809. this.envMap = null;
  8810. this.combine = MultiplyOperation;
  8811. this.reflectivity = 1;
  8812. this.refractionRatio = 0.98;
  8813. this.wireframe = false;
  8814. this.wireframeLinewidth = 1;
  8815. this.wireframeLinecap = 'round';
  8816. this.wireframeLinejoin = 'round';
  8817. this.skinning = false;
  8818. this.morphTargets = false;
  8819. this.lights = false;
  8820. this.setValues( parameters );
  8821. }
  8822. MeshBasicMaterial.prototype = Object.create( Material.prototype );
  8823. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  8824. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  8825. MeshBasicMaterial.prototype.copy = function ( source ) {
  8826. Material.prototype.copy.call( this, source );
  8827. this.color.copy( source.color );
  8828. this.map = source.map;
  8829. this.aoMap = source.aoMap;
  8830. this.aoMapIntensity = source.aoMapIntensity;
  8831. this.specularMap = source.specularMap;
  8832. this.alphaMap = source.alphaMap;
  8833. this.envMap = source.envMap;
  8834. this.combine = source.combine;
  8835. this.reflectivity = source.reflectivity;
  8836. this.refractionRatio = source.refractionRatio;
  8837. this.wireframe = source.wireframe;
  8838. this.wireframeLinewidth = source.wireframeLinewidth;
  8839. this.wireframeLinecap = source.wireframeLinecap;
  8840. this.wireframeLinejoin = source.wireframeLinejoin;
  8841. this.skinning = source.skinning;
  8842. this.morphTargets = source.morphTargets;
  8843. return this;
  8844. };
  8845. /**
  8846. * @author mrdoob / http://mrdoob.com/
  8847. * @author alteredq / http://alteredqualia.com/
  8848. * @author mikael emtinger / http://gomo.se/
  8849. * @author jonobr1 / http://jonobr1.com/
  8850. */
  8851. function Mesh( geometry, material ) {
  8852. Object3D.call( this );
  8853. this.type = 'Mesh';
  8854. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  8855. this.material = material !== undefined ? material : new MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  8856. this.drawMode = TrianglesDrawMode;
  8857. this.updateMorphTargets();
  8858. }
  8859. Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), {
  8860. constructor: Mesh,
  8861. isMesh: true,
  8862. setDrawMode: function ( value ) {
  8863. this.drawMode = value;
  8864. },
  8865. copy: function ( source ) {
  8866. Object3D.prototype.copy.call( this, source );
  8867. this.drawMode = source.drawMode;
  8868. return this;
  8869. },
  8870. updateMorphTargets: function () {
  8871. var morphTargets = this.geometry.morphTargets;
  8872. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  8873. this.morphTargetInfluences = [];
  8874. this.morphTargetDictionary = {};
  8875. for ( var m = 0, ml = morphTargets.length; m < ml; m ++ ) {
  8876. this.morphTargetInfluences.push( 0 );
  8877. this.morphTargetDictionary[ morphTargets[ m ].name ] = m;
  8878. }
  8879. }
  8880. },
  8881. raycast: ( function () {
  8882. var inverseMatrix = new Matrix4();
  8883. var ray = new Ray();
  8884. var sphere = new Sphere();
  8885. var vA = new Vector3();
  8886. var vB = new Vector3();
  8887. var vC = new Vector3();
  8888. var tempA = new Vector3();
  8889. var tempB = new Vector3();
  8890. var tempC = new Vector3();
  8891. var uvA = new Vector2();
  8892. var uvB = new Vector2();
  8893. var uvC = new Vector2();
  8894. var barycoord = new Vector3();
  8895. var intersectionPoint = new Vector3();
  8896. var intersectionPointWorld = new Vector3();
  8897. function uvIntersection( point, p1, p2, p3, uv1, uv2, uv3 ) {
  8898. Triangle.barycoordFromPoint( point, p1, p2, p3, barycoord );
  8899. uv1.multiplyScalar( barycoord.x );
  8900. uv2.multiplyScalar( barycoord.y );
  8901. uv3.multiplyScalar( barycoord.z );
  8902. uv1.add( uv2 ).add( uv3 );
  8903. return uv1.clone();
  8904. }
  8905. function checkIntersection( object, raycaster, ray, pA, pB, pC, point ) {
  8906. var intersect;
  8907. var material = object.material;
  8908. if ( material.side === BackSide ) {
  8909. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  8910. } else {
  8911. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );
  8912. }
  8913. if ( intersect === null ) return null;
  8914. intersectionPointWorld.copy( point );
  8915. intersectionPointWorld.applyMatrix4( object.matrixWorld );
  8916. var distance = raycaster.ray.origin.distanceTo( intersectionPointWorld );
  8917. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  8918. return {
  8919. distance: distance,
  8920. point: intersectionPointWorld.clone(),
  8921. object: object
  8922. };
  8923. }
  8924. function checkBufferGeometryIntersection( object, raycaster, ray, positions, uvs, a, b, c ) {
  8925. vA.fromArray( positions, a * 3 );
  8926. vB.fromArray( positions, b * 3 );
  8927. vC.fromArray( positions, c * 3 );
  8928. var intersection = checkIntersection( object, raycaster, ray, vA, vB, vC, intersectionPoint );
  8929. if ( intersection ) {
  8930. if ( uvs ) {
  8931. uvA.fromArray( uvs, a * 2 );
  8932. uvB.fromArray( uvs, b * 2 );
  8933. uvC.fromArray( uvs, c * 2 );
  8934. intersection.uv = uvIntersection( intersectionPoint, vA, vB, vC, uvA, uvB, uvC );
  8935. }
  8936. intersection.face = new Face3( a, b, c, Triangle.normal( vA, vB, vC ) );
  8937. intersection.faceIndex = a;
  8938. }
  8939. return intersection;
  8940. }
  8941. return function raycast( raycaster, intersects ) {
  8942. var geometry = this.geometry;
  8943. var material = this.material;
  8944. var matrixWorld = this.matrixWorld;
  8945. if ( material === undefined ) return;
  8946. // Checking boundingSphere distance to ray
  8947. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  8948. sphere.copy( geometry.boundingSphere );
  8949. sphere.applyMatrix4( matrixWorld );
  8950. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  8951. //
  8952. inverseMatrix.getInverse( matrixWorld );
  8953. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  8954. // Check boundingBox before continuing
  8955. if ( geometry.boundingBox !== null ) {
  8956. if ( ray.intersectsBox( geometry.boundingBox ) === false ) return;
  8957. }
  8958. var uvs, intersection;
  8959. if ( (geometry && geometry.isBufferGeometry) ) {
  8960. var a, b, c;
  8961. var index = geometry.index;
  8962. var attributes = geometry.attributes;
  8963. var positions = attributes.position.array;
  8964. if ( attributes.uv !== undefined ) {
  8965. uvs = attributes.uv.array;
  8966. }
  8967. if ( index !== null ) {
  8968. var indices = index.array;
  8969. for ( var i = 0, l = indices.length; i < l; i += 3 ) {
  8970. a = indices[ i ];
  8971. b = indices[ i + 1 ];
  8972. c = indices[ i + 2 ];
  8973. intersection = checkBufferGeometryIntersection( this, raycaster, ray, positions, uvs, a, b, c );
  8974. if ( intersection ) {
  8975. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indices buffer semantics
  8976. intersects.push( intersection );
  8977. }
  8978. }
  8979. } else {
  8980. for ( var i = 0, l = positions.length; i < l; i += 9 ) {
  8981. a = i / 3;
  8982. b = a + 1;
  8983. c = a + 2;
  8984. intersection = checkBufferGeometryIntersection( this, raycaster, ray, positions, uvs, a, b, c );
  8985. if ( intersection ) {
  8986. intersection.index = a; // triangle number in positions buffer semantics
  8987. intersects.push( intersection );
  8988. }
  8989. }
  8990. }
  8991. } else if ( (geometry && geometry.isGeometry) ) {
  8992. var fvA, fvB, fvC;
  8993. var isFaceMaterial = (material && material.isMultiMaterial);
  8994. var materials = isFaceMaterial === true ? material.materials : null;
  8995. var vertices = geometry.vertices;
  8996. var faces = geometry.faces;
  8997. var faceVertexUvs = geometry.faceVertexUvs[ 0 ];
  8998. if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs;
  8999. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  9000. var face = faces[ f ];
  9001. var faceMaterial = isFaceMaterial === true ? materials[ face.materialIndex ] : material;
  9002. if ( faceMaterial === undefined ) continue;
  9003. fvA = vertices[ face.a ];
  9004. fvB = vertices[ face.b ];
  9005. fvC = vertices[ face.c ];
  9006. if ( faceMaterial.morphTargets === true ) {
  9007. var morphTargets = geometry.morphTargets;
  9008. var morphInfluences = this.morphTargetInfluences;
  9009. vA.set( 0, 0, 0 );
  9010. vB.set( 0, 0, 0 );
  9011. vC.set( 0, 0, 0 );
  9012. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  9013. var influence = morphInfluences[ t ];
  9014. if ( influence === 0 ) continue;
  9015. var targets = morphTargets[ t ].vertices;
  9016. vA.addScaledVector( tempA.subVectors( targets[ face.a ], fvA ), influence );
  9017. vB.addScaledVector( tempB.subVectors( targets[ face.b ], fvB ), influence );
  9018. vC.addScaledVector( tempC.subVectors( targets[ face.c ], fvC ), influence );
  9019. }
  9020. vA.add( fvA );
  9021. vB.add( fvB );
  9022. vC.add( fvC );
  9023. fvA = vA;
  9024. fvB = vB;
  9025. fvC = vC;
  9026. }
  9027. intersection = checkIntersection( this, raycaster, ray, fvA, fvB, fvC, intersectionPoint );
  9028. if ( intersection ) {
  9029. if ( uvs ) {
  9030. var uvs_f = uvs[ f ];
  9031. uvA.copy( uvs_f[ 0 ] );
  9032. uvB.copy( uvs_f[ 1 ] );
  9033. uvC.copy( uvs_f[ 2 ] );
  9034. intersection.uv = uvIntersection( intersectionPoint, fvA, fvB, fvC, uvA, uvB, uvC );
  9035. }
  9036. intersection.face = face;
  9037. intersection.faceIndex = f;
  9038. intersects.push( intersection );
  9039. }
  9040. }
  9041. }
  9042. };
  9043. }() ),
  9044. clone: function () {
  9045. return new this.constructor( this.geometry, this.material ).copy( this );
  9046. }
  9047. } );
  9048. /**
  9049. * @author mrdoob / http://mrdoob.com/
  9050. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  9051. */
  9052. function PlaneBufferGeometry( width, height, widthSegments, heightSegments ) {
  9053. BufferGeometry.call( this );
  9054. this.type = 'PlaneBufferGeometry';
  9055. this.parameters = {
  9056. width: width,
  9057. height: height,
  9058. widthSegments: widthSegments,
  9059. heightSegments: heightSegments
  9060. };
  9061. var width_half = width / 2;
  9062. var height_half = height / 2;
  9063. var gridX = Math.floor( widthSegments ) || 1;
  9064. var gridY = Math.floor( heightSegments ) || 1;
  9065. var gridX1 = gridX + 1;
  9066. var gridY1 = gridY + 1;
  9067. var segment_width = width / gridX;
  9068. var segment_height = height / gridY;
  9069. var vertices = new Float32Array( gridX1 * gridY1 * 3 );
  9070. var normals = new Float32Array( gridX1 * gridY1 * 3 );
  9071. var uvs = new Float32Array( gridX1 * gridY1 * 2 );
  9072. var offset = 0;
  9073. var offset2 = 0;
  9074. for ( var iy = 0; iy < gridY1; iy ++ ) {
  9075. var y = iy * segment_height - height_half;
  9076. for ( var ix = 0; ix < gridX1; ix ++ ) {
  9077. var x = ix * segment_width - width_half;
  9078. vertices[ offset ] = x;
  9079. vertices[ offset + 1 ] = - y;
  9080. normals[ offset + 2 ] = 1;
  9081. uvs[ offset2 ] = ix / gridX;
  9082. uvs[ offset2 + 1 ] = 1 - ( iy / gridY );
  9083. offset += 3;
  9084. offset2 += 2;
  9085. }
  9086. }
  9087. offset = 0;
  9088. var indices = new ( ( vertices.length / 3 ) > 65535 ? Uint32Array : Uint16Array )( gridX * gridY * 6 );
  9089. for ( var iy = 0; iy < gridY; iy ++ ) {
  9090. for ( var ix = 0; ix < gridX; ix ++ ) {
  9091. var a = ix + gridX1 * iy;
  9092. var b = ix + gridX1 * ( iy + 1 );
  9093. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  9094. var d = ( ix + 1 ) + gridX1 * iy;
  9095. indices[ offset ] = a;
  9096. indices[ offset + 1 ] = b;
  9097. indices[ offset + 2 ] = d;
  9098. indices[ offset + 3 ] = b;
  9099. indices[ offset + 4 ] = c;
  9100. indices[ offset + 5 ] = d;
  9101. offset += 6;
  9102. }
  9103. }
  9104. this.setIndex( new BufferAttribute( indices, 1 ) );
  9105. this.addAttribute( 'position', new BufferAttribute( vertices, 3 ) );
  9106. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) );
  9107. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) );
  9108. }
  9109. PlaneBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  9110. PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry;
  9111. /**
  9112. * @author mrdoob / http://mrdoob.com/
  9113. * @author mikael emtinger / http://gomo.se/
  9114. * @author WestLangley / http://github.com/WestLangley
  9115. */
  9116. function Camera() {
  9117. Object3D.call( this );
  9118. this.type = 'Camera';
  9119. this.matrixWorldInverse = new Matrix4();
  9120. this.projectionMatrix = new Matrix4();
  9121. }
  9122. Camera.prototype = Object.create( Object3D.prototype );
  9123. Camera.prototype.constructor = Camera;
  9124. Camera.prototype.isCamera = true;
  9125. Camera.prototype.getWorldDirection = function () {
  9126. var quaternion = new Quaternion();
  9127. return function getWorldDirection( optionalTarget ) {
  9128. var result = optionalTarget || new Vector3();
  9129. this.getWorldQuaternion( quaternion );
  9130. return result.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  9131. };
  9132. }();
  9133. Camera.prototype.lookAt = function () {
  9134. // This routine does not support cameras with rotated and/or translated parent(s)
  9135. var m1 = new Matrix4();
  9136. return function lookAt( vector ) {
  9137. m1.lookAt( this.position, vector, this.up );
  9138. this.quaternion.setFromRotationMatrix( m1 );
  9139. };
  9140. }();
  9141. Camera.prototype.clone = function () {
  9142. return new this.constructor().copy( this );
  9143. };
  9144. Camera.prototype.copy = function ( source ) {
  9145. Object3D.prototype.copy.call( this, source );
  9146. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  9147. this.projectionMatrix.copy( source.projectionMatrix );
  9148. return this;
  9149. };
  9150. /**
  9151. * @author mrdoob / http://mrdoob.com/
  9152. * @author greggman / http://games.greggman.com/
  9153. * @author zz85 / http://www.lab4games.net/zz85/blog
  9154. * @author tschw
  9155. */
  9156. function PerspectiveCamera( fov, aspect, near, far ) {
  9157. Camera.call( this );
  9158. this.type = 'PerspectiveCamera';
  9159. this.fov = fov !== undefined ? fov : 50;
  9160. this.zoom = 1;
  9161. this.near = near !== undefined ? near : 0.1;
  9162. this.far = far !== undefined ? far : 2000;
  9163. this.focus = 10;
  9164. this.aspect = aspect !== undefined ? aspect : 1;
  9165. this.view = null;
  9166. this.filmGauge = 35; // width of the film (default in millimeters)
  9167. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  9168. this.updateProjectionMatrix();
  9169. }
  9170. PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  9171. constructor: PerspectiveCamera,
  9172. isPerspectiveCamera: true,
  9173. copy: function ( source ) {
  9174. Camera.prototype.copy.call( this, source );
  9175. this.fov = source.fov;
  9176. this.zoom = source.zoom;
  9177. this.near = source.near;
  9178. this.far = source.far;
  9179. this.focus = source.focus;
  9180. this.aspect = source.aspect;
  9181. this.view = source.view === null ? null : Object.assign( {}, source.view );
  9182. this.filmGauge = source.filmGauge;
  9183. this.filmOffset = source.filmOffset;
  9184. return this;
  9185. },
  9186. /**
  9187. * Sets the FOV by focal length in respect to the current .filmGauge.
  9188. *
  9189. * The default film gauge is 35, so that the focal length can be specified for
  9190. * a 35mm (full frame) camera.
  9191. *
  9192. * Values for focal length and film gauge must have the same unit.
  9193. */
  9194. setFocalLength: function ( focalLength ) {
  9195. // see http://www.bobatkins.com/photography/technical/field_of_view.html
  9196. var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  9197. this.fov = exports.Math.RAD2DEG * 2 * Math.atan( vExtentSlope );
  9198. this.updateProjectionMatrix();
  9199. },
  9200. /**
  9201. * Calculates the focal length from the current .fov and .filmGauge.
  9202. */
  9203. getFocalLength: function () {
  9204. var vExtentSlope = Math.tan( exports.Math.DEG2RAD * 0.5 * this.fov );
  9205. return 0.5 * this.getFilmHeight() / vExtentSlope;
  9206. },
  9207. getEffectiveFOV: function () {
  9208. return exports.Math.RAD2DEG * 2 * Math.atan(
  9209. Math.tan( exports.Math.DEG2RAD * 0.5 * this.fov ) / this.zoom );
  9210. },
  9211. getFilmWidth: function () {
  9212. // film not completely covered in portrait format (aspect < 1)
  9213. return this.filmGauge * Math.min( this.aspect, 1 );
  9214. },
  9215. getFilmHeight: function () {
  9216. // film not completely covered in landscape format (aspect > 1)
  9217. return this.filmGauge / Math.max( this.aspect, 1 );
  9218. },
  9219. /**
  9220. * Sets an offset in a larger frustum. This is useful for multi-window or
  9221. * multi-monitor/multi-machine setups.
  9222. *
  9223. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  9224. * the monitors are in grid like this
  9225. *
  9226. * +---+---+---+
  9227. * | A | B | C |
  9228. * +---+---+---+
  9229. * | D | E | F |
  9230. * +---+---+---+
  9231. *
  9232. * then for each monitor you would call it like this
  9233. *
  9234. * var w = 1920;
  9235. * var h = 1080;
  9236. * var fullWidth = w * 3;
  9237. * var fullHeight = h * 2;
  9238. *
  9239. * --A--
  9240. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  9241. * --B--
  9242. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  9243. * --C--
  9244. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  9245. * --D--
  9246. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  9247. * --E--
  9248. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  9249. * --F--
  9250. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  9251. *
  9252. * Note there is no reason monitors have to be the same size or in a grid.
  9253. */
  9254. setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
  9255. this.aspect = fullWidth / fullHeight;
  9256. this.view = {
  9257. fullWidth: fullWidth,
  9258. fullHeight: fullHeight,
  9259. offsetX: x,
  9260. offsetY: y,
  9261. width: width,
  9262. height: height
  9263. };
  9264. this.updateProjectionMatrix();
  9265. },
  9266. clearViewOffset: function() {
  9267. this.view = null;
  9268. this.updateProjectionMatrix();
  9269. },
  9270. updateProjectionMatrix: function () {
  9271. var near = this.near,
  9272. top = near * Math.tan(
  9273. exports.Math.DEG2RAD * 0.5 * this.fov ) / this.zoom,
  9274. height = 2 * top,
  9275. width = this.aspect * height,
  9276. left = - 0.5 * width,
  9277. view = this.view;
  9278. if ( view !== null ) {
  9279. var fullWidth = view.fullWidth,
  9280. fullHeight = view.fullHeight;
  9281. left += view.offsetX * width / fullWidth;
  9282. top -= view.offsetY * height / fullHeight;
  9283. width *= view.width / fullWidth;
  9284. height *= view.height / fullHeight;
  9285. }
  9286. var skew = this.filmOffset;
  9287. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  9288. this.projectionMatrix.makeFrustum(
  9289. left, left + width, top - height, top, near, this.far );
  9290. },
  9291. toJSON: function ( meta ) {
  9292. var data = Object3D.prototype.toJSON.call( this, meta );
  9293. data.object.fov = this.fov;
  9294. data.object.zoom = this.zoom;
  9295. data.object.near = this.near;
  9296. data.object.far = this.far;
  9297. data.object.focus = this.focus;
  9298. data.object.aspect = this.aspect;
  9299. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  9300. data.object.filmGauge = this.filmGauge;
  9301. data.object.filmOffset = this.filmOffset;
  9302. return data;
  9303. }
  9304. } );
  9305. /**
  9306. * @author alteredq / http://alteredqualia.com/
  9307. * @author arose / http://github.com/arose
  9308. */
  9309. function OrthographicCamera( left, right, top, bottom, near, far ) {
  9310. Camera.call( this );
  9311. this.type = 'OrthographicCamera';
  9312. this.zoom = 1;
  9313. this.view = null;
  9314. this.left = left;
  9315. this.right = right;
  9316. this.top = top;
  9317. this.bottom = bottom;
  9318. this.near = ( near !== undefined ) ? near : 0.1;
  9319. this.far = ( far !== undefined ) ? far : 2000;
  9320. this.updateProjectionMatrix();
  9321. }
  9322. OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  9323. constructor: OrthographicCamera,
  9324. isOrthographicCamera: true,
  9325. copy: function ( source ) {
  9326. Camera.prototype.copy.call( this, source );
  9327. this.left = source.left;
  9328. this.right = source.right;
  9329. this.top = source.top;
  9330. this.bottom = source.bottom;
  9331. this.near = source.near;
  9332. this.far = source.far;
  9333. this.zoom = source.zoom;
  9334. this.view = source.view === null ? null : Object.assign( {}, source.view );
  9335. return this;
  9336. },
  9337. setViewOffset: function( fullWidth, fullHeight, x, y, width, height ) {
  9338. this.view = {
  9339. fullWidth: fullWidth,
  9340. fullHeight: fullHeight,
  9341. offsetX: x,
  9342. offsetY: y,
  9343. width: width,
  9344. height: height
  9345. };
  9346. this.updateProjectionMatrix();
  9347. },
  9348. clearViewOffset: function() {
  9349. this.view = null;
  9350. this.updateProjectionMatrix();
  9351. },
  9352. updateProjectionMatrix: function () {
  9353. var dx = ( this.right - this.left ) / ( 2 * this.zoom );
  9354. var dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  9355. var cx = ( this.right + this.left ) / 2;
  9356. var cy = ( this.top + this.bottom ) / 2;
  9357. var left = cx - dx;
  9358. var right = cx + dx;
  9359. var top = cy + dy;
  9360. var bottom = cy - dy;
  9361. if ( this.view !== null ) {
  9362. var zoomW = this.zoom / ( this.view.width / this.view.fullWidth );
  9363. var zoomH = this.zoom / ( this.view.height / this.view.fullHeight );
  9364. var scaleW = ( this.right - this.left ) / this.view.width;
  9365. var scaleH = ( this.top - this.bottom ) / this.view.height;
  9366. left += scaleW * ( this.view.offsetX / zoomW );
  9367. right = left + scaleW * ( this.view.width / zoomW );
  9368. top -= scaleH * ( this.view.offsetY / zoomH );
  9369. bottom = top - scaleH * ( this.view.height / zoomH );
  9370. }
  9371. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  9372. },
  9373. toJSON: function ( meta ) {
  9374. var data = Object3D.prototype.toJSON.call( this, meta );
  9375. data.object.zoom = this.zoom;
  9376. data.object.left = this.left;
  9377. data.object.right = this.right;
  9378. data.object.top = this.top;
  9379. data.object.bottom = this.bottom;
  9380. data.object.near = this.near;
  9381. data.object.far = this.far;
  9382. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  9383. return data;
  9384. }
  9385. } );
  9386. /**
  9387. * @author mrdoob / http://mrdoob.com/
  9388. */
  9389. function WebGLIndexedBufferRenderer( gl, extensions, infoRender ) {
  9390. var mode;
  9391. function setMode( value ) {
  9392. mode = value;
  9393. }
  9394. var type, size;
  9395. function setIndex( index ) {
  9396. if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) {
  9397. type = gl.UNSIGNED_INT;
  9398. size = 4;
  9399. } else {
  9400. type = gl.UNSIGNED_SHORT;
  9401. size = 2;
  9402. }
  9403. }
  9404. function render( start, count ) {
  9405. gl.drawElements( mode, count, type, start * size );
  9406. infoRender.calls ++;
  9407. infoRender.vertices += count;
  9408. if ( mode === gl.TRIANGLES ) infoRender.faces += count / 3;
  9409. }
  9410. function renderInstances( geometry, start, count ) {
  9411. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  9412. if ( extension === null ) {
  9413. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9414. return;
  9415. }
  9416. extension.drawElementsInstancedANGLE( mode, count, type, start * size, geometry.maxInstancedCount );
  9417. infoRender.calls ++;
  9418. infoRender.vertices += count * geometry.maxInstancedCount;
  9419. if ( mode === gl.TRIANGLES ) infoRender.faces += geometry.maxInstancedCount * count / 3;
  9420. }
  9421. return {
  9422. setMode: setMode,
  9423. setIndex: setIndex,
  9424. render: render,
  9425. renderInstances: renderInstances
  9426. };
  9427. }
  9428. /**
  9429. * @author mrdoob / http://mrdoob.com/
  9430. */
  9431. function WebGLBufferRenderer( gl, extensions, infoRender ) {
  9432. var mode;
  9433. function setMode( value ) {
  9434. mode = value;
  9435. }
  9436. function render( start, count ) {
  9437. gl.drawArrays( mode, start, count );
  9438. infoRender.calls ++;
  9439. infoRender.vertices += count;
  9440. if ( mode === gl.TRIANGLES ) infoRender.faces += count / 3;
  9441. }
  9442. function renderInstances( geometry ) {
  9443. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  9444. if ( extension === null ) {
  9445. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9446. return;
  9447. }
  9448. var position = geometry.attributes.position;
  9449. var count = 0;
  9450. if ( (position && position.isInterleavedBufferAttribute) ) {
  9451. count = position.data.count;
  9452. extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount );
  9453. } else {
  9454. count = position.count;
  9455. extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount );
  9456. }
  9457. infoRender.calls ++;
  9458. infoRender.vertices += count * geometry.maxInstancedCount;
  9459. if ( mode === gl.TRIANGLES ) infoRender.faces += geometry.maxInstancedCount * count / 3;
  9460. }
  9461. return {
  9462. setMode: setMode,
  9463. render: render,
  9464. renderInstances: renderInstances
  9465. };
  9466. }
  9467. function WebGLLights() {
  9468. var lights = {};
  9469. return {
  9470. get: function ( light ) {
  9471. if ( lights[ light.id ] !== undefined ) {
  9472. return lights[ light.id ];
  9473. }
  9474. var uniforms;
  9475. switch ( light.type ) {
  9476. case 'DirectionalLight':
  9477. uniforms = {
  9478. direction: new Vector3(),
  9479. color: new Color(),
  9480. shadow: false,
  9481. shadowBias: 0,
  9482. shadowRadius: 1,
  9483. shadowMapSize: new Vector2()
  9484. };
  9485. break;
  9486. case 'SpotLight':
  9487. uniforms = {
  9488. position: new Vector3(),
  9489. direction: new Vector3(),
  9490. color: new Color(),
  9491. distance: 0,
  9492. coneCos: 0,
  9493. penumbraCos: 0,
  9494. decay: 0,
  9495. shadow: false,
  9496. shadowBias: 0,
  9497. shadowRadius: 1,
  9498. shadowMapSize: new Vector2()
  9499. };
  9500. break;
  9501. case 'PointLight':
  9502. uniforms = {
  9503. position: new Vector3(),
  9504. color: new Color(),
  9505. distance: 0,
  9506. decay: 0,
  9507. shadow: false,
  9508. shadowBias: 0,
  9509. shadowRadius: 1,
  9510. shadowMapSize: new Vector2()
  9511. };
  9512. break;
  9513. case 'HemisphereLight':
  9514. uniforms = {
  9515. direction: new Vector3(),
  9516. skyColor: new Color(),
  9517. groundColor: new Color()
  9518. };
  9519. break;
  9520. }
  9521. lights[ light.id ] = uniforms;
  9522. return uniforms;
  9523. }
  9524. };
  9525. }
  9526. /**
  9527. * @author mrdoob / http://mrdoob.com/
  9528. */
  9529. function addLineNumbers( string ) {
  9530. var lines = string.split( '\n' );
  9531. for ( var i = 0; i < lines.length; i ++ ) {
  9532. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  9533. }
  9534. return lines.join( '\n' );
  9535. }
  9536. function WebGLShader( gl, type, string ) {
  9537. var shader = gl.createShader( type );
  9538. gl.shaderSource( shader, string );
  9539. gl.compileShader( shader );
  9540. if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) {
  9541. console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' );
  9542. }
  9543. if ( gl.getShaderInfoLog( shader ) !== '' ) {
  9544. console.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', type === gl.VERTEX_SHADER ? 'vertex' : 'fragment', gl.getShaderInfoLog( shader ), addLineNumbers( string ) );
  9545. }
  9546. // --enable-privileged-webgl-extension
  9547. // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  9548. return shader;
  9549. }
  9550. var programIdCount = 0;
  9551. function getEncodingComponents( encoding ) {
  9552. switch ( encoding ) {
  9553. case LinearEncoding:
  9554. return [ 'Linear','( value )' ];
  9555. case sRGBEncoding:
  9556. return [ 'sRGB','( value )' ];
  9557. case RGBEEncoding:
  9558. return [ 'RGBE','( value )' ];
  9559. case RGBM7Encoding:
  9560. return [ 'RGBM','( value, 7.0 )' ];
  9561. case RGBM16Encoding:
  9562. return [ 'RGBM','( value, 16.0 )' ];
  9563. case RGBDEncoding:
  9564. return [ 'RGBD','( value, 256.0 )' ];
  9565. case GammaEncoding:
  9566. return [ 'Gamma','( value, float( GAMMA_FACTOR ) )' ];
  9567. default:
  9568. throw new Error( 'unsupported encoding: ' + encoding );
  9569. }
  9570. }
  9571. function getTexelDecodingFunction( functionName, encoding ) {
  9572. var components = getEncodingComponents( encoding );
  9573. return "vec4 " + functionName + "( vec4 value ) { return " + components[ 0 ] + "ToLinear" + components[ 1 ] + "; }";
  9574. }
  9575. function getTexelEncodingFunction( functionName, encoding ) {
  9576. var components = getEncodingComponents( encoding );
  9577. return "vec4 " + functionName + "( vec4 value ) { return LinearTo" + components[ 0 ] + components[ 1 ] + "; }";
  9578. }
  9579. function getToneMappingFunction( functionName, toneMapping ) {
  9580. var toneMappingName;
  9581. switch ( toneMapping ) {
  9582. case LinearToneMapping:
  9583. toneMappingName = "Linear";
  9584. break;
  9585. case ReinhardToneMapping:
  9586. toneMappingName = "Reinhard";
  9587. break;
  9588. case Uncharted2ToneMapping:
  9589. toneMappingName = "Uncharted2";
  9590. break;
  9591. case CineonToneMapping:
  9592. toneMappingName = "OptimizedCineon";
  9593. break;
  9594. default:
  9595. throw new Error( 'unsupported toneMapping: ' + toneMapping );
  9596. }
  9597. return "vec3 " + functionName + "( vec3 color ) { return " + toneMappingName + "ToneMapping( color ); }";
  9598. }
  9599. function generateExtensions( extensions, parameters, rendererExtensions ) {
  9600. extensions = extensions || {};
  9601. var chunks = [
  9602. ( extensions.derivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.normalMap || parameters.flatShading ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  9603. ( extensions.fragDepth || parameters.logarithmicDepthBuffer ) && rendererExtensions.get( 'EXT_frag_depth' ) ? '#extension GL_EXT_frag_depth : enable' : '',
  9604. ( extensions.drawBuffers ) && rendererExtensions.get( 'WEBGL_draw_buffers' ) ? '#extension GL_EXT_draw_buffers : require' : '',
  9605. ( extensions.shaderTextureLOD || parameters.envMap ) && rendererExtensions.get( 'EXT_shader_texture_lod' ) ? '#extension GL_EXT_shader_texture_lod : enable' : '',
  9606. ];
  9607. return chunks.filter( filterEmptyLine ).join( '\n' );
  9608. }
  9609. function generateDefines( defines ) {
  9610. var chunks = [];
  9611. for ( var name in defines ) {
  9612. var value = defines[ name ];
  9613. if ( value === false ) continue;
  9614. chunks.push( '#define ' + name + ' ' + value );
  9615. }
  9616. return chunks.join( '\n' );
  9617. }
  9618. function fetchAttributeLocations( gl, program, identifiers ) {
  9619. var attributes = {};
  9620. var n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  9621. for ( var i = 0; i < n; i ++ ) {
  9622. var info = gl.getActiveAttrib( program, i );
  9623. var name = info.name;
  9624. // console.log("THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:", name, i );
  9625. attributes[ name ] = gl.getAttribLocation( program, name );
  9626. }
  9627. return attributes;
  9628. }
  9629. function filterEmptyLine( string ) {
  9630. return string !== '';
  9631. }
  9632. function replaceLightNums( string, parameters ) {
  9633. return string
  9634. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  9635. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  9636. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  9637. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights );
  9638. }
  9639. function parseIncludes( string ) {
  9640. var pattern = /#include +<([\w\d.]+)>/g;
  9641. function replace( match, include ) {
  9642. var replace = ShaderChunk[ include ];
  9643. if ( replace === undefined ) {
  9644. throw new Error( 'Can not resolve #include <' + include + '>' );
  9645. }
  9646. return parseIncludes( replace );
  9647. }
  9648. return string.replace( pattern, replace );
  9649. }
  9650. function unrollLoops( string ) {
  9651. var pattern = /for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  9652. function replace( match, start, end, snippet ) {
  9653. var unroll = '';
  9654. for ( var i = parseInt( start ); i < parseInt( end ); i ++ ) {
  9655. unroll += snippet.replace( /\[ i \]/g, '[ ' + i + ' ]' );
  9656. }
  9657. return unroll;
  9658. }
  9659. return string.replace( pattern, replace );
  9660. }
  9661. function WebGLProgram( renderer, code, material, parameters ) {
  9662. var gl = renderer.context;
  9663. var extensions = material.extensions;
  9664. var defines = material.defines;
  9665. var vertexShader = material.__webglShader.vertexShader;
  9666. var fragmentShader = material.__webglShader.fragmentShader;
  9667. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  9668. if ( parameters.shadowMapType === PCFShadowMap ) {
  9669. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  9670. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  9671. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  9672. }
  9673. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  9674. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  9675. var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  9676. if ( parameters.envMap ) {
  9677. switch ( material.envMap.mapping ) {
  9678. case CubeReflectionMapping:
  9679. case CubeRefractionMapping:
  9680. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  9681. break;
  9682. case CubeUVReflectionMapping:
  9683. case CubeUVRefractionMapping:
  9684. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  9685. break;
  9686. case EquirectangularReflectionMapping:
  9687. case EquirectangularRefractionMapping:
  9688. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  9689. break;
  9690. case SphericalReflectionMapping:
  9691. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  9692. break;
  9693. }
  9694. switch ( material.envMap.mapping ) {
  9695. case CubeRefractionMapping:
  9696. case EquirectangularRefractionMapping:
  9697. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  9698. break;
  9699. }
  9700. switch ( material.combine ) {
  9701. case MultiplyOperation:
  9702. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  9703. break;
  9704. case MixOperation:
  9705. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  9706. break;
  9707. case AddOperation:
  9708. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  9709. break;
  9710. }
  9711. }
  9712. var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  9713. // console.log( 'building new program ' );
  9714. //
  9715. var customExtensions = generateExtensions( extensions, parameters, renderer.extensions );
  9716. var customDefines = generateDefines( defines );
  9717. //
  9718. var program = gl.createProgram();
  9719. var prefixVertex, prefixFragment;
  9720. if ( material.isRawShaderMaterial ) {
  9721. prefixVertex = [
  9722. customDefines,
  9723. '\n'
  9724. ].filter( filterEmptyLine ).join( '\n' );
  9725. prefixFragment = [
  9726. customExtensions,
  9727. customDefines,
  9728. '\n'
  9729. ].filter( filterEmptyLine ).join( '\n' );
  9730. } else {
  9731. prefixVertex = [
  9732. 'precision ' + parameters.precision + ' float;',
  9733. 'precision ' + parameters.precision + ' int;',
  9734. '#define SHADER_NAME ' + material.__webglShader.name,
  9735. customDefines,
  9736. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  9737. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  9738. '#define MAX_BONES ' + parameters.maxBones,
  9739. parameters.map ? '#define USE_MAP' : '',
  9740. parameters.envMap ? '#define USE_ENVMAP' : '',
  9741. parameters.envMap ? '#define ' + envMapModeDefine : '',
  9742. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  9743. parameters.aoMap ? '#define USE_AOMAP' : '',
  9744. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  9745. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  9746. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  9747. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  9748. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  9749. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  9750. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  9751. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  9752. parameters.vertexColors ? '#define USE_COLOR' : '',
  9753. parameters.flatShading ? '#define FLAT_SHADED' : '',
  9754. parameters.skinning ? '#define USE_SKINNING' : '',
  9755. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  9756. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  9757. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  9758. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  9759. parameters.flipSided ? '#define FLIP_SIDED' : '',
  9760. '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes,
  9761. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  9762. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  9763. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  9764. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  9765. parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  9766. 'uniform mat4 modelMatrix;',
  9767. 'uniform mat4 modelViewMatrix;',
  9768. 'uniform mat4 projectionMatrix;',
  9769. 'uniform mat4 viewMatrix;',
  9770. 'uniform mat3 normalMatrix;',
  9771. 'uniform vec3 cameraPosition;',
  9772. 'attribute vec3 position;',
  9773. 'attribute vec3 normal;',
  9774. 'attribute vec2 uv;',
  9775. '#ifdef USE_COLOR',
  9776. ' attribute vec3 color;',
  9777. '#endif',
  9778. '#ifdef USE_MORPHTARGETS',
  9779. ' attribute vec3 morphTarget0;',
  9780. ' attribute vec3 morphTarget1;',
  9781. ' attribute vec3 morphTarget2;',
  9782. ' attribute vec3 morphTarget3;',
  9783. ' #ifdef USE_MORPHNORMALS',
  9784. ' attribute vec3 morphNormal0;',
  9785. ' attribute vec3 morphNormal1;',
  9786. ' attribute vec3 morphNormal2;',
  9787. ' attribute vec3 morphNormal3;',
  9788. ' #else',
  9789. ' attribute vec3 morphTarget4;',
  9790. ' attribute vec3 morphTarget5;',
  9791. ' attribute vec3 morphTarget6;',
  9792. ' attribute vec3 morphTarget7;',
  9793. ' #endif',
  9794. '#endif',
  9795. '#ifdef USE_SKINNING',
  9796. ' attribute vec4 skinIndex;',
  9797. ' attribute vec4 skinWeight;',
  9798. '#endif',
  9799. '\n'
  9800. ].filter( filterEmptyLine ).join( '\n' );
  9801. prefixFragment = [
  9802. customExtensions,
  9803. 'precision ' + parameters.precision + ' float;',
  9804. 'precision ' + parameters.precision + ' int;',
  9805. '#define SHADER_NAME ' + material.__webglShader.name,
  9806. customDefines,
  9807. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest : '',
  9808. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  9809. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  9810. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  9811. parameters.map ? '#define USE_MAP' : '',
  9812. parameters.envMap ? '#define USE_ENVMAP' : '',
  9813. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  9814. parameters.envMap ? '#define ' + envMapModeDefine : '',
  9815. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  9816. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  9817. parameters.aoMap ? '#define USE_AOMAP' : '',
  9818. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  9819. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  9820. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  9821. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  9822. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  9823. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  9824. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  9825. parameters.vertexColors ? '#define USE_COLOR' : '',
  9826. parameters.flatShading ? '#define FLAT_SHADED' : '',
  9827. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  9828. parameters.flipSided ? '#define FLIP_SIDED' : '',
  9829. '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes,
  9830. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  9831. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  9832. parameters.premultipliedAlpha ? "#define PREMULTIPLIED_ALPHA" : '',
  9833. parameters.physicallyCorrectLights ? "#define PHYSICALLY_CORRECT_LIGHTS" : '',
  9834. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  9835. parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  9836. parameters.envMap && renderer.extensions.get( 'EXT_shader_texture_lod' ) ? '#define TEXTURE_LOD_EXT' : '',
  9837. 'uniform mat4 viewMatrix;',
  9838. 'uniform vec3 cameraPosition;',
  9839. ( parameters.toneMapping !== NoToneMapping ) ? "#define TONE_MAPPING" : '',
  9840. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  9841. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( "toneMapping", parameters.toneMapping ) : '',
  9842. ( 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
  9843. parameters.mapEncoding ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '',
  9844. parameters.envMapEncoding ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '',
  9845. parameters.emissiveMapEncoding ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '',
  9846. parameters.outputEncoding ? getTexelEncodingFunction( "linearToOutputTexel", parameters.outputEncoding ) : '',
  9847. parameters.depthPacking ? "#define DEPTH_PACKING " + material.depthPacking : '',
  9848. '\n'
  9849. ].filter( filterEmptyLine ).join( '\n' );
  9850. }
  9851. vertexShader = parseIncludes( vertexShader, parameters );
  9852. vertexShader = replaceLightNums( vertexShader, parameters );
  9853. fragmentShader = parseIncludes( fragmentShader, parameters );
  9854. fragmentShader = replaceLightNums( fragmentShader, parameters );
  9855. if ( ! material.isShaderMaterial ) {
  9856. vertexShader = unrollLoops( vertexShader );
  9857. fragmentShader = unrollLoops( fragmentShader );
  9858. }
  9859. var vertexGlsl = prefixVertex + vertexShader;
  9860. var fragmentGlsl = prefixFragment + fragmentShader;
  9861. // console.log( '*VERTEX*', vertexGlsl );
  9862. // console.log( '*FRAGMENT*', fragmentGlsl );
  9863. var glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  9864. var glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  9865. gl.attachShader( program, glVertexShader );
  9866. gl.attachShader( program, glFragmentShader );
  9867. // Force a particular attribute to index 0.
  9868. if ( material.index0AttributeName !== undefined ) {
  9869. gl.bindAttribLocation( program, 0, material.index0AttributeName );
  9870. } else if ( parameters.morphTargets === true ) {
  9871. // programs with morphTargets displace position out of attribute 0
  9872. gl.bindAttribLocation( program, 0, 'position' );
  9873. }
  9874. gl.linkProgram( program );
  9875. var programLog = gl.getProgramInfoLog( program );
  9876. var vertexLog = gl.getShaderInfoLog( glVertexShader );
  9877. var fragmentLog = gl.getShaderInfoLog( glFragmentShader );
  9878. var runnable = true;
  9879. var haveDiagnostics = true;
  9880. // console.log( '**VERTEX**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glVertexShader ) );
  9881. // console.log( '**FRAGMENT**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glFragmentShader ) );
  9882. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  9883. runnable = false;
  9884. console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), 'gl.VALIDATE_STATUS', gl.getProgramParameter( program, gl.VALIDATE_STATUS ), 'gl.getProgramInfoLog', programLog, vertexLog, fragmentLog );
  9885. } else if ( programLog !== '' ) {
  9886. console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog );
  9887. } else if ( vertexLog === '' || fragmentLog === '' ) {
  9888. haveDiagnostics = false;
  9889. }
  9890. if ( haveDiagnostics ) {
  9891. this.diagnostics = {
  9892. runnable: runnable,
  9893. material: material,
  9894. programLog: programLog,
  9895. vertexShader: {
  9896. log: vertexLog,
  9897. prefix: prefixVertex
  9898. },
  9899. fragmentShader: {
  9900. log: fragmentLog,
  9901. prefix: prefixFragment
  9902. }
  9903. };
  9904. }
  9905. // clean up
  9906. gl.deleteShader( glVertexShader );
  9907. gl.deleteShader( glFragmentShader );
  9908. // set up caching for uniform locations
  9909. var cachedUniforms;
  9910. this.getUniforms = function() {
  9911. if ( cachedUniforms === undefined ) {
  9912. cachedUniforms =
  9913. new WebGLUniforms( gl, program, renderer );
  9914. }
  9915. return cachedUniforms;
  9916. };
  9917. // set up caching for attribute locations
  9918. var cachedAttributes;
  9919. this.getAttributes = function() {
  9920. if ( cachedAttributes === undefined ) {
  9921. cachedAttributes = fetchAttributeLocations( gl, program );
  9922. }
  9923. return cachedAttributes;
  9924. };
  9925. // free resource
  9926. this.destroy = function() {
  9927. gl.deleteProgram( program );
  9928. this.program = undefined;
  9929. };
  9930. // DEPRECATED
  9931. Object.defineProperties( this, {
  9932. uniforms: {
  9933. get: function() {
  9934. console.warn( 'THREE.WebGLProgram: .uniforms is now .getUniforms().' );
  9935. return this.getUniforms();
  9936. }
  9937. },
  9938. attributes: {
  9939. get: function() {
  9940. console.warn( 'THREE.WebGLProgram: .attributes is now .getAttributes().' );
  9941. return this.getAttributes();
  9942. }
  9943. }
  9944. } );
  9945. //
  9946. this.id = programIdCount ++;
  9947. this.code = code;
  9948. this.usedTimes = 1;
  9949. this.program = program;
  9950. this.vertexShader = glVertexShader;
  9951. this.fragmentShader = glFragmentShader;
  9952. return this;
  9953. }
  9954. function WebGLPrograms( renderer, capabilities ) {
  9955. var programs = [];
  9956. var shaderIDs = {
  9957. MeshDepthMaterial: 'depth',
  9958. MeshNormalMaterial: 'normal',
  9959. MeshBasicMaterial: 'basic',
  9960. MeshLambertMaterial: 'lambert',
  9961. MeshPhongMaterial: 'phong',
  9962. MeshStandardMaterial: 'physical',
  9963. MeshPhysicalMaterial: 'physical',
  9964. LineBasicMaterial: 'basic',
  9965. LineDashedMaterial: 'dashed',
  9966. PointsMaterial: 'points'
  9967. };
  9968. var parameterNames = [
  9969. "precision", "supportsVertexTextures", "map", "mapEncoding", "envMap", "envMapMode", "envMapEncoding",
  9970. "lightMap", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "displacementMap", "specularMap",
  9971. "roughnessMap", "metalnessMap",
  9972. "alphaMap", "combine", "vertexColors", "fog", "useFog", "fogExp",
  9973. "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning",
  9974. "maxBones", "useVertexTexture", "morphTargets", "morphNormals",
  9975. "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha",
  9976. "numDirLights", "numPointLights", "numSpotLights", "numHemiLights",
  9977. "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights',
  9978. "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "depthPacking"
  9979. ];
  9980. function allocateBones( object ) {
  9981. if ( capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture ) {
  9982. return 1024;
  9983. } else {
  9984. // default for when object is not specified
  9985. // ( for example when prebuilding shader to be used with multiple objects )
  9986. //
  9987. // - leave some extra space for other uniforms
  9988. // - limit here is ANGLE's 254 max uniform vectors
  9989. // (up to 54 should be safe)
  9990. var nVertexUniforms = capabilities.maxVertexUniforms;
  9991. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  9992. var maxBones = nVertexMatrices;
  9993. if ( object !== undefined && (object && object.isSkinnedMesh) ) {
  9994. maxBones = Math.min( object.skeleton.bones.length, maxBones );
  9995. if ( maxBones < object.skeleton.bones.length ) {
  9996. console.warn( 'WebGLRenderer: too many bones - ' + object.skeleton.bones.length + ', this GPU supports just ' + maxBones + ' (try OpenGL instead of ANGLE)' );
  9997. }
  9998. }
  9999. return maxBones;
  10000. }
  10001. }
  10002. function getTextureEncodingFromMap( map, gammaOverrideLinear ) {
  10003. var encoding;
  10004. if ( ! map ) {
  10005. encoding = LinearEncoding;
  10006. } else if ( (map && map.isTexture) ) {
  10007. encoding = map.encoding;
  10008. } else if ( (map && map.isWebGLRenderTarget) ) {
  10009. console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." );
  10010. encoding = map.texture.encoding;
  10011. }
  10012. // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point.
  10013. if ( encoding === LinearEncoding && gammaOverrideLinear ) {
  10014. encoding = GammaEncoding;
  10015. }
  10016. return encoding;
  10017. }
  10018. this.getParameters = function ( material, lights, fog, nClipPlanes, object ) {
  10019. var shaderID = shaderIDs[ material.type ];
  10020. // heuristics to create shader parameters according to lights in the scene
  10021. // (not to blow over maxLights budget)
  10022. var maxBones = allocateBones( object );
  10023. var precision = renderer.getPrecision();
  10024. if ( material.precision !== null ) {
  10025. precision = capabilities.getMaxPrecision( material.precision );
  10026. if ( precision !== material.precision ) {
  10027. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  10028. }
  10029. }
  10030. var currentRenderTarget = renderer.getCurrentRenderTarget();
  10031. var parameters = {
  10032. shaderID: shaderID,
  10033. precision: precision,
  10034. supportsVertexTextures: capabilities.vertexTextures,
  10035. outputEncoding: getTextureEncodingFromMap( ( ! currentRenderTarget ) ? null : currentRenderTarget.texture, renderer.gammaOutput ),
  10036. map: !! material.map,
  10037. mapEncoding: getTextureEncodingFromMap( material.map, renderer.gammaInput ),
  10038. envMap: !! material.envMap,
  10039. envMapMode: material.envMap && material.envMap.mapping,
  10040. envMapEncoding: getTextureEncodingFromMap( material.envMap, renderer.gammaInput ),
  10041. envMapCubeUV: ( !! material.envMap ) && ( ( material.envMap.mapping === CubeUVReflectionMapping ) || ( material.envMap.mapping === CubeUVRefractionMapping ) ),
  10042. lightMap: !! material.lightMap,
  10043. aoMap: !! material.aoMap,
  10044. emissiveMap: !! material.emissiveMap,
  10045. emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap, renderer.gammaInput ),
  10046. bumpMap: !! material.bumpMap,
  10047. normalMap: !! material.normalMap,
  10048. displacementMap: !! material.displacementMap,
  10049. roughnessMap: !! material.roughnessMap,
  10050. metalnessMap: !! material.metalnessMap,
  10051. specularMap: !! material.specularMap,
  10052. alphaMap: !! material.alphaMap,
  10053. combine: material.combine,
  10054. vertexColors: material.vertexColors,
  10055. fog: !! fog,
  10056. useFog: material.fog,
  10057. fogExp: (fog && fog.isFogExp2),
  10058. flatShading: material.shading === FlatShading,
  10059. sizeAttenuation: material.sizeAttenuation,
  10060. logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer,
  10061. skinning: material.skinning,
  10062. maxBones: maxBones,
  10063. useVertexTexture: capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture,
  10064. morphTargets: material.morphTargets,
  10065. morphNormals: material.morphNormals,
  10066. maxMorphTargets: renderer.maxMorphTargets,
  10067. maxMorphNormals: renderer.maxMorphNormals,
  10068. numDirLights: lights.directional.length,
  10069. numPointLights: lights.point.length,
  10070. numSpotLights: lights.spot.length,
  10071. numHemiLights: lights.hemi.length,
  10072. numClippingPlanes: nClipPlanes,
  10073. shadowMapEnabled: renderer.shadowMap.enabled && object.receiveShadow && lights.shadows.length > 0,
  10074. shadowMapType: renderer.shadowMap.type,
  10075. toneMapping: renderer.toneMapping,
  10076. physicallyCorrectLights: renderer.physicallyCorrectLights,
  10077. premultipliedAlpha: material.premultipliedAlpha,
  10078. alphaTest: material.alphaTest,
  10079. doubleSided: material.side === DoubleSide,
  10080. flipSided: material.side === BackSide,
  10081. depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false
  10082. };
  10083. return parameters;
  10084. };
  10085. this.getProgramCode = function ( material, parameters ) {
  10086. var array = [];
  10087. if ( parameters.shaderID ) {
  10088. array.push( parameters.shaderID );
  10089. } else {
  10090. array.push( material.fragmentShader );
  10091. array.push( material.vertexShader );
  10092. }
  10093. if ( material.defines !== undefined ) {
  10094. for ( var name in material.defines ) {
  10095. array.push( name );
  10096. array.push( material.defines[ name ] );
  10097. }
  10098. }
  10099. for ( var i = 0; i < parameterNames.length; i ++ ) {
  10100. array.push( parameters[ parameterNames[ i ] ] );
  10101. }
  10102. return array.join();
  10103. };
  10104. this.acquireProgram = function ( material, parameters, code ) {
  10105. var program;
  10106. // Check if code has been already compiled
  10107. for ( var p = 0, pl = programs.length; p < pl; p ++ ) {
  10108. var programInfo = programs[ p ];
  10109. if ( programInfo.code === code ) {
  10110. program = programInfo;
  10111. ++ program.usedTimes;
  10112. break;
  10113. }
  10114. }
  10115. if ( program === undefined ) {
  10116. program = new WebGLProgram( renderer, code, material, parameters );
  10117. programs.push( program );
  10118. }
  10119. return program;
  10120. };
  10121. this.releaseProgram = function( program ) {
  10122. if ( -- program.usedTimes === 0 ) {
  10123. // Remove from unordered set
  10124. var i = programs.indexOf( program );
  10125. programs[ i ] = programs[ programs.length - 1 ];
  10126. programs.pop();
  10127. // Free WebGL resources
  10128. program.destroy();
  10129. }
  10130. };
  10131. // Exposed for resource monitoring & error feedback via renderer.info:
  10132. this.programs = programs;
  10133. }
  10134. function WebGLGeometries( gl, properties, info ) {
  10135. var geometries = {};
  10136. function onGeometryDispose( event ) {
  10137. var geometry = event.target;
  10138. var buffergeometry = geometries[ geometry.id ];
  10139. if ( buffergeometry.index !== null ) {
  10140. deleteAttribute( buffergeometry.index );
  10141. }
  10142. deleteAttributes( buffergeometry.attributes );
  10143. geometry.removeEventListener( 'dispose', onGeometryDispose );
  10144. delete geometries[ geometry.id ];
  10145. // TODO
  10146. var property = properties.get( geometry );
  10147. if ( property.wireframe ) {
  10148. deleteAttribute( property.wireframe );
  10149. }
  10150. properties.delete( geometry );
  10151. var bufferproperty = properties.get( buffergeometry );
  10152. if ( bufferproperty.wireframe ) {
  10153. deleteAttribute( bufferproperty.wireframe );
  10154. }
  10155. properties.delete( buffergeometry );
  10156. //
  10157. info.memory.geometries --;
  10158. }
  10159. function getAttributeBuffer( attribute ) {
  10160. if ( attribute.isInterleavedBufferAttribute ) {
  10161. return properties.get( attribute.data ).__webglBuffer;
  10162. }
  10163. return properties.get( attribute ).__webglBuffer;
  10164. }
  10165. function deleteAttribute( attribute ) {
  10166. var buffer = getAttributeBuffer( attribute );
  10167. if ( buffer !== undefined ) {
  10168. gl.deleteBuffer( buffer );
  10169. removeAttributeBuffer( attribute );
  10170. }
  10171. }
  10172. function deleteAttributes( attributes ) {
  10173. for ( var name in attributes ) {
  10174. deleteAttribute( attributes[ name ] );
  10175. }
  10176. }
  10177. function removeAttributeBuffer( attribute ) {
  10178. if ( attribute.isInterleavedBufferAttribute ) {
  10179. properties.delete( attribute.data );
  10180. } else {
  10181. properties.delete( attribute );
  10182. }
  10183. }
  10184. return {
  10185. get: function ( object ) {
  10186. var geometry = object.geometry;
  10187. if ( geometries[ geometry.id ] !== undefined ) {
  10188. return geometries[ geometry.id ];
  10189. }
  10190. geometry.addEventListener( 'dispose', onGeometryDispose );
  10191. var buffergeometry;
  10192. if ( geometry.isBufferGeometry ) {
  10193. buffergeometry = geometry;
  10194. } else if ( geometry.isGeometry ) {
  10195. if ( geometry._bufferGeometry === undefined ) {
  10196. geometry._bufferGeometry = new BufferGeometry().setFromObject( object );
  10197. }
  10198. buffergeometry = geometry._bufferGeometry;
  10199. }
  10200. geometries[ geometry.id ] = buffergeometry;
  10201. info.memory.geometries ++;
  10202. return buffergeometry;
  10203. }
  10204. };
  10205. }
  10206. function WebGLObjects( gl, properties, info ) {
  10207. var geometries = new WebGLGeometries( gl, properties, info );
  10208. //
  10209. function update( object ) {
  10210. // TODO: Avoid updating twice (when using shadowMap). Maybe add frame counter.
  10211. var geometry = geometries.get( object );
  10212. if ( object.geometry.isGeometry ) {
  10213. geometry.updateFromObject( object );
  10214. }
  10215. var index = geometry.index;
  10216. var attributes = geometry.attributes;
  10217. if ( index !== null ) {
  10218. updateAttribute( index, gl.ELEMENT_ARRAY_BUFFER );
  10219. }
  10220. for ( var name in attributes ) {
  10221. updateAttribute( attributes[ name ], gl.ARRAY_BUFFER );
  10222. }
  10223. // morph targets
  10224. var morphAttributes = geometry.morphAttributes;
  10225. for ( var name in morphAttributes ) {
  10226. var array = morphAttributes[ name ];
  10227. for ( var i = 0, l = array.length; i < l; i ++ ) {
  10228. updateAttribute( array[ i ], gl.ARRAY_BUFFER );
  10229. }
  10230. }
  10231. return geometry;
  10232. }
  10233. function updateAttribute( attribute, bufferType ) {
  10234. var data = ( attribute.isInterleavedBufferAttribute ) ? attribute.data : attribute;
  10235. var attributeProperties = properties.get( data );
  10236. if ( attributeProperties.__webglBuffer === undefined ) {
  10237. createBuffer( attributeProperties, data, bufferType );
  10238. } else if ( attributeProperties.version !== data.version ) {
  10239. updateBuffer( attributeProperties, data, bufferType );
  10240. }
  10241. }
  10242. function createBuffer( attributeProperties, data, bufferType ) {
  10243. attributeProperties.__webglBuffer = gl.createBuffer();
  10244. gl.bindBuffer( bufferType, attributeProperties.__webglBuffer );
  10245. var usage = data.dynamic ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW;
  10246. gl.bufferData( bufferType, data.array, usage );
  10247. attributeProperties.version = data.version;
  10248. }
  10249. function updateBuffer( attributeProperties, data, bufferType ) {
  10250. gl.bindBuffer( bufferType, attributeProperties.__webglBuffer );
  10251. if ( data.dynamic === false || data.updateRange.count === - 1 ) {
  10252. // Not using update ranges
  10253. gl.bufferSubData( bufferType, 0, data.array );
  10254. } else if ( data.updateRange.count === 0 ) {
  10255. 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.' );
  10256. } else {
  10257. gl.bufferSubData( bufferType, data.updateRange.offset * data.array.BYTES_PER_ELEMENT,
  10258. data.array.subarray( data.updateRange.offset, data.updateRange.offset + data.updateRange.count ) );
  10259. data.updateRange.count = 0; // reset range
  10260. }
  10261. attributeProperties.version = data.version;
  10262. }
  10263. function getAttributeBuffer( attribute ) {
  10264. if ( attribute.isInterleavedBufferAttribute ) {
  10265. return properties.get( attribute.data ).__webglBuffer;
  10266. }
  10267. return properties.get( attribute ).__webglBuffer;
  10268. }
  10269. function getWireframeAttribute( geometry ) {
  10270. var property = properties.get( geometry );
  10271. if ( property.wireframe !== undefined ) {
  10272. return property.wireframe;
  10273. }
  10274. var indices = [];
  10275. var index = geometry.index;
  10276. var attributes = geometry.attributes;
  10277. var position = attributes.position;
  10278. // console.time( 'wireframe' );
  10279. if ( index !== null ) {
  10280. var edges = {};
  10281. var array = index.array;
  10282. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  10283. var a = array[ i + 0 ];
  10284. var b = array[ i + 1 ];
  10285. var c = array[ i + 2 ];
  10286. if ( checkEdge( edges, a, b ) ) indices.push( a, b );
  10287. if ( checkEdge( edges, b, c ) ) indices.push( b, c );
  10288. if ( checkEdge( edges, c, a ) ) indices.push( c, a );
  10289. }
  10290. } else {
  10291. var array = attributes.position.array;
  10292. for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  10293. var a = i + 0;
  10294. var b = i + 1;
  10295. var c = i + 2;
  10296. indices.push( a, b, b, c, c, a );
  10297. }
  10298. }
  10299. // console.timeEnd( 'wireframe' );
  10300. var TypeArray = position.count > 65535 ? Uint32Array : Uint16Array;
  10301. var attribute = new BufferAttribute( new TypeArray( indices ), 1 );
  10302. updateAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  10303. property.wireframe = attribute;
  10304. return attribute;
  10305. }
  10306. function checkEdge( edges, a, b ) {
  10307. if ( a > b ) {
  10308. var tmp = a;
  10309. a = b;
  10310. b = tmp;
  10311. }
  10312. var list = edges[ a ];
  10313. if ( list === undefined ) {
  10314. edges[ a ] = [ b ];
  10315. return true;
  10316. } else if ( list.indexOf( b ) === -1 ) {
  10317. list.push( b );
  10318. return true;
  10319. }
  10320. return false;
  10321. }
  10322. return {
  10323. getAttributeBuffer: getAttributeBuffer,
  10324. getWireframeAttribute: getWireframeAttribute,
  10325. update: update
  10326. };
  10327. }
  10328. function WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, info ) {
  10329. var _infoMemory = info.memory;
  10330. var _isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && _gl instanceof WebGL2RenderingContext );
  10331. //
  10332. function clampToMaxSize( image, maxSize ) {
  10333. if ( image.width > maxSize || image.height > maxSize ) {
  10334. // Warning: Scaling through the canvas will only work with images that use
  10335. // premultiplied alpha.
  10336. var scale = maxSize / Math.max( image.width, image.height );
  10337. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  10338. canvas.width = Math.floor( image.width * scale );
  10339. canvas.height = Math.floor( image.height * scale );
  10340. var context = canvas.getContext( '2d' );
  10341. context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
  10342. console.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  10343. return canvas;
  10344. }
  10345. return image;
  10346. }
  10347. function isPowerOfTwo( image ) {
  10348. return exports.Math.isPowerOfTwo( image.width ) && exports.Math.isPowerOfTwo( image.height );
  10349. }
  10350. function makePowerOfTwo( image ) {
  10351. if ( image instanceof HTMLImageElement || image instanceof HTMLCanvasElement ) {
  10352. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  10353. canvas.width = exports.Math.nearestPowerOfTwo( image.width );
  10354. canvas.height = exports.Math.nearestPowerOfTwo( image.height );
  10355. var context = canvas.getContext( '2d' );
  10356. context.drawImage( image, 0, 0, canvas.width, canvas.height );
  10357. console.warn( 'THREE.WebGLRenderer: image is not power of two (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  10358. return canvas;
  10359. }
  10360. return image;
  10361. }
  10362. function textureNeedsPowerOfTwo( texture ) {
  10363. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) return true;
  10364. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) return true;
  10365. return false;
  10366. }
  10367. // Fallback filters for non-power-of-2 textures
  10368. function filterFallback( f ) {
  10369. if ( f === NearestFilter || f === NearestMipMapNearestFilter || f === NearestMipMapLinearFilter ) {
  10370. return _gl.NEAREST;
  10371. }
  10372. return _gl.LINEAR;
  10373. }
  10374. //
  10375. function onTextureDispose( event ) {
  10376. var texture = event.target;
  10377. texture.removeEventListener( 'dispose', onTextureDispose );
  10378. deallocateTexture( texture );
  10379. _infoMemory.textures --;
  10380. }
  10381. function onRenderTargetDispose( event ) {
  10382. var renderTarget = event.target;
  10383. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  10384. deallocateRenderTarget( renderTarget );
  10385. _infoMemory.textures --;
  10386. }
  10387. //
  10388. function deallocateTexture( texture ) {
  10389. var textureProperties = properties.get( texture );
  10390. if ( texture.image && textureProperties.__image__webglTextureCube ) {
  10391. // cube texture
  10392. _gl.deleteTexture( textureProperties.__image__webglTextureCube );
  10393. } else {
  10394. // 2D texture
  10395. if ( textureProperties.__webglInit === undefined ) return;
  10396. _gl.deleteTexture( textureProperties.__webglTexture );
  10397. }
  10398. // remove all webgl properties
  10399. properties.delete( texture );
  10400. }
  10401. function deallocateRenderTarget( renderTarget ) {
  10402. var renderTargetProperties = properties.get( renderTarget );
  10403. var textureProperties = properties.get( renderTarget.texture );
  10404. if ( ! renderTarget ) return;
  10405. if ( textureProperties.__webglTexture !== undefined ) {
  10406. _gl.deleteTexture( textureProperties.__webglTexture );
  10407. }
  10408. if ( renderTarget.depthTexture ) {
  10409. renderTarget.depthTexture.dispose();
  10410. }
  10411. if ( (renderTarget && renderTarget.isWebGLRenderTargetCube) ) {
  10412. for ( var i = 0; i < 6; i ++ ) {
  10413. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  10414. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  10415. }
  10416. } else {
  10417. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  10418. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  10419. }
  10420. properties.delete( renderTarget.texture );
  10421. properties.delete( renderTarget );
  10422. }
  10423. //
  10424. function setTexture2D( texture, slot ) {
  10425. var textureProperties = properties.get( texture );
  10426. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  10427. var image = texture.image;
  10428. if ( image === undefined ) {
  10429. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined', texture );
  10430. } else if ( image.complete === false ) {
  10431. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture );
  10432. } else {
  10433. uploadTexture( textureProperties, texture, slot );
  10434. return;
  10435. }
  10436. }
  10437. state.activeTexture( _gl.TEXTURE0 + slot );
  10438. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  10439. }
  10440. function setTextureCube( texture, slot ) {
  10441. var textureProperties = properties.get( texture );
  10442. if ( texture.image.length === 6 ) {
  10443. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  10444. if ( ! textureProperties.__image__webglTextureCube ) {
  10445. texture.addEventListener( 'dispose', onTextureDispose );
  10446. textureProperties.__image__webglTextureCube = _gl.createTexture();
  10447. _infoMemory.textures ++;
  10448. }
  10449. state.activeTexture( _gl.TEXTURE0 + slot );
  10450. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  10451. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  10452. var isCompressed = (texture && texture.isCompressedTexture);
  10453. var isDataTexture = (texture.image[ 0 ] && texture.image[ 0 ].isDataTexture);
  10454. var cubeImage = [];
  10455. for ( var i = 0; i < 6; i ++ ) {
  10456. if ( ! isCompressed && ! isDataTexture ) {
  10457. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], capabilities.maxCubemapSize );
  10458. } else {
  10459. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  10460. }
  10461. }
  10462. var image = cubeImage[ 0 ],
  10463. isPowerOfTwoImage = isPowerOfTwo( image ),
  10464. glFormat = paramThreeToGL( texture.format ),
  10465. glType = paramThreeToGL( texture.type );
  10466. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isPowerOfTwoImage );
  10467. for ( var i = 0; i < 6; i ++ ) {
  10468. if ( ! isCompressed ) {
  10469. if ( isDataTexture ) {
  10470. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  10471. } else {
  10472. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  10473. }
  10474. } else {
  10475. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  10476. for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  10477. mipmap = mipmaps[ j ];
  10478. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  10479. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  10480. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  10481. } else {
  10482. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()" );
  10483. }
  10484. } else {
  10485. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  10486. }
  10487. }
  10488. }
  10489. }
  10490. if ( texture.generateMipmaps && isPowerOfTwoImage ) {
  10491. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  10492. }
  10493. textureProperties.__version = texture.version;
  10494. if ( texture.onUpdate ) texture.onUpdate( texture );
  10495. } else {
  10496. state.activeTexture( _gl.TEXTURE0 + slot );
  10497. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  10498. }
  10499. }
  10500. }
  10501. function setTextureCubeDynamic( texture, slot ) {
  10502. state.activeTexture( _gl.TEXTURE0 + slot );
  10503. state.bindTexture( _gl.TEXTURE_CUBE_MAP, properties.get( texture ).__webglTexture );
  10504. }
  10505. function setTextureParameters( textureType, texture, isPowerOfTwoImage ) {
  10506. var extension;
  10507. if ( isPowerOfTwoImage ) {
  10508. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  10509. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  10510. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  10511. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  10512. } else {
  10513. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  10514. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  10515. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  10516. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.', texture );
  10517. }
  10518. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  10519. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  10520. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  10521. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.', texture );
  10522. }
  10523. }
  10524. extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  10525. if ( extension ) {
  10526. if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return;
  10527. if ( texture.type === HalfFloatType && extensions.get( 'OES_texture_half_float_linear' ) === null ) return;
  10528. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  10529. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  10530. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  10531. }
  10532. }
  10533. }
  10534. function uploadTexture( textureProperties, texture, slot ) {
  10535. if ( textureProperties.__webglInit === undefined ) {
  10536. textureProperties.__webglInit = true;
  10537. texture.addEventListener( 'dispose', onTextureDispose );
  10538. textureProperties.__webglTexture = _gl.createTexture();
  10539. _infoMemory.textures ++;
  10540. }
  10541. state.activeTexture( _gl.TEXTURE0 + slot );
  10542. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  10543. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  10544. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  10545. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  10546. var image = clampToMaxSize( texture.image, capabilities.maxTextureSize );
  10547. if ( textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( image ) === false ) {
  10548. image = makePowerOfTwo( image );
  10549. }
  10550. var isPowerOfTwoImage = isPowerOfTwo( image ),
  10551. glFormat = paramThreeToGL( texture.format ),
  10552. glType = paramThreeToGL( texture.type );
  10553. setTextureParameters( _gl.TEXTURE_2D, texture, isPowerOfTwoImage );
  10554. var mipmap, mipmaps = texture.mipmaps;
  10555. if ( (texture && texture.isDepthTexture) ) {
  10556. // populate depth texture with dummy data
  10557. var internalFormat = _gl.DEPTH_COMPONENT;
  10558. if ( texture.type === FloatType ) {
  10559. if ( !_isWebGL2 ) throw new Error('Float Depth Texture only supported in WebGL2.0');
  10560. internalFormat = _gl.DEPTH_COMPONENT32F;
  10561. } else if ( _isWebGL2 ) {
  10562. // WebGL 2.0 requires signed internalformat for glTexImage2D
  10563. internalFormat = _gl.DEPTH_COMPONENT16;
  10564. }
  10565. // Depth stencil textures need the DEPTH_STENCIL internal format
  10566. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  10567. if ( texture.format === DepthStencilFormat ) {
  10568. internalFormat = _gl.DEPTH_STENCIL;
  10569. }
  10570. state.texImage2D( _gl.TEXTURE_2D, 0, internalFormat, image.width, image.height, 0, glFormat, glType, null );
  10571. } else if ( (texture && texture.isDataTexture) ) {
  10572. // use manually created mipmaps if available
  10573. // if there are no manual mipmaps
  10574. // set 0 level mipmap and then use GL to generate other mipmap levels
  10575. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  10576. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  10577. mipmap = mipmaps[ i ];
  10578. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  10579. }
  10580. texture.generateMipmaps = false;
  10581. } else {
  10582. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  10583. }
  10584. } else if ( (texture && texture.isCompressedTexture) ) {
  10585. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  10586. mipmap = mipmaps[ i ];
  10587. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  10588. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  10589. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  10590. } else {
  10591. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()" );
  10592. }
  10593. } else {
  10594. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  10595. }
  10596. }
  10597. } else {
  10598. // regular Texture (image, video, canvas)
  10599. // use manually created mipmaps if available
  10600. // if there are no manual mipmaps
  10601. // set 0 level mipmap and then use GL to generate other mipmap levels
  10602. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  10603. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  10604. mipmap = mipmaps[ i ];
  10605. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  10606. }
  10607. texture.generateMipmaps = false;
  10608. } else {
  10609. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, image );
  10610. }
  10611. }
  10612. if ( texture.generateMipmaps && isPowerOfTwoImage ) _gl.generateMipmap( _gl.TEXTURE_2D );
  10613. textureProperties.__version = texture.version;
  10614. if ( texture.onUpdate ) texture.onUpdate( texture );
  10615. }
  10616. // Render targets
  10617. // Setup storage for target texture and bind it to correct framebuffer
  10618. function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) {
  10619. var glFormat = paramThreeToGL( renderTarget.texture.format );
  10620. var glType = paramThreeToGL( renderTarget.texture.type );
  10621. state.texImage2D( textureTarget, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  10622. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  10623. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
  10624. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  10625. }
  10626. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  10627. function setupRenderBufferStorage( renderbuffer, renderTarget ) {
  10628. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  10629. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  10630. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  10631. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  10632. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  10633. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  10634. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  10635. } else {
  10636. // FIXME: We don't support !depth !stencil
  10637. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  10638. }
  10639. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  10640. }
  10641. // Setup resources for a Depth Texture for a FBO (needs an extension)
  10642. function setupDepthTexture( framebuffer, renderTarget ) {
  10643. var isCube = ( (renderTarget && renderTarget.isWebGLRenderTargetCube) );
  10644. if ( isCube ) throw new Error('Depth Texture with cube render targets is not supported!');
  10645. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  10646. if ( !( (renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture) ) ) {
  10647. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  10648. }
  10649. // upload an empty depth texture with framebuffer size
  10650. if ( !properties.get( renderTarget.depthTexture ).__webglTexture ||
  10651. renderTarget.depthTexture.image.width !== renderTarget.width ||
  10652. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  10653. renderTarget.depthTexture.image.width = renderTarget.width;
  10654. renderTarget.depthTexture.image.height = renderTarget.height;
  10655. renderTarget.depthTexture.needsUpdate = true;
  10656. }
  10657. setTexture2D( renderTarget.depthTexture, 0 );
  10658. var webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  10659. if ( renderTarget.depthTexture.format === DepthFormat ) {
  10660. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  10661. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  10662. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  10663. } else {
  10664. throw new Error('Unknown depthTexture format')
  10665. }
  10666. }
  10667. // Setup GL resources for a non-texture depth buffer
  10668. function setupDepthRenderbuffer( renderTarget ) {
  10669. var renderTargetProperties = properties.get( renderTarget );
  10670. var isCube = ( (renderTarget && renderTarget.isWebGLRenderTargetCube) );
  10671. if ( renderTarget.depthTexture ) {
  10672. if ( isCube ) throw new Error('target.depthTexture not supported in Cube render targets');
  10673. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  10674. } else {
  10675. if ( isCube ) {
  10676. renderTargetProperties.__webglDepthbuffer = [];
  10677. for ( var i = 0; i < 6; i ++ ) {
  10678. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  10679. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  10680. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget );
  10681. }
  10682. } else {
  10683. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  10684. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  10685. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget );
  10686. }
  10687. }
  10688. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  10689. }
  10690. // Set up GL resources for the render target
  10691. function setupRenderTarget( renderTarget ) {
  10692. var renderTargetProperties = properties.get( renderTarget );
  10693. var textureProperties = properties.get( renderTarget.texture );
  10694. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  10695. textureProperties.__webglTexture = _gl.createTexture();
  10696. _infoMemory.textures ++;
  10697. var isCube = ( (renderTarget && renderTarget.isWebGLRenderTargetCube) );
  10698. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget );
  10699. // Setup framebuffer
  10700. if ( isCube ) {
  10701. renderTargetProperties.__webglFramebuffer = [];
  10702. for ( var i = 0; i < 6; i ++ ) {
  10703. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  10704. }
  10705. } else {
  10706. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  10707. }
  10708. // Setup color buffer
  10709. if ( isCube ) {
  10710. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  10711. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, isTargetPowerOfTwo );
  10712. for ( var i = 0; i < 6; i ++ ) {
  10713. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  10714. }
  10715. if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  10716. state.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  10717. } else {
  10718. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  10719. setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, isTargetPowerOfTwo );
  10720. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D );
  10721. if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  10722. state.bindTexture( _gl.TEXTURE_2D, null );
  10723. }
  10724. // Setup depth and stencil buffers
  10725. if ( renderTarget.depthBuffer ) {
  10726. setupDepthRenderbuffer( renderTarget );
  10727. }
  10728. }
  10729. function updateRenderTargetMipmap( renderTarget ) {
  10730. var texture = renderTarget.texture;
  10731. if ( texture.generateMipmaps && isPowerOfTwo( renderTarget ) &&
  10732. texture.minFilter !== NearestFilter &&
  10733. texture.minFilter !== LinearFilter ) {
  10734. var target = (renderTarget && renderTarget.isWebGLRenderTargetCube) ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  10735. var webglTexture = properties.get( texture ).__webglTexture;
  10736. state.bindTexture( target, webglTexture );
  10737. _gl.generateMipmap( target );
  10738. state.bindTexture( target, null );
  10739. }
  10740. }
  10741. this.setTexture2D = setTexture2D;
  10742. this.setTextureCube = setTextureCube;
  10743. this.setTextureCubeDynamic = setTextureCubeDynamic;
  10744. this.setupRenderTarget = setupRenderTarget;
  10745. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  10746. }
  10747. /**
  10748. * @author fordacious / fordacious.github.io
  10749. */
  10750. function WebGLProperties() {
  10751. var properties = {};
  10752. return {
  10753. get: function ( object ) {
  10754. var uuid = object.uuid;
  10755. var map = properties[ uuid ];
  10756. if ( map === undefined ) {
  10757. map = {};
  10758. properties[ uuid ] = map;
  10759. }
  10760. return map;
  10761. },
  10762. delete: function ( object ) {
  10763. delete properties[ object.uuid ];
  10764. },
  10765. clear: function () {
  10766. properties = {};
  10767. }
  10768. };
  10769. }
  10770. function WebGLState( gl, extensions, paramThreeToGL ) {
  10771. function ColorBuffer() {
  10772. var locked = false;
  10773. var color = new Vector4();
  10774. var currentColorMask = null;
  10775. var currentColorClear = new Vector4();
  10776. return {
  10777. setMask: function ( colorMask ) {
  10778. if ( currentColorMask !== colorMask && ! locked ) {
  10779. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  10780. currentColorMask = colorMask;
  10781. }
  10782. },
  10783. setLocked: function ( lock ) {
  10784. locked = lock;
  10785. },
  10786. setClear: function ( r, g, b, a ) {
  10787. color.set( r, g, b, a );
  10788. if ( currentColorClear.equals( color ) === false ) {
  10789. gl.clearColor( r, g, b, a );
  10790. currentColorClear.copy( color );
  10791. }
  10792. },
  10793. reset: function () {
  10794. locked = false;
  10795. currentColorMask = null;
  10796. currentColorClear.set( 0, 0, 0, 1 );
  10797. }
  10798. };
  10799. }
  10800. function DepthBuffer() {
  10801. var locked = false;
  10802. var currentDepthMask = null;
  10803. var currentDepthFunc = null;
  10804. var currentDepthClear = null;
  10805. return {
  10806. setTest: function ( depthTest ) {
  10807. if ( depthTest ) {
  10808. enable( gl.DEPTH_TEST );
  10809. } else {
  10810. disable( gl.DEPTH_TEST );
  10811. }
  10812. },
  10813. setMask: function ( depthMask ) {
  10814. if ( currentDepthMask !== depthMask && ! locked ) {
  10815. gl.depthMask( depthMask );
  10816. currentDepthMask = depthMask;
  10817. }
  10818. },
  10819. setFunc: function ( depthFunc ) {
  10820. if ( currentDepthFunc !== depthFunc ) {
  10821. if ( depthFunc ) {
  10822. switch ( depthFunc ) {
  10823. case NeverDepth:
  10824. gl.depthFunc( gl.NEVER );
  10825. break;
  10826. case AlwaysDepth:
  10827. gl.depthFunc( gl.ALWAYS );
  10828. break;
  10829. case LessDepth:
  10830. gl.depthFunc( gl.LESS );
  10831. break;
  10832. case LessEqualDepth:
  10833. gl.depthFunc( gl.LEQUAL );
  10834. break;
  10835. case EqualDepth:
  10836. gl.depthFunc( gl.EQUAL );
  10837. break;
  10838. case GreaterEqualDepth:
  10839. gl.depthFunc( gl.GEQUAL );
  10840. break;
  10841. case GreaterDepth:
  10842. gl.depthFunc( gl.GREATER );
  10843. break;
  10844. case NotEqualDepth:
  10845. gl.depthFunc( gl.NOTEQUAL );
  10846. break;
  10847. default:
  10848. gl.depthFunc( gl.LEQUAL );
  10849. }
  10850. } else {
  10851. gl.depthFunc( gl.LEQUAL );
  10852. }
  10853. currentDepthFunc = depthFunc;
  10854. }
  10855. },
  10856. setLocked: function ( lock ) {
  10857. locked = lock;
  10858. },
  10859. setClear: function ( depth ) {
  10860. if ( currentDepthClear !== depth ) {
  10861. gl.clearDepth( depth );
  10862. currentDepthClear = depth;
  10863. }
  10864. },
  10865. reset: function () {
  10866. locked = false;
  10867. currentDepthMask = null;
  10868. currentDepthFunc = null;
  10869. currentDepthClear = null;
  10870. }
  10871. };
  10872. }
  10873. function StencilBuffer() {
  10874. var locked = false;
  10875. var currentStencilMask = null;
  10876. var currentStencilFunc = null;
  10877. var currentStencilRef = null;
  10878. var currentStencilFuncMask = null;
  10879. var currentStencilFail = null;
  10880. var currentStencilZFail = null;
  10881. var currentStencilZPass = null;
  10882. var currentStencilClear = null;
  10883. return {
  10884. setTest: function ( stencilTest ) {
  10885. if ( stencilTest ) {
  10886. enable( gl.STENCIL_TEST );
  10887. } else {
  10888. disable( gl.STENCIL_TEST );
  10889. }
  10890. },
  10891. setMask: function ( stencilMask ) {
  10892. if ( currentStencilMask !== stencilMask && ! locked ) {
  10893. gl.stencilMask( stencilMask );
  10894. currentStencilMask = stencilMask;
  10895. }
  10896. },
  10897. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  10898. if ( currentStencilFunc !== stencilFunc ||
  10899. currentStencilRef !== stencilRef ||
  10900. currentStencilFuncMask !== stencilMask ) {
  10901. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  10902. currentStencilFunc = stencilFunc;
  10903. currentStencilRef = stencilRef;
  10904. currentStencilFuncMask = stencilMask;
  10905. }
  10906. },
  10907. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  10908. if ( currentStencilFail !== stencilFail ||
  10909. currentStencilZFail !== stencilZFail ||
  10910. currentStencilZPass !== stencilZPass ) {
  10911. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  10912. currentStencilFail = stencilFail;
  10913. currentStencilZFail = stencilZFail;
  10914. currentStencilZPass = stencilZPass;
  10915. }
  10916. },
  10917. setLocked: function ( lock ) {
  10918. locked = lock;
  10919. },
  10920. setClear: function ( stencil ) {
  10921. if ( currentStencilClear !== stencil ) {
  10922. gl.clearStencil( stencil );
  10923. currentStencilClear = stencil;
  10924. }
  10925. },
  10926. reset: function () {
  10927. locked = false;
  10928. currentStencilMask = null;
  10929. currentStencilFunc = null;
  10930. currentStencilRef = null;
  10931. currentStencilFuncMask = null;
  10932. currentStencilFail = null;
  10933. currentStencilZFail = null;
  10934. currentStencilZPass = null;
  10935. currentStencilClear = null;
  10936. }
  10937. };
  10938. }
  10939. //
  10940. var colorBuffer = new ColorBuffer();
  10941. var depthBuffer = new DepthBuffer();
  10942. var stencilBuffer = new StencilBuffer();
  10943. var maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  10944. var newAttributes = new Uint8Array( maxVertexAttributes );
  10945. var enabledAttributes = new Uint8Array( maxVertexAttributes );
  10946. var attributeDivisors = new Uint8Array( maxVertexAttributes );
  10947. var capabilities = {};
  10948. var compressedTextureFormats = null;
  10949. var currentBlending = null;
  10950. var currentBlendEquation = null;
  10951. var currentBlendSrc = null;
  10952. var currentBlendDst = null;
  10953. var currentBlendEquationAlpha = null;
  10954. var currentBlendSrcAlpha = null;
  10955. var currentBlendDstAlpha = null;
  10956. var currentPremultipledAlpha = false;
  10957. var currentFlipSided = null;
  10958. var currentCullFace = null;
  10959. var currentLineWidth = null;
  10960. var currentPolygonOffsetFactor = null;
  10961. var currentPolygonOffsetUnits = null;
  10962. var currentScissorTest = null;
  10963. var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  10964. var currentTextureSlot = null;
  10965. var currentBoundTextures = {};
  10966. var currentScissor = new Vector4();
  10967. var currentViewport = new Vector4();
  10968. function createTexture( type, target, count ) {
  10969. var data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  10970. var texture = gl.createTexture();
  10971. gl.bindTexture( type, texture );
  10972. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  10973. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  10974. for ( var i = 0; i < count; i ++ ) {
  10975. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  10976. }
  10977. return texture;
  10978. }
  10979. var emptyTextures = {};
  10980. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  10981. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  10982. //
  10983. function init() {
  10984. clearColor( 0, 0, 0, 1 );
  10985. clearDepth( 1 );
  10986. clearStencil( 0 );
  10987. enable( gl.DEPTH_TEST );
  10988. setDepthFunc( LessEqualDepth );
  10989. setFlipSided( false );
  10990. setCullFace( CullFaceBack );
  10991. enable( gl.CULL_FACE );
  10992. enable( gl.BLEND );
  10993. setBlending( NormalBlending );
  10994. }
  10995. function initAttributes() {
  10996. for ( var i = 0, l = newAttributes.length; i < l; i ++ ) {
  10997. newAttributes[ i ] = 0;
  10998. }
  10999. }
  11000. function enableAttribute( attribute ) {
  11001. newAttributes[ attribute ] = 1;
  11002. if ( enabledAttributes[ attribute ] === 0 ) {
  11003. gl.enableVertexAttribArray( attribute );
  11004. enabledAttributes[ attribute ] = 1;
  11005. }
  11006. if ( attributeDivisors[ attribute ] !== 0 ) {
  11007. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  11008. extension.vertexAttribDivisorANGLE( attribute, 0 );
  11009. attributeDivisors[ attribute ] = 0;
  11010. }
  11011. }
  11012. function enableAttributeAndDivisor( attribute, meshPerAttribute, extension ) {
  11013. newAttributes[ attribute ] = 1;
  11014. if ( enabledAttributes[ attribute ] === 0 ) {
  11015. gl.enableVertexAttribArray( attribute );
  11016. enabledAttributes[ attribute ] = 1;
  11017. }
  11018. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  11019. extension.vertexAttribDivisorANGLE( attribute, meshPerAttribute );
  11020. attributeDivisors[ attribute ] = meshPerAttribute;
  11021. }
  11022. }
  11023. function disableUnusedAttributes() {
  11024. for ( var i = 0, l = enabledAttributes.length; i !== l; ++ i ) {
  11025. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  11026. gl.disableVertexAttribArray( i );
  11027. enabledAttributes[ i ] = 0;
  11028. }
  11029. }
  11030. }
  11031. function enable( id ) {
  11032. if ( capabilities[ id ] !== true ) {
  11033. gl.enable( id );
  11034. capabilities[ id ] = true;
  11035. }
  11036. }
  11037. function disable( id ) {
  11038. if ( capabilities[ id ] !== false ) {
  11039. gl.disable( id );
  11040. capabilities[ id ] = false;
  11041. }
  11042. }
  11043. function getCompressedTextureFormats() {
  11044. if ( compressedTextureFormats === null ) {
  11045. compressedTextureFormats = [];
  11046. if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) ||
  11047. extensions.get( 'WEBGL_compressed_texture_s3tc' ) ||
  11048. extensions.get( 'WEBGL_compressed_texture_etc1' ) ) {
  11049. var formats = gl.getParameter( gl.COMPRESSED_TEXTURE_FORMATS );
  11050. for ( var i = 0; i < formats.length; i ++ ) {
  11051. compressedTextureFormats.push( formats[ i ] );
  11052. }
  11053. }
  11054. }
  11055. return compressedTextureFormats;
  11056. }
  11057. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  11058. if ( blending !== NoBlending ) {
  11059. enable( gl.BLEND );
  11060. } else {
  11061. disable( gl.BLEND );
  11062. currentBlending = blending; // no blending, that is
  11063. return;
  11064. }
  11065. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  11066. if ( blending === AdditiveBlending ) {
  11067. if ( premultipliedAlpha ) {
  11068. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11069. gl.blendFuncSeparate( gl.ONE, gl.ONE, gl.ONE, gl.ONE );
  11070. } else {
  11071. gl.blendEquation( gl.FUNC_ADD );
  11072. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  11073. }
  11074. } else if ( blending === SubtractiveBlending ) {
  11075. if ( premultipliedAlpha ) {
  11076. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11077. gl.blendFuncSeparate( gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA );
  11078. } else {
  11079. gl.blendEquation( gl.FUNC_ADD );
  11080. gl.blendFunc( gl.ZERO, gl.ONE_MINUS_SRC_COLOR );
  11081. }
  11082. } else if ( blending === MultiplyBlending ) {
  11083. if ( premultipliedAlpha ) {
  11084. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11085. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  11086. } else {
  11087. gl.blendEquation( gl.FUNC_ADD );
  11088. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  11089. }
  11090. } else {
  11091. if ( premultipliedAlpha ) {
  11092. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11093. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  11094. } else {
  11095. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11096. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  11097. }
  11098. }
  11099. currentBlending = blending;
  11100. currentPremultipledAlpha = premultipliedAlpha;
  11101. }
  11102. if ( blending === CustomBlending ) {
  11103. blendEquationAlpha = blendEquationAlpha || blendEquation;
  11104. blendSrcAlpha = blendSrcAlpha || blendSrc;
  11105. blendDstAlpha = blendDstAlpha || blendDst;
  11106. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  11107. gl.blendEquationSeparate( paramThreeToGL( blendEquation ), paramThreeToGL( blendEquationAlpha ) );
  11108. currentBlendEquation = blendEquation;
  11109. currentBlendEquationAlpha = blendEquationAlpha;
  11110. }
  11111. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  11112. gl.blendFuncSeparate( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ), paramThreeToGL( blendSrcAlpha ), paramThreeToGL( blendDstAlpha ) );
  11113. currentBlendSrc = blendSrc;
  11114. currentBlendDst = blendDst;
  11115. currentBlendSrcAlpha = blendSrcAlpha;
  11116. currentBlendDstAlpha = blendDstAlpha;
  11117. }
  11118. } else {
  11119. currentBlendEquation = null;
  11120. currentBlendSrc = null;
  11121. currentBlendDst = null;
  11122. currentBlendEquationAlpha = null;
  11123. currentBlendSrcAlpha = null;
  11124. currentBlendDstAlpha = null;
  11125. }
  11126. }
  11127. // TODO Deprecate
  11128. function setColorWrite( colorWrite ) {
  11129. colorBuffer.setMask( colorWrite );
  11130. }
  11131. function setDepthTest( depthTest ) {
  11132. depthBuffer.setTest( depthTest );
  11133. }
  11134. function setDepthWrite( depthWrite ) {
  11135. depthBuffer.setMask( depthWrite );
  11136. }
  11137. function setDepthFunc( depthFunc ) {
  11138. depthBuffer.setFunc( depthFunc );
  11139. }
  11140. function setStencilTest( stencilTest ) {
  11141. stencilBuffer.setTest( stencilTest );
  11142. }
  11143. function setStencilWrite( stencilWrite ) {
  11144. stencilBuffer.setMask( stencilWrite );
  11145. }
  11146. function setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  11147. stencilBuffer.setFunc( stencilFunc, stencilRef, stencilMask );
  11148. }
  11149. function setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  11150. stencilBuffer.setOp( stencilFail, stencilZFail, stencilZPass );
  11151. }
  11152. //
  11153. function setFlipSided( flipSided ) {
  11154. if ( currentFlipSided !== flipSided ) {
  11155. if ( flipSided ) {
  11156. gl.frontFace( gl.CW );
  11157. } else {
  11158. gl.frontFace( gl.CCW );
  11159. }
  11160. currentFlipSided = flipSided;
  11161. }
  11162. }
  11163. function setCullFace( cullFace ) {
  11164. if ( cullFace !== CullFaceNone ) {
  11165. enable( gl.CULL_FACE );
  11166. if ( cullFace !== currentCullFace ) {
  11167. if ( cullFace === CullFaceBack ) {
  11168. gl.cullFace( gl.BACK );
  11169. } else if ( cullFace === CullFaceFront ) {
  11170. gl.cullFace( gl.FRONT );
  11171. } else {
  11172. gl.cullFace( gl.FRONT_AND_BACK );
  11173. }
  11174. }
  11175. } else {
  11176. disable( gl.CULL_FACE );
  11177. }
  11178. currentCullFace = cullFace;
  11179. }
  11180. function setLineWidth( width ) {
  11181. if ( width !== currentLineWidth ) {
  11182. gl.lineWidth( width );
  11183. currentLineWidth = width;
  11184. }
  11185. }
  11186. function setPolygonOffset( polygonOffset, factor, units ) {
  11187. if ( polygonOffset ) {
  11188. enable( gl.POLYGON_OFFSET_FILL );
  11189. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  11190. gl.polygonOffset( factor, units );
  11191. currentPolygonOffsetFactor = factor;
  11192. currentPolygonOffsetUnits = units;
  11193. }
  11194. } else {
  11195. disable( gl.POLYGON_OFFSET_FILL );
  11196. }
  11197. }
  11198. function getScissorTest() {
  11199. return currentScissorTest;
  11200. }
  11201. function setScissorTest( scissorTest ) {
  11202. currentScissorTest = scissorTest;
  11203. if ( scissorTest ) {
  11204. enable( gl.SCISSOR_TEST );
  11205. } else {
  11206. disable( gl.SCISSOR_TEST );
  11207. }
  11208. }
  11209. // texture
  11210. function activeTexture( webglSlot ) {
  11211. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  11212. if ( currentTextureSlot !== webglSlot ) {
  11213. gl.activeTexture( webglSlot );
  11214. currentTextureSlot = webglSlot;
  11215. }
  11216. }
  11217. function bindTexture( webglType, webglTexture ) {
  11218. if ( currentTextureSlot === null ) {
  11219. activeTexture();
  11220. }
  11221. var boundTexture = currentBoundTextures[ currentTextureSlot ];
  11222. if ( boundTexture === undefined ) {
  11223. boundTexture = { type: undefined, texture: undefined };
  11224. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  11225. }
  11226. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  11227. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  11228. boundTexture.type = webglType;
  11229. boundTexture.texture = webglTexture;
  11230. }
  11231. }
  11232. function compressedTexImage2D() {
  11233. try {
  11234. gl.compressedTexImage2D.apply( gl, arguments );
  11235. } catch ( error ) {
  11236. console.error( error );
  11237. }
  11238. }
  11239. function texImage2D() {
  11240. try {
  11241. gl.texImage2D.apply( gl, arguments );
  11242. } catch ( error ) {
  11243. console.error( error );
  11244. }
  11245. }
  11246. // TODO Deprecate
  11247. function clearColor( r, g, b, a ) {
  11248. colorBuffer.setClear( r, g, b, a );
  11249. }
  11250. function clearDepth( depth ) {
  11251. depthBuffer.setClear( depth );
  11252. }
  11253. function clearStencil( stencil ) {
  11254. stencilBuffer.setClear( stencil );
  11255. }
  11256. //
  11257. function scissor( scissor ) {
  11258. if ( currentScissor.equals( scissor ) === false ) {
  11259. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  11260. currentScissor.copy( scissor );
  11261. }
  11262. }
  11263. function viewport( viewport ) {
  11264. if ( currentViewport.equals( viewport ) === false ) {
  11265. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  11266. currentViewport.copy( viewport );
  11267. }
  11268. }
  11269. //
  11270. function reset() {
  11271. for ( var i = 0; i < enabledAttributes.length; i ++ ) {
  11272. if ( enabledAttributes[ i ] === 1 ) {
  11273. gl.disableVertexAttribArray( i );
  11274. enabledAttributes[ i ] = 0;
  11275. }
  11276. }
  11277. capabilities = {};
  11278. compressedTextureFormats = null;
  11279. currentTextureSlot = null;
  11280. currentBoundTextures = {};
  11281. currentBlending = null;
  11282. currentFlipSided = null;
  11283. currentCullFace = null;
  11284. colorBuffer.reset();
  11285. depthBuffer.reset();
  11286. stencilBuffer.reset();
  11287. }
  11288. return {
  11289. buffers: {
  11290. color: colorBuffer,
  11291. depth: depthBuffer,
  11292. stencil: stencilBuffer
  11293. },
  11294. init: init,
  11295. initAttributes: initAttributes,
  11296. enableAttribute: enableAttribute,
  11297. enableAttributeAndDivisor: enableAttributeAndDivisor,
  11298. disableUnusedAttributes: disableUnusedAttributes,
  11299. enable: enable,
  11300. disable: disable,
  11301. getCompressedTextureFormats: getCompressedTextureFormats,
  11302. setBlending: setBlending,
  11303. setColorWrite: setColorWrite,
  11304. setDepthTest: setDepthTest,
  11305. setDepthWrite: setDepthWrite,
  11306. setDepthFunc: setDepthFunc,
  11307. setStencilTest: setStencilTest,
  11308. setStencilWrite: setStencilWrite,
  11309. setStencilFunc: setStencilFunc,
  11310. setStencilOp: setStencilOp,
  11311. setFlipSided: setFlipSided,
  11312. setCullFace: setCullFace,
  11313. setLineWidth: setLineWidth,
  11314. setPolygonOffset: setPolygonOffset,
  11315. getScissorTest: getScissorTest,
  11316. setScissorTest: setScissorTest,
  11317. activeTexture: activeTexture,
  11318. bindTexture: bindTexture,
  11319. compressedTexImage2D: compressedTexImage2D,
  11320. texImage2D: texImage2D,
  11321. clearColor: clearColor,
  11322. clearDepth: clearDepth,
  11323. clearStencil: clearStencil,
  11324. scissor: scissor,
  11325. viewport: viewport,
  11326. reset: reset
  11327. };
  11328. }
  11329. /**
  11330. * @author mrdoob / http://mrdoob.com/
  11331. */
  11332. function WebGLCapabilities( gl, extensions, parameters ) {
  11333. var maxAnisotropy;
  11334. function getMaxAnisotropy() {
  11335. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  11336. var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  11337. if ( extension !== null ) {
  11338. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  11339. } else {
  11340. maxAnisotropy = 0;
  11341. }
  11342. return maxAnisotropy;
  11343. }
  11344. function getMaxPrecision( precision ) {
  11345. if ( precision === 'highp' ) {
  11346. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  11347. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  11348. return 'highp';
  11349. }
  11350. precision = 'mediump';
  11351. }
  11352. if ( precision === 'mediump' ) {
  11353. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  11354. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  11355. return 'mediump';
  11356. }
  11357. }
  11358. return 'lowp';
  11359. }
  11360. var precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  11361. var maxPrecision = getMaxPrecision( precision );
  11362. if ( maxPrecision !== precision ) {
  11363. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  11364. precision = maxPrecision;
  11365. }
  11366. var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true && !! extensions.get( 'EXT_frag_depth' );
  11367. var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  11368. var maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  11369. var maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  11370. var maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  11371. var maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  11372. var maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  11373. var maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  11374. var maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  11375. var vertexTextures = maxVertexTextures > 0;
  11376. var floatFragmentTextures = !! extensions.get( 'OES_texture_float' );
  11377. var floatVertexTextures = vertexTextures && floatFragmentTextures;
  11378. return {
  11379. getMaxAnisotropy: getMaxAnisotropy,
  11380. getMaxPrecision: getMaxPrecision,
  11381. precision: precision,
  11382. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11383. maxTextures: maxTextures,
  11384. maxVertexTextures: maxVertexTextures,
  11385. maxTextureSize: maxTextureSize,
  11386. maxCubemapSize: maxCubemapSize,
  11387. maxAttributes: maxAttributes,
  11388. maxVertexUniforms: maxVertexUniforms,
  11389. maxVaryings: maxVaryings,
  11390. maxFragmentUniforms: maxFragmentUniforms,
  11391. vertexTextures: vertexTextures,
  11392. floatFragmentTextures: floatFragmentTextures,
  11393. floatVertexTextures: floatVertexTextures
  11394. };
  11395. }
  11396. /**
  11397. * @author mrdoob / http://mrdoob.com/
  11398. */
  11399. function WebGLExtensions( gl ) {
  11400. var extensions = {};
  11401. return {
  11402. get: function ( name ) {
  11403. if ( extensions[ name ] !== undefined ) {
  11404. return extensions[ name ];
  11405. }
  11406. var extension;
  11407. switch ( name ) {
  11408. case 'WEBGL_depth_texture':
  11409. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  11410. break;
  11411. case 'EXT_texture_filter_anisotropic':
  11412. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  11413. break;
  11414. case 'WEBGL_compressed_texture_s3tc':
  11415. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  11416. break;
  11417. case 'WEBGL_compressed_texture_pvrtc':
  11418. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  11419. break;
  11420. case 'WEBGL_compressed_texture_etc1':
  11421. extension = gl.getExtension( 'WEBGL_compressed_texture_etc1' );
  11422. break;
  11423. default:
  11424. extension = gl.getExtension( name );
  11425. }
  11426. if ( extension === null ) {
  11427. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  11428. }
  11429. extensions[ name ] = extension;
  11430. return extension;
  11431. }
  11432. };
  11433. }
  11434. function WebGLClipping() {
  11435. var scope = this,
  11436. globalState = null,
  11437. numGlobalPlanes = 0,
  11438. localClippingEnabled = false,
  11439. renderingShadows = false,
  11440. plane = new Plane(),
  11441. viewNormalMatrix = new Matrix3(),
  11442. uniform = { value: null, needsUpdate: false };
  11443. this.uniform = uniform;
  11444. this.numPlanes = 0;
  11445. this.init = function( planes, enableLocalClipping, camera ) {
  11446. var enabled =
  11447. planes.length !== 0 ||
  11448. enableLocalClipping ||
  11449. // enable state of previous frame - the clipping code has to
  11450. // run another frame in order to reset the state:
  11451. numGlobalPlanes !== 0 ||
  11452. localClippingEnabled;
  11453. localClippingEnabled = enableLocalClipping;
  11454. globalState = projectPlanes( planes, camera, 0 );
  11455. numGlobalPlanes = planes.length;
  11456. return enabled;
  11457. };
  11458. this.beginShadows = function() {
  11459. renderingShadows = true;
  11460. projectPlanes( null );
  11461. };
  11462. this.endShadows = function() {
  11463. renderingShadows = false;
  11464. resetGlobalState();
  11465. };
  11466. this.setState = function( planes, clipShadows, camera, cache, fromCache ) {
  11467. if ( ! localClippingEnabled ||
  11468. planes === null || planes.length === 0 ||
  11469. renderingShadows && ! clipShadows ) {
  11470. // there's no local clipping
  11471. if ( renderingShadows ) {
  11472. // there's no global clipping
  11473. projectPlanes( null );
  11474. } else {
  11475. resetGlobalState();
  11476. }
  11477. } else {
  11478. var nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  11479. lGlobal = nGlobal * 4,
  11480. dstArray = cache.clippingState || null;
  11481. uniform.value = dstArray; // ensure unique state
  11482. dstArray = projectPlanes( planes, camera, lGlobal, fromCache );
  11483. for ( var i = 0; i !== lGlobal; ++ i ) {
  11484. dstArray[ i ] = globalState[ i ];
  11485. }
  11486. cache.clippingState = dstArray;
  11487. this.numPlanes += nGlobal;
  11488. }
  11489. };
  11490. function resetGlobalState() {
  11491. if ( uniform.value !== globalState ) {
  11492. uniform.value = globalState;
  11493. uniform.needsUpdate = numGlobalPlanes > 0;
  11494. }
  11495. scope.numPlanes = numGlobalPlanes;
  11496. }
  11497. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  11498. var nPlanes = planes !== null ? planes.length : 0,
  11499. dstArray = null;
  11500. if ( nPlanes !== 0 ) {
  11501. dstArray = uniform.value;
  11502. if ( skipTransform !== true || dstArray === null ) {
  11503. var flatSize = dstOffset + nPlanes * 4,
  11504. viewMatrix = camera.matrixWorldInverse;
  11505. viewNormalMatrix.getNormalMatrix( viewMatrix );
  11506. if ( dstArray === null || dstArray.length < flatSize ) {
  11507. dstArray = new Float32Array( flatSize );
  11508. }
  11509. for ( var i = 0, i4 = dstOffset;
  11510. i !== nPlanes; ++ i, i4 += 4 ) {
  11511. plane.copy( planes[ i ] ).
  11512. applyMatrix4( viewMatrix, viewNormalMatrix );
  11513. plane.normal.toArray( dstArray, i4 );
  11514. dstArray[ i4 + 3 ] = plane.constant;
  11515. }
  11516. }
  11517. uniform.value = dstArray;
  11518. uniform.needsUpdate = true;
  11519. }
  11520. scope.numPlanes = nPlanes;
  11521. return dstArray;
  11522. }
  11523. }
  11524. /**
  11525. * @author supereggbert / http://www.paulbrunt.co.uk/
  11526. * @author mrdoob / http://mrdoob.com/
  11527. * @author alteredq / http://alteredqualia.com/
  11528. * @author szimek / https://github.com/szimek/
  11529. * @author tschw
  11530. */
  11531. function WebGLRenderer( parameters ) {
  11532. console.log( 'THREE.WebGLRenderer', REVISION );
  11533. parameters = parameters || {};
  11534. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ),
  11535. _context = parameters.context !== undefined ? parameters.context : null,
  11536. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  11537. _depth = parameters.depth !== undefined ? parameters.depth : true,
  11538. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  11539. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  11540. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  11541. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false;
  11542. var lights = [];
  11543. var opaqueObjects = [];
  11544. var opaqueObjectsLastIndex = - 1;
  11545. var transparentObjects = [];
  11546. var transparentObjectsLastIndex = - 1;
  11547. var morphInfluences = new Float32Array( 8 );
  11548. var sprites = [];
  11549. var lensFlares = [];
  11550. // public properties
  11551. this.domElement = _canvas;
  11552. this.context = null;
  11553. // clearing
  11554. this.autoClear = true;
  11555. this.autoClearColor = true;
  11556. this.autoClearDepth = true;
  11557. this.autoClearStencil = true;
  11558. // scene graph
  11559. this.sortObjects = true;
  11560. // user-defined clipping
  11561. this.clippingPlanes = [];
  11562. this.localClippingEnabled = false;
  11563. // physically based shading
  11564. this.gammaFactor = 2.0; // for backwards compatibility
  11565. this.gammaInput = false;
  11566. this.gammaOutput = false;
  11567. // physical lights
  11568. this.physicallyCorrectLights = false;
  11569. // tone mapping
  11570. this.toneMapping = LinearToneMapping;
  11571. this.toneMappingExposure = 1.0;
  11572. this.toneMappingWhitePoint = 1.0;
  11573. // morphs
  11574. this.maxMorphTargets = 8;
  11575. this.maxMorphNormals = 4;
  11576. // internal properties
  11577. var _this = this,
  11578. // internal state cache
  11579. _currentProgram = null,
  11580. _currentRenderTarget = null,
  11581. _currentFramebuffer = null,
  11582. _currentMaterialId = - 1,
  11583. _currentGeometryProgram = '',
  11584. _currentCamera = null,
  11585. _currentScissor = new Vector4(),
  11586. _currentScissorTest = null,
  11587. _currentViewport = new Vector4(),
  11588. //
  11589. _usedTextureUnits = 0,
  11590. //
  11591. _clearColor = new Color( 0x000000 ),
  11592. _clearAlpha = 0,
  11593. _width = _canvas.width,
  11594. _height = _canvas.height,
  11595. _pixelRatio = 1,
  11596. _scissor = new Vector4( 0, 0, _width, _height ),
  11597. _scissorTest = false,
  11598. _viewport = new Vector4( 0, 0, _width, _height ),
  11599. // frustum
  11600. _frustum = new Frustum(),
  11601. // clipping
  11602. _clipping = new WebGLClipping(),
  11603. _clippingEnabled = false,
  11604. _localClippingEnabled = false,
  11605. _sphere = new Sphere(),
  11606. // camera matrices cache
  11607. _projScreenMatrix = new Matrix4(),
  11608. _vector3 = new Vector3(),
  11609. // light arrays cache
  11610. _lights = {
  11611. hash: '',
  11612. ambient: [ 0, 0, 0 ],
  11613. directional: [],
  11614. directionalShadowMap: [],
  11615. directionalShadowMatrix: [],
  11616. spot: [],
  11617. spotShadowMap: [],
  11618. spotShadowMatrix: [],
  11619. point: [],
  11620. pointShadowMap: [],
  11621. pointShadowMatrix: [],
  11622. hemi: [],
  11623. shadows: []
  11624. },
  11625. // info
  11626. _infoRender = {
  11627. calls: 0,
  11628. vertices: 0,
  11629. faces: 0,
  11630. points: 0
  11631. };
  11632. this.info = {
  11633. render: _infoRender,
  11634. memory: {
  11635. geometries: 0,
  11636. textures: 0
  11637. },
  11638. programs: null
  11639. };
  11640. // initialize
  11641. var _gl;
  11642. try {
  11643. var attributes = {
  11644. alpha: _alpha,
  11645. depth: _depth,
  11646. stencil: _stencil,
  11647. antialias: _antialias,
  11648. premultipliedAlpha: _premultipliedAlpha,
  11649. preserveDrawingBuffer: _preserveDrawingBuffer
  11650. };
  11651. _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  11652. if ( _gl === null ) {
  11653. if ( _canvas.getContext( 'webgl' ) !== null ) {
  11654. throw 'Error creating WebGL context with your selected attributes.';
  11655. } else {
  11656. throw 'Error creating WebGL context.';
  11657. }
  11658. }
  11659. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  11660. if ( _gl.getShaderPrecisionFormat === undefined ) {
  11661. _gl.getShaderPrecisionFormat = function () {
  11662. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  11663. };
  11664. }
  11665. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  11666. } catch ( error ) {
  11667. console.error( 'THREE.WebGLRenderer: ' + error );
  11668. }
  11669. var extensions = new WebGLExtensions( _gl );
  11670. extensions.get( 'WEBGL_depth_texture' );
  11671. extensions.get( 'OES_texture_float' );
  11672. extensions.get( 'OES_texture_float_linear' );
  11673. extensions.get( 'OES_texture_half_float' );
  11674. extensions.get( 'OES_texture_half_float_linear' );
  11675. extensions.get( 'OES_standard_derivatives' );
  11676. extensions.get( 'ANGLE_instanced_arrays' );
  11677. if ( extensions.get( 'OES_element_index_uint' ) ) {
  11678. BufferGeometry.MaxIndex = 4294967296;
  11679. }
  11680. var capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  11681. var state = new WebGLState( _gl, extensions, paramThreeToGL );
  11682. var properties = new WebGLProperties();
  11683. var textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, this.info );
  11684. var objects = new WebGLObjects( _gl, properties, this.info );
  11685. var programCache = new WebGLPrograms( this, capabilities );
  11686. var lightCache = new WebGLLights();
  11687. this.info.programs = programCache.programs;
  11688. var bufferRenderer = new WebGLBufferRenderer( _gl, extensions, _infoRender );
  11689. var indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, _infoRender );
  11690. //
  11691. var backgroundCamera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  11692. var backgroundCamera2 = new PerspectiveCamera();
  11693. var backgroundPlaneMesh = new Mesh(
  11694. new PlaneBufferGeometry( 2, 2 ),
  11695. new MeshBasicMaterial( { depthTest: false, depthWrite: false, fog: false } )
  11696. );
  11697. var backgroundBoxShader = ShaderLib[ 'cube' ];
  11698. var backgroundBoxMesh = new Mesh(
  11699. new BoxBufferGeometry( 5, 5, 5 ),
  11700. new ShaderMaterial( {
  11701. uniforms: backgroundBoxShader.uniforms,
  11702. vertexShader: backgroundBoxShader.vertexShader,
  11703. fragmentShader: backgroundBoxShader.fragmentShader,
  11704. side: BackSide,
  11705. depthTest: false,
  11706. depthWrite: false,
  11707. fog: false
  11708. } )
  11709. );
  11710. //
  11711. function getTargetPixelRatio() {
  11712. return _currentRenderTarget === null ? _pixelRatio : 1;
  11713. }
  11714. function glClearColor( r, g, b, a ) {
  11715. if ( _premultipliedAlpha === true ) {
  11716. r *= a; g *= a; b *= a;
  11717. }
  11718. state.clearColor( r, g, b, a );
  11719. }
  11720. function setDefaultGLState() {
  11721. state.init();
  11722. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
  11723. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
  11724. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  11725. }
  11726. function resetGLState() {
  11727. _currentProgram = null;
  11728. _currentCamera = null;
  11729. _currentGeometryProgram = '';
  11730. _currentMaterialId = - 1;
  11731. state.reset();
  11732. }
  11733. setDefaultGLState();
  11734. this.context = _gl;
  11735. this.capabilities = capabilities;
  11736. this.extensions = extensions;
  11737. this.properties = properties;
  11738. this.state = state;
  11739. // shadow map
  11740. var shadowMap = new WebGLShadowMap( this, _lights, objects, capabilities );
  11741. this.shadowMap = shadowMap;
  11742. // Plugins
  11743. var spritePlugin = new SpritePlugin( this, sprites );
  11744. var lensFlarePlugin = new LensFlarePlugin( this, lensFlares );
  11745. // API
  11746. this.getContext = function () {
  11747. return _gl;
  11748. };
  11749. this.getContextAttributes = function () {
  11750. return _gl.getContextAttributes();
  11751. };
  11752. this.forceContextLoss = function () {
  11753. extensions.get( 'WEBGL_lose_context' ).loseContext();
  11754. };
  11755. this.getMaxAnisotropy = function () {
  11756. return capabilities.getMaxAnisotropy();
  11757. };
  11758. this.getPrecision = function () {
  11759. return capabilities.precision;
  11760. };
  11761. this.getPixelRatio = function () {
  11762. return _pixelRatio;
  11763. };
  11764. this.setPixelRatio = function ( value ) {
  11765. if ( value === undefined ) return;
  11766. _pixelRatio = value;
  11767. this.setSize( _viewport.z, _viewport.w, false );
  11768. };
  11769. this.getSize = function () {
  11770. return {
  11771. width: _width,
  11772. height: _height
  11773. };
  11774. };
  11775. this.setSize = function ( width, height, updateStyle ) {
  11776. _width = width;
  11777. _height = height;
  11778. _canvas.width = width * _pixelRatio;
  11779. _canvas.height = height * _pixelRatio;
  11780. if ( updateStyle !== false ) {
  11781. _canvas.style.width = width + 'px';
  11782. _canvas.style.height = height + 'px';
  11783. }
  11784. this.setViewport( 0, 0, width, height );
  11785. };
  11786. this.setViewport = function ( x, y, width, height ) {
  11787. state.viewport( _viewport.set( x, y, width, height ) );
  11788. };
  11789. this.setScissor = function ( x, y, width, height ) {
  11790. state.scissor( _scissor.set( x, y, width, height ) );
  11791. };
  11792. this.setScissorTest = function ( boolean ) {
  11793. state.setScissorTest( _scissorTest = boolean );
  11794. };
  11795. // Clearing
  11796. this.getClearColor = function () {
  11797. return _clearColor;
  11798. };
  11799. this.setClearColor = function ( color, alpha ) {
  11800. _clearColor.set( color );
  11801. _clearAlpha = alpha !== undefined ? alpha : 1;
  11802. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  11803. };
  11804. this.getClearAlpha = function () {
  11805. return _clearAlpha;
  11806. };
  11807. this.setClearAlpha = function ( alpha ) {
  11808. _clearAlpha = alpha;
  11809. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  11810. };
  11811. this.clear = function ( color, depth, stencil ) {
  11812. var bits = 0;
  11813. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  11814. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  11815. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  11816. _gl.clear( bits );
  11817. };
  11818. this.clearColor = function () {
  11819. this.clear( true, false, false );
  11820. };
  11821. this.clearDepth = function () {
  11822. this.clear( false, true, false );
  11823. };
  11824. this.clearStencil = function () {
  11825. this.clear( false, false, true );
  11826. };
  11827. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  11828. this.setRenderTarget( renderTarget );
  11829. this.clear( color, depth, stencil );
  11830. };
  11831. // Reset
  11832. this.resetGLState = resetGLState;
  11833. this.dispose = function() {
  11834. transparentObjects = [];
  11835. transparentObjectsLastIndex = -1;
  11836. opaqueObjects = [];
  11837. opaqueObjectsLastIndex = -1;
  11838. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  11839. };
  11840. // Events
  11841. function onContextLost( event ) {
  11842. event.preventDefault();
  11843. resetGLState();
  11844. setDefaultGLState();
  11845. properties.clear();
  11846. }
  11847. function onMaterialDispose( event ) {
  11848. var material = event.target;
  11849. material.removeEventListener( 'dispose', onMaterialDispose );
  11850. deallocateMaterial( material );
  11851. }
  11852. // Buffer deallocation
  11853. function deallocateMaterial( material ) {
  11854. releaseMaterialProgramReference( material );
  11855. properties.delete( material );
  11856. }
  11857. function releaseMaterialProgramReference( material ) {
  11858. var programInfo = properties.get( material ).program;
  11859. material.program = undefined;
  11860. if ( programInfo !== undefined ) {
  11861. programCache.releaseProgram( programInfo );
  11862. }
  11863. }
  11864. // Buffer rendering
  11865. this.renderBufferImmediate = function ( object, program, material ) {
  11866. state.initAttributes();
  11867. var buffers = properties.get( object );
  11868. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  11869. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  11870. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  11871. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  11872. var attributes = program.getAttributes();
  11873. if ( object.hasPositions ) {
  11874. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position );
  11875. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  11876. state.enableAttribute( attributes.position );
  11877. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11878. }
  11879. if ( object.hasNormals ) {
  11880. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal );
  11881. if ( ! material.isMeshPhongMaterial &&
  11882. ! material.isMeshStandardMaterial &&
  11883. material.shading === FlatShading ) {
  11884. for ( var i = 0, l = object.count * 3; i < l; i += 9 ) {
  11885. var array = object.normalArray;
  11886. var nx = ( array[ i + 0 ] + array[ i + 3 ] + array[ i + 6 ] ) / 3;
  11887. var ny = ( array[ i + 1 ] + array[ i + 4 ] + array[ i + 7 ] ) / 3;
  11888. var nz = ( array[ i + 2 ] + array[ i + 5 ] + array[ i + 8 ] ) / 3;
  11889. array[ i + 0 ] = nx;
  11890. array[ i + 1 ] = ny;
  11891. array[ i + 2 ] = nz;
  11892. array[ i + 3 ] = nx;
  11893. array[ i + 4 ] = ny;
  11894. array[ i + 5 ] = nz;
  11895. array[ i + 6 ] = nx;
  11896. array[ i + 7 ] = ny;
  11897. array[ i + 8 ] = nz;
  11898. }
  11899. }
  11900. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  11901. state.enableAttribute( attributes.normal );
  11902. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  11903. }
  11904. if ( object.hasUvs && material.map ) {
  11905. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv );
  11906. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  11907. state.enableAttribute( attributes.uv );
  11908. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  11909. }
  11910. if ( object.hasColors && material.vertexColors !== NoColors ) {
  11911. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color );
  11912. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  11913. state.enableAttribute( attributes.color );
  11914. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  11915. }
  11916. state.disableUnusedAttributes();
  11917. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  11918. object.count = 0;
  11919. };
  11920. this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) {
  11921. setMaterial( material );
  11922. var program = setProgram( camera, fog, material, object );
  11923. var updateBuffers = false;
  11924. var geometryProgram = geometry.id + '_' + program.id + '_' + material.wireframe;
  11925. if ( geometryProgram !== _currentGeometryProgram ) {
  11926. _currentGeometryProgram = geometryProgram;
  11927. updateBuffers = true;
  11928. }
  11929. // morph targets
  11930. var morphTargetInfluences = object.morphTargetInfluences;
  11931. if ( morphTargetInfluences !== undefined ) {
  11932. var activeInfluences = [];
  11933. for ( var i = 0, l = morphTargetInfluences.length; i < l; i ++ ) {
  11934. var influence = morphTargetInfluences[ i ];
  11935. activeInfluences.push( [ influence, i ] );
  11936. }
  11937. activeInfluences.sort( absNumericalSort );
  11938. if ( activeInfluences.length > 8 ) {
  11939. activeInfluences.length = 8;
  11940. }
  11941. var morphAttributes = geometry.morphAttributes;
  11942. for ( var i = 0, l = activeInfluences.length; i < l; i ++ ) {
  11943. var influence = activeInfluences[ i ];
  11944. morphInfluences[ i ] = influence[ 0 ];
  11945. if ( influence[ 0 ] !== 0 ) {
  11946. var index = influence[ 1 ];
  11947. if ( material.morphTargets === true && morphAttributes.position ) geometry.addAttribute( 'morphTarget' + i, morphAttributes.position[ index ] );
  11948. if ( material.morphNormals === true && morphAttributes.normal ) geometry.addAttribute( 'morphNormal' + i, morphAttributes.normal[ index ] );
  11949. } else {
  11950. if ( material.morphTargets === true ) geometry.removeAttribute( 'morphTarget' + i );
  11951. if ( material.morphNormals === true ) geometry.removeAttribute( 'morphNormal' + i );
  11952. }
  11953. }
  11954. for ( var i = activeInfluences.length, il = morphInfluences.length; i < il; i ++ ) {
  11955. morphInfluences[ i ] = 0.0;
  11956. }
  11957. program.getUniforms().setValue(
  11958. _gl, 'morphTargetInfluences', morphInfluences );
  11959. updateBuffers = true;
  11960. }
  11961. //
  11962. var index = geometry.index;
  11963. var position = geometry.attributes.position;
  11964. if ( material.wireframe === true ) {
  11965. index = objects.getWireframeAttribute( geometry );
  11966. }
  11967. var renderer;
  11968. if ( index !== null ) {
  11969. renderer = indexedBufferRenderer;
  11970. renderer.setIndex( index );
  11971. } else {
  11972. renderer = bufferRenderer;
  11973. }
  11974. if ( updateBuffers ) {
  11975. setupVertexAttributes( material, program, geometry );
  11976. if ( index !== null ) {
  11977. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, objects.getAttributeBuffer( index ) );
  11978. }
  11979. }
  11980. //
  11981. var dataStart = 0;
  11982. var dataCount = 0;
  11983. if ( index !== null ) {
  11984. dataCount = index.count;
  11985. } else if ( position !== undefined ) {
  11986. dataCount = position.count;
  11987. }
  11988. var rangeStart = geometry.drawRange.start;
  11989. var rangeCount = geometry.drawRange.count;
  11990. var groupStart = group !== null ? group.start : 0;
  11991. var groupCount = group !== null ? group.count : Infinity;
  11992. var drawStart = Math.max( dataStart, rangeStart, groupStart );
  11993. var drawEnd = Math.min( dataStart + dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  11994. var drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  11995. if ( drawCount === 0 ) return;
  11996. //
  11997. if ( object.isMesh ) {
  11998. if ( material.wireframe === true ) {
  11999. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  12000. renderer.setMode( _gl.LINES );
  12001. } else {
  12002. switch ( object.drawMode ) {
  12003. case TrianglesDrawMode:
  12004. renderer.setMode( _gl.TRIANGLES );
  12005. break;
  12006. case TriangleStripDrawMode:
  12007. renderer.setMode( _gl.TRIANGLE_STRIP );
  12008. break;
  12009. case TriangleFanDrawMode:
  12010. renderer.setMode( _gl.TRIANGLE_FAN );
  12011. break;
  12012. }
  12013. }
  12014. } else if ( object.isLine ) {
  12015. var lineWidth = material.linewidth;
  12016. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  12017. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  12018. if ( object.isLineSegments ) {
  12019. renderer.setMode( _gl.LINES );
  12020. } else {
  12021. renderer.setMode( _gl.LINE_STRIP );
  12022. }
  12023. } else if ( object.isPoints ) {
  12024. renderer.setMode( _gl.POINTS );
  12025. }
  12026. if ( geometry && geometry.isInstancedBufferGeometry ) {
  12027. if ( geometry.maxInstancedCount > 0 ) {
  12028. renderer.renderInstances( geometry, drawStart, drawCount );
  12029. }
  12030. } else {
  12031. renderer.render( drawStart, drawCount );
  12032. }
  12033. };
  12034. function setupVertexAttributes( material, program, geometry, startIndex ) {
  12035. var extension;
  12036. if ( geometry && geometry.isInstancedBufferGeometry ) {
  12037. extension = extensions.get( 'ANGLE_instanced_arrays' );
  12038. if ( extension === null ) {
  12039. console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  12040. return;
  12041. }
  12042. }
  12043. if ( startIndex === undefined ) startIndex = 0;
  12044. state.initAttributes();
  12045. var geometryAttributes = geometry.attributes;
  12046. var programAttributes = program.getAttributes();
  12047. var materialDefaultAttributeValues = material.defaultAttributeValues;
  12048. for ( var name in programAttributes ) {
  12049. var programAttribute = programAttributes[ name ];
  12050. if ( programAttribute >= 0 ) {
  12051. var geometryAttribute = geometryAttributes[ name ];
  12052. if ( geometryAttribute !== undefined ) {
  12053. var type = _gl.FLOAT;
  12054. var array = geometryAttribute.array;
  12055. var normalized = geometryAttribute.normalized;
  12056. if ( array instanceof Float32Array ) {
  12057. type = _gl.FLOAT;
  12058. } else if ( array instanceof Float64Array ) {
  12059. console.warn( "Unsupported data buffer format: Float64Array" );
  12060. } else if ( array instanceof Uint16Array ) {
  12061. type = _gl.UNSIGNED_SHORT;
  12062. } else if ( array instanceof Int16Array ) {
  12063. type = _gl.SHORT;
  12064. } else if ( array instanceof Uint32Array ) {
  12065. type = _gl.UNSIGNED_INT;
  12066. } else if ( array instanceof Int32Array ) {
  12067. type = _gl.INT;
  12068. } else if ( array instanceof Int8Array ) {
  12069. type = _gl.BYTE;
  12070. } else if ( array instanceof Uint8Array ) {
  12071. type = _gl.UNSIGNED_BYTE;
  12072. }
  12073. var size = geometryAttribute.itemSize;
  12074. var buffer = objects.getAttributeBuffer( geometryAttribute );
  12075. if ( geometryAttribute && geometryAttribute.isInterleavedBufferAttribute ) {
  12076. var data = geometryAttribute.data;
  12077. var stride = data.stride;
  12078. var offset = geometryAttribute.offset;
  12079. if ( data && data.isInstancedInterleavedBuffer ) {
  12080. state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute, extension );
  12081. if ( geometry.maxInstancedCount === undefined ) {
  12082. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  12083. }
  12084. } else {
  12085. state.enableAttribute( programAttribute );
  12086. }
  12087. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  12088. _gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * data.array.BYTES_PER_ELEMENT, ( startIndex * stride + offset ) * data.array.BYTES_PER_ELEMENT );
  12089. } else {
  12090. if ( geometryAttribute && geometryAttribute.isInstancedBufferAttribute ) {
  12091. state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute, extension );
  12092. if ( geometry.maxInstancedCount === undefined ) {
  12093. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  12094. }
  12095. } else {
  12096. state.enableAttribute( programAttribute );
  12097. }
  12098. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  12099. _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, startIndex * size * geometryAttribute.array.BYTES_PER_ELEMENT );
  12100. }
  12101. } else if ( materialDefaultAttributeValues !== undefined ) {
  12102. var value = materialDefaultAttributeValues[ name ];
  12103. if ( value !== undefined ) {
  12104. switch ( value.length ) {
  12105. case 2:
  12106. _gl.vertexAttrib2fv( programAttribute, value );
  12107. break;
  12108. case 3:
  12109. _gl.vertexAttrib3fv( programAttribute, value );
  12110. break;
  12111. case 4:
  12112. _gl.vertexAttrib4fv( programAttribute, value );
  12113. break;
  12114. default:
  12115. _gl.vertexAttrib1fv( programAttribute, value );
  12116. }
  12117. }
  12118. }
  12119. }
  12120. }
  12121. state.disableUnusedAttributes();
  12122. }
  12123. // Sorting
  12124. function absNumericalSort( a, b ) {
  12125. return Math.abs( b[ 0 ] ) - Math.abs( a[ 0 ] );
  12126. }
  12127. function painterSortStable( a, b ) {
  12128. if ( a.object.renderOrder !== b.object.renderOrder ) {
  12129. return a.object.renderOrder - b.object.renderOrder;
  12130. } else if ( a.material.program && b.material.program && a.material.program !== b.material.program ) {
  12131. return a.material.program.id - b.material.program.id;
  12132. } else if ( a.material.id !== b.material.id ) {
  12133. return a.material.id - b.material.id;
  12134. } else if ( a.z !== b.z ) {
  12135. return a.z - b.z;
  12136. } else {
  12137. return a.id - b.id;
  12138. }
  12139. }
  12140. function reversePainterSortStable( a, b ) {
  12141. if ( a.object.renderOrder !== b.object.renderOrder ) {
  12142. return a.object.renderOrder - b.object.renderOrder;
  12143. } if ( a.z !== b.z ) {
  12144. return b.z - a.z;
  12145. } else {
  12146. return a.id - b.id;
  12147. }
  12148. }
  12149. // Rendering
  12150. this.render = function ( scene, camera, renderTarget, forceClear ) {
  12151. if ( ( camera && camera.isCamera ) === false ) {
  12152. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  12153. return;
  12154. }
  12155. var fog = scene.fog;
  12156. // reset caching for this frame
  12157. _currentGeometryProgram = '';
  12158. _currentMaterialId = - 1;
  12159. _currentCamera = null;
  12160. // update scene graph
  12161. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  12162. // update camera matrices and frustum
  12163. if ( camera.parent === null ) camera.updateMatrixWorld();
  12164. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  12165. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  12166. _frustum.setFromMatrix( _projScreenMatrix );
  12167. lights.length = 0;
  12168. opaqueObjectsLastIndex = - 1;
  12169. transparentObjectsLastIndex = - 1;
  12170. sprites.length = 0;
  12171. lensFlares.length = 0;
  12172. _localClippingEnabled = this.localClippingEnabled;
  12173. _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  12174. projectObject( scene, camera );
  12175. opaqueObjects.length = opaqueObjectsLastIndex + 1;
  12176. transparentObjects.length = transparentObjectsLastIndex + 1;
  12177. if ( _this.sortObjects === true ) {
  12178. opaqueObjects.sort( painterSortStable );
  12179. transparentObjects.sort( reversePainterSortStable );
  12180. }
  12181. //
  12182. if ( _clippingEnabled ) _clipping.beginShadows();
  12183. setupShadows( lights );
  12184. shadowMap.render( scene, camera );
  12185. setupLights( lights, camera );
  12186. if ( _clippingEnabled ) _clipping.endShadows();
  12187. //
  12188. _infoRender.calls = 0;
  12189. _infoRender.vertices = 0;
  12190. _infoRender.faces = 0;
  12191. _infoRender.points = 0;
  12192. if ( renderTarget === undefined ) {
  12193. renderTarget = null;
  12194. }
  12195. this.setRenderTarget( renderTarget );
  12196. //
  12197. var background = scene.background;
  12198. if ( background === null ) {
  12199. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  12200. } else if ( background && background.isColor ) {
  12201. glClearColor( background.r, background.g, background.b, 1 );
  12202. forceClear = true;
  12203. }
  12204. if ( this.autoClear || forceClear ) {
  12205. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  12206. }
  12207. if ( background && background.isCubeTexture ) {
  12208. backgroundCamera2.projectionMatrix.copy( camera.projectionMatrix );
  12209. backgroundCamera2.matrixWorld.extractRotation( camera.matrixWorld );
  12210. backgroundCamera2.matrixWorldInverse.getInverse( backgroundCamera2.matrixWorld );
  12211. backgroundBoxMesh.material.uniforms[ "tCube" ].value = background;
  12212. backgroundBoxMesh.modelViewMatrix.multiplyMatrices( backgroundCamera2.matrixWorldInverse, backgroundBoxMesh.matrixWorld );
  12213. objects.update( backgroundBoxMesh );
  12214. _this.renderBufferDirect( backgroundCamera2, null, backgroundBoxMesh.geometry, backgroundBoxMesh.material, backgroundBoxMesh, null );
  12215. } else if ( background && background.isTexture ) {
  12216. backgroundPlaneMesh.material.map = background;
  12217. objects.update( backgroundPlaneMesh );
  12218. _this.renderBufferDirect( backgroundCamera, null, backgroundPlaneMesh.geometry, backgroundPlaneMesh.material, backgroundPlaneMesh, null );
  12219. }
  12220. //
  12221. if ( scene.overrideMaterial ) {
  12222. var overrideMaterial = scene.overrideMaterial;
  12223. renderObjects( opaqueObjects, camera, fog, overrideMaterial );
  12224. renderObjects( transparentObjects, camera, fog, overrideMaterial );
  12225. } else {
  12226. // opaque pass (front-to-back order)
  12227. state.setBlending( NoBlending );
  12228. renderObjects( opaqueObjects, camera, fog );
  12229. // transparent pass (back-to-front order)
  12230. renderObjects( transparentObjects, camera, fog );
  12231. }
  12232. // custom render plugins (post pass)
  12233. spritePlugin.render( scene, camera );
  12234. lensFlarePlugin.render( scene, camera, _currentViewport );
  12235. // Generate mipmap if we're using any kind of mipmap filtering
  12236. if ( renderTarget ) {
  12237. textures.updateRenderTargetMipmap( renderTarget );
  12238. }
  12239. // Ensure depth buffer writing is enabled so it can be cleared on next render
  12240. state.setDepthTest( true );
  12241. state.setDepthWrite( true );
  12242. state.setColorWrite( true );
  12243. // _gl.finish();
  12244. };
  12245. function pushRenderItem( object, geometry, material, z, group ) {
  12246. var array, index;
  12247. // allocate the next position in the appropriate array
  12248. if ( material.transparent ) {
  12249. array = transparentObjects;
  12250. index = ++ transparentObjectsLastIndex;
  12251. } else {
  12252. array = opaqueObjects;
  12253. index = ++ opaqueObjectsLastIndex;
  12254. }
  12255. // recycle existing render item or grow the array
  12256. var renderItem = array[ index ];
  12257. if ( renderItem !== undefined ) {
  12258. renderItem.id = object.id;
  12259. renderItem.object = object;
  12260. renderItem.geometry = geometry;
  12261. renderItem.material = material;
  12262. renderItem.z = _vector3.z;
  12263. renderItem.group = group;
  12264. } else {
  12265. renderItem = {
  12266. id: object.id,
  12267. object: object,
  12268. geometry: geometry,
  12269. material: material,
  12270. z: _vector3.z,
  12271. group: group
  12272. };
  12273. // assert( index === array.length );
  12274. array.push( renderItem );
  12275. }
  12276. }
  12277. // TODO Duplicated code (Frustum)
  12278. function isObjectViewable( object ) {
  12279. var geometry = object.geometry;
  12280. if ( geometry.boundingSphere === null )
  12281. geometry.computeBoundingSphere();
  12282. _sphere.copy( geometry.boundingSphere ).
  12283. applyMatrix4( object.matrixWorld );
  12284. return isSphereViewable( _sphere );
  12285. }
  12286. function isSpriteViewable( sprite ) {
  12287. _sphere.center.set( 0, 0, 0 );
  12288. _sphere.radius = 0.7071067811865476;
  12289. _sphere.applyMatrix4( sprite.matrixWorld );
  12290. return isSphereViewable( _sphere );
  12291. }
  12292. function isSphereViewable( sphere ) {
  12293. if ( ! _frustum.intersectsSphere( sphere ) ) return false;
  12294. var numPlanes = _clipping.numPlanes;
  12295. if ( numPlanes === 0 ) return true;
  12296. var planes = _this.clippingPlanes,
  12297. center = sphere.center,
  12298. negRad = - sphere.radius,
  12299. i = 0;
  12300. do {
  12301. // out when deeper than radius in the negative halfspace
  12302. if ( planes[ i ].distanceToPoint( center ) < negRad ) return false;
  12303. } while ( ++ i !== numPlanes );
  12304. return true;
  12305. }
  12306. function projectObject( object, camera ) {
  12307. if ( object.visible === false ) return;
  12308. var visible = ( object.layers.mask & camera.layers.mask ) !== 0;
  12309. if ( visible ) {
  12310. if ( object.isLight ) {
  12311. lights.push( object );
  12312. } else if ( object.isSprite ) {
  12313. if ( object.frustumCulled === false || isSpriteViewable( object ) === true ) {
  12314. sprites.push( object );
  12315. }
  12316. } else if ( object.isLensFlare ) {
  12317. lensFlares.push( object );
  12318. } else if ( object.isImmediateRenderObject ) {
  12319. if ( _this.sortObjects === true ) {
  12320. _vector3.setFromMatrixPosition( object.matrixWorld );
  12321. _vector3.applyProjection( _projScreenMatrix );
  12322. }
  12323. pushRenderItem( object, null, object.material, _vector3.z, null );
  12324. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  12325. if ( object.isSkinnedMesh ) {
  12326. object.skeleton.update();
  12327. }
  12328. if ( object.frustumCulled === false || isObjectViewable( object ) === true ) {
  12329. var material = object.material;
  12330. if ( material.visible === true ) {
  12331. if ( _this.sortObjects === true ) {
  12332. _vector3.setFromMatrixPosition( object.matrixWorld );
  12333. _vector3.applyProjection( _projScreenMatrix );
  12334. }
  12335. var geometry = objects.update( object );
  12336. if ( material.isMultiMaterial ) {
  12337. var groups = geometry.groups;
  12338. var materials = material.materials;
  12339. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  12340. var group = groups[ i ];
  12341. var groupMaterial = materials[ group.materialIndex ];
  12342. if ( groupMaterial.visible === true ) {
  12343. pushRenderItem( object, geometry, groupMaterial, _vector3.z, group );
  12344. }
  12345. }
  12346. } else {
  12347. pushRenderItem( object, geometry, material, _vector3.z, null );
  12348. }
  12349. }
  12350. }
  12351. }
  12352. }
  12353. var children = object.children;
  12354. for ( var i = 0, l = children.length; i < l; i ++ ) {
  12355. projectObject( children[ i ], camera );
  12356. }
  12357. }
  12358. function renderObjects( renderList, camera, fog, overrideMaterial ) {
  12359. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  12360. var renderItem = renderList[ i ];
  12361. var object = renderItem.object;
  12362. var geometry = renderItem.geometry;
  12363. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  12364. var group = renderItem.group;
  12365. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  12366. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  12367. if ( object.isImmediateRenderObject ) {
  12368. setMaterial( material );
  12369. var program = setProgram( camera, fog, material, object );
  12370. _currentGeometryProgram = '';
  12371. object.render( function ( object ) {
  12372. _this.renderBufferImmediate( object, program, material );
  12373. } );
  12374. } else {
  12375. _this.renderBufferDirect( camera, fog, geometry, material, object, group );
  12376. }
  12377. }
  12378. }
  12379. function initMaterial( material, fog, object ) {
  12380. var materialProperties = properties.get( material );
  12381. var parameters = programCache.getParameters(
  12382. material, _lights, fog, _clipping.numPlanes, object );
  12383. var code = programCache.getProgramCode( material, parameters );
  12384. var program = materialProperties.program;
  12385. var programChange = true;
  12386. if ( program === undefined ) {
  12387. // new material
  12388. material.addEventListener( 'dispose', onMaterialDispose );
  12389. } else if ( program.code !== code ) {
  12390. // changed glsl or parameters
  12391. releaseMaterialProgramReference( material );
  12392. } else if ( parameters.shaderID !== undefined ) {
  12393. // same glsl and uniform list
  12394. return;
  12395. } else {
  12396. // only rebuild uniform list
  12397. programChange = false;
  12398. }
  12399. if ( programChange ) {
  12400. if ( parameters.shaderID ) {
  12401. var shader = ShaderLib[ parameters.shaderID ];
  12402. materialProperties.__webglShader = {
  12403. name: material.type,
  12404. uniforms: exports.UniformsUtils.clone( shader.uniforms ),
  12405. vertexShader: shader.vertexShader,
  12406. fragmentShader: shader.fragmentShader
  12407. };
  12408. } else {
  12409. materialProperties.__webglShader = {
  12410. name: material.type,
  12411. uniforms: material.uniforms,
  12412. vertexShader: material.vertexShader,
  12413. fragmentShader: material.fragmentShader
  12414. };
  12415. }
  12416. material.__webglShader = materialProperties.__webglShader;
  12417. program = programCache.acquireProgram( material, parameters, code );
  12418. materialProperties.program = program;
  12419. material.program = program;
  12420. }
  12421. var attributes = program.getAttributes();
  12422. if ( material.morphTargets ) {
  12423. material.numSupportedMorphTargets = 0;
  12424. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  12425. if ( attributes[ 'morphTarget' + i ] >= 0 ) {
  12426. material.numSupportedMorphTargets ++;
  12427. }
  12428. }
  12429. }
  12430. if ( material.morphNormals ) {
  12431. material.numSupportedMorphNormals = 0;
  12432. for ( var i = 0; i < _this.maxMorphNormals; i ++ ) {
  12433. if ( attributes[ 'morphNormal' + i ] >= 0 ) {
  12434. material.numSupportedMorphNormals ++;
  12435. }
  12436. }
  12437. }
  12438. var uniforms = materialProperties.__webglShader.uniforms;
  12439. if ( ! material.isShaderMaterial &&
  12440. ! material.isRawShaderMaterial ||
  12441. material.clipping === true ) {
  12442. materialProperties.numClippingPlanes = _clipping.numPlanes;
  12443. uniforms.clippingPlanes = _clipping.uniform;
  12444. }
  12445. materialProperties.fog = fog;
  12446. // store the light setup it was created for
  12447. materialProperties.lightsHash = _lights.hash;
  12448. if ( material.lights ) {
  12449. // wire up the material to this renderer's lighting state
  12450. uniforms.ambientLightColor.value = _lights.ambient;
  12451. uniforms.directionalLights.value = _lights.directional;
  12452. uniforms.spotLights.value = _lights.spot;
  12453. uniforms.pointLights.value = _lights.point;
  12454. uniforms.hemisphereLights.value = _lights.hemi;
  12455. uniforms.directionalShadowMap.value = _lights.directionalShadowMap;
  12456. uniforms.directionalShadowMatrix.value = _lights.directionalShadowMatrix;
  12457. uniforms.spotShadowMap.value = _lights.spotShadowMap;
  12458. uniforms.spotShadowMatrix.value = _lights.spotShadowMatrix;
  12459. uniforms.pointShadowMap.value = _lights.pointShadowMap;
  12460. uniforms.pointShadowMatrix.value = _lights.pointShadowMatrix;
  12461. }
  12462. var progUniforms = materialProperties.program.getUniforms(),
  12463. uniformsList =
  12464. WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  12465. materialProperties.uniformsList = uniformsList;
  12466. materialProperties.dynamicUniforms =
  12467. WebGLUniforms.splitDynamic( uniformsList, uniforms );
  12468. }
  12469. function setMaterial( material ) {
  12470. material.side === DoubleSide
  12471. ? state.disable( _gl.CULL_FACE )
  12472. : state.enable( _gl.CULL_FACE );
  12473. state.setFlipSided( material.side === BackSide );
  12474. material.transparent === true
  12475. ? state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha )
  12476. : state.setBlending( NoBlending );
  12477. state.setDepthFunc( material.depthFunc );
  12478. state.setDepthTest( material.depthTest );
  12479. state.setDepthWrite( material.depthWrite );
  12480. state.setColorWrite( material.colorWrite );
  12481. state.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  12482. }
  12483. function setProgram( camera, fog, material, object ) {
  12484. _usedTextureUnits = 0;
  12485. var materialProperties = properties.get( material );
  12486. if ( _clippingEnabled ) {
  12487. if ( _localClippingEnabled || camera !== _currentCamera ) {
  12488. var useCache =
  12489. camera === _currentCamera &&
  12490. material.id === _currentMaterialId;
  12491. // we might want to call this function with some ClippingGroup
  12492. // object instead of the material, once it becomes feasible
  12493. // (#8465, #8379)
  12494. _clipping.setState(
  12495. material.clippingPlanes, material.clipShadows,
  12496. camera, materialProperties, useCache );
  12497. }
  12498. }
  12499. if ( material.needsUpdate === false ) {
  12500. if ( materialProperties.program === undefined ) {
  12501. material.needsUpdate = true;
  12502. } else if ( material.fog && materialProperties.fog !== fog ) {
  12503. material.needsUpdate = true;
  12504. } else if ( material.lights && materialProperties.lightsHash !== _lights.hash ) {
  12505. material.needsUpdate = true;
  12506. } else if ( materialProperties.numClippingPlanes !== undefined &&
  12507. materialProperties.numClippingPlanes !== _clipping.numPlanes ) {
  12508. material.needsUpdate = true;
  12509. }
  12510. }
  12511. if ( material.needsUpdate ) {
  12512. initMaterial( material, fog, object );
  12513. material.needsUpdate = false;
  12514. }
  12515. var refreshProgram = false;
  12516. var refreshMaterial = false;
  12517. var refreshLights = false;
  12518. var program = materialProperties.program,
  12519. p_uniforms = program.getUniforms(),
  12520. m_uniforms = materialProperties.__webglShader.uniforms;
  12521. if ( program.id !== _currentProgram ) {
  12522. _gl.useProgram( program.program );
  12523. _currentProgram = program.id;
  12524. refreshProgram = true;
  12525. refreshMaterial = true;
  12526. refreshLights = true;
  12527. }
  12528. if ( material.id !== _currentMaterialId ) {
  12529. _currentMaterialId = material.id;
  12530. refreshMaterial = true;
  12531. }
  12532. if ( refreshProgram || camera !== _currentCamera ) {
  12533. p_uniforms.set( _gl, camera, 'projectionMatrix' );
  12534. if ( capabilities.logarithmicDepthBuffer ) {
  12535. p_uniforms.setValue( _gl, 'logDepthBufFC',
  12536. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  12537. }
  12538. if ( camera !== _currentCamera ) {
  12539. _currentCamera = camera;
  12540. // lighting uniforms depend on the camera so enforce an update
  12541. // now, in case this material supports lights - or later, when
  12542. // the next material that does gets activated:
  12543. refreshMaterial = true; // set to true on material change
  12544. refreshLights = true; // remains set until update done
  12545. }
  12546. // load material specific uniforms
  12547. // (shader material also gets them for the sake of genericity)
  12548. if ( material.isShaderMaterial ||
  12549. material.isMeshPhongMaterial ||
  12550. material.isMeshStandardMaterial ||
  12551. material.envMap ) {
  12552. var uCamPos = p_uniforms.map.cameraPosition;
  12553. if ( uCamPos !== undefined ) {
  12554. uCamPos.setValue( _gl,
  12555. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  12556. }
  12557. }
  12558. if ( material.isMeshPhongMaterial ||
  12559. material.isMeshLambertMaterial ||
  12560. material.isMeshBasicMaterial ||
  12561. material.isMeshStandardMaterial ||
  12562. material.isShaderMaterial ||
  12563. material.skinning ) {
  12564. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  12565. }
  12566. p_uniforms.set( _gl, _this, 'toneMappingExposure' );
  12567. p_uniforms.set( _gl, _this, 'toneMappingWhitePoint' );
  12568. }
  12569. // skinning uniforms must be set even if material didn't change
  12570. // auto-setting of texture unit for bone texture must go before other textures
  12571. // not sure why, but otherwise weird things happen
  12572. if ( material.skinning ) {
  12573. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  12574. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  12575. var skeleton = object.skeleton;
  12576. if ( skeleton ) {
  12577. if ( capabilities.floatVertexTextures && skeleton.useVertexTexture ) {
  12578. p_uniforms.set( _gl, skeleton, 'boneTexture' );
  12579. p_uniforms.set( _gl, skeleton, 'boneTextureWidth' );
  12580. p_uniforms.set( _gl, skeleton, 'boneTextureHeight' );
  12581. } else {
  12582. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  12583. }
  12584. }
  12585. }
  12586. if ( refreshMaterial ) {
  12587. if ( material.lights ) {
  12588. // the current material requires lighting info
  12589. // note: all lighting uniforms are always set correctly
  12590. // they simply reference the renderer's state for their
  12591. // values
  12592. //
  12593. // use the current material's .needsUpdate flags to set
  12594. // the GL state when required
  12595. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  12596. }
  12597. // refresh uniforms common to several materials
  12598. if ( fog && material.fog ) {
  12599. refreshUniformsFog( m_uniforms, fog );
  12600. }
  12601. if ( material.isMeshBasicMaterial ||
  12602. material.isMeshLambertMaterial ||
  12603. material.isMeshPhongMaterial ||
  12604. material.isMeshStandardMaterial ||
  12605. material.isMeshDepthMaterial ) {
  12606. refreshUniformsCommon( m_uniforms, material );
  12607. }
  12608. // refresh single material specific uniforms
  12609. if ( material.isLineBasicMaterial ) {
  12610. refreshUniformsLine( m_uniforms, material );
  12611. } else if ( material.isLineDashedMaterial ) {
  12612. refreshUniformsLine( m_uniforms, material );
  12613. refreshUniformsDash( m_uniforms, material );
  12614. } else if ( material.isPointsMaterial ) {
  12615. refreshUniformsPoints( m_uniforms, material );
  12616. } else if ( material.isMeshLambertMaterial ) {
  12617. refreshUniformsLambert( m_uniforms, material );
  12618. } else if ( material.isMeshPhongMaterial ) {
  12619. refreshUniformsPhong( m_uniforms, material );
  12620. } else if ( material.isMeshPhysicalMaterial ) {
  12621. refreshUniformsPhysical( m_uniforms, material );
  12622. } else if ( material.isMeshStandardMaterial ) {
  12623. refreshUniformsStandard( m_uniforms, material );
  12624. } else if ( material.isMeshDepthMaterial ) {
  12625. if ( material.displacementMap ) {
  12626. m_uniforms.displacementMap.value = material.displacementMap;
  12627. m_uniforms.displacementScale.value = material.displacementScale;
  12628. m_uniforms.displacementBias.value = material.displacementBias;
  12629. }
  12630. } else if ( material.isMeshNormalMaterial ) {
  12631. m_uniforms.opacity.value = material.opacity;
  12632. }
  12633. WebGLUniforms.upload(
  12634. _gl, materialProperties.uniformsList, m_uniforms, _this );
  12635. }
  12636. // common matrices
  12637. p_uniforms.set( _gl, object, 'modelViewMatrix' );
  12638. p_uniforms.set( _gl, object, 'normalMatrix' );
  12639. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  12640. // dynamic uniforms
  12641. var dynUniforms = materialProperties.dynamicUniforms;
  12642. if ( dynUniforms !== null ) {
  12643. WebGLUniforms.evalDynamic(
  12644. dynUniforms, m_uniforms, object, camera );
  12645. WebGLUniforms.upload( _gl, dynUniforms, m_uniforms, _this );
  12646. }
  12647. return program;
  12648. }
  12649. // Uniforms (refresh uniforms objects)
  12650. function refreshUniformsCommon( uniforms, material ) {
  12651. uniforms.opacity.value = material.opacity;
  12652. uniforms.diffuse.value = material.color;
  12653. if ( material.emissive ) {
  12654. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  12655. }
  12656. uniforms.map.value = material.map;
  12657. uniforms.specularMap.value = material.specularMap;
  12658. uniforms.alphaMap.value = material.alphaMap;
  12659. if ( material.aoMap ) {
  12660. uniforms.aoMap.value = material.aoMap;
  12661. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  12662. }
  12663. // uv repeat and offset setting priorities
  12664. // 1. color map
  12665. // 2. specular map
  12666. // 3. normal map
  12667. // 4. bump map
  12668. // 5. alpha map
  12669. // 6. emissive map
  12670. var uvScaleMap;
  12671. if ( material.map ) {
  12672. uvScaleMap = material.map;
  12673. } else if ( material.specularMap ) {
  12674. uvScaleMap = material.specularMap;
  12675. } else if ( material.displacementMap ) {
  12676. uvScaleMap = material.displacementMap;
  12677. } else if ( material.normalMap ) {
  12678. uvScaleMap = material.normalMap;
  12679. } else if ( material.bumpMap ) {
  12680. uvScaleMap = material.bumpMap;
  12681. } else if ( material.roughnessMap ) {
  12682. uvScaleMap = material.roughnessMap;
  12683. } else if ( material.metalnessMap ) {
  12684. uvScaleMap = material.metalnessMap;
  12685. } else if ( material.alphaMap ) {
  12686. uvScaleMap = material.alphaMap;
  12687. } else if ( material.emissiveMap ) {
  12688. uvScaleMap = material.emissiveMap;
  12689. }
  12690. if ( uvScaleMap !== undefined ) {
  12691. // backwards compatibility
  12692. if ( uvScaleMap.isWebGLRenderTarget ) {
  12693. uvScaleMap = uvScaleMap.texture;
  12694. }
  12695. var offset = uvScaleMap.offset;
  12696. var repeat = uvScaleMap.repeat;
  12697. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  12698. }
  12699. uniforms.envMap.value = material.envMap;
  12700. // don't flip CubeTexture envMaps, flip everything else:
  12701. // WebGLRenderTargetCube will be flipped for backwards compatibility
  12702. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  12703. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  12704. uniforms.flipEnvMap.value = ( ! ( material.envMap && material.envMap.isCubeTexture ) ) ? 1 : - 1;
  12705. uniforms.reflectivity.value = material.reflectivity;
  12706. uniforms.refractionRatio.value = material.refractionRatio;
  12707. }
  12708. function refreshUniformsLine( uniforms, material ) {
  12709. uniforms.diffuse.value = material.color;
  12710. uniforms.opacity.value = material.opacity;
  12711. }
  12712. function refreshUniformsDash( uniforms, material ) {
  12713. uniforms.dashSize.value = material.dashSize;
  12714. uniforms.totalSize.value = material.dashSize + material.gapSize;
  12715. uniforms.scale.value = material.scale;
  12716. }
  12717. function refreshUniformsPoints( uniforms, material ) {
  12718. uniforms.diffuse.value = material.color;
  12719. uniforms.opacity.value = material.opacity;
  12720. uniforms.size.value = material.size * _pixelRatio;
  12721. uniforms.scale.value = _canvas.clientHeight * 0.5;
  12722. uniforms.map.value = material.map;
  12723. if ( material.map !== null ) {
  12724. var offset = material.map.offset;
  12725. var repeat = material.map.repeat;
  12726. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  12727. }
  12728. }
  12729. function refreshUniformsFog( uniforms, fog ) {
  12730. uniforms.fogColor.value = fog.color;
  12731. if ( fog.isFog ) {
  12732. uniforms.fogNear.value = fog.near;
  12733. uniforms.fogFar.value = fog.far;
  12734. } else if ( fog.isFogExp2 ) {
  12735. uniforms.fogDensity.value = fog.density;
  12736. }
  12737. }
  12738. function refreshUniformsLambert( uniforms, material ) {
  12739. if ( material.lightMap ) {
  12740. uniforms.lightMap.value = material.lightMap;
  12741. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  12742. }
  12743. if ( material.emissiveMap ) {
  12744. uniforms.emissiveMap.value = material.emissiveMap;
  12745. }
  12746. }
  12747. function refreshUniformsPhong( uniforms, material ) {
  12748. uniforms.specular.value = material.specular;
  12749. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  12750. if ( material.lightMap ) {
  12751. uniforms.lightMap.value = material.lightMap;
  12752. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  12753. }
  12754. if ( material.emissiveMap ) {
  12755. uniforms.emissiveMap.value = material.emissiveMap;
  12756. }
  12757. if ( material.bumpMap ) {
  12758. uniforms.bumpMap.value = material.bumpMap;
  12759. uniforms.bumpScale.value = material.bumpScale;
  12760. }
  12761. if ( material.normalMap ) {
  12762. uniforms.normalMap.value = material.normalMap;
  12763. uniforms.normalScale.value.copy( material.normalScale );
  12764. }
  12765. if ( material.displacementMap ) {
  12766. uniforms.displacementMap.value = material.displacementMap;
  12767. uniforms.displacementScale.value = material.displacementScale;
  12768. uniforms.displacementBias.value = material.displacementBias;
  12769. }
  12770. }
  12771. function refreshUniformsStandard( uniforms, material ) {
  12772. uniforms.roughness.value = material.roughness;
  12773. uniforms.metalness.value = material.metalness;
  12774. if ( material.roughnessMap ) {
  12775. uniforms.roughnessMap.value = material.roughnessMap;
  12776. }
  12777. if ( material.metalnessMap ) {
  12778. uniforms.metalnessMap.value = material.metalnessMap;
  12779. }
  12780. if ( material.lightMap ) {
  12781. uniforms.lightMap.value = material.lightMap;
  12782. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  12783. }
  12784. if ( material.emissiveMap ) {
  12785. uniforms.emissiveMap.value = material.emissiveMap;
  12786. }
  12787. if ( material.bumpMap ) {
  12788. uniforms.bumpMap.value = material.bumpMap;
  12789. uniforms.bumpScale.value = material.bumpScale;
  12790. }
  12791. if ( material.normalMap ) {
  12792. uniforms.normalMap.value = material.normalMap;
  12793. uniforms.normalScale.value.copy( material.normalScale );
  12794. }
  12795. if ( material.displacementMap ) {
  12796. uniforms.displacementMap.value = material.displacementMap;
  12797. uniforms.displacementScale.value = material.displacementScale;
  12798. uniforms.displacementBias.value = material.displacementBias;
  12799. }
  12800. if ( material.envMap ) {
  12801. //uniforms.envMap.value = material.envMap; // part of uniforms common
  12802. uniforms.envMapIntensity.value = material.envMapIntensity;
  12803. }
  12804. }
  12805. function refreshUniformsPhysical( uniforms, material ) {
  12806. uniforms.clearCoat.value = material.clearCoat;
  12807. uniforms.clearCoatRoughness.value = material.clearCoatRoughness;
  12808. refreshUniformsStandard( uniforms, material );
  12809. }
  12810. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  12811. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  12812. uniforms.ambientLightColor.needsUpdate = value;
  12813. uniforms.directionalLights.needsUpdate = value;
  12814. uniforms.pointLights.needsUpdate = value;
  12815. uniforms.spotLights.needsUpdate = value;
  12816. uniforms.hemisphereLights.needsUpdate = value;
  12817. }
  12818. // Lighting
  12819. function setupShadows( lights ) {
  12820. var lightShadowsLength = 0;
  12821. for ( var i = 0, l = lights.length; i < l; i ++ ) {
  12822. var light = lights[ i ];
  12823. if ( light.castShadow ) {
  12824. _lights.shadows[ lightShadowsLength ++ ] = light;
  12825. }
  12826. }
  12827. _lights.shadows.length = lightShadowsLength;
  12828. }
  12829. function setupLights( lights, camera ) {
  12830. var l, ll, light,
  12831. r = 0, g = 0, b = 0,
  12832. color,
  12833. intensity,
  12834. distance,
  12835. shadowMap,
  12836. viewMatrix = camera.matrixWorldInverse,
  12837. directionalLength = 0,
  12838. pointLength = 0,
  12839. spotLength = 0,
  12840. hemiLength = 0;
  12841. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  12842. light = lights[ l ];
  12843. color = light.color;
  12844. intensity = light.intensity;
  12845. distance = light.distance;
  12846. shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  12847. if ( light.isAmbientLight ) {
  12848. r += color.r * intensity;
  12849. g += color.g * intensity;
  12850. b += color.b * intensity;
  12851. } else if ( light.isDirectionalLight ) {
  12852. var uniforms = lightCache.get( light );
  12853. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  12854. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12855. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  12856. uniforms.direction.sub( _vector3 );
  12857. uniforms.direction.transformDirection( viewMatrix );
  12858. uniforms.shadow = light.castShadow;
  12859. if ( light.castShadow ) {
  12860. uniforms.shadowBias = light.shadow.bias;
  12861. uniforms.shadowRadius = light.shadow.radius;
  12862. uniforms.shadowMapSize = light.shadow.mapSize;
  12863. }
  12864. _lights.directionalShadowMap[ directionalLength ] = shadowMap;
  12865. _lights.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  12866. _lights.directional[ directionalLength ++ ] = uniforms;
  12867. } else if ( light.isSpotLight ) {
  12868. var uniforms = lightCache.get( light );
  12869. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12870. uniforms.position.applyMatrix4( viewMatrix );
  12871. uniforms.color.copy( color ).multiplyScalar( intensity );
  12872. uniforms.distance = distance;
  12873. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12874. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  12875. uniforms.direction.sub( _vector3 );
  12876. uniforms.direction.transformDirection( viewMatrix );
  12877. uniforms.coneCos = Math.cos( light.angle );
  12878. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  12879. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  12880. uniforms.shadow = light.castShadow;
  12881. if ( light.castShadow ) {
  12882. uniforms.shadowBias = light.shadow.bias;
  12883. uniforms.shadowRadius = light.shadow.radius;
  12884. uniforms.shadowMapSize = light.shadow.mapSize;
  12885. }
  12886. _lights.spotShadowMap[ spotLength ] = shadowMap;
  12887. _lights.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  12888. _lights.spot[ spotLength ++ ] = uniforms;
  12889. } else if ( light.isPointLight ) {
  12890. var uniforms = lightCache.get( light );
  12891. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12892. uniforms.position.applyMatrix4( viewMatrix );
  12893. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  12894. uniforms.distance = light.distance;
  12895. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  12896. uniforms.shadow = light.castShadow;
  12897. if ( light.castShadow ) {
  12898. uniforms.shadowBias = light.shadow.bias;
  12899. uniforms.shadowRadius = light.shadow.radius;
  12900. uniforms.shadowMapSize = light.shadow.mapSize;
  12901. }
  12902. _lights.pointShadowMap[ pointLength ] = shadowMap;
  12903. if ( _lights.pointShadowMatrix[ pointLength ] === undefined ) {
  12904. _lights.pointShadowMatrix[ pointLength ] = new Matrix4();
  12905. }
  12906. // for point lights we set the shadow matrix to be a translation-only matrix
  12907. // equal to inverse of the light's position
  12908. _vector3.setFromMatrixPosition( light.matrixWorld ).negate();
  12909. _lights.pointShadowMatrix[ pointLength ].identity().setPosition( _vector3 );
  12910. _lights.point[ pointLength ++ ] = uniforms;
  12911. } else if ( light.isHemisphereLight ) {
  12912. var uniforms = lightCache.get( light );
  12913. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12914. uniforms.direction.transformDirection( viewMatrix );
  12915. uniforms.direction.normalize();
  12916. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  12917. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  12918. _lights.hemi[ hemiLength ++ ] = uniforms;
  12919. }
  12920. }
  12921. _lights.ambient[ 0 ] = r;
  12922. _lights.ambient[ 1 ] = g;
  12923. _lights.ambient[ 2 ] = b;
  12924. _lights.directional.length = directionalLength;
  12925. _lights.spot.length = spotLength;
  12926. _lights.point.length = pointLength;
  12927. _lights.hemi.length = hemiLength;
  12928. _lights.hash = directionalLength + ',' + pointLength + ',' + spotLength + ',' + hemiLength + ',' + _lights.shadows.length;
  12929. }
  12930. // GL state setting
  12931. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  12932. state.setCullFace( cullFace );
  12933. state.setFlipSided( frontFaceDirection === FrontFaceDirectionCW );
  12934. };
  12935. // Textures
  12936. function allocTextureUnit() {
  12937. var textureUnit = _usedTextureUnits;
  12938. if ( textureUnit >= capabilities.maxTextures ) {
  12939. console.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  12940. }
  12941. _usedTextureUnits += 1;
  12942. return textureUnit;
  12943. }
  12944. this.allocTextureUnit = allocTextureUnit;
  12945. // this.setTexture2D = setTexture2D;
  12946. this.setTexture2D = ( function() {
  12947. var warned = false;
  12948. // backwards compatibility: peel texture.texture
  12949. return function setTexture2D( texture, slot ) {
  12950. if ( texture && texture.isWebGLRenderTarget ) {
  12951. if ( ! warned ) {
  12952. console.warn( "THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead." );
  12953. warned = true;
  12954. }
  12955. texture = texture.texture;
  12956. }
  12957. textures.setTexture2D( texture, slot );
  12958. };
  12959. }() );
  12960. this.setTexture = ( function() {
  12961. var warned = false;
  12962. return function setTexture( texture, slot ) {
  12963. if ( ! warned ) {
  12964. console.warn( "THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead." );
  12965. warned = true;
  12966. }
  12967. textures.setTexture2D( texture, slot );
  12968. };
  12969. }() );
  12970. this.setTextureCube = ( function() {
  12971. var warned = false;
  12972. return function setTextureCube( texture, slot ) {
  12973. // backwards compatibility: peel texture.texture
  12974. if ( texture && texture.isWebGLRenderTargetCube ) {
  12975. if ( ! warned ) {
  12976. console.warn( "THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead." );
  12977. warned = true;
  12978. }
  12979. texture = texture.texture;
  12980. }
  12981. // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture
  12982. // TODO: unify these code paths
  12983. if ( ( texture && texture.isCubeTexture ) ||
  12984. ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {
  12985. // CompressedTexture can have Array in image :/
  12986. // this function alone should take care of cube textures
  12987. textures.setTextureCube( texture, slot );
  12988. } else {
  12989. // assumed: texture property of THREE.WebGLRenderTargetCube
  12990. textures.setTextureCubeDynamic( texture, slot );
  12991. }
  12992. };
  12993. }() );
  12994. this.getCurrentRenderTarget = function() {
  12995. return _currentRenderTarget;
  12996. };
  12997. this.setRenderTarget = function ( renderTarget ) {
  12998. _currentRenderTarget = renderTarget;
  12999. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  13000. textures.setupRenderTarget( renderTarget );
  13001. }
  13002. var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube );
  13003. var framebuffer;
  13004. if ( renderTarget ) {
  13005. var renderTargetProperties = properties.get( renderTarget );
  13006. if ( isCube ) {
  13007. framebuffer = renderTargetProperties.__webglFramebuffer[ renderTarget.activeCubeFace ];
  13008. } else {
  13009. framebuffer = renderTargetProperties.__webglFramebuffer;
  13010. }
  13011. _currentScissor.copy( renderTarget.scissor );
  13012. _currentScissorTest = renderTarget.scissorTest;
  13013. _currentViewport.copy( renderTarget.viewport );
  13014. } else {
  13015. framebuffer = null;
  13016. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio );
  13017. _currentScissorTest = _scissorTest;
  13018. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio );
  13019. }
  13020. if ( _currentFramebuffer !== framebuffer ) {
  13021. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13022. _currentFramebuffer = framebuffer;
  13023. }
  13024. state.scissor( _currentScissor );
  13025. state.setScissorTest( _currentScissorTest );
  13026. state.viewport( _currentViewport );
  13027. if ( isCube ) {
  13028. var textureProperties = properties.get( renderTarget.texture );
  13029. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, renderTarget.activeMipMapLevel );
  13030. }
  13031. };
  13032. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) {
  13033. if ( ( renderTarget && renderTarget.isWebGLRenderTarget ) === false ) {
  13034. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  13035. return;
  13036. }
  13037. var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  13038. if ( framebuffer ) {
  13039. var restore = false;
  13040. if ( framebuffer !== _currentFramebuffer ) {
  13041. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13042. restore = true;
  13043. }
  13044. try {
  13045. var texture = renderTarget.texture;
  13046. var textureFormat = texture.format;
  13047. var textureType = texture.type;
  13048. if ( textureFormat !== RGBAFormat && paramThreeToGL( textureFormat ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  13049. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  13050. return;
  13051. }
  13052. if ( textureType !== UnsignedByteType && paramThreeToGL( textureType ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // IE11, Edge and Chrome Mac < 52 (#9513)
  13053. ! ( textureType === FloatType && ( extensions.get( 'OES_texture_float' ) || extensions.get( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  13054. ! ( textureType === HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) {
  13055. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  13056. return;
  13057. }
  13058. if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
  13059. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  13060. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  13061. _gl.readPixels( x, y, width, height, paramThreeToGL( textureFormat ), paramThreeToGL( textureType ), buffer );
  13062. }
  13063. } else {
  13064. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  13065. }
  13066. } finally {
  13067. if ( restore ) {
  13068. _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
  13069. }
  13070. }
  13071. }
  13072. };
  13073. // Map three.js constants to WebGL constants
  13074. function paramThreeToGL( p ) {
  13075. var extension;
  13076. if ( p === RepeatWrapping ) return _gl.REPEAT;
  13077. if ( p === ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  13078. if ( p === MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  13079. if ( p === NearestFilter ) return _gl.NEAREST;
  13080. if ( p === NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  13081. if ( p === NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  13082. if ( p === LinearFilter ) return _gl.LINEAR;
  13083. if ( p === LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  13084. if ( p === LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  13085. if ( p === UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  13086. if ( p === UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  13087. if ( p === UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  13088. if ( p === UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  13089. if ( p === ByteType ) return _gl.BYTE;
  13090. if ( p === ShortType ) return _gl.SHORT;
  13091. if ( p === UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  13092. if ( p === IntType ) return _gl.INT;
  13093. if ( p === UnsignedIntType ) return _gl.UNSIGNED_INT;
  13094. if ( p === FloatType ) return _gl.FLOAT;
  13095. extension = extensions.get( 'OES_texture_half_float' );
  13096. if ( extension !== null ) {
  13097. if ( p === HalfFloatType ) return extension.HALF_FLOAT_OES;
  13098. }
  13099. if ( p === AlphaFormat ) return _gl.ALPHA;
  13100. if ( p === RGBFormat ) return _gl.RGB;
  13101. if ( p === RGBAFormat ) return _gl.RGBA;
  13102. if ( p === LuminanceFormat ) return _gl.LUMINANCE;
  13103. if ( p === LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  13104. if ( p === DepthFormat ) return _gl.DEPTH_COMPONENT;
  13105. if ( p === DepthStencilFormat ) return _gl.DEPTH_STENCIL;
  13106. if ( p === AddEquation ) return _gl.FUNC_ADD;
  13107. if ( p === SubtractEquation ) return _gl.FUNC_SUBTRACT;
  13108. if ( p === ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  13109. if ( p === ZeroFactor ) return _gl.ZERO;
  13110. if ( p === OneFactor ) return _gl.ONE;
  13111. if ( p === SrcColorFactor ) return _gl.SRC_COLOR;
  13112. if ( p === OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  13113. if ( p === SrcAlphaFactor ) return _gl.SRC_ALPHA;
  13114. if ( p === OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  13115. if ( p === DstAlphaFactor ) return _gl.DST_ALPHA;
  13116. if ( p === OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  13117. if ( p === DstColorFactor ) return _gl.DST_COLOR;
  13118. if ( p === OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  13119. if ( p === SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  13120. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  13121. if ( extension !== null ) {
  13122. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  13123. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  13124. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  13125. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  13126. }
  13127. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  13128. if ( extension !== null ) {
  13129. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  13130. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  13131. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  13132. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  13133. }
  13134. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  13135. if ( extension !== null ) {
  13136. if ( p === RGB_ETC1_Format ) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  13137. }
  13138. extension = extensions.get( 'EXT_blend_minmax' );
  13139. if ( extension !== null ) {
  13140. if ( p === MinEquation ) return extension.MIN_EXT;
  13141. if ( p === MaxEquation ) return extension.MAX_EXT;
  13142. }
  13143. extension = extensions.get( 'WEBGL_depth_texture' );
  13144. if ( extension !== null ){
  13145. if ( p === UnsignedInt248Type ) return extension.UNSIGNED_INT_24_8_WEBGL;
  13146. }
  13147. return 0;
  13148. }
  13149. }
  13150. /**
  13151. * @author mrdoob / http://mrdoob.com/
  13152. * @author alteredq / http://alteredqualia.com/
  13153. */
  13154. function FogExp2 ( color, density ) {
  13155. this.name = '';
  13156. this.color = new Color( color );
  13157. this.density = ( density !== undefined ) ? density : 0.00025;
  13158. }
  13159. FogExp2.prototype.isFogExp2 = true;
  13160. FogExp2.prototype.clone = function () {
  13161. return new FogExp2( this.color.getHex(), this.density );
  13162. };
  13163. FogExp2.prototype.toJSON = function ( meta ) {
  13164. return {
  13165. type: 'FogExp2',
  13166. color: this.color.getHex(),
  13167. density: this.density
  13168. };
  13169. };
  13170. /**
  13171. * @author mrdoob / http://mrdoob.com/
  13172. * @author alteredq / http://alteredqualia.com/
  13173. */
  13174. function Fog ( color, near, far ) {
  13175. this.name = '';
  13176. this.color = new Color( color );
  13177. this.near = ( near !== undefined ) ? near : 1;
  13178. this.far = ( far !== undefined ) ? far : 1000;
  13179. }
  13180. Fog.prototype.isFog = true;
  13181. Fog.prototype.clone = function () {
  13182. return new Fog( this.color.getHex(), this.near, this.far );
  13183. };
  13184. Fog.prototype.toJSON = function ( meta ) {
  13185. return {
  13186. type: 'Fog',
  13187. color: this.color.getHex(),
  13188. near: this.near,
  13189. far: this.far
  13190. };
  13191. };
  13192. /**
  13193. * @author mrdoob / http://mrdoob.com/
  13194. */
  13195. function Scene () {
  13196. Object3D.call( this );
  13197. this.type = 'Scene';
  13198. this.background = null;
  13199. this.fog = null;
  13200. this.overrideMaterial = null;
  13201. this.autoUpdate = true; // checked by the renderer
  13202. }
  13203. Scene.prototype = Object.create( Object3D.prototype );
  13204. Scene.prototype.constructor = Scene;
  13205. Scene.prototype.copy = function ( source, recursive ) {
  13206. Object3D.prototype.copy.call( this, source, recursive );
  13207. if ( source.background !== null ) this.background = source.background.clone();
  13208. if ( source.fog !== null ) this.fog = source.fog.clone();
  13209. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  13210. this.autoUpdate = source.autoUpdate;
  13211. this.matrixAutoUpdate = source.matrixAutoUpdate;
  13212. return this;
  13213. };
  13214. Scene.prototype.toJSON = function ( meta ) {
  13215. var data = Object3D.prototype.toJSON.call( this, meta );
  13216. if ( this.background !== null ) data.object.background = this.background.toJSON( meta );
  13217. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  13218. return data;
  13219. };
  13220. /**
  13221. * @author mikael emtinger / http://gomo.se/
  13222. * @author alteredq / http://alteredqualia.com/
  13223. */
  13224. function LensFlare( texture, size, distance, blending, color ) {
  13225. Object3D.call( this );
  13226. this.lensFlares = [];
  13227. this.positionScreen = new Vector3();
  13228. this.customUpdateCallback = undefined;
  13229. if ( texture !== undefined ) {
  13230. this.add( texture, size, distance, blending, color );
  13231. }
  13232. }
  13233. LensFlare.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13234. constructor: LensFlare,
  13235. isLensFlare: true,
  13236. copy: function ( source ) {
  13237. Object3D.prototype.copy.call( this, source );
  13238. this.positionScreen.copy( source.positionScreen );
  13239. this.customUpdateCallback = source.customUpdateCallback;
  13240. for ( var i = 0, l = source.lensFlares.length; i < l; i ++ ) {
  13241. this.lensFlares.push( source.lensFlares[ i ] );
  13242. }
  13243. return this;
  13244. },
  13245. add: function ( texture, size, distance, blending, color, opacity ) {
  13246. if ( size === undefined ) size = - 1;
  13247. if ( distance === undefined ) distance = 0;
  13248. if ( opacity === undefined ) opacity = 1;
  13249. if ( color === undefined ) color = new Color( 0xffffff );
  13250. if ( blending === undefined ) blending = NormalBlending;
  13251. distance = Math.min( distance, Math.max( 0, distance ) );
  13252. this.lensFlares.push( {
  13253. texture: texture, // THREE.Texture
  13254. size: size, // size in pixels (-1 = use texture.width)
  13255. distance: distance, // distance (0-1) from light source (0=at light source)
  13256. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is in front z = 1 is back
  13257. scale: 1, // scale
  13258. rotation: 0, // rotation
  13259. opacity: opacity, // opacity
  13260. color: color, // color
  13261. blending: blending // blending
  13262. } );
  13263. },
  13264. /*
  13265. * Update lens flares update positions on all flares based on the screen position
  13266. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  13267. */
  13268. updateLensFlares: function () {
  13269. var f, fl = this.lensFlares.length;
  13270. var flare;
  13271. var vecX = - this.positionScreen.x * 2;
  13272. var vecY = - this.positionScreen.y * 2;
  13273. for ( f = 0; f < fl; f ++ ) {
  13274. flare = this.lensFlares[ f ];
  13275. flare.x = this.positionScreen.x + vecX * flare.distance;
  13276. flare.y = this.positionScreen.y + vecY * flare.distance;
  13277. flare.wantedRotation = flare.x * Math.PI * 0.25;
  13278. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  13279. }
  13280. }
  13281. } );
  13282. /**
  13283. * @author alteredq / http://alteredqualia.com/
  13284. *
  13285. * parameters = {
  13286. * color: <hex>,
  13287. * opacity: <float>,
  13288. * map: new THREE.Texture( <Image> ),
  13289. *
  13290. * uvOffset: new THREE.Vector2(),
  13291. * uvScale: new THREE.Vector2()
  13292. * }
  13293. */
  13294. function SpriteMaterial( parameters ) {
  13295. Material.call( this );
  13296. this.type = 'SpriteMaterial';
  13297. this.color = new Color( 0xffffff );
  13298. this.map = null;
  13299. this.rotation = 0;
  13300. this.fog = false;
  13301. this.lights = false;
  13302. this.setValues( parameters );
  13303. }
  13304. SpriteMaterial.prototype = Object.create( Material.prototype );
  13305. SpriteMaterial.prototype.constructor = SpriteMaterial;
  13306. SpriteMaterial.prototype.copy = function ( source ) {
  13307. Material.prototype.copy.call( this, source );
  13308. this.color.copy( source.color );
  13309. this.map = source.map;
  13310. this.rotation = source.rotation;
  13311. return this;
  13312. };
  13313. /**
  13314. * @author mikael emtinger / http://gomo.se/
  13315. * @author alteredq / http://alteredqualia.com/
  13316. */
  13317. function Sprite( material ) {
  13318. Object3D.call( this );
  13319. this.type = 'Sprite';
  13320. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  13321. }
  13322. Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13323. constructor: Sprite,
  13324. isSprite: true,
  13325. raycast: ( function () {
  13326. var matrixPosition = new Vector3();
  13327. return function raycast( raycaster, intersects ) {
  13328. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  13329. var distanceSq = raycaster.ray.distanceSqToPoint( matrixPosition );
  13330. var guessSizeSq = this.scale.x * this.scale.y / 4;
  13331. if ( distanceSq > guessSizeSq ) {
  13332. return;
  13333. }
  13334. intersects.push( {
  13335. distance: Math.sqrt( distanceSq ),
  13336. point: this.position,
  13337. face: null,
  13338. object: this
  13339. } );
  13340. };
  13341. }() ),
  13342. clone: function () {
  13343. return new this.constructor( this.material ).copy( this );
  13344. }
  13345. } );
  13346. /**
  13347. * @author mikael emtinger / http://gomo.se/
  13348. * @author alteredq / http://alteredqualia.com/
  13349. * @author mrdoob / http://mrdoob.com/
  13350. */
  13351. function LOD() {
  13352. Object3D.call( this );
  13353. this.type = 'LOD';
  13354. Object.defineProperties( this, {
  13355. levels: {
  13356. enumerable: true,
  13357. value: []
  13358. }
  13359. } );
  13360. }
  13361. LOD.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13362. constructor: LOD,
  13363. copy: function ( source ) {
  13364. Object3D.prototype.copy.call( this, source, false );
  13365. var levels = source.levels;
  13366. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  13367. var level = levels[ i ];
  13368. this.addLevel( level.object.clone(), level.distance );
  13369. }
  13370. return this;
  13371. },
  13372. addLevel: function ( object, distance ) {
  13373. if ( distance === undefined ) distance = 0;
  13374. distance = Math.abs( distance );
  13375. var levels = this.levels;
  13376. for ( var l = 0; l < levels.length; l ++ ) {
  13377. if ( distance < levels[ l ].distance ) {
  13378. break;
  13379. }
  13380. }
  13381. levels.splice( l, 0, { distance: distance, object: object } );
  13382. this.add( object );
  13383. },
  13384. getObjectForDistance: function ( distance ) {
  13385. var levels = this.levels;
  13386. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  13387. if ( distance < levels[ i ].distance ) {
  13388. break;
  13389. }
  13390. }
  13391. return levels[ i - 1 ].object;
  13392. },
  13393. raycast: ( function () {
  13394. var matrixPosition = new Vector3();
  13395. return function raycast( raycaster, intersects ) {
  13396. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  13397. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  13398. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  13399. };
  13400. }() ),
  13401. update: function () {
  13402. var v1 = new Vector3();
  13403. var v2 = new Vector3();
  13404. return function update( camera ) {
  13405. var levels = this.levels;
  13406. if ( levels.length > 1 ) {
  13407. v1.setFromMatrixPosition( camera.matrixWorld );
  13408. v2.setFromMatrixPosition( this.matrixWorld );
  13409. var distance = v1.distanceTo( v2 );
  13410. levels[ 0 ].object.visible = true;
  13411. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  13412. if ( distance >= levels[ i ].distance ) {
  13413. levels[ i - 1 ].object.visible = false;
  13414. levels[ i ].object.visible = true;
  13415. } else {
  13416. break;
  13417. }
  13418. }
  13419. for ( ; i < l; i ++ ) {
  13420. levels[ i ].object.visible = false;
  13421. }
  13422. }
  13423. };
  13424. }(),
  13425. toJSON: function ( meta ) {
  13426. var data = Object3D.prototype.toJSON.call( this, meta );
  13427. data.object.levels = [];
  13428. var levels = this.levels;
  13429. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  13430. var level = levels[ i ];
  13431. data.object.levels.push( {
  13432. object: level.object.uuid,
  13433. distance: level.distance
  13434. } );
  13435. }
  13436. return data;
  13437. }
  13438. } );
  13439. /**
  13440. * @author alteredq / http://alteredqualia.com/
  13441. */
  13442. function DataTexture( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  13443. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  13444. this.image = { data: data, width: width, height: height };
  13445. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  13446. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  13447. this.flipY = false;
  13448. this.generateMipmaps = false;
  13449. }
  13450. DataTexture.prototype = Object.create( Texture.prototype );
  13451. DataTexture.prototype.constructor = DataTexture;
  13452. DataTexture.prototype.isDataTexture = true;
  13453. /**
  13454. * @author mikael emtinger / http://gomo.se/
  13455. * @author alteredq / http://alteredqualia.com/
  13456. * @author michael guerrero / http://realitymeltdown.com
  13457. * @author ikerr / http://verold.com
  13458. */
  13459. function Skeleton( bones, boneInverses, useVertexTexture ) {
  13460. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  13461. this.identityMatrix = new Matrix4();
  13462. // copy the bone array
  13463. bones = bones || [];
  13464. this.bones = bones.slice( 0 );
  13465. // create a bone texture or an array of floats
  13466. if ( this.useVertexTexture ) {
  13467. // layout (1 matrix = 4 pixels)
  13468. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  13469. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  13470. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  13471. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  13472. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  13473. var size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  13474. size = exports.Math.nextPowerOfTwo( Math.ceil( size ) );
  13475. size = Math.max( size, 4 );
  13476. this.boneTextureWidth = size;
  13477. this.boneTextureHeight = size;
  13478. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  13479. this.boneTexture = new DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, RGBAFormat, FloatType );
  13480. } else {
  13481. this.boneMatrices = new Float32Array( 16 * this.bones.length );
  13482. }
  13483. // use the supplied bone inverses or calculate the inverses
  13484. if ( boneInverses === undefined ) {
  13485. this.calculateInverses();
  13486. } else {
  13487. if ( this.bones.length === boneInverses.length ) {
  13488. this.boneInverses = boneInverses.slice( 0 );
  13489. } else {
  13490. console.warn( 'THREE.Skeleton bonInverses is the wrong length.' );
  13491. this.boneInverses = [];
  13492. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13493. this.boneInverses.push( new Matrix4() );
  13494. }
  13495. }
  13496. }
  13497. }
  13498. Object.assign( Skeleton.prototype, {
  13499. calculateInverses: function () {
  13500. this.boneInverses = [];
  13501. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13502. var inverse = new Matrix4();
  13503. if ( this.bones[ b ] ) {
  13504. inverse.getInverse( this.bones[ b ].matrixWorld );
  13505. }
  13506. this.boneInverses.push( inverse );
  13507. }
  13508. },
  13509. pose: function () {
  13510. var bone;
  13511. // recover the bind-time world matrices
  13512. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13513. bone = this.bones[ b ];
  13514. if ( bone ) {
  13515. bone.matrixWorld.getInverse( this.boneInverses[ b ] );
  13516. }
  13517. }
  13518. // compute the local matrices, positions, rotations and scales
  13519. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13520. bone = this.bones[ b ];
  13521. if ( bone ) {
  13522. if ( (bone.parent && bone.parent.isBone) ) {
  13523. bone.matrix.getInverse( bone.parent.matrixWorld );
  13524. bone.matrix.multiply( bone.matrixWorld );
  13525. } else {
  13526. bone.matrix.copy( bone.matrixWorld );
  13527. }
  13528. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  13529. }
  13530. }
  13531. },
  13532. update: ( function () {
  13533. var offsetMatrix = new Matrix4();
  13534. return function update() {
  13535. // flatten bone matrices to array
  13536. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13537. // compute the offset between the current and the original transform
  13538. var matrix = this.bones[ b ] ? this.bones[ b ].matrixWorld : this.identityMatrix;
  13539. offsetMatrix.multiplyMatrices( matrix, this.boneInverses[ b ] );
  13540. offsetMatrix.toArray( this.boneMatrices, b * 16 );
  13541. }
  13542. if ( this.useVertexTexture ) {
  13543. this.boneTexture.needsUpdate = true;
  13544. }
  13545. };
  13546. } )(),
  13547. clone: function () {
  13548. return new Skeleton( this.bones, this.boneInverses, this.useVertexTexture );
  13549. }
  13550. } );
  13551. /**
  13552. * @author mikael emtinger / http://gomo.se/
  13553. * @author alteredq / http://alteredqualia.com/
  13554. * @author ikerr / http://verold.com
  13555. */
  13556. function Bone( skin ) {
  13557. Object3D.call( this );
  13558. this.type = 'Bone';
  13559. this.skin = skin;
  13560. }
  13561. Bone.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13562. constructor: Bone,
  13563. isBone: true,
  13564. copy: function ( source ) {
  13565. Object3D.prototype.copy.call( this, source );
  13566. this.skin = source.skin;
  13567. return this;
  13568. }
  13569. } );
  13570. /**
  13571. * @author mikael emtinger / http://gomo.se/
  13572. * @author alteredq / http://alteredqualia.com/
  13573. * @author ikerr / http://verold.com
  13574. */
  13575. function SkinnedMesh( geometry, material, useVertexTexture ) {
  13576. Mesh.call( this, geometry, material );
  13577. this.type = 'SkinnedMesh';
  13578. this.bindMode = "attached";
  13579. this.bindMatrix = new Matrix4();
  13580. this.bindMatrixInverse = new Matrix4();
  13581. // init bones
  13582. // TODO: remove bone creation as there is no reason (other than
  13583. // convenience) for THREE.SkinnedMesh to do this.
  13584. var bones = [];
  13585. if ( this.geometry && this.geometry.bones !== undefined ) {
  13586. var bone, gbone;
  13587. for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {
  13588. gbone = this.geometry.bones[ b ];
  13589. bone = new Bone( this );
  13590. bones.push( bone );
  13591. bone.name = gbone.name;
  13592. bone.position.fromArray( gbone.pos );
  13593. bone.quaternion.fromArray( gbone.rotq );
  13594. if ( gbone.scl !== undefined ) bone.scale.fromArray( gbone.scl );
  13595. }
  13596. for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {
  13597. gbone = this.geometry.bones[ b ];
  13598. if ( gbone.parent !== - 1 && gbone.parent !== null &&
  13599. bones[ gbone.parent ] !== undefined ) {
  13600. bones[ gbone.parent ].add( bones[ b ] );
  13601. } else {
  13602. this.add( bones[ b ] );
  13603. }
  13604. }
  13605. }
  13606. this.normalizeSkinWeights();
  13607. this.updateMatrixWorld( true );
  13608. this.bind( new Skeleton( bones, undefined, useVertexTexture ), this.matrixWorld );
  13609. }
  13610. SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {
  13611. constructor: SkinnedMesh,
  13612. isSkinnedMesh: true,
  13613. bind: function( skeleton, bindMatrix ) {
  13614. this.skeleton = skeleton;
  13615. if ( bindMatrix === undefined ) {
  13616. this.updateMatrixWorld( true );
  13617. this.skeleton.calculateInverses();
  13618. bindMatrix = this.matrixWorld;
  13619. }
  13620. this.bindMatrix.copy( bindMatrix );
  13621. this.bindMatrixInverse.getInverse( bindMatrix );
  13622. },
  13623. pose: function () {
  13624. this.skeleton.pose();
  13625. },
  13626. normalizeSkinWeights: function () {
  13627. if ( (this.geometry && this.geometry.isGeometry) ) {
  13628. for ( var i = 0; i < this.geometry.skinWeights.length; i ++ ) {
  13629. var sw = this.geometry.skinWeights[ i ];
  13630. var scale = 1.0 / sw.lengthManhattan();
  13631. if ( scale !== Infinity ) {
  13632. sw.multiplyScalar( scale );
  13633. } else {
  13634. sw.set( 1, 0, 0, 0 ); // do something reasonable
  13635. }
  13636. }
  13637. } else if ( (this.geometry && this.geometry.isBufferGeometry) ) {
  13638. var vec = new Vector4();
  13639. var skinWeight = this.geometry.attributes.skinWeight;
  13640. for ( var i = 0; i < skinWeight.count; i ++ ) {
  13641. vec.x = skinWeight.getX( i );
  13642. vec.y = skinWeight.getY( i );
  13643. vec.z = skinWeight.getZ( i );
  13644. vec.w = skinWeight.getW( i );
  13645. var scale = 1.0 / vec.lengthManhattan();
  13646. if ( scale !== Infinity ) {
  13647. vec.multiplyScalar( scale );
  13648. } else {
  13649. vec.set( 1, 0, 0, 0 ); // do something reasonable
  13650. }
  13651. skinWeight.setXYZW( i, vec.x, vec.y, vec.z, vec.w );
  13652. }
  13653. }
  13654. },
  13655. updateMatrixWorld: function( force ) {
  13656. Mesh.prototype.updateMatrixWorld.call( this, true );
  13657. if ( this.bindMode === "attached" ) {
  13658. this.bindMatrixInverse.getInverse( this.matrixWorld );
  13659. } else if ( this.bindMode === "detached" ) {
  13660. this.bindMatrixInverse.getInverse( this.bindMatrix );
  13661. } else {
  13662. console.warn( 'THREE.SkinnedMesh unrecognized bindMode: ' + this.bindMode );
  13663. }
  13664. },
  13665. clone: function() {
  13666. return new this.constructor( this.geometry, this.material, this.skeleton.useVertexTexture ).copy( this );
  13667. }
  13668. } );
  13669. /**
  13670. * @author mrdoob / http://mrdoob.com/
  13671. * @author alteredq / http://alteredqualia.com/
  13672. *
  13673. * parameters = {
  13674. * color: <hex>,
  13675. * opacity: <float>,
  13676. *
  13677. * linewidth: <float>,
  13678. * linecap: "round",
  13679. * linejoin: "round"
  13680. * }
  13681. */
  13682. function LineBasicMaterial( parameters ) {
  13683. Material.call( this );
  13684. this.type = 'LineBasicMaterial';
  13685. this.color = new Color( 0xffffff );
  13686. this.linewidth = 1;
  13687. this.linecap = 'round';
  13688. this.linejoin = 'round';
  13689. this.lights = false;
  13690. this.setValues( parameters );
  13691. }
  13692. LineBasicMaterial.prototype = Object.create( Material.prototype );
  13693. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  13694. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  13695. LineBasicMaterial.prototype.copy = function ( source ) {
  13696. Material.prototype.copy.call( this, source );
  13697. this.color.copy( source.color );
  13698. this.linewidth = source.linewidth;
  13699. this.linecap = source.linecap;
  13700. this.linejoin = source.linejoin;
  13701. return this;
  13702. };
  13703. /**
  13704. * @author mrdoob / http://mrdoob.com/
  13705. */
  13706. function Line( geometry, material, mode ) {
  13707. if ( mode === 1 ) {
  13708. console.warn( 'THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead.' );
  13709. return new LineSegments( geometry, material );
  13710. }
  13711. Object3D.call( this );
  13712. this.type = 'Line';
  13713. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  13714. this.material = material !== undefined ? material : new LineBasicMaterial( { color: Math.random() * 0xffffff } );
  13715. }
  13716. Line.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13717. constructor: Line,
  13718. isLine: true,
  13719. raycast: ( function () {
  13720. var inverseMatrix = new Matrix4();
  13721. var ray = new Ray();
  13722. var sphere = new Sphere();
  13723. return function raycast( raycaster, intersects ) {
  13724. var precision = raycaster.linePrecision;
  13725. var precisionSq = precision * precision;
  13726. var geometry = this.geometry;
  13727. var matrixWorld = this.matrixWorld;
  13728. // Checking boundingSphere distance to ray
  13729. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  13730. sphere.copy( geometry.boundingSphere );
  13731. sphere.applyMatrix4( matrixWorld );
  13732. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  13733. //
  13734. inverseMatrix.getInverse( matrixWorld );
  13735. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  13736. var vStart = new Vector3();
  13737. var vEnd = new Vector3();
  13738. var interSegment = new Vector3();
  13739. var interRay = new Vector3();
  13740. var step = (this && this.isLineSegments) ? 2 : 1;
  13741. if ( (geometry && geometry.isBufferGeometry) ) {
  13742. var index = geometry.index;
  13743. var attributes = geometry.attributes;
  13744. var positions = attributes.position.array;
  13745. if ( index !== null ) {
  13746. var indices = index.array;
  13747. for ( var i = 0, l = indices.length - 1; i < l; i += step ) {
  13748. var a = indices[ i ];
  13749. var b = indices[ i + 1 ];
  13750. vStart.fromArray( positions, a * 3 );
  13751. vEnd.fromArray( positions, b * 3 );
  13752. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  13753. if ( distSq > precisionSq ) continue;
  13754. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  13755. var distance = raycaster.ray.origin.distanceTo( interRay );
  13756. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  13757. intersects.push( {
  13758. distance: distance,
  13759. // What do we want? intersection point on the ray or on the segment??
  13760. // point: raycaster.ray.at( distance ),
  13761. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  13762. index: i,
  13763. face: null,
  13764. faceIndex: null,
  13765. object: this
  13766. } );
  13767. }
  13768. } else {
  13769. for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) {
  13770. vStart.fromArray( positions, 3 * i );
  13771. vEnd.fromArray( positions, 3 * i + 3 );
  13772. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  13773. if ( distSq > precisionSq ) continue;
  13774. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  13775. var distance = raycaster.ray.origin.distanceTo( interRay );
  13776. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  13777. intersects.push( {
  13778. distance: distance,
  13779. // What do we want? intersection point on the ray or on the segment??
  13780. // point: raycaster.ray.at( distance ),
  13781. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  13782. index: i,
  13783. face: null,
  13784. faceIndex: null,
  13785. object: this
  13786. } );
  13787. }
  13788. }
  13789. } else if ( (geometry && geometry.isGeometry) ) {
  13790. var vertices = geometry.vertices;
  13791. var nbVertices = vertices.length;
  13792. for ( var i = 0; i < nbVertices - 1; i += step ) {
  13793. var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  13794. if ( distSq > precisionSq ) continue;
  13795. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  13796. var distance = raycaster.ray.origin.distanceTo( interRay );
  13797. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  13798. intersects.push( {
  13799. distance: distance,
  13800. // What do we want? intersection point on the ray or on the segment??
  13801. // point: raycaster.ray.at( distance ),
  13802. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  13803. index: i,
  13804. face: null,
  13805. faceIndex: null,
  13806. object: this
  13807. } );
  13808. }
  13809. }
  13810. };
  13811. }() ),
  13812. clone: function () {
  13813. return new this.constructor( this.geometry, this.material ).copy( this );
  13814. }
  13815. } );
  13816. /**
  13817. * @author mrdoob / http://mrdoob.com/
  13818. */
  13819. function LineSegments( geometry, material ) {
  13820. Line.call( this, geometry, material );
  13821. this.type = 'LineSegments';
  13822. }
  13823. LineSegments.prototype = Object.assign( Object.create( Line.prototype ), {
  13824. constructor: LineSegments,
  13825. isLineSegments: true
  13826. } );
  13827. /**
  13828. * @author mrdoob / http://mrdoob.com/
  13829. * @author alteredq / http://alteredqualia.com/
  13830. *
  13831. * parameters = {
  13832. * color: <hex>,
  13833. * opacity: <float>,
  13834. * map: new THREE.Texture( <Image> ),
  13835. *
  13836. * size: <float>,
  13837. * sizeAttenuation: <bool>
  13838. * }
  13839. */
  13840. function PointsMaterial( parameters ) {
  13841. Material.call( this );
  13842. this.type = 'PointsMaterial';
  13843. this.color = new Color( 0xffffff );
  13844. this.map = null;
  13845. this.size = 1;
  13846. this.sizeAttenuation = true;
  13847. this.lights = false;
  13848. this.setValues( parameters );
  13849. }
  13850. PointsMaterial.prototype = Object.create( Material.prototype );
  13851. PointsMaterial.prototype.constructor = PointsMaterial;
  13852. PointsMaterial.prototype.isPointsMaterial = true;
  13853. PointsMaterial.prototype.copy = function ( source ) {
  13854. Material.prototype.copy.call( this, source );
  13855. this.color.copy( source.color );
  13856. this.map = source.map;
  13857. this.size = source.size;
  13858. this.sizeAttenuation = source.sizeAttenuation;
  13859. return this;
  13860. };
  13861. /**
  13862. * @author alteredq / http://alteredqualia.com/
  13863. */
  13864. function Points( geometry, material ) {
  13865. Object3D.call( this );
  13866. this.type = 'Points';
  13867. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  13868. this.material = material !== undefined ? material : new PointsMaterial( { color: Math.random() * 0xffffff } );
  13869. }
  13870. Points.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13871. constructor: Points,
  13872. isPoints: true,
  13873. raycast: ( function () {
  13874. var inverseMatrix = new Matrix4();
  13875. var ray = new Ray();
  13876. var sphere = new Sphere();
  13877. return function raycast( raycaster, intersects ) {
  13878. var object = this;
  13879. var geometry = this.geometry;
  13880. var matrixWorld = this.matrixWorld;
  13881. var threshold = raycaster.params.Points.threshold;
  13882. // Checking boundingSphere distance to ray
  13883. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  13884. sphere.copy( geometry.boundingSphere );
  13885. sphere.applyMatrix4( matrixWorld );
  13886. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  13887. //
  13888. inverseMatrix.getInverse( matrixWorld );
  13889. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  13890. var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  13891. var localThresholdSq = localThreshold * localThreshold;
  13892. var position = new Vector3();
  13893. function testPoint( point, index ) {
  13894. var rayPointDistanceSq = ray.distanceSqToPoint( point );
  13895. if ( rayPointDistanceSq < localThresholdSq ) {
  13896. var intersectPoint = ray.closestPointToPoint( point );
  13897. intersectPoint.applyMatrix4( matrixWorld );
  13898. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  13899. if ( distance < raycaster.near || distance > raycaster.far ) return;
  13900. intersects.push( {
  13901. distance: distance,
  13902. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  13903. point: intersectPoint.clone(),
  13904. index: index,
  13905. face: null,
  13906. object: object
  13907. } );
  13908. }
  13909. }
  13910. if ( (geometry && geometry.isBufferGeometry) ) {
  13911. var index = geometry.index;
  13912. var attributes = geometry.attributes;
  13913. var positions = attributes.position.array;
  13914. if ( index !== null ) {
  13915. var indices = index.array;
  13916. for ( var i = 0, il = indices.length; i < il; i ++ ) {
  13917. var a = indices[ i ];
  13918. position.fromArray( positions, a * 3 );
  13919. testPoint( position, a );
  13920. }
  13921. } else {
  13922. for ( var i = 0, l = positions.length / 3; i < l; i ++ ) {
  13923. position.fromArray( positions, i * 3 );
  13924. testPoint( position, i );
  13925. }
  13926. }
  13927. } else {
  13928. var vertices = geometry.vertices;
  13929. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  13930. testPoint( vertices[ i ], i );
  13931. }
  13932. }
  13933. };
  13934. }() ),
  13935. clone: function () {
  13936. return new this.constructor( this.geometry, this.material ).copy( this );
  13937. }
  13938. } );
  13939. /**
  13940. * @author mrdoob / http://mrdoob.com/
  13941. */
  13942. function Group() {
  13943. Object3D.call( this );
  13944. this.type = 'Group';
  13945. }
  13946. Group.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13947. constructor: Group
  13948. } );
  13949. /**
  13950. * @author mrdoob / http://mrdoob.com/
  13951. */
  13952. function VideoTexture( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  13953. Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  13954. this.generateMipmaps = false;
  13955. var scope = this;
  13956. function update() {
  13957. requestAnimationFrame( update );
  13958. if ( video.readyState >= video.HAVE_CURRENT_DATA ) {
  13959. scope.needsUpdate = true;
  13960. }
  13961. }
  13962. update();
  13963. }
  13964. VideoTexture.prototype = Object.create( Texture.prototype );
  13965. VideoTexture.prototype.constructor = VideoTexture;
  13966. /**
  13967. * @author alteredq / http://alteredqualia.com/
  13968. */
  13969. function CompressedTexture( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  13970. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  13971. this.image = { width: width, height: height };
  13972. this.mipmaps = mipmaps;
  13973. // no flipping for cube textures
  13974. // (also flipping doesn't work for compressed textures )
  13975. this.flipY = false;
  13976. // can't generate mipmaps for compressed textures
  13977. // mips must be embedded in DDS files
  13978. this.generateMipmaps = false;
  13979. }
  13980. CompressedTexture.prototype = Object.create( Texture.prototype );
  13981. CompressedTexture.prototype.constructor = CompressedTexture;
  13982. CompressedTexture.prototype.isCompressedTexture = true;
  13983. /**
  13984. * @author mrdoob / http://mrdoob.com/
  13985. */
  13986. function CanvasTexture( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  13987. Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  13988. this.needsUpdate = true;
  13989. }
  13990. CanvasTexture.prototype = Object.create( Texture.prototype );
  13991. CanvasTexture.prototype.constructor = CanvasTexture;
  13992. /**
  13993. * @author Matt DesLauriers / @mattdesl
  13994. * @author atix / arthursilber.de
  13995. */
  13996. function DepthTexture( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  13997. format = format !== undefined ? format : DepthFormat;
  13998. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  13999. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' )
  14000. }
  14001. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  14002. this.image = { width: width, height: height };
  14003. this.type = type !== undefined ? type : UnsignedShortType;
  14004. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  14005. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  14006. this.flipY = false;
  14007. this.generateMipmaps = false;
  14008. }
  14009. DepthTexture.prototype = Object.create( Texture.prototype );
  14010. DepthTexture.prototype.constructor = DepthTexture;
  14011. DepthTexture.prototype.isDepthTexture = true;
  14012. /**
  14013. * @author mrdoob / http://mrdoob.com/
  14014. */
  14015. function ShadowMaterial() {
  14016. ShaderMaterial.call( this, {
  14017. uniforms: exports.UniformsUtils.merge( [
  14018. UniformsLib[ "lights" ],
  14019. {
  14020. opacity: { value: 1.0 }
  14021. }
  14022. ] ),
  14023. vertexShader: ShaderChunk[ 'shadow_vert' ],
  14024. fragmentShader: ShaderChunk[ 'shadow_frag' ]
  14025. } );
  14026. this.lights = true;
  14027. this.transparent = true;
  14028. Object.defineProperties( this, {
  14029. opacity: {
  14030. enumerable: true,
  14031. get: function () {
  14032. return this.uniforms.opacity.value;
  14033. },
  14034. set: function ( value ) {
  14035. this.uniforms.opacity.value = value;
  14036. }
  14037. }
  14038. } );
  14039. }
  14040. ShadowMaterial.prototype = Object.create( ShaderMaterial.prototype );
  14041. ShadowMaterial.prototype.constructor = ShadowMaterial;
  14042. ShadowMaterial.prototype.isShadowMaterial = true;
  14043. /**
  14044. * @author mrdoob / http://mrdoob.com/
  14045. */
  14046. function RawShaderMaterial( parameters ) {
  14047. ShaderMaterial.call( this, parameters );
  14048. this.type = 'RawShaderMaterial';
  14049. }
  14050. RawShaderMaterial.prototype = Object.create( ShaderMaterial.prototype );
  14051. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  14052. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  14053. /**
  14054. * @author mrdoob / http://mrdoob.com/
  14055. */
  14056. function MultiMaterial( materials ) {
  14057. this.uuid = exports.Math.generateUUID();
  14058. this.type = 'MultiMaterial';
  14059. this.materials = materials instanceof Array ? materials : [];
  14060. this.visible = true;
  14061. }
  14062. MultiMaterial.prototype = {
  14063. constructor: MultiMaterial,
  14064. isMultiMaterial: true,
  14065. toJSON: function ( meta ) {
  14066. var output = {
  14067. metadata: {
  14068. version: 4.2,
  14069. type: 'material',
  14070. generator: 'MaterialExporter'
  14071. },
  14072. uuid: this.uuid,
  14073. type: this.type,
  14074. materials: []
  14075. };
  14076. var materials = this.materials;
  14077. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  14078. var material = materials[ i ].toJSON( meta );
  14079. delete material.metadata;
  14080. output.materials.push( material );
  14081. }
  14082. output.visible = this.visible;
  14083. return output;
  14084. },
  14085. clone: function () {
  14086. var material = new this.constructor();
  14087. for ( var i = 0; i < this.materials.length; i ++ ) {
  14088. material.materials.push( this.materials[ i ].clone() );
  14089. }
  14090. material.visible = this.visible;
  14091. return material;
  14092. }
  14093. };
  14094. /**
  14095. * @author WestLangley / http://github.com/WestLangley
  14096. *
  14097. * parameters = {
  14098. * color: <hex>,
  14099. * roughness: <float>,
  14100. * metalness: <float>,
  14101. * opacity: <float>,
  14102. *
  14103. * map: new THREE.Texture( <Image> ),
  14104. *
  14105. * lightMap: new THREE.Texture( <Image> ),
  14106. * lightMapIntensity: <float>
  14107. *
  14108. * aoMap: new THREE.Texture( <Image> ),
  14109. * aoMapIntensity: <float>
  14110. *
  14111. * emissive: <hex>,
  14112. * emissiveIntensity: <float>
  14113. * emissiveMap: new THREE.Texture( <Image> ),
  14114. *
  14115. * bumpMap: new THREE.Texture( <Image> ),
  14116. * bumpScale: <float>,
  14117. *
  14118. * normalMap: new THREE.Texture( <Image> ),
  14119. * normalScale: <Vector2>,
  14120. *
  14121. * displacementMap: new THREE.Texture( <Image> ),
  14122. * displacementScale: <float>,
  14123. * displacementBias: <float>,
  14124. *
  14125. * roughnessMap: new THREE.Texture( <Image> ),
  14126. *
  14127. * metalnessMap: new THREE.Texture( <Image> ),
  14128. *
  14129. * alphaMap: new THREE.Texture( <Image> ),
  14130. *
  14131. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  14132. * envMapIntensity: <float>
  14133. *
  14134. * refractionRatio: <float>,
  14135. *
  14136. * wireframe: <boolean>,
  14137. * wireframeLinewidth: <float>,
  14138. *
  14139. * skinning: <bool>,
  14140. * morphTargets: <bool>,
  14141. * morphNormals: <bool>
  14142. * }
  14143. */
  14144. function MeshStandardMaterial( parameters ) {
  14145. Material.call( this );
  14146. this.defines = { 'STANDARD': '' };
  14147. this.type = 'MeshStandardMaterial';
  14148. this.color = new Color( 0xffffff ); // diffuse
  14149. this.roughness = 0.5;
  14150. this.metalness = 0.5;
  14151. this.map = null;
  14152. this.lightMap = null;
  14153. this.lightMapIntensity = 1.0;
  14154. this.aoMap = null;
  14155. this.aoMapIntensity = 1.0;
  14156. this.emissive = new Color( 0x000000 );
  14157. this.emissiveIntensity = 1.0;
  14158. this.emissiveMap = null;
  14159. this.bumpMap = null;
  14160. this.bumpScale = 1;
  14161. this.normalMap = null;
  14162. this.normalScale = new Vector2( 1, 1 );
  14163. this.displacementMap = null;
  14164. this.displacementScale = 1;
  14165. this.displacementBias = 0;
  14166. this.roughnessMap = null;
  14167. this.metalnessMap = null;
  14168. this.alphaMap = null;
  14169. this.envMap = null;
  14170. this.envMapIntensity = 1.0;
  14171. this.refractionRatio = 0.98;
  14172. this.wireframe = false;
  14173. this.wireframeLinewidth = 1;
  14174. this.wireframeLinecap = 'round';
  14175. this.wireframeLinejoin = 'round';
  14176. this.skinning = false;
  14177. this.morphTargets = false;
  14178. this.morphNormals = false;
  14179. this.setValues( parameters );
  14180. }
  14181. MeshStandardMaterial.prototype = Object.create( Material.prototype );
  14182. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  14183. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  14184. MeshStandardMaterial.prototype.copy = function ( source ) {
  14185. Material.prototype.copy.call( this, source );
  14186. this.defines = { 'STANDARD': '' };
  14187. this.color.copy( source.color );
  14188. this.roughness = source.roughness;
  14189. this.metalness = source.metalness;
  14190. this.map = source.map;
  14191. this.lightMap = source.lightMap;
  14192. this.lightMapIntensity = source.lightMapIntensity;
  14193. this.aoMap = source.aoMap;
  14194. this.aoMapIntensity = source.aoMapIntensity;
  14195. this.emissive.copy( source.emissive );
  14196. this.emissiveMap = source.emissiveMap;
  14197. this.emissiveIntensity = source.emissiveIntensity;
  14198. this.bumpMap = source.bumpMap;
  14199. this.bumpScale = source.bumpScale;
  14200. this.normalMap = source.normalMap;
  14201. this.normalScale.copy( source.normalScale );
  14202. this.displacementMap = source.displacementMap;
  14203. this.displacementScale = source.displacementScale;
  14204. this.displacementBias = source.displacementBias;
  14205. this.roughnessMap = source.roughnessMap;
  14206. this.metalnessMap = source.metalnessMap;
  14207. this.alphaMap = source.alphaMap;
  14208. this.envMap = source.envMap;
  14209. this.envMapIntensity = source.envMapIntensity;
  14210. this.refractionRatio = source.refractionRatio;
  14211. this.wireframe = source.wireframe;
  14212. this.wireframeLinewidth = source.wireframeLinewidth;
  14213. this.wireframeLinecap = source.wireframeLinecap;
  14214. this.wireframeLinejoin = source.wireframeLinejoin;
  14215. this.skinning = source.skinning;
  14216. this.morphTargets = source.morphTargets;
  14217. this.morphNormals = source.morphNormals;
  14218. return this;
  14219. };
  14220. /**
  14221. * @author WestLangley / http://github.com/WestLangley
  14222. *
  14223. * parameters = {
  14224. * reflectivity: <float>
  14225. * }
  14226. */
  14227. function MeshPhysicalMaterial( parameters ) {
  14228. MeshStandardMaterial.call( this );
  14229. this.defines = { 'PHYSICAL': '' };
  14230. this.type = 'MeshPhysicalMaterial';
  14231. this.reflectivity = 0.5; // maps to F0 = 0.04
  14232. this.clearCoat = 0.0;
  14233. this.clearCoatRoughness = 0.0;
  14234. this.setValues( parameters );
  14235. }
  14236. MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype );
  14237. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  14238. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  14239. MeshPhysicalMaterial.prototype.copy = function ( source ) {
  14240. MeshStandardMaterial.prototype.copy.call( this, source );
  14241. this.defines = { 'PHYSICAL': '' };
  14242. this.reflectivity = source.reflectivity;
  14243. this.clearCoat = source.clearCoat;
  14244. this.clearCoatRoughness = source.clearCoatRoughness;
  14245. return this;
  14246. };
  14247. /**
  14248. * @author mrdoob / http://mrdoob.com/
  14249. * @author alteredq / http://alteredqualia.com/
  14250. *
  14251. * parameters = {
  14252. * color: <hex>,
  14253. * specular: <hex>,
  14254. * shininess: <float>,
  14255. * opacity: <float>,
  14256. *
  14257. * map: new THREE.Texture( <Image> ),
  14258. *
  14259. * lightMap: new THREE.Texture( <Image> ),
  14260. * lightMapIntensity: <float>
  14261. *
  14262. * aoMap: new THREE.Texture( <Image> ),
  14263. * aoMapIntensity: <float>
  14264. *
  14265. * emissive: <hex>,
  14266. * emissiveIntensity: <float>
  14267. * emissiveMap: new THREE.Texture( <Image> ),
  14268. *
  14269. * bumpMap: new THREE.Texture( <Image> ),
  14270. * bumpScale: <float>,
  14271. *
  14272. * normalMap: new THREE.Texture( <Image> ),
  14273. * normalScale: <Vector2>,
  14274. *
  14275. * displacementMap: new THREE.Texture( <Image> ),
  14276. * displacementScale: <float>,
  14277. * displacementBias: <float>,
  14278. *
  14279. * specularMap: new THREE.Texture( <Image> ),
  14280. *
  14281. * alphaMap: new THREE.Texture( <Image> ),
  14282. *
  14283. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  14284. * combine: THREE.Multiply,
  14285. * reflectivity: <float>,
  14286. * refractionRatio: <float>,
  14287. *
  14288. * wireframe: <boolean>,
  14289. * wireframeLinewidth: <float>,
  14290. *
  14291. * skinning: <bool>,
  14292. * morphTargets: <bool>,
  14293. * morphNormals: <bool>
  14294. * }
  14295. */
  14296. function MeshPhongMaterial( parameters ) {
  14297. Material.call( this );
  14298. this.type = 'MeshPhongMaterial';
  14299. this.color = new Color( 0xffffff ); // diffuse
  14300. this.specular = new Color( 0x111111 );
  14301. this.shininess = 30;
  14302. this.map = null;
  14303. this.lightMap = null;
  14304. this.lightMapIntensity = 1.0;
  14305. this.aoMap = null;
  14306. this.aoMapIntensity = 1.0;
  14307. this.emissive = new Color( 0x000000 );
  14308. this.emissiveIntensity = 1.0;
  14309. this.emissiveMap = null;
  14310. this.bumpMap = null;
  14311. this.bumpScale = 1;
  14312. this.normalMap = null;
  14313. this.normalScale = new Vector2( 1, 1 );
  14314. this.displacementMap = null;
  14315. this.displacementScale = 1;
  14316. this.displacementBias = 0;
  14317. this.specularMap = null;
  14318. this.alphaMap = null;
  14319. this.envMap = null;
  14320. this.combine = MultiplyOperation;
  14321. this.reflectivity = 1;
  14322. this.refractionRatio = 0.98;
  14323. this.wireframe = false;
  14324. this.wireframeLinewidth = 1;
  14325. this.wireframeLinecap = 'round';
  14326. this.wireframeLinejoin = 'round';
  14327. this.skinning = false;
  14328. this.morphTargets = false;
  14329. this.morphNormals = false;
  14330. this.setValues( parameters );
  14331. }
  14332. MeshPhongMaterial.prototype = Object.create( Material.prototype );
  14333. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  14334. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  14335. MeshPhongMaterial.prototype.copy = function ( source ) {
  14336. Material.prototype.copy.call( this, source );
  14337. this.color.copy( source.color );
  14338. this.specular.copy( source.specular );
  14339. this.shininess = source.shininess;
  14340. this.map = source.map;
  14341. this.lightMap = source.lightMap;
  14342. this.lightMapIntensity = source.lightMapIntensity;
  14343. this.aoMap = source.aoMap;
  14344. this.aoMapIntensity = source.aoMapIntensity;
  14345. this.emissive.copy( source.emissive );
  14346. this.emissiveMap = source.emissiveMap;
  14347. this.emissiveIntensity = source.emissiveIntensity;
  14348. this.bumpMap = source.bumpMap;
  14349. this.bumpScale = source.bumpScale;
  14350. this.normalMap = source.normalMap;
  14351. this.normalScale.copy( source.normalScale );
  14352. this.displacementMap = source.displacementMap;
  14353. this.displacementScale = source.displacementScale;
  14354. this.displacementBias = source.displacementBias;
  14355. this.specularMap = source.specularMap;
  14356. this.alphaMap = source.alphaMap;
  14357. this.envMap = source.envMap;
  14358. this.combine = source.combine;
  14359. this.reflectivity = source.reflectivity;
  14360. this.refractionRatio = source.refractionRatio;
  14361. this.wireframe = source.wireframe;
  14362. this.wireframeLinewidth = source.wireframeLinewidth;
  14363. this.wireframeLinecap = source.wireframeLinecap;
  14364. this.wireframeLinejoin = source.wireframeLinejoin;
  14365. this.skinning = source.skinning;
  14366. this.morphTargets = source.morphTargets;
  14367. this.morphNormals = source.morphNormals;
  14368. return this;
  14369. };
  14370. /**
  14371. * @author mrdoob / http://mrdoob.com/
  14372. *
  14373. * parameters = {
  14374. * opacity: <float>,
  14375. *
  14376. * wireframe: <boolean>,
  14377. * wireframeLinewidth: <float>
  14378. * }
  14379. */
  14380. function MeshNormalMaterial( parameters ) {
  14381. Material.call( this, parameters );
  14382. this.type = 'MeshNormalMaterial';
  14383. this.wireframe = false;
  14384. this.wireframeLinewidth = 1;
  14385. this.fog = false;
  14386. this.lights = false;
  14387. this.morphTargets = false;
  14388. this.setValues( parameters );
  14389. }
  14390. MeshNormalMaterial.prototype = Object.create( Material.prototype );
  14391. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  14392. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  14393. MeshNormalMaterial.prototype.copy = function ( source ) {
  14394. Material.prototype.copy.call( this, source );
  14395. this.wireframe = source.wireframe;
  14396. this.wireframeLinewidth = source.wireframeLinewidth;
  14397. return this;
  14398. };
  14399. /**
  14400. * @author mrdoob / http://mrdoob.com/
  14401. * @author alteredq / http://alteredqualia.com/
  14402. *
  14403. * parameters = {
  14404. * color: <hex>,
  14405. * opacity: <float>,
  14406. *
  14407. * map: new THREE.Texture( <Image> ),
  14408. *
  14409. * lightMap: new THREE.Texture( <Image> ),
  14410. * lightMapIntensity: <float>
  14411. *
  14412. * aoMap: new THREE.Texture( <Image> ),
  14413. * aoMapIntensity: <float>
  14414. *
  14415. * emissive: <hex>,
  14416. * emissiveIntensity: <float>
  14417. * emissiveMap: new THREE.Texture( <Image> ),
  14418. *
  14419. * specularMap: new THREE.Texture( <Image> ),
  14420. *
  14421. * alphaMap: new THREE.Texture( <Image> ),
  14422. *
  14423. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  14424. * combine: THREE.Multiply,
  14425. * reflectivity: <float>,
  14426. * refractionRatio: <float>,
  14427. *
  14428. * wireframe: <boolean>,
  14429. * wireframeLinewidth: <float>,
  14430. *
  14431. * skinning: <bool>,
  14432. * morphTargets: <bool>,
  14433. * morphNormals: <bool>
  14434. * }
  14435. */
  14436. function MeshLambertMaterial( parameters ) {
  14437. Material.call( this );
  14438. this.type = 'MeshLambertMaterial';
  14439. this.color = new Color( 0xffffff ); // diffuse
  14440. this.map = null;
  14441. this.lightMap = null;
  14442. this.lightMapIntensity = 1.0;
  14443. this.aoMap = null;
  14444. this.aoMapIntensity = 1.0;
  14445. this.emissive = new Color( 0x000000 );
  14446. this.emissiveIntensity = 1.0;
  14447. this.emissiveMap = null;
  14448. this.specularMap = null;
  14449. this.alphaMap = null;
  14450. this.envMap = null;
  14451. this.combine = MultiplyOperation;
  14452. this.reflectivity = 1;
  14453. this.refractionRatio = 0.98;
  14454. this.wireframe = false;
  14455. this.wireframeLinewidth = 1;
  14456. this.wireframeLinecap = 'round';
  14457. this.wireframeLinejoin = 'round';
  14458. this.skinning = false;
  14459. this.morphTargets = false;
  14460. this.morphNormals = false;
  14461. this.setValues( parameters );
  14462. }
  14463. MeshLambertMaterial.prototype = Object.create( Material.prototype );
  14464. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  14465. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  14466. MeshLambertMaterial.prototype.copy = function ( source ) {
  14467. Material.prototype.copy.call( this, source );
  14468. this.color.copy( source.color );
  14469. this.map = source.map;
  14470. this.lightMap = source.lightMap;
  14471. this.lightMapIntensity = source.lightMapIntensity;
  14472. this.aoMap = source.aoMap;
  14473. this.aoMapIntensity = source.aoMapIntensity;
  14474. this.emissive.copy( source.emissive );
  14475. this.emissiveMap = source.emissiveMap;
  14476. this.emissiveIntensity = source.emissiveIntensity;
  14477. this.specularMap = source.specularMap;
  14478. this.alphaMap = source.alphaMap;
  14479. this.envMap = source.envMap;
  14480. this.combine = source.combine;
  14481. this.reflectivity = source.reflectivity;
  14482. this.refractionRatio = source.refractionRatio;
  14483. this.wireframe = source.wireframe;
  14484. this.wireframeLinewidth = source.wireframeLinewidth;
  14485. this.wireframeLinecap = source.wireframeLinecap;
  14486. this.wireframeLinejoin = source.wireframeLinejoin;
  14487. this.skinning = source.skinning;
  14488. this.morphTargets = source.morphTargets;
  14489. this.morphNormals = source.morphNormals;
  14490. return this;
  14491. };
  14492. /**
  14493. * @author alteredq / http://alteredqualia.com/
  14494. *
  14495. * parameters = {
  14496. * color: <hex>,
  14497. * opacity: <float>,
  14498. *
  14499. * linewidth: <float>,
  14500. *
  14501. * scale: <float>,
  14502. * dashSize: <float>,
  14503. * gapSize: <float>
  14504. * }
  14505. */
  14506. function LineDashedMaterial( parameters ) {
  14507. Material.call( this );
  14508. this.type = 'LineDashedMaterial';
  14509. this.color = new Color( 0xffffff );
  14510. this.linewidth = 1;
  14511. this.scale = 1;
  14512. this.dashSize = 3;
  14513. this.gapSize = 1;
  14514. this.lights = false;
  14515. this.setValues( parameters );
  14516. }
  14517. LineDashedMaterial.prototype = Object.create( Material.prototype );
  14518. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  14519. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  14520. LineDashedMaterial.prototype.copy = function ( source ) {
  14521. Material.prototype.copy.call( this, source );
  14522. this.color.copy( source.color );
  14523. this.linewidth = source.linewidth;
  14524. this.scale = source.scale;
  14525. this.dashSize = source.dashSize;
  14526. this.gapSize = source.gapSize;
  14527. return this;
  14528. };
  14529. var Materials = Object.freeze({
  14530. ShadowMaterial: ShadowMaterial,
  14531. SpriteMaterial: SpriteMaterial,
  14532. RawShaderMaterial: RawShaderMaterial,
  14533. ShaderMaterial: ShaderMaterial,
  14534. PointsMaterial: PointsMaterial,
  14535. MultiMaterial: MultiMaterial,
  14536. MeshPhysicalMaterial: MeshPhysicalMaterial,
  14537. MeshStandardMaterial: MeshStandardMaterial,
  14538. MeshPhongMaterial: MeshPhongMaterial,
  14539. MeshNormalMaterial: MeshNormalMaterial,
  14540. MeshLambertMaterial: MeshLambertMaterial,
  14541. MeshDepthMaterial: MeshDepthMaterial,
  14542. MeshBasicMaterial: MeshBasicMaterial,
  14543. LineDashedMaterial: LineDashedMaterial,
  14544. LineBasicMaterial: LineBasicMaterial,
  14545. Material: Material
  14546. });
  14547. /**
  14548. * @author mrdoob / http://mrdoob.com/
  14549. */
  14550. exports.Cache = {
  14551. enabled: false,
  14552. files: {},
  14553. add: function ( key, file ) {
  14554. if ( this.enabled === false ) return;
  14555. // console.log( 'THREE.Cache', 'Adding key:', key );
  14556. this.files[ key ] = file;
  14557. },
  14558. get: function ( key ) {
  14559. if ( this.enabled === false ) return;
  14560. // console.log( 'THREE.Cache', 'Checking key:', key );
  14561. return this.files[ key ];
  14562. },
  14563. remove: function ( key ) {
  14564. delete this.files[ key ];
  14565. },
  14566. clear: function () {
  14567. this.files = {};
  14568. }
  14569. };
  14570. /**
  14571. * @author mrdoob / http://mrdoob.com/
  14572. */
  14573. function LoadingManager( onLoad, onProgress, onError ) {
  14574. var scope = this;
  14575. var isLoading = false, itemsLoaded = 0, itemsTotal = 0;
  14576. this.onStart = undefined;
  14577. this.onLoad = onLoad;
  14578. this.onProgress = onProgress;
  14579. this.onError = onError;
  14580. this.itemStart = function ( url ) {
  14581. itemsTotal ++;
  14582. if ( isLoading === false ) {
  14583. if ( scope.onStart !== undefined ) {
  14584. scope.onStart( url, itemsLoaded, itemsTotal );
  14585. }
  14586. }
  14587. isLoading = true;
  14588. };
  14589. this.itemEnd = function ( url ) {
  14590. itemsLoaded ++;
  14591. if ( scope.onProgress !== undefined ) {
  14592. scope.onProgress( url, itemsLoaded, itemsTotal );
  14593. }
  14594. if ( itemsLoaded === itemsTotal ) {
  14595. isLoading = false;
  14596. if ( scope.onLoad !== undefined ) {
  14597. scope.onLoad();
  14598. }
  14599. }
  14600. };
  14601. this.itemError = function ( url ) {
  14602. if ( scope.onError !== undefined ) {
  14603. scope.onError( url );
  14604. }
  14605. };
  14606. }
  14607. exports.DefaultLoadingManager = new LoadingManager();
  14608. /**
  14609. * @author mrdoob / http://mrdoob.com/
  14610. */
  14611. function XHRLoader( manager ) {
  14612. this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager;
  14613. }
  14614. Object.assign( XHRLoader.prototype, {
  14615. load: function ( url, onLoad, onProgress, onError ) {
  14616. if ( this.path !== undefined ) url = this.path + url;
  14617. var scope = this;
  14618. var cached = exports.Cache.get( url );
  14619. if ( cached !== undefined ) {
  14620. scope.manager.itemStart( url );
  14621. setTimeout( function () {
  14622. if ( onLoad ) onLoad( cached );
  14623. scope.manager.itemEnd( url );
  14624. }, 0 );
  14625. return cached;
  14626. }
  14627. var request = new XMLHttpRequest();
  14628. request.open( 'GET', url, true );
  14629. request.addEventListener( 'load', function ( event ) {
  14630. var response = event.target.response;
  14631. exports.Cache.add( url, response );
  14632. if ( this.status === 200 ) {
  14633. if ( onLoad ) onLoad( response );
  14634. scope.manager.itemEnd( url );
  14635. } else if ( this.status === 0 ) {
  14636. // Some browsers return HTTP Status 0 when using non-http protocol
  14637. // e.g. 'file://' or 'data://'. Handle as success.
  14638. console.warn( 'THREE.XHRLoader: HTTP Status 0 received.' );
  14639. if ( onLoad ) onLoad( response );
  14640. scope.manager.itemEnd( url );
  14641. } else {
  14642. if ( onError ) onError( event );
  14643. scope.manager.itemError( url );
  14644. }
  14645. }, false );
  14646. if ( onProgress !== undefined ) {
  14647. request.addEventListener( 'progress', function ( event ) {
  14648. onProgress( event );
  14649. }, false );
  14650. }
  14651. request.addEventListener( 'error', function ( event ) {
  14652. if ( onError ) onError( event );
  14653. scope.manager.itemError( url );
  14654. }, false );
  14655. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  14656. if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;
  14657. if ( request.overrideMimeType ) request.overrideMimeType( 'text/plain' );
  14658. request.send( null );
  14659. scope.manager.itemStart( url );
  14660. return request;
  14661. },
  14662. setPath: function ( value ) {
  14663. this.path = value;
  14664. return this;
  14665. },
  14666. setResponseType: function ( value ) {
  14667. this.responseType = value;
  14668. return this;
  14669. },
  14670. setWithCredentials: function ( value ) {
  14671. this.withCredentials = value;
  14672. return this;
  14673. }
  14674. } );
  14675. /**
  14676. * @author mrdoob / http://mrdoob.com/
  14677. *
  14678. * Abstract Base class to block based textures loader (dds, pvr, ...)
  14679. */
  14680. function CompressedTextureLoader( manager ) {
  14681. this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager;
  14682. // override in sub classes
  14683. this._parser = null;
  14684. }
  14685. Object.assign( CompressedTextureLoader.prototype, {
  14686. load: function ( url, onLoad, onProgress, onError ) {
  14687. var scope = this;
  14688. var images = [];
  14689. var texture = new CompressedTexture();
  14690. texture.image = images;
  14691. var loader = new XHRLoader( this.manager );
  14692. loader.setPath( this.path );
  14693. loader.setResponseType( 'arraybuffer' );
  14694. function loadTexture( i ) {
  14695. loader.load( url[ i ], function ( buffer ) {
  14696. var texDatas = scope._parser( buffer, true );
  14697. images[ i ] = {
  14698. width: texDatas.width,
  14699. height: texDatas.height,
  14700. format: texDatas.format,
  14701. mipmaps: texDatas.mipmaps
  14702. };
  14703. loaded += 1;
  14704. if ( loaded === 6 ) {
  14705. if ( texDatas.mipmapCount === 1 )
  14706. texture.minFilter = LinearFilter;
  14707. texture.format = texDatas.format;
  14708. texture.needsUpdate = true;
  14709. if ( onLoad ) onLoad( texture );
  14710. }
  14711. }, onProgress, onError );
  14712. }
  14713. if ( Array.isArray( url ) ) {
  14714. var loaded = 0;
  14715. for ( var i = 0, il = url.length; i < il; ++ i ) {
  14716. loadTexture( i );
  14717. }
  14718. } else {
  14719. // compressed cubemap texture stored in a single DDS file
  14720. loader.load( url, function ( buffer ) {
  14721. var texDatas = scope._parser( buffer, true );
  14722. if ( texDatas.isCubemap ) {
  14723. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  14724. for ( var f = 0; f < faces; f ++ ) {
  14725. images[ f ] = { mipmaps : [] };
  14726. for ( var i = 0; i < texDatas.mipmapCount; i ++ ) {
  14727. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  14728. images[ f ].format = texDatas.format;
  14729. images[ f ].width = texDatas.width;
  14730. images[ f ].height = texDatas.height;
  14731. }
  14732. }
  14733. } else {
  14734. texture.image.width = texDatas.width;
  14735. texture.image.height = texDatas.height;
  14736. texture.mipmaps = texDatas.mipmaps;
  14737. }
  14738. if ( texDatas.mipmapCount === 1 ) {
  14739. texture.minFilter = LinearFilter;
  14740. }
  14741. texture.format = texDatas.format;
  14742. texture.needsUpdate = true;
  14743. if ( onLoad ) onLoad( texture );
  14744. }, onProgress, onError );
  14745. }
  14746. return texture;
  14747. },
  14748. setPath: function ( value ) {
  14749. this.path = value;
  14750. return this;
  14751. }
  14752. } );
  14753. /**
  14754. * @author Nikos M. / https://github.com/foo123/
  14755. *
  14756. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  14757. */
  14758. var DataTextureLoader = BinaryTextureLoader;
  14759. function BinaryTextureLoader( manager ) {
  14760. this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager;
  14761. // override in sub classes
  14762. this._parser = null;
  14763. }
  14764. Object.assign( BinaryTextureLoader.prototype, {
  14765. load: function ( url, onLoad, onProgress, onError ) {
  14766. var scope = this;
  14767. var texture = new DataTexture();
  14768. var loader = new XHRLoader( this.manager );
  14769. loader.setResponseType( 'arraybuffer' );
  14770. loader.load( url, function ( buffer ) {
  14771. var texData = scope._parser( buffer );
  14772. if ( ! texData ) return;
  14773. if ( undefined !== texData.image ) {
  14774. texture.image = texData.image;
  14775. } else if ( undefined !== texData.data ) {
  14776. texture.image.width = texData.width;
  14777. texture.image.height = texData.height;
  14778. texture.image.data = texData.data;
  14779. }
  14780. texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : ClampToEdgeWrapping;
  14781. texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : ClampToEdgeWrapping;
  14782. texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : LinearFilter;
  14783. texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : LinearMipMapLinearFilter;
  14784. texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1;
  14785. if ( undefined !== texData.format ) {
  14786. texture.format = texData.format;
  14787. }
  14788. if ( undefined !== texData.type ) {
  14789. texture.type = texData.type;
  14790. }
  14791. if ( undefined !== texData.mipmaps ) {
  14792. texture.mipmaps = texData.mipmaps;
  14793. }
  14794. if ( 1 === texData.mipmapCount ) {
  14795. texture.minFilter = LinearFilter;
  14796. }
  14797. texture.needsUpdate = true;
  14798. if ( onLoad ) onLoad( texture, texData );
  14799. }, onProgress, onError );
  14800. return texture;
  14801. }
  14802. } );
  14803. /**
  14804. * @author mrdoob / http://mrdoob.com/
  14805. */
  14806. function ImageLoader( manager ) {
  14807. this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager;
  14808. }
  14809. Object.assign( ImageLoader.prototype, {
  14810. load: function ( url, onLoad, onProgress, onError ) {
  14811. var scope = this;
  14812. var image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' );
  14813. image.onload = function () {
  14814. URL.revokeObjectURL( image.src );
  14815. if ( onLoad ) onLoad( image );
  14816. scope.manager.itemEnd( url );
  14817. };
  14818. if ( url.indexOf( 'data:' ) === 0 ) {
  14819. image.src = url;
  14820. } else {
  14821. var loader = new XHRLoader();
  14822. loader.setPath( this.path );
  14823. loader.setResponseType( 'blob' );
  14824. loader.setWithCredentials( this.withCredentials );
  14825. loader.load( url, function ( blob ) {
  14826. image.src = URL.createObjectURL( blob );
  14827. }, onProgress, onError );
  14828. }
  14829. scope.manager.itemStart( url );
  14830. return image;
  14831. },
  14832. setCrossOrigin: function ( value ) {
  14833. this.crossOrigin = value;
  14834. return this;
  14835. },
  14836. setWithCredentials: function ( value ) {
  14837. this.withCredentials = value;
  14838. return this;
  14839. },
  14840. setPath: function ( value ) {
  14841. this.path = value;
  14842. return this;
  14843. }
  14844. } );
  14845. /**
  14846. * @author mrdoob / http://mrdoob.com/
  14847. */
  14848. function CubeTextureLoader( manager ) {
  14849. this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager;
  14850. }
  14851. Object.assign( CubeTextureLoader.prototype, {
  14852. load: function ( urls, onLoad, onProgress, onError ) {
  14853. var texture = new CubeTexture();
  14854. var loader = new ImageLoader( this.manager );
  14855. loader.setCrossOrigin( this.crossOrigin );
  14856. loader.setPath( this.path );
  14857. var loaded = 0;
  14858. function loadTexture( i ) {
  14859. loader.load( urls[ i ], function ( image ) {
  14860. texture.images[ i ] = image;
  14861. loaded ++;
  14862. if ( loaded === 6 ) {
  14863. texture.needsUpdate = true;
  14864. if ( onLoad ) onLoad( texture );
  14865. }
  14866. }, undefined, onError );
  14867. }
  14868. for ( var i = 0; i < urls.length; ++ i ) {
  14869. loadTexture( i );
  14870. }
  14871. return texture;
  14872. },
  14873. setCrossOrigin: function ( value ) {
  14874. this.crossOrigin = value;
  14875. return this;
  14876. },
  14877. setPath: function ( value ) {
  14878. this.path = value;
  14879. return this;
  14880. }
  14881. } );
  14882. /**
  14883. * @author mrdoob / http://mrdoob.com/
  14884. */
  14885. function TextureLoader( manager ) {
  14886. this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager;
  14887. }
  14888. Object.assign( TextureLoader.prototype, {
  14889. load: function ( url, onLoad, onProgress, onError ) {
  14890. var texture = new Texture();
  14891. var loader = new ImageLoader( this.manager );
  14892. loader.setCrossOrigin( this.crossOrigin );
  14893. loader.setWithCredentials( this.withCredentials );
  14894. loader.setPath( this.path );
  14895. loader.load( url, function ( image ) {
  14896. // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  14897. var isJPEG = url.search( /\.(jpg|jpeg)$/ ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0;
  14898. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  14899. texture.image = image;
  14900. texture.needsUpdate = true;
  14901. if ( onLoad !== undefined ) {
  14902. onLoad( texture );
  14903. }
  14904. }, onProgress, onError );
  14905. return texture;
  14906. },
  14907. setCrossOrigin: function ( value ) {
  14908. this.crossOrigin = value;
  14909. return this;
  14910. },
  14911. setWithCredentials: function ( value ) {
  14912. this.withCredentials = value;
  14913. return this;
  14914. },
  14915. setPath: function ( value ) {
  14916. this.path = value;
  14917. return this;
  14918. }
  14919. } );
  14920. /**
  14921. * @author mrdoob / http://mrdoob.com/
  14922. * @author alteredq / http://alteredqualia.com/
  14923. */
  14924. function Light( color, intensity ) {
  14925. Object3D.call( this );
  14926. this.type = 'Light';
  14927. this.color = new Color( color );
  14928. this.intensity = intensity !== undefined ? intensity : 1;
  14929. this.receiveShadow = undefined;
  14930. }
  14931. Light.prototype = Object.assign( Object.create( Object3D.prototype ), {
  14932. constructor: Light,
  14933. isLight: true,
  14934. copy: function ( source ) {
  14935. Object3D.prototype.copy.call( this, source );
  14936. this.color.copy( source.color );
  14937. this.intensity = source.intensity;
  14938. return this;
  14939. },
  14940. toJSON: function ( meta ) {
  14941. var data = Object3D.prototype.toJSON.call( this, meta );
  14942. data.object.color = this.color.getHex();
  14943. data.object.intensity = this.intensity;
  14944. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  14945. if ( this.distance !== undefined ) data.object.distance = this.distance;
  14946. if ( this.angle !== undefined ) data.object.angle = this.angle;
  14947. if ( this.decay !== undefined ) data.object.decay = this.decay;
  14948. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  14949. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  14950. return data;
  14951. }
  14952. } );
  14953. /**
  14954. * @author alteredq / http://alteredqualia.com/
  14955. */
  14956. function HemisphereLight( skyColor, groundColor, intensity ) {
  14957. Light.call( this, skyColor, intensity );
  14958. this.type = 'HemisphereLight';
  14959. this.castShadow = undefined;
  14960. this.position.copy( Object3D.DefaultUp );
  14961. this.updateMatrix();
  14962. this.groundColor = new Color( groundColor );
  14963. }
  14964. HemisphereLight.prototype = Object.assign( Object.create( Light.prototype ), {
  14965. constructor: HemisphereLight,
  14966. isHemisphereLight: true,
  14967. copy: function ( source ) {
  14968. Light.prototype.copy.call( this, source );
  14969. this.groundColor.copy( source.groundColor );
  14970. return this;
  14971. }
  14972. } );
  14973. /**
  14974. * @author mrdoob / http://mrdoob.com/
  14975. */
  14976. function LightShadow( camera ) {
  14977. this.camera = camera;
  14978. this.bias = 0;
  14979. this.radius = 1;
  14980. this.mapSize = new Vector2( 512, 512 );
  14981. this.map = null;
  14982. this.matrix = new Matrix4();
  14983. }
  14984. Object.assign( LightShadow.prototype, {
  14985. copy: function ( source ) {
  14986. this.camera = source.camera.clone();
  14987. this.bias = source.bias;
  14988. this.radius = source.radius;
  14989. this.mapSize.copy( source.mapSize );
  14990. return this;
  14991. },
  14992. clone: function () {
  14993. return new this.constructor().copy( this );
  14994. },
  14995. toJSON: function () {
  14996. var object = {};
  14997. if ( this.bias !== 0 ) object.bias = this.bias;
  14998. if ( this.radius !== 1 ) object.radius = this.radius;
  14999. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  15000. object.camera = this.camera.toJSON( false ).object;
  15001. delete object.camera.matrix;
  15002. return object;
  15003. }
  15004. } );
  15005. /**
  15006. * @author mrdoob / http://mrdoob.com/
  15007. */
  15008. function SpotLightShadow() {
  15009. LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  15010. }
  15011. SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  15012. constructor: SpotLightShadow,
  15013. isSpotLightShadow: true,
  15014. update: function ( light ) {
  15015. var fov = exports.Math.RAD2DEG * 2 * light.angle;
  15016. var aspect = this.mapSize.width / this.mapSize.height;
  15017. var far = light.distance || 500;
  15018. var camera = this.camera;
  15019. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  15020. camera.fov = fov;
  15021. camera.aspect = aspect;
  15022. camera.far = far;
  15023. camera.updateProjectionMatrix();
  15024. }
  15025. }
  15026. } );
  15027. /**
  15028. * @author alteredq / http://alteredqualia.com/
  15029. */
  15030. function SpotLight( color, intensity, distance, angle, penumbra, decay ) {
  15031. Light.call( this, color, intensity );
  15032. this.type = 'SpotLight';
  15033. this.position.copy( Object3D.DefaultUp );
  15034. this.updateMatrix();
  15035. this.target = new Object3D();
  15036. Object.defineProperty( this, 'power', {
  15037. get: function () {
  15038. // intensity = power per solid angle.
  15039. // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  15040. return this.intensity * Math.PI;
  15041. },
  15042. set: function ( power ) {
  15043. // intensity = power per solid angle.
  15044. // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  15045. this.intensity = power / Math.PI;
  15046. }
  15047. } );
  15048. this.distance = ( distance !== undefined ) ? distance : 0;
  15049. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  15050. this.penumbra = ( penumbra !== undefined ) ? penumbra : 0;
  15051. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  15052. this.shadow = new SpotLightShadow();
  15053. }
  15054. SpotLight.prototype = Object.assign( Object.create( Light.prototype ), {
  15055. constructor: SpotLight,
  15056. isSpotLight: true,
  15057. copy: function ( source ) {
  15058. Light.prototype.copy.call( this, source );
  15059. this.distance = source.distance;
  15060. this.angle = source.angle;
  15061. this.penumbra = source.penumbra;
  15062. this.decay = source.decay;
  15063. this.target = source.target.clone();
  15064. this.shadow = source.shadow.clone();
  15065. return this;
  15066. }
  15067. } );
  15068. /**
  15069. * @author mrdoob / http://mrdoob.com/
  15070. */
  15071. function PointLight( color, intensity, distance, decay ) {
  15072. Light.call( this, color, intensity );
  15073. this.type = 'PointLight';
  15074. Object.defineProperty( this, 'power', {
  15075. get: function () {
  15076. // intensity = power per solid angle.
  15077. // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  15078. return this.intensity * 4 * Math.PI;
  15079. },
  15080. set: function ( power ) {
  15081. // intensity = power per solid angle.
  15082. // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  15083. this.intensity = power / ( 4 * Math.PI );
  15084. }
  15085. } );
  15086. this.distance = ( distance !== undefined ) ? distance : 0;
  15087. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  15088. this.shadow = new LightShadow( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  15089. }
  15090. PointLight.prototype = Object.assign( Object.create( Light.prototype ), {
  15091. constructor: PointLight,
  15092. isPointLight: true,
  15093. copy: function ( source ) {
  15094. Light.prototype.copy.call( this, source );
  15095. this.distance = source.distance;
  15096. this.decay = source.decay;
  15097. this.shadow = source.shadow.clone();
  15098. return this;
  15099. }
  15100. } );
  15101. /**
  15102. * @author mrdoob / http://mrdoob.com/
  15103. */
  15104. function DirectionalLightShadow( light ) {
  15105. LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  15106. }
  15107. DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  15108. constructor: DirectionalLightShadow
  15109. } );
  15110. /**
  15111. * @author mrdoob / http://mrdoob.com/
  15112. * @author alteredq / http://alteredqualia.com/
  15113. */
  15114. function DirectionalLight( color, intensity ) {
  15115. Light.call( this, color, intensity );
  15116. this.type = 'DirectionalLight';
  15117. this.position.copy( Object3D.DefaultUp );
  15118. this.updateMatrix();
  15119. this.target = new Object3D();
  15120. this.shadow = new DirectionalLightShadow();
  15121. }
  15122. DirectionalLight.prototype = Object.assign( Object.create( Light.prototype ), {
  15123. constructor: DirectionalLight,
  15124. isDirectionalLight: true,
  15125. copy: function ( source ) {
  15126. Light.prototype.copy.call( this, source );
  15127. this.target = source.target.clone();
  15128. this.shadow = source.shadow.clone();
  15129. return this;
  15130. }
  15131. } );
  15132. /**
  15133. * @author mrdoob / http://mrdoob.com/
  15134. */
  15135. function AmbientLight( color, intensity ) {
  15136. Light.call( this, color, intensity );
  15137. this.type = 'AmbientLight';
  15138. this.castShadow = undefined;
  15139. }
  15140. AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), {
  15141. constructor: AmbientLight,
  15142. isAmbientLight: true,
  15143. } );
  15144. /**
  15145. * @author tschw
  15146. * @author Ben Houston / http://clara.io/
  15147. * @author David Sarno / http://lighthaus.us/
  15148. */
  15149. exports.AnimationUtils = {
  15150. // same as Array.prototype.slice, but also works on typed arrays
  15151. arraySlice: function( array, from, to ) {
  15152. if ( exports.AnimationUtils.isTypedArray( array ) ) {
  15153. return new array.constructor( array.subarray( from, to ) );
  15154. }
  15155. return array.slice( from, to );
  15156. },
  15157. // converts an array to a specific type
  15158. convertArray: function( array, type, forceClone ) {
  15159. if ( ! array || // let 'undefined' and 'null' pass
  15160. ! forceClone && array.constructor === type ) return array;
  15161. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  15162. return new type( array ); // create typed array
  15163. }
  15164. return Array.prototype.slice.call( array ); // create Array
  15165. },
  15166. isTypedArray: function( object ) {
  15167. return ArrayBuffer.isView( object ) &&
  15168. ! ( object instanceof DataView );
  15169. },
  15170. // returns an array by which times and values can be sorted
  15171. getKeyframeOrder: function( times ) {
  15172. function compareTime( i, j ) {
  15173. return times[ i ] - times[ j ];
  15174. }
  15175. var n = times.length;
  15176. var result = new Array( n );
  15177. for ( var i = 0; i !== n; ++ i ) result[ i ] = i;
  15178. result.sort( compareTime );
  15179. return result;
  15180. },
  15181. // uses the array previously returned by 'getKeyframeOrder' to sort data
  15182. sortedArray: function( values, stride, order ) {
  15183. var nValues = values.length;
  15184. var result = new values.constructor( nValues );
  15185. for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  15186. var srcOffset = order[ i ] * stride;
  15187. for ( var j = 0; j !== stride; ++ j ) {
  15188. result[ dstOffset ++ ] = values[ srcOffset + j ];
  15189. }
  15190. }
  15191. return result;
  15192. },
  15193. // function for parsing AOS keyframe formats
  15194. flattenJSON: function( jsonKeys, times, values, valuePropertyName ) {
  15195. var i = 1, key = jsonKeys[ 0 ];
  15196. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  15197. key = jsonKeys[ i ++ ];
  15198. }
  15199. if ( key === undefined ) return; // no data
  15200. var value = key[ valuePropertyName ];
  15201. if ( value === undefined ) return; // no data
  15202. if ( Array.isArray( value ) ) {
  15203. do {
  15204. value = key[ valuePropertyName ];
  15205. if ( value !== undefined ) {
  15206. times.push( key.time );
  15207. values.push.apply( values, value ); // push all elements
  15208. }
  15209. key = jsonKeys[ i ++ ];
  15210. } while ( key !== undefined );
  15211. } else if ( value.toArray !== undefined ) {
  15212. // ...assume THREE.Math-ish
  15213. do {
  15214. value = key[ valuePropertyName ];
  15215. if ( value !== undefined ) {
  15216. times.push( key.time );
  15217. value.toArray( values, values.length );
  15218. }
  15219. key = jsonKeys[ i ++ ];
  15220. } while ( key !== undefined );
  15221. } else {
  15222. // otherwise push as-is
  15223. do {
  15224. value = key[ valuePropertyName ];
  15225. if ( value !== undefined ) {
  15226. times.push( key.time );
  15227. values.push( value );
  15228. }
  15229. key = jsonKeys[ i ++ ];
  15230. } while ( key !== undefined );
  15231. }
  15232. }
  15233. };
  15234. /**
  15235. * Abstract base class of interpolants over parametric samples.
  15236. *
  15237. * The parameter domain is one dimensional, typically the time or a path
  15238. * along a curve defined by the data.
  15239. *
  15240. * The sample values can have any dimensionality and derived classes may
  15241. * apply special interpretations to the data.
  15242. *
  15243. * This class provides the interval seek in a Template Method, deferring
  15244. * the actual interpolation to derived classes.
  15245. *
  15246. * Time complexity is O(1) for linear access crossing at most two points
  15247. * and O(log N) for random access, where N is the number of positions.
  15248. *
  15249. * References:
  15250. *
  15251. * http://www.oodesign.com/template-method-pattern.html
  15252. *
  15253. * @author tschw
  15254. */
  15255. function Interpolant(
  15256. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  15257. this.parameterPositions = parameterPositions;
  15258. this._cachedIndex = 0;
  15259. this.resultBuffer = resultBuffer !== undefined ?
  15260. resultBuffer : new sampleValues.constructor( sampleSize );
  15261. this.sampleValues = sampleValues;
  15262. this.valueSize = sampleSize;
  15263. }
  15264. Interpolant.prototype = {
  15265. constructor: Interpolant,
  15266. evaluate: function( t ) {
  15267. var pp = this.parameterPositions,
  15268. i1 = this._cachedIndex,
  15269. t1 = pp[ i1 ],
  15270. t0 = pp[ i1 - 1 ];
  15271. validate_interval: {
  15272. seek: {
  15273. var right;
  15274. linear_scan: {
  15275. //- See http://jsperf.com/comparison-to-undefined/3
  15276. //- slower code:
  15277. //-
  15278. //- if ( t >= t1 || t1 === undefined ) {
  15279. forward_scan: if ( ! ( t < t1 ) ) {
  15280. for ( var giveUpAt = i1 + 2; ;) {
  15281. if ( t1 === undefined ) {
  15282. if ( t < t0 ) break forward_scan;
  15283. // after end
  15284. i1 = pp.length;
  15285. this._cachedIndex = i1;
  15286. return this.afterEnd_( i1 - 1, t, t0 );
  15287. }
  15288. if ( i1 === giveUpAt ) break; // this loop
  15289. t0 = t1;
  15290. t1 = pp[ ++ i1 ];
  15291. if ( t < t1 ) {
  15292. // we have arrived at the sought interval
  15293. break seek;
  15294. }
  15295. }
  15296. // prepare binary search on the right side of the index
  15297. right = pp.length;
  15298. break linear_scan;
  15299. }
  15300. //- slower code:
  15301. //- if ( t < t0 || t0 === undefined ) {
  15302. if ( ! ( t >= t0 ) ) {
  15303. // looping?
  15304. var t1global = pp[ 1 ];
  15305. if ( t < t1global ) {
  15306. i1 = 2; // + 1, using the scan for the details
  15307. t0 = t1global;
  15308. }
  15309. // linear reverse scan
  15310. for ( var giveUpAt = i1 - 2; ;) {
  15311. if ( t0 === undefined ) {
  15312. // before start
  15313. this._cachedIndex = 0;
  15314. return this.beforeStart_( 0, t, t1 );
  15315. }
  15316. if ( i1 === giveUpAt ) break; // this loop
  15317. t1 = t0;
  15318. t0 = pp[ -- i1 - 1 ];
  15319. if ( t >= t0 ) {
  15320. // we have arrived at the sought interval
  15321. break seek;
  15322. }
  15323. }
  15324. // prepare binary search on the left side of the index
  15325. right = i1;
  15326. i1 = 0;
  15327. break linear_scan;
  15328. }
  15329. // the interval is valid
  15330. break validate_interval;
  15331. } // linear scan
  15332. // binary search
  15333. while ( i1 < right ) {
  15334. var mid = ( i1 + right ) >>> 1;
  15335. if ( t < pp[ mid ] ) {
  15336. right = mid;
  15337. } else {
  15338. i1 = mid + 1;
  15339. }
  15340. }
  15341. t1 = pp[ i1 ];
  15342. t0 = pp[ i1 - 1 ];
  15343. // check boundary cases, again
  15344. if ( t0 === undefined ) {
  15345. this._cachedIndex = 0;
  15346. return this.beforeStart_( 0, t, t1 );
  15347. }
  15348. if ( t1 === undefined ) {
  15349. i1 = pp.length;
  15350. this._cachedIndex = i1;
  15351. return this.afterEnd_( i1 - 1, t0, t );
  15352. }
  15353. } // seek
  15354. this._cachedIndex = i1;
  15355. this.intervalChanged_( i1, t0, t1 );
  15356. } // validate_interval
  15357. return this.interpolate_( i1, t0, t, t1 );
  15358. },
  15359. settings: null, // optional, subclass-specific settings structure
  15360. // Note: The indirection allows central control of many interpolants.
  15361. // --- Protected interface
  15362. DefaultSettings_: {},
  15363. getSettings_: function() {
  15364. return this.settings || this.DefaultSettings_;
  15365. },
  15366. copySampleValue_: function( index ) {
  15367. // copies a sample value to the result buffer
  15368. var result = this.resultBuffer,
  15369. values = this.sampleValues,
  15370. stride = this.valueSize,
  15371. offset = index * stride;
  15372. for ( var i = 0; i !== stride; ++ i ) {
  15373. result[ i ] = values[ offset + i ];
  15374. }
  15375. return result;
  15376. },
  15377. // Template methods for derived classes:
  15378. interpolate_: function( i1, t0, t, t1 ) {
  15379. throw new Error( "call to abstract method" );
  15380. // implementations shall return this.resultBuffer
  15381. },
  15382. intervalChanged_: function( i1, t0, t1 ) {
  15383. // empty
  15384. }
  15385. };
  15386. Object.assign( Interpolant.prototype, {
  15387. beforeStart_: //( 0, t, t0 ), returns this.resultBuffer
  15388. Interpolant.prototype.copySampleValue_,
  15389. afterEnd_: //( N-1, tN-1, t ), returns this.resultBuffer
  15390. Interpolant.prototype.copySampleValue_
  15391. } );
  15392. /**
  15393. * Fast and simple cubic spline interpolant.
  15394. *
  15395. * It was derived from a Hermitian construction setting the first derivative
  15396. * at each sample position to the linear slope between neighboring positions
  15397. * over their parameter interval.
  15398. *
  15399. * @author tschw
  15400. */
  15401. function CubicInterpolant(
  15402. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  15403. Interpolant.call(
  15404. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  15405. this._weightPrev = -0;
  15406. this._offsetPrev = -0;
  15407. this._weightNext = -0;
  15408. this._offsetNext = -0;
  15409. }
  15410. CubicInterpolant.prototype =
  15411. Object.assign( Object.create( Interpolant.prototype ), {
  15412. constructor: CubicInterpolant,
  15413. DefaultSettings_: {
  15414. endingStart: ZeroCurvatureEnding,
  15415. endingEnd: ZeroCurvatureEnding
  15416. },
  15417. intervalChanged_: function( i1, t0, t1 ) {
  15418. var pp = this.parameterPositions,
  15419. iPrev = i1 - 2,
  15420. iNext = i1 + 1,
  15421. tPrev = pp[ iPrev ],
  15422. tNext = pp[ iNext ];
  15423. if ( tPrev === undefined ) {
  15424. switch ( this.getSettings_().endingStart ) {
  15425. case ZeroSlopeEnding:
  15426. // f'(t0) = 0
  15427. iPrev = i1;
  15428. tPrev = 2 * t0 - t1;
  15429. break;
  15430. case WrapAroundEnding:
  15431. // use the other end of the curve
  15432. iPrev = pp.length - 2;
  15433. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  15434. break;
  15435. default: // ZeroCurvatureEnding
  15436. // f''(t0) = 0 a.k.a. Natural Spline
  15437. iPrev = i1;
  15438. tPrev = t1;
  15439. }
  15440. }
  15441. if ( tNext === undefined ) {
  15442. switch ( this.getSettings_().endingEnd ) {
  15443. case ZeroSlopeEnding:
  15444. // f'(tN) = 0
  15445. iNext = i1;
  15446. tNext = 2 * t1 - t0;
  15447. break;
  15448. case WrapAroundEnding:
  15449. // use the other end of the curve
  15450. iNext = 1;
  15451. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  15452. break;
  15453. default: // ZeroCurvatureEnding
  15454. // f''(tN) = 0, a.k.a. Natural Spline
  15455. iNext = i1 - 1;
  15456. tNext = t0;
  15457. }
  15458. }
  15459. var halfDt = ( t1 - t0 ) * 0.5,
  15460. stride = this.valueSize;
  15461. this._weightPrev = halfDt / ( t0 - tPrev );
  15462. this._weightNext = halfDt / ( tNext - t1 );
  15463. this._offsetPrev = iPrev * stride;
  15464. this._offsetNext = iNext * stride;
  15465. },
  15466. interpolate_: function( i1, t0, t, t1 ) {
  15467. var result = this.resultBuffer,
  15468. values = this.sampleValues,
  15469. stride = this.valueSize,
  15470. o1 = i1 * stride, o0 = o1 - stride,
  15471. oP = this._offsetPrev, oN = this._offsetNext,
  15472. wP = this._weightPrev, wN = this._weightNext,
  15473. p = ( t - t0 ) / ( t1 - t0 ),
  15474. pp = p * p,
  15475. ppp = pp * p;
  15476. // evaluate polynomials
  15477. var sP = - wP * ppp + 2 * wP * pp - wP * p;
  15478. var s0 = ( 1 + wP ) * ppp + (-1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  15479. var s1 = (-1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  15480. var sN = wN * ppp - wN * pp;
  15481. // combine data linearly
  15482. for ( var i = 0; i !== stride; ++ i ) {
  15483. result[ i ] =
  15484. sP * values[ oP + i ] +
  15485. s0 * values[ o0 + i ] +
  15486. s1 * values[ o1 + i ] +
  15487. sN * values[ oN + i ];
  15488. }
  15489. return result;
  15490. }
  15491. } );
  15492. /**
  15493. * @author tschw
  15494. */
  15495. function LinearInterpolant(
  15496. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  15497. Interpolant.call(
  15498. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  15499. }
  15500. LinearInterpolant.prototype =
  15501. Object.assign( Object.create( Interpolant.prototype ), {
  15502. constructor: LinearInterpolant,
  15503. interpolate_: function( i1, t0, t, t1 ) {
  15504. var result = this.resultBuffer,
  15505. values = this.sampleValues,
  15506. stride = this.valueSize,
  15507. offset1 = i1 * stride,
  15508. offset0 = offset1 - stride,
  15509. weight1 = ( t - t0 ) / ( t1 - t0 ),
  15510. weight0 = 1 - weight1;
  15511. for ( var i = 0; i !== stride; ++ i ) {
  15512. result[ i ] =
  15513. values[ offset0 + i ] * weight0 +
  15514. values[ offset1 + i ] * weight1;
  15515. }
  15516. return result;
  15517. }
  15518. } );
  15519. /**
  15520. *
  15521. * Interpolant that evaluates to the sample value at the position preceeding
  15522. * the parameter.
  15523. *
  15524. * @author tschw
  15525. */
  15526. function DiscreteInterpolant(
  15527. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  15528. Interpolant.call(
  15529. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  15530. }
  15531. DiscreteInterpolant.prototype =
  15532. Object.assign( Object.create( Interpolant.prototype ), {
  15533. constructor: DiscreteInterpolant,
  15534. interpolate_: function( i1, t0, t, t1 ) {
  15535. return this.copySampleValue_( i1 - 1 );
  15536. }
  15537. } );
  15538. var KeyframeTrackPrototype;
  15539. KeyframeTrackPrototype = {
  15540. TimeBufferType: Float32Array,
  15541. ValueBufferType: Float32Array,
  15542. DefaultInterpolation: InterpolateLinear,
  15543. InterpolantFactoryMethodDiscrete: function( result ) {
  15544. return new DiscreteInterpolant(
  15545. this.times, this.values, this.getValueSize(), result );
  15546. },
  15547. InterpolantFactoryMethodLinear: function( result ) {
  15548. return new LinearInterpolant(
  15549. this.times, this.values, this.getValueSize(), result );
  15550. },
  15551. InterpolantFactoryMethodSmooth: function( result ) {
  15552. return new CubicInterpolant(
  15553. this.times, this.values, this.getValueSize(), result );
  15554. },
  15555. setInterpolation: function( interpolation ) {
  15556. var factoryMethod;
  15557. switch ( interpolation ) {
  15558. case InterpolateDiscrete:
  15559. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  15560. break;
  15561. case InterpolateLinear:
  15562. factoryMethod = this.InterpolantFactoryMethodLinear;
  15563. break;
  15564. case InterpolateSmooth:
  15565. factoryMethod = this.InterpolantFactoryMethodSmooth;
  15566. break;
  15567. }
  15568. if ( factoryMethod === undefined ) {
  15569. var message = "unsupported interpolation for " +
  15570. this.ValueTypeName + " keyframe track named " + this.name;
  15571. if ( this.createInterpolant === undefined ) {
  15572. // fall back to default, unless the default itself is messed up
  15573. if ( interpolation !== this.DefaultInterpolation ) {
  15574. this.setInterpolation( this.DefaultInterpolation );
  15575. } else {
  15576. throw new Error( message ); // fatal, in this case
  15577. }
  15578. }
  15579. console.warn( message );
  15580. return;
  15581. }
  15582. this.createInterpolant = factoryMethod;
  15583. },
  15584. getInterpolation: function() {
  15585. switch ( this.createInterpolant ) {
  15586. case this.InterpolantFactoryMethodDiscrete:
  15587. return InterpolateDiscrete;
  15588. case this.InterpolantFactoryMethodLinear:
  15589. return InterpolateLinear;
  15590. case this.InterpolantFactoryMethodSmooth:
  15591. return InterpolateSmooth;
  15592. }
  15593. },
  15594. getValueSize: function() {
  15595. return this.values.length / this.times.length;
  15596. },
  15597. // move all keyframes either forwards or backwards in time
  15598. shift: function( timeOffset ) {
  15599. if( timeOffset !== 0.0 ) {
  15600. var times = this.times;
  15601. for( var i = 0, n = times.length; i !== n; ++ i ) {
  15602. times[ i ] += timeOffset;
  15603. }
  15604. }
  15605. return this;
  15606. },
  15607. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  15608. scale: function( timeScale ) {
  15609. if( timeScale !== 1.0 ) {
  15610. var times = this.times;
  15611. for( var i = 0, n = times.length; i !== n; ++ i ) {
  15612. times[ i ] *= timeScale;
  15613. }
  15614. }
  15615. return this;
  15616. },
  15617. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  15618. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  15619. trim: function( startTime, endTime ) {
  15620. var times = this.times,
  15621. nKeys = times.length,
  15622. from = 0,
  15623. to = nKeys - 1;
  15624. while ( from !== nKeys && times[ from ] < startTime ) ++ from;
  15625. while ( to !== -1 && times[ to ] > endTime ) -- to;
  15626. ++ to; // inclusive -> exclusive bound
  15627. if( from !== 0 || to !== nKeys ) {
  15628. // empty tracks are forbidden, so keep at least one keyframe
  15629. if ( from >= to ) to = Math.max( to , 1 ), from = to - 1;
  15630. var stride = this.getValueSize();
  15631. this.times = exports.AnimationUtils.arraySlice( times, from, to );
  15632. this.values = exports.AnimationUtils.
  15633. arraySlice( this.values, from * stride, to * stride );
  15634. }
  15635. return this;
  15636. },
  15637. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  15638. validate: function() {
  15639. var valid = true;
  15640. var valueSize = this.getValueSize();
  15641. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  15642. console.error( "invalid value size in track", this );
  15643. valid = false;
  15644. }
  15645. var times = this.times,
  15646. values = this.values,
  15647. nKeys = times.length;
  15648. if( nKeys === 0 ) {
  15649. console.error( "track is empty", this );
  15650. valid = false;
  15651. }
  15652. var prevTime = null;
  15653. for( var i = 0; i !== nKeys; i ++ ) {
  15654. var currTime = times[ i ];
  15655. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  15656. console.error( "time is not a valid number", this, i, currTime );
  15657. valid = false;
  15658. break;
  15659. }
  15660. if( prevTime !== null && prevTime > currTime ) {
  15661. console.error( "out of order keys", this, i, currTime, prevTime );
  15662. valid = false;
  15663. break;
  15664. }
  15665. prevTime = currTime;
  15666. }
  15667. if ( values !== undefined ) {
  15668. if ( exports.AnimationUtils.isTypedArray( values ) ) {
  15669. for ( var i = 0, n = values.length; i !== n; ++ i ) {
  15670. var value = values[ i ];
  15671. if ( isNaN( value ) ) {
  15672. console.error( "value is not a valid number", this, i, value );
  15673. valid = false;
  15674. break;
  15675. }
  15676. }
  15677. }
  15678. }
  15679. return valid;
  15680. },
  15681. // removes equivalent sequential keys as common in morph target sequences
  15682. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  15683. optimize: function() {
  15684. var times = this.times,
  15685. values = this.values,
  15686. stride = this.getValueSize(),
  15687. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  15688. writeIndex = 1,
  15689. lastIndex = times.length - 1;
  15690. for( var i = 1; i < lastIndex; ++ i ) {
  15691. var keep = false;
  15692. var time = times[ i ];
  15693. var timeNext = times[ i + 1 ];
  15694. // remove adjacent keyframes scheduled at the same time
  15695. if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) {
  15696. if ( ! smoothInterpolation ) {
  15697. // remove unnecessary keyframes same as their neighbors
  15698. var offset = i * stride,
  15699. offsetP = offset - stride,
  15700. offsetN = offset + stride;
  15701. for ( var j = 0; j !== stride; ++ j ) {
  15702. var value = values[ offset + j ];
  15703. if ( value !== values[ offsetP + j ] ||
  15704. value !== values[ offsetN + j ] ) {
  15705. keep = true;
  15706. break;
  15707. }
  15708. }
  15709. } else keep = true;
  15710. }
  15711. // in-place compaction
  15712. if ( keep ) {
  15713. if ( i !== writeIndex ) {
  15714. times[ writeIndex ] = times[ i ];
  15715. var readOffset = i * stride,
  15716. writeOffset = writeIndex * stride;
  15717. for ( var j = 0; j !== stride; ++ j )
  15718. values[ writeOffset + j ] = values[ readOffset + j ];
  15719. }
  15720. ++ writeIndex;
  15721. }
  15722. }
  15723. // flush last keyframe (compaction looks ahead)
  15724. times[ writeIndex ++ ] = times[ lastIndex ];
  15725. for ( var readOffset = lastIndex * stride, j = 0; j !== stride; ++ j )
  15726. values[ writeOffset + j ] = values[ readOffset + j ];
  15727. if ( writeIndex !== times.length ) {
  15728. this.times = exports.AnimationUtils.arraySlice( times, 0, writeIndex );
  15729. this.values = exports.AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  15730. }
  15731. return this;
  15732. }
  15733. }
  15734. function KeyframeTrackConstructor( name, times, values, interpolation ) {
  15735. if( name === undefined ) throw new Error( "track name is undefined" );
  15736. if( times === undefined || times.length === 0 ) {
  15737. throw new Error( "no keyframes in track named " + name );
  15738. }
  15739. this.name = name;
  15740. this.times = exports.AnimationUtils.convertArray( times, this.TimeBufferType );
  15741. this.values = exports.AnimationUtils.convertArray( values, this.ValueBufferType );
  15742. this.setInterpolation( interpolation || this.DefaultInterpolation );
  15743. this.validate();
  15744. this.optimize();
  15745. }
  15746. /**
  15747. *
  15748. * A Track of vectored keyframe values.
  15749. *
  15750. *
  15751. * @author Ben Houston / http://clara.io/
  15752. * @author David Sarno / http://lighthaus.us/
  15753. * @author tschw
  15754. */
  15755. function VectorKeyframeTrack( name, times, values, interpolation ) {
  15756. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  15757. }
  15758. VectorKeyframeTrack.prototype =
  15759. Object.assign( Object.create( KeyframeTrackPrototype ), {
  15760. constructor: VectorKeyframeTrack,
  15761. ValueTypeName: 'vector'
  15762. // ValueBufferType is inherited
  15763. // DefaultInterpolation is inherited
  15764. } );
  15765. /**
  15766. * Spherical linear unit quaternion interpolant.
  15767. *
  15768. * @author tschw
  15769. */
  15770. function QuaternionLinearInterpolant(
  15771. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  15772. Interpolant.call(
  15773. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  15774. }
  15775. QuaternionLinearInterpolant.prototype =
  15776. Object.assign( Object.create( Interpolant.prototype ), {
  15777. constructor: QuaternionLinearInterpolant,
  15778. interpolate_: function( i1, t0, t, t1 ) {
  15779. var result = this.resultBuffer,
  15780. values = this.sampleValues,
  15781. stride = this.valueSize,
  15782. offset = i1 * stride,
  15783. alpha = ( t - t0 ) / ( t1 - t0 );
  15784. for ( var end = offset + stride; offset !== end; offset += 4 ) {
  15785. Quaternion.slerpFlat( result, 0,
  15786. values, offset - stride, values, offset, alpha );
  15787. }
  15788. return result;
  15789. }
  15790. } );
  15791. /**
  15792. *
  15793. * A Track of quaternion keyframe values.
  15794. *
  15795. * @author Ben Houston / http://clara.io/
  15796. * @author David Sarno / http://lighthaus.us/
  15797. * @author tschw
  15798. */
  15799. function QuaternionKeyframeTrack( name, times, values, interpolation ) {
  15800. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  15801. }
  15802. QuaternionKeyframeTrack.prototype =
  15803. Object.assign( Object.create( KeyframeTrackPrototype ), {
  15804. constructor: QuaternionKeyframeTrack,
  15805. ValueTypeName: 'quaternion',
  15806. // ValueBufferType is inherited
  15807. DefaultInterpolation: InterpolateLinear,
  15808. InterpolantFactoryMethodLinear: function( result ) {
  15809. return new QuaternionLinearInterpolant(
  15810. this.times, this.values, this.getValueSize(), result );
  15811. },
  15812. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  15813. } );
  15814. /**
  15815. *
  15816. * A Track of numeric keyframe values.
  15817. *
  15818. * @author Ben Houston / http://clara.io/
  15819. * @author David Sarno / http://lighthaus.us/
  15820. * @author tschw
  15821. */
  15822. function NumberKeyframeTrack( name, times, values, interpolation ) {
  15823. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  15824. }
  15825. NumberKeyframeTrack.prototype =
  15826. Object.assign( Object.create( KeyframeTrackPrototype ), {
  15827. constructor: NumberKeyframeTrack,
  15828. ValueTypeName: 'number',
  15829. // ValueBufferType is inherited
  15830. // DefaultInterpolation is inherited
  15831. } );
  15832. /**
  15833. *
  15834. * A Track that interpolates Strings
  15835. *
  15836. *
  15837. * @author Ben Houston / http://clara.io/
  15838. * @author David Sarno / http://lighthaus.us/
  15839. * @author tschw
  15840. */
  15841. function StringKeyframeTrack( name, times, values, interpolation ) {
  15842. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  15843. }
  15844. StringKeyframeTrack.prototype =
  15845. Object.assign( Object.create( KeyframeTrackPrototype ), {
  15846. constructor: StringKeyframeTrack,
  15847. ValueTypeName: 'string',
  15848. ValueBufferType: Array,
  15849. DefaultInterpolation: InterpolateDiscrete,
  15850. InterpolantFactoryMethodLinear: undefined,
  15851. InterpolantFactoryMethodSmooth: undefined
  15852. } );
  15853. /**
  15854. *
  15855. * A Track of Boolean keyframe values.
  15856. *
  15857. *
  15858. * @author Ben Houston / http://clara.io/
  15859. * @author David Sarno / http://lighthaus.us/
  15860. * @author tschw
  15861. */
  15862. function BooleanKeyframeTrack( name, times, values ) {
  15863. KeyframeTrackConstructor.call( this, name, times, values );
  15864. }
  15865. BooleanKeyframeTrack.prototype =
  15866. Object.assign( Object.create( KeyframeTrackPrototype ), {
  15867. constructor: BooleanKeyframeTrack,
  15868. ValueTypeName: 'bool',
  15869. ValueBufferType: Array,
  15870. DefaultInterpolation: InterpolateDiscrete,
  15871. InterpolantFactoryMethodLinear: undefined,
  15872. InterpolantFactoryMethodSmooth: undefined
  15873. // Note: Actually this track could have a optimized / compressed
  15874. // representation of a single value and a custom interpolant that
  15875. // computes "firstValue ^ isOdd( index )".
  15876. } );
  15877. /**
  15878. *
  15879. * A Track of keyframe values that represent color.
  15880. *
  15881. *
  15882. * @author Ben Houston / http://clara.io/
  15883. * @author David Sarno / http://lighthaus.us/
  15884. * @author tschw
  15885. */
  15886. function ColorKeyframeTrack( name, times, values, interpolation ) {
  15887. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  15888. }
  15889. ColorKeyframeTrack.prototype =
  15890. Object.assign( Object.create( KeyframeTrackPrototype ), {
  15891. constructor: ColorKeyframeTrack,
  15892. ValueTypeName: 'color'
  15893. // ValueBufferType is inherited
  15894. // DefaultInterpolation is inherited
  15895. // Note: Very basic implementation and nothing special yet.
  15896. // However, this is the place for color space parameterization.
  15897. } );
  15898. /**
  15899. *
  15900. * A timed sequence of keyframes for a specific property.
  15901. *
  15902. *
  15903. * @author Ben Houston / http://clara.io/
  15904. * @author David Sarno / http://lighthaus.us/
  15905. * @author tschw
  15906. */
  15907. function KeyframeTrack( name, times, values, interpolation ) {
  15908. KeyframeTrackConstructor.apply( this, arguments );
  15909. }
  15910. KeyframeTrack.prototype = KeyframeTrackPrototype;
  15911. KeyframeTrackPrototype.constructor = KeyframeTrack;
  15912. // Static methods:
  15913. Object.assign( KeyframeTrack, {
  15914. // Serialization (in static context, because of constructor invocation
  15915. // and automatic invocation of .toJSON):
  15916. parse: function( json ) {
  15917. if( json.type === undefined ) {
  15918. throw new Error( "track type undefined, can not parse" );
  15919. }
  15920. var trackType = KeyframeTrack._getTrackTypeForValueTypeName( json.type );
  15921. if ( json.times === undefined ) {
  15922. var times = [], values = [];
  15923. exports.AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  15924. json.times = times;
  15925. json.values = values;
  15926. }
  15927. // derived classes can define a static parse method
  15928. if ( trackType.parse !== undefined ) {
  15929. return trackType.parse( json );
  15930. } else {
  15931. // by default, we asssume a constructor compatible with the base
  15932. return new trackType(
  15933. json.name, json.times, json.values, json.interpolation );
  15934. }
  15935. },
  15936. toJSON: function( track ) {
  15937. var trackType = track.constructor;
  15938. var json;
  15939. // derived classes can define a static toJSON method
  15940. if ( trackType.toJSON !== undefined ) {
  15941. json = trackType.toJSON( track );
  15942. } else {
  15943. // by default, we assume the data can be serialized as-is
  15944. json = {
  15945. 'name': track.name,
  15946. 'times': exports.AnimationUtils.convertArray( track.times, Array ),
  15947. 'values': exports.AnimationUtils.convertArray( track.values, Array )
  15948. };
  15949. var interpolation = track.getInterpolation();
  15950. if ( interpolation !== track.DefaultInterpolation ) {
  15951. json.interpolation = interpolation;
  15952. }
  15953. }
  15954. json.type = track.ValueTypeName; // mandatory
  15955. return json;
  15956. },
  15957. _getTrackTypeForValueTypeName: function( typeName ) {
  15958. switch( typeName.toLowerCase() ) {
  15959. case "scalar":
  15960. case "double":
  15961. case "float":
  15962. case "number":
  15963. case "integer":
  15964. return NumberKeyframeTrack;
  15965. case "vector":
  15966. case "vector2":
  15967. case "vector3":
  15968. case "vector4":
  15969. return VectorKeyframeTrack;
  15970. case "color":
  15971. return ColorKeyframeTrack;
  15972. case "quaternion":
  15973. return QuaternionKeyframeTrack;
  15974. case "bool":
  15975. case "boolean":
  15976. return BooleanKeyframeTrack;
  15977. case "string":
  15978. return StringKeyframeTrack;
  15979. }
  15980. throw new Error( "Unsupported typeName: " + typeName );
  15981. }
  15982. } );
  15983. /**
  15984. *
  15985. * Reusable set of Tracks that represent an animation.
  15986. *
  15987. * @author Ben Houston / http://clara.io/
  15988. * @author David Sarno / http://lighthaus.us/
  15989. */
  15990. function AnimationClip( name, duration, tracks ) {
  15991. this.name = name;
  15992. this.tracks = tracks;
  15993. this.duration = ( duration !== undefined ) ? duration : -1;
  15994. this.uuid = exports.Math.generateUUID();
  15995. // this means it should figure out its duration by scanning the tracks
  15996. if ( this.duration < 0 ) {
  15997. this.resetDuration();
  15998. }
  15999. this.optimize();
  16000. }
  16001. AnimationClip.prototype = {
  16002. constructor: AnimationClip,
  16003. resetDuration: function() {
  16004. var tracks = this.tracks,
  16005. duration = 0;
  16006. for ( var i = 0, n = tracks.length; i !== n; ++ i ) {
  16007. var track = this.tracks[ i ];
  16008. duration = Math.max(
  16009. duration, track.times[ track.times.length - 1 ] );
  16010. }
  16011. this.duration = duration;
  16012. },
  16013. trim: function() {
  16014. for ( var i = 0; i < this.tracks.length; i ++ ) {
  16015. this.tracks[ i ].trim( 0, this.duration );
  16016. }
  16017. return this;
  16018. },
  16019. optimize: function() {
  16020. for ( var i = 0; i < this.tracks.length; i ++ ) {
  16021. this.tracks[ i ].optimize();
  16022. }
  16023. return this;
  16024. }
  16025. };
  16026. // Static methods:
  16027. Object.assign( AnimationClip, {
  16028. parse: function( json ) {
  16029. var tracks = [],
  16030. jsonTracks = json.tracks,
  16031. frameTime = 1.0 / ( json.fps || 1.0 );
  16032. for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  16033. tracks.push( KeyframeTrack.parse( jsonTracks[ i ] ).scale( frameTime ) );
  16034. }
  16035. return new AnimationClip( json.name, json.duration, tracks );
  16036. },
  16037. toJSON: function( clip ) {
  16038. var tracks = [],
  16039. clipTracks = clip.tracks;
  16040. var json = {
  16041. 'name': clip.name,
  16042. 'duration': clip.duration,
  16043. 'tracks': tracks
  16044. };
  16045. for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) {
  16046. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  16047. }
  16048. return json;
  16049. },
  16050. CreateFromMorphTargetSequence: function( name, morphTargetSequence, fps, noLoop ) {
  16051. var numMorphTargets = morphTargetSequence.length;
  16052. var tracks = [];
  16053. for ( var i = 0; i < numMorphTargets; i ++ ) {
  16054. var times = [];
  16055. var values = [];
  16056. times.push(
  16057. ( i + numMorphTargets - 1 ) % numMorphTargets,
  16058. i,
  16059. ( i + 1 ) % numMorphTargets );
  16060. values.push( 0, 1, 0 );
  16061. var order = exports.AnimationUtils.getKeyframeOrder( times );
  16062. times = exports.AnimationUtils.sortedArray( times, 1, order );
  16063. values = exports.AnimationUtils.sortedArray( values, 1, order );
  16064. // if there is a key at the first frame, duplicate it as the
  16065. // last frame as well for perfect loop.
  16066. if ( ! noLoop && times[ 0 ] === 0 ) {
  16067. times.push( numMorphTargets );
  16068. values.push( values[ 0 ] );
  16069. }
  16070. tracks.push(
  16071. new NumberKeyframeTrack(
  16072. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  16073. times, values
  16074. ).scale( 1.0 / fps ) );
  16075. }
  16076. return new AnimationClip( name, -1, tracks );
  16077. },
  16078. findByName: function( objectOrClipArray, name ) {
  16079. var clipArray = objectOrClipArray;
  16080. if ( ! Array.isArray( objectOrClipArray ) ) {
  16081. var o = objectOrClipArray;
  16082. clipArray = o.geometry && o.geometry.animations || o.animations;
  16083. }
  16084. for ( var i = 0; i < clipArray.length; i ++ ) {
  16085. if ( clipArray[ i ].name === name ) {
  16086. return clipArray[ i ];
  16087. }
  16088. }
  16089. return null;
  16090. },
  16091. CreateClipsFromMorphTargetSequences: function( morphTargets, fps, noLoop ) {
  16092. var animationToMorphTargets = {};
  16093. // tested with https://regex101.com/ on trick sequences
  16094. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  16095. var pattern = /^([\w-]*?)([\d]+)$/;
  16096. // sort morph target names into animation groups based
  16097. // patterns like Walk_001, Walk_002, Run_001, Run_002
  16098. for ( var i = 0, il = morphTargets.length; i < il; i ++ ) {
  16099. var morphTarget = morphTargets[ i ];
  16100. var parts = morphTarget.name.match( pattern );
  16101. if ( parts && parts.length > 1 ) {
  16102. var name = parts[ 1 ];
  16103. var animationMorphTargets = animationToMorphTargets[ name ];
  16104. if ( ! animationMorphTargets ) {
  16105. animationToMorphTargets[ name ] = animationMorphTargets = [];
  16106. }
  16107. animationMorphTargets.push( morphTarget );
  16108. }
  16109. }
  16110. var clips = [];
  16111. for ( var name in animationToMorphTargets ) {
  16112. clips.push( AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  16113. }
  16114. return clips;
  16115. },
  16116. // parse the animation.hierarchy format
  16117. parseAnimation: function( animation, bones, nodeName ) {
  16118. if ( ! animation ) {
  16119. console.error( " no animation in JSONLoader data" );
  16120. return null;
  16121. }
  16122. var addNonemptyTrack = function(
  16123. trackType, trackName, animationKeys, propertyName, destTracks ) {
  16124. // only return track if there are actually keys.
  16125. if ( animationKeys.length !== 0 ) {
  16126. var times = [];
  16127. var values = [];
  16128. exports.AnimationUtils.flattenJSON(
  16129. animationKeys, times, values, propertyName );
  16130. // empty keys are filtered out, so check again
  16131. if ( times.length !== 0 ) {
  16132. destTracks.push( new trackType( trackName, times, values ) );
  16133. }
  16134. }
  16135. };
  16136. var tracks = [];
  16137. var clipName = animation.name || 'default';
  16138. // automatic length determination in AnimationClip.
  16139. var duration = animation.length || -1;
  16140. var fps = animation.fps || 30;
  16141. var hierarchyTracks = animation.hierarchy || [];
  16142. for ( var h = 0; h < hierarchyTracks.length; h ++ ) {
  16143. var animationKeys = hierarchyTracks[ h ].keys;
  16144. // skip empty tracks
  16145. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  16146. // process morph targets in a way exactly compatible
  16147. // with AnimationHandler.init( animation )
  16148. if ( animationKeys[0].morphTargets ) {
  16149. // figure out all morph targets used in this track
  16150. var morphTargetNames = {};
  16151. for ( var k = 0; k < animationKeys.length; k ++ ) {
  16152. if ( animationKeys[k].morphTargets ) {
  16153. for ( var m = 0; m < animationKeys[k].morphTargets.length; m ++ ) {
  16154. morphTargetNames[ animationKeys[k].morphTargets[m] ] = -1;
  16155. }
  16156. }
  16157. }
  16158. // create a track for each morph target with all zero
  16159. // morphTargetInfluences except for the keys in which
  16160. // the morphTarget is named.
  16161. for ( var morphTargetName in morphTargetNames ) {
  16162. var times = [];
  16163. var values = [];
  16164. for ( var m = 0;
  16165. m !== animationKeys[k].morphTargets.length; ++ m ) {
  16166. var animationKey = animationKeys[k];
  16167. times.push( animationKey.time );
  16168. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  16169. }
  16170. tracks.push( new NumberKeyframeTrack(
  16171. '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  16172. }
  16173. duration = morphTargetNames.length * ( fps || 1.0 );
  16174. } else {
  16175. // ...assume skeletal animation
  16176. var boneName = '.bones[' + bones[ h ].name + ']';
  16177. addNonemptyTrack(
  16178. VectorKeyframeTrack, boneName + '.position',
  16179. animationKeys, 'pos', tracks );
  16180. addNonemptyTrack(
  16181. QuaternionKeyframeTrack, boneName + '.quaternion',
  16182. animationKeys, 'rot', tracks );
  16183. addNonemptyTrack(
  16184. VectorKeyframeTrack, boneName + '.scale',
  16185. animationKeys, 'scl', tracks );
  16186. }
  16187. }
  16188. if ( tracks.length === 0 ) {
  16189. return null;
  16190. }
  16191. var clip = new AnimationClip( clipName, duration, tracks );
  16192. return clip;
  16193. }
  16194. } );
  16195. /**
  16196. * @author mrdoob / http://mrdoob.com/
  16197. */
  16198. function MaterialLoader( manager ) {
  16199. this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager;
  16200. this.textures = {};
  16201. }
  16202. Object.assign( MaterialLoader.prototype, {
  16203. load: function ( url, onLoad, onProgress, onError ) {
  16204. var scope = this;
  16205. var loader = new XHRLoader( scope.manager );
  16206. loader.load( url, function ( text ) {
  16207. onLoad( scope.parse( JSON.parse( text ) ) );
  16208. }, onProgress, onError );
  16209. },
  16210. setTextures: function ( value ) {
  16211. this.textures = value;
  16212. },
  16213. parse: function ( json ) {
  16214. var textures = this.textures;
  16215. function getTexture( name ) {
  16216. if ( textures[ name ] === undefined ) {
  16217. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  16218. }
  16219. return textures[ name ];
  16220. }
  16221. var material = new Materials[ json.type ]();
  16222. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  16223. if ( json.name !== undefined ) material.name = json.name;
  16224. if ( json.color !== undefined ) material.color.setHex( json.color );
  16225. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  16226. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  16227. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  16228. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  16229. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  16230. if ( json.uniforms !== undefined ) material.uniforms = json.uniforms;
  16231. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  16232. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  16233. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  16234. if ( json.fog !== undefined ) material.fog = json.fog;
  16235. if ( json.shading !== undefined ) material.shading = json.shading;
  16236. if ( json.blending !== undefined ) material.blending = json.blending;
  16237. if ( json.side !== undefined ) material.side = json.side;
  16238. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  16239. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  16240. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  16241. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  16242. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  16243. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  16244. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  16245. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  16246. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  16247. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  16248. if ( json.skinning !== undefined ) material.skinning = json.skinning;
  16249. if ( json.morphTargets !== undefined ) material.morphTargets = json.morphTargets;
  16250. // for PointsMaterial
  16251. if ( json.size !== undefined ) material.size = json.size;
  16252. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  16253. // maps
  16254. if ( json.map !== undefined ) material.map = getTexture( json.map );
  16255. if ( json.alphaMap !== undefined ) {
  16256. material.alphaMap = getTexture( json.alphaMap );
  16257. material.transparent = true;
  16258. }
  16259. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  16260. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  16261. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  16262. if ( json.normalScale !== undefined ) {
  16263. var normalScale = json.normalScale;
  16264. if ( Array.isArray( normalScale ) === false ) {
  16265. // Blender exporter used to export a scalar. See #7459
  16266. normalScale = [ normalScale, normalScale ];
  16267. }
  16268. material.normalScale = new Vector2().fromArray( normalScale );
  16269. }
  16270. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  16271. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  16272. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  16273. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  16274. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  16275. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  16276. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  16277. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  16278. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  16279. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  16280. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  16281. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  16282. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  16283. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  16284. // MultiMaterial
  16285. if ( json.materials !== undefined ) {
  16286. for ( var i = 0, l = json.materials.length; i < l; i ++ ) {
  16287. material.materials.push( this.parse( json.materials[ i ] ) );
  16288. }
  16289. }
  16290. return material;
  16291. }
  16292. } );
  16293. /**
  16294. * @author mrdoob / http://mrdoob.com/
  16295. */
  16296. function BufferGeometryLoader( manager ) {
  16297. this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager;
  16298. }
  16299. Object.assign( BufferGeometryLoader.prototype, {
  16300. load: function ( url, onLoad, onProgress, onError ) {
  16301. var scope = this;
  16302. var loader = new XHRLoader( scope.manager );
  16303. loader.load( url, function ( text ) {
  16304. onLoad( scope.parse( JSON.parse( text ) ) );
  16305. }, onProgress, onError );
  16306. },
  16307. parse: function ( json ) {
  16308. var geometry = new BufferGeometry();
  16309. var index = json.data.index;
  16310. var TYPED_ARRAYS = {
  16311. 'Int8Array': Int8Array,
  16312. 'Uint8Array': Uint8Array,
  16313. 'Uint8ClampedArray': Uint8ClampedArray,
  16314. 'Int16Array': Int16Array,
  16315. 'Uint16Array': Uint16Array,
  16316. 'Int32Array': Int32Array,
  16317. 'Uint32Array': Uint32Array,
  16318. 'Float32Array': Float32Array,
  16319. 'Float64Array': Float64Array
  16320. };
  16321. if ( index !== undefined ) {
  16322. var typedArray = new TYPED_ARRAYS[ index.type ]( index.array );
  16323. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  16324. }
  16325. var attributes = json.data.attributes;
  16326. for ( var key in attributes ) {
  16327. var attribute = attributes[ key ];
  16328. var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array );
  16329. geometry.addAttribute( key, new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ) );
  16330. }
  16331. var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  16332. if ( groups !== undefined ) {
  16333. for ( var i = 0, n = groups.length; i !== n; ++ i ) {
  16334. var group = groups[ i ];
  16335. geometry.addGroup( group.start, group.count, group.materialIndex );
  16336. }
  16337. }
  16338. var boundingSphere = json.data.boundingSphere;
  16339. if ( boundingSphere !== undefined ) {
  16340. var center = new Vector3();
  16341. if ( boundingSphere.center !== undefined ) {
  16342. center.fromArray( boundingSphere.center );
  16343. }
  16344. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  16345. }
  16346. return geometry;
  16347. }
  16348. } );
  16349. /**
  16350. * @author alteredq / http://alteredqualia.com/
  16351. */
  16352. function Loader() {
  16353. this.onLoadStart = function () {};
  16354. this.onLoadProgress = function () {};
  16355. this.onLoadComplete = function () {};
  16356. }
  16357. Loader.prototype = {
  16358. constructor: Loader,
  16359. crossOrigin: undefined,
  16360. extractUrlBase: function ( url ) {
  16361. var parts = url.split( '/' );
  16362. if ( parts.length === 1 ) return './';
  16363. parts.pop();
  16364. return parts.join( '/' ) + '/';
  16365. },
  16366. initMaterials: function ( materials, texturePath, crossOrigin ) {
  16367. var array = [];
  16368. for ( var i = 0; i < materials.length; ++ i ) {
  16369. array[ i ] = this.createMaterial( materials[ i ], texturePath, crossOrigin );
  16370. }
  16371. return array;
  16372. },
  16373. createMaterial: ( function () {
  16374. var color, textureLoader, materialLoader;
  16375. return function createMaterial( m, texturePath, crossOrigin ) {
  16376. if ( color === undefined ) color = new Color();
  16377. if ( textureLoader === undefined ) textureLoader = new TextureLoader();
  16378. if ( materialLoader === undefined ) materialLoader = new MaterialLoader();
  16379. // convert from old material format
  16380. var textures = {};
  16381. function loadTexture( path, repeat, offset, wrap, anisotropy ) {
  16382. var fullPath = texturePath + path;
  16383. var loader = Loader.Handlers.get( fullPath );
  16384. var texture;
  16385. if ( loader !== null ) {
  16386. texture = loader.load( fullPath );
  16387. } else {
  16388. textureLoader.setCrossOrigin( crossOrigin );
  16389. texture = textureLoader.load( fullPath );
  16390. }
  16391. if ( repeat !== undefined ) {
  16392. texture.repeat.fromArray( repeat );
  16393. if ( repeat[ 0 ] !== 1 ) texture.wrapS = RepeatWrapping;
  16394. if ( repeat[ 1 ] !== 1 ) texture.wrapT = RepeatWrapping;
  16395. }
  16396. if ( offset !== undefined ) {
  16397. texture.offset.fromArray( offset );
  16398. }
  16399. if ( wrap !== undefined ) {
  16400. if ( wrap[ 0 ] === 'repeat' ) texture.wrapS = RepeatWrapping;
  16401. if ( wrap[ 0 ] === 'mirror' ) texture.wrapS = MirroredRepeatWrapping;
  16402. if ( wrap[ 1 ] === 'repeat' ) texture.wrapT = RepeatWrapping;
  16403. if ( wrap[ 1 ] === 'mirror' ) texture.wrapT = MirroredRepeatWrapping;
  16404. }
  16405. if ( anisotropy !== undefined ) {
  16406. texture.anisotropy = anisotropy;
  16407. }
  16408. var uuid = exports.Math.generateUUID();
  16409. textures[ uuid ] = texture;
  16410. return uuid;
  16411. }
  16412. //
  16413. var json = {
  16414. uuid: exports.Math.generateUUID(),
  16415. type: 'MeshLambertMaterial'
  16416. };
  16417. for ( var name in m ) {
  16418. var value = m[ name ];
  16419. switch ( name ) {
  16420. case 'DbgColor':
  16421. case 'DbgIndex':
  16422. case 'opticalDensity':
  16423. case 'illumination':
  16424. break;
  16425. case 'DbgName':
  16426. json.name = value;
  16427. break;
  16428. case 'blending':
  16429. json.blending = BlendingMode[ value ];
  16430. break;
  16431. case 'colorAmbient':
  16432. case 'mapAmbient':
  16433. console.warn( 'THREE.Loader.createMaterial:', name, 'is no longer supported.' );
  16434. break;
  16435. case 'colorDiffuse':
  16436. json.color = color.fromArray( value ).getHex();
  16437. break;
  16438. case 'colorSpecular':
  16439. json.specular = color.fromArray( value ).getHex();
  16440. break;
  16441. case 'colorEmissive':
  16442. json.emissive = color.fromArray( value ).getHex();
  16443. break;
  16444. case 'specularCoef':
  16445. json.shininess = value;
  16446. break;
  16447. case 'shading':
  16448. if ( value.toLowerCase() === 'basic' ) json.type = 'MeshBasicMaterial';
  16449. if ( value.toLowerCase() === 'phong' ) json.type = 'MeshPhongMaterial';
  16450. if ( value.toLowerCase() === 'standard' ) json.type = 'MeshStandardMaterial';
  16451. break;
  16452. case 'mapDiffuse':
  16453. json.map = loadTexture( value, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  16454. break;
  16455. case 'mapDiffuseRepeat':
  16456. case 'mapDiffuseOffset':
  16457. case 'mapDiffuseWrap':
  16458. case 'mapDiffuseAnisotropy':
  16459. break;
  16460. case 'mapEmissive':
  16461. json.emissiveMap = loadTexture( value, m.mapEmissiveRepeat, m.mapEmissiveOffset, m.mapEmissiveWrap, m.mapEmissiveAnisotropy );
  16462. break;
  16463. case 'mapEmissiveRepeat':
  16464. case 'mapEmissiveOffset':
  16465. case 'mapEmissiveWrap':
  16466. case 'mapEmissiveAnisotropy':
  16467. break;
  16468. case 'mapLight':
  16469. json.lightMap = loadTexture( value, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  16470. break;
  16471. case 'mapLightRepeat':
  16472. case 'mapLightOffset':
  16473. case 'mapLightWrap':
  16474. case 'mapLightAnisotropy':
  16475. break;
  16476. case 'mapAO':
  16477. json.aoMap = loadTexture( value, m.mapAORepeat, m.mapAOOffset, m.mapAOWrap, m.mapAOAnisotropy );
  16478. break;
  16479. case 'mapAORepeat':
  16480. case 'mapAOOffset':
  16481. case 'mapAOWrap':
  16482. case 'mapAOAnisotropy':
  16483. break;
  16484. case 'mapBump':
  16485. json.bumpMap = loadTexture( value, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  16486. break;
  16487. case 'mapBumpScale':
  16488. json.bumpScale = value;
  16489. break;
  16490. case 'mapBumpRepeat':
  16491. case 'mapBumpOffset':
  16492. case 'mapBumpWrap':
  16493. case 'mapBumpAnisotropy':
  16494. break;
  16495. case 'mapNormal':
  16496. json.normalMap = loadTexture( value, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  16497. break;
  16498. case 'mapNormalFactor':
  16499. json.normalScale = [ value, value ];
  16500. break;
  16501. case 'mapNormalRepeat':
  16502. case 'mapNormalOffset':
  16503. case 'mapNormalWrap':
  16504. case 'mapNormalAnisotropy':
  16505. break;
  16506. case 'mapSpecular':
  16507. json.specularMap = loadTexture( value, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  16508. break;
  16509. case 'mapSpecularRepeat':
  16510. case 'mapSpecularOffset':
  16511. case 'mapSpecularWrap':
  16512. case 'mapSpecularAnisotropy':
  16513. break;
  16514. case 'mapMetalness':
  16515. json.metalnessMap = loadTexture( value, m.mapMetalnessRepeat, m.mapMetalnessOffset, m.mapMetalnessWrap, m.mapMetalnessAnisotropy );
  16516. break;
  16517. case 'mapMetalnessRepeat':
  16518. case 'mapMetalnessOffset':
  16519. case 'mapMetalnessWrap':
  16520. case 'mapMetalnessAnisotropy':
  16521. break;
  16522. case 'mapRoughness':
  16523. json.roughnessMap = loadTexture( value, m.mapRoughnessRepeat, m.mapRoughnessOffset, m.mapRoughnessWrap, m.mapRoughnessAnisotropy );
  16524. break;
  16525. case 'mapRoughnessRepeat':
  16526. case 'mapRoughnessOffset':
  16527. case 'mapRoughnessWrap':
  16528. case 'mapRoughnessAnisotropy':
  16529. break;
  16530. case 'mapAlpha':
  16531. json.alphaMap = loadTexture( value, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy );
  16532. break;
  16533. case 'mapAlphaRepeat':
  16534. case 'mapAlphaOffset':
  16535. case 'mapAlphaWrap':
  16536. case 'mapAlphaAnisotropy':
  16537. break;
  16538. case 'flipSided':
  16539. json.side = BackSide;
  16540. break;
  16541. case 'doubleSided':
  16542. json.side = DoubleSide;
  16543. break;
  16544. case 'transparency':
  16545. console.warn( 'THREE.Loader.createMaterial: transparency has been renamed to opacity' );
  16546. json.opacity = value;
  16547. break;
  16548. case 'depthTest':
  16549. case 'depthWrite':
  16550. case 'colorWrite':
  16551. case 'opacity':
  16552. case 'reflectivity':
  16553. case 'transparent':
  16554. case 'visible':
  16555. case 'wireframe':
  16556. json[ name ] = value;
  16557. break;
  16558. case 'vertexColors':
  16559. if ( value === true ) json.vertexColors = VertexColors;
  16560. if ( value === 'face' ) json.vertexColors = FaceColors;
  16561. break;
  16562. default:
  16563. console.error( 'THREE.Loader.createMaterial: Unsupported', name, value );
  16564. break;
  16565. }
  16566. }
  16567. if ( json.type === 'MeshBasicMaterial' ) delete json.emissive;
  16568. if ( json.type !== 'MeshPhongMaterial' ) delete json.specular;
  16569. if ( json.opacity < 1 ) json.transparent = true;
  16570. materialLoader.setTextures( textures );
  16571. return materialLoader.parse( json );
  16572. };
  16573. } )()
  16574. };
  16575. Loader.Handlers = {
  16576. handlers: [],
  16577. add: function ( regex, loader ) {
  16578. this.handlers.push( regex, loader );
  16579. },
  16580. get: function ( file ) {
  16581. var handlers = this.handlers;
  16582. for ( var i = 0, l = handlers.length; i < l; i += 2 ) {
  16583. var regex = handlers[ i ];
  16584. var loader = handlers[ i + 1 ];
  16585. if ( regex.test( file ) ) {
  16586. return loader;
  16587. }
  16588. }
  16589. return null;
  16590. }
  16591. };
  16592. /**
  16593. * @author mrdoob / http://mrdoob.com/
  16594. * @author alteredq / http://alteredqualia.com/
  16595. */
  16596. function JSONLoader( manager ) {
  16597. if ( typeof manager === 'boolean' ) {
  16598. console.warn( 'THREE.JSONLoader: showStatus parameter has been removed from constructor.' );
  16599. manager = undefined;
  16600. }
  16601. this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager;
  16602. this.withCredentials = false;
  16603. }
  16604. Object.assign( JSONLoader.prototype, {
  16605. load: function( url, onLoad, onProgress, onError ) {
  16606. var scope = this;
  16607. var texturePath = this.texturePath && ( typeof this.texturePath === "string" ) ? this.texturePath : Loader.prototype.extractUrlBase( url );
  16608. var loader = new XHRLoader( this.manager );
  16609. loader.setWithCredentials( this.withCredentials );
  16610. loader.load( url, function ( text ) {
  16611. var json = JSON.parse( text );
  16612. var metadata = json.metadata;
  16613. if ( metadata !== undefined ) {
  16614. var type = metadata.type;
  16615. if ( type !== undefined ) {
  16616. if ( type.toLowerCase() === 'object' ) {
  16617. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' );
  16618. return;
  16619. }
  16620. if ( type.toLowerCase() === 'scene' ) {
  16621. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.SceneLoader instead.' );
  16622. return;
  16623. }
  16624. }
  16625. }
  16626. var object = scope.parse( json, texturePath );
  16627. onLoad( object.geometry, object.materials );
  16628. }, onProgress, onError );
  16629. },
  16630. setTexturePath: function ( value ) {
  16631. this.texturePath = value;
  16632. },
  16633. parse: function ( json, texturePath ) {
  16634. var geometry = new Geometry(),
  16635. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  16636. parseModel( scale );
  16637. parseSkin();
  16638. parseMorphing( scale );
  16639. parseAnimations();
  16640. geometry.computeFaceNormals();
  16641. geometry.computeBoundingSphere();
  16642. function parseModel( scale ) {
  16643. function isBitSet( value, position ) {
  16644. return value & ( 1 << position );
  16645. }
  16646. var i, j, fi,
  16647. offset, zLength,
  16648. colorIndex, normalIndex, uvIndex, materialIndex,
  16649. type,
  16650. isQuad,
  16651. hasMaterial,
  16652. hasFaceVertexUv,
  16653. hasFaceNormal, hasFaceVertexNormal,
  16654. hasFaceColor, hasFaceVertexColor,
  16655. vertex, face, faceA, faceB, hex, normal,
  16656. uvLayer, uv, u, v,
  16657. faces = json.faces,
  16658. vertices = json.vertices,
  16659. normals = json.normals,
  16660. colors = json.colors,
  16661. nUvLayers = 0;
  16662. if ( json.uvs !== undefined ) {
  16663. // disregard empty arrays
  16664. for ( i = 0; i < json.uvs.length; i ++ ) {
  16665. if ( json.uvs[ i ].length ) nUvLayers ++;
  16666. }
  16667. for ( i = 0; i < nUvLayers; i ++ ) {
  16668. geometry.faceVertexUvs[ i ] = [];
  16669. }
  16670. }
  16671. offset = 0;
  16672. zLength = vertices.length;
  16673. while ( offset < zLength ) {
  16674. vertex = new Vector3();
  16675. vertex.x = vertices[ offset ++ ] * scale;
  16676. vertex.y = vertices[ offset ++ ] * scale;
  16677. vertex.z = vertices[ offset ++ ] * scale;
  16678. geometry.vertices.push( vertex );
  16679. }
  16680. offset = 0;
  16681. zLength = faces.length;
  16682. while ( offset < zLength ) {
  16683. type = faces[ offset ++ ];
  16684. isQuad = isBitSet( type, 0 );
  16685. hasMaterial = isBitSet( type, 1 );
  16686. hasFaceVertexUv = isBitSet( type, 3 );
  16687. hasFaceNormal = isBitSet( type, 4 );
  16688. hasFaceVertexNormal = isBitSet( type, 5 );
  16689. hasFaceColor = isBitSet( type, 6 );
  16690. hasFaceVertexColor = isBitSet( type, 7 );
  16691. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  16692. if ( isQuad ) {
  16693. faceA = new Face3();
  16694. faceA.a = faces[ offset ];
  16695. faceA.b = faces[ offset + 1 ];
  16696. faceA.c = faces[ offset + 3 ];
  16697. faceB = new Face3();
  16698. faceB.a = faces[ offset + 1 ];
  16699. faceB.b = faces[ offset + 2 ];
  16700. faceB.c = faces[ offset + 3 ];
  16701. offset += 4;
  16702. if ( hasMaterial ) {
  16703. materialIndex = faces[ offset ++ ];
  16704. faceA.materialIndex = materialIndex;
  16705. faceB.materialIndex = materialIndex;
  16706. }
  16707. // to get face <=> uv index correspondence
  16708. fi = geometry.faces.length;
  16709. if ( hasFaceVertexUv ) {
  16710. for ( i = 0; i < nUvLayers; i ++ ) {
  16711. uvLayer = json.uvs[ i ];
  16712. geometry.faceVertexUvs[ i ][ fi ] = [];
  16713. geometry.faceVertexUvs[ i ][ fi + 1 ] = [];
  16714. for ( j = 0; j < 4; j ++ ) {
  16715. uvIndex = faces[ offset ++ ];
  16716. u = uvLayer[ uvIndex * 2 ];
  16717. v = uvLayer[ uvIndex * 2 + 1 ];
  16718. uv = new Vector2( u, v );
  16719. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  16720. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  16721. }
  16722. }
  16723. }
  16724. if ( hasFaceNormal ) {
  16725. normalIndex = faces[ offset ++ ] * 3;
  16726. faceA.normal.set(
  16727. normals[ normalIndex ++ ],
  16728. normals[ normalIndex ++ ],
  16729. normals[ normalIndex ]
  16730. );
  16731. faceB.normal.copy( faceA.normal );
  16732. }
  16733. if ( hasFaceVertexNormal ) {
  16734. for ( i = 0; i < 4; i ++ ) {
  16735. normalIndex = faces[ offset ++ ] * 3;
  16736. normal = new Vector3(
  16737. normals[ normalIndex ++ ],
  16738. normals[ normalIndex ++ ],
  16739. normals[ normalIndex ]
  16740. );
  16741. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  16742. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  16743. }
  16744. }
  16745. if ( hasFaceColor ) {
  16746. colorIndex = faces[ offset ++ ];
  16747. hex = colors[ colorIndex ];
  16748. faceA.color.setHex( hex );
  16749. faceB.color.setHex( hex );
  16750. }
  16751. if ( hasFaceVertexColor ) {
  16752. for ( i = 0; i < 4; i ++ ) {
  16753. colorIndex = faces[ offset ++ ];
  16754. hex = colors[ colorIndex ];
  16755. if ( i !== 2 ) faceA.vertexColors.push( new Color( hex ) );
  16756. if ( i !== 0 ) faceB.vertexColors.push( new Color( hex ) );
  16757. }
  16758. }
  16759. geometry.faces.push( faceA );
  16760. geometry.faces.push( faceB );
  16761. } else {
  16762. face = new Face3();
  16763. face.a = faces[ offset ++ ];
  16764. face.b = faces[ offset ++ ];
  16765. face.c = faces[ offset ++ ];
  16766. if ( hasMaterial ) {
  16767. materialIndex = faces[ offset ++ ];
  16768. face.materialIndex = materialIndex;
  16769. }
  16770. // to get face <=> uv index correspondence
  16771. fi = geometry.faces.length;
  16772. if ( hasFaceVertexUv ) {
  16773. for ( i = 0; i < nUvLayers; i ++ ) {
  16774. uvLayer = json.uvs[ i ];
  16775. geometry.faceVertexUvs[ i ][ fi ] = [];
  16776. for ( j = 0; j < 3; j ++ ) {
  16777. uvIndex = faces[ offset ++ ];
  16778. u = uvLayer[ uvIndex * 2 ];
  16779. v = uvLayer[ uvIndex * 2 + 1 ];
  16780. uv = new Vector2( u, v );
  16781. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  16782. }
  16783. }
  16784. }
  16785. if ( hasFaceNormal ) {
  16786. normalIndex = faces[ offset ++ ] * 3;
  16787. face.normal.set(
  16788. normals[ normalIndex ++ ],
  16789. normals[ normalIndex ++ ],
  16790. normals[ normalIndex ]
  16791. );
  16792. }
  16793. if ( hasFaceVertexNormal ) {
  16794. for ( i = 0; i < 3; i ++ ) {
  16795. normalIndex = faces[ offset ++ ] * 3;
  16796. normal = new Vector3(
  16797. normals[ normalIndex ++ ],
  16798. normals[ normalIndex ++ ],
  16799. normals[ normalIndex ]
  16800. );
  16801. face.vertexNormals.push( normal );
  16802. }
  16803. }
  16804. if ( hasFaceColor ) {
  16805. colorIndex = faces[ offset ++ ];
  16806. face.color.setHex( colors[ colorIndex ] );
  16807. }
  16808. if ( hasFaceVertexColor ) {
  16809. for ( i = 0; i < 3; i ++ ) {
  16810. colorIndex = faces[ offset ++ ];
  16811. face.vertexColors.push( new Color( colors[ colorIndex ] ) );
  16812. }
  16813. }
  16814. geometry.faces.push( face );
  16815. }
  16816. }
  16817. }
  16818. function parseSkin() {
  16819. var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2;
  16820. if ( json.skinWeights ) {
  16821. for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {
  16822. var x = json.skinWeights[ i ];
  16823. var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
  16824. var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
  16825. var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;
  16826. geometry.skinWeights.push( new Vector4( x, y, z, w ) );
  16827. }
  16828. }
  16829. if ( json.skinIndices ) {
  16830. for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {
  16831. var a = json.skinIndices[ i ];
  16832. var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
  16833. var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
  16834. var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;
  16835. geometry.skinIndices.push( new Vector4( a, b, c, d ) );
  16836. }
  16837. }
  16838. geometry.bones = json.bones;
  16839. if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {
  16840. console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
  16841. geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );
  16842. }
  16843. }
  16844. function parseMorphing( scale ) {
  16845. if ( json.morphTargets !== undefined ) {
  16846. for ( var i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  16847. geometry.morphTargets[ i ] = {};
  16848. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  16849. geometry.morphTargets[ i ].vertices = [];
  16850. var dstVertices = geometry.morphTargets[ i ].vertices;
  16851. var srcVertices = json.morphTargets[ i ].vertices;
  16852. for ( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  16853. var vertex = new Vector3();
  16854. vertex.x = srcVertices[ v ] * scale;
  16855. vertex.y = srcVertices[ v + 1 ] * scale;
  16856. vertex.z = srcVertices[ v + 2 ] * scale;
  16857. dstVertices.push( vertex );
  16858. }
  16859. }
  16860. }
  16861. if ( json.morphColors !== undefined && json.morphColors.length > 0 ) {
  16862. console.warn( 'THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.' );
  16863. var faces = geometry.faces;
  16864. var morphColors = json.morphColors[ 0 ].colors;
  16865. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  16866. faces[ i ].color.fromArray( morphColors, i * 3 );
  16867. }
  16868. }
  16869. }
  16870. function parseAnimations() {
  16871. var outputAnimations = [];
  16872. // parse old style Bone/Hierarchy animations
  16873. var animations = [];
  16874. if ( json.animation !== undefined ) {
  16875. animations.push( json.animation );
  16876. }
  16877. if ( json.animations !== undefined ) {
  16878. if ( json.animations.length ) {
  16879. animations = animations.concat( json.animations );
  16880. } else {
  16881. animations.push( json.animations );
  16882. }
  16883. }
  16884. for ( var i = 0; i < animations.length; i ++ ) {
  16885. var clip = AnimationClip.parseAnimation( animations[ i ], geometry.bones );
  16886. if ( clip ) outputAnimations.push( clip );
  16887. }
  16888. // parse implicit morph animations
  16889. if ( geometry.morphTargets ) {
  16890. // TODO: Figure out what an appropraite FPS is for morph target animations -- defaulting to 10, but really it is completely arbitrary.
  16891. var morphAnimationClips = AnimationClip.CreateClipsFromMorphTargetSequences( geometry.morphTargets, 10 );
  16892. outputAnimations = outputAnimations.concat( morphAnimationClips );
  16893. }
  16894. if ( outputAnimations.length > 0 ) geometry.animations = outputAnimations;
  16895. }
  16896. if ( json.materials === undefined || json.materials.length === 0 ) {
  16897. return { geometry: geometry };
  16898. } else {
  16899. var materials = Loader.prototype.initMaterials( json.materials, texturePath, this.crossOrigin );
  16900. return { geometry: geometry, materials: materials };
  16901. }
  16902. }
  16903. } );
  16904. /**
  16905. * @author mrdoob / http://mrdoob.com/
  16906. */
  16907. function WireframeGeometry( geometry ) {
  16908. BufferGeometry.call( this );
  16909. var edge = [ 0, 0 ], hash = {};
  16910. function sortFunction( a, b ) {
  16911. return a - b;
  16912. }
  16913. var keys = [ 'a', 'b', 'c' ];
  16914. if ( (geometry && geometry.isGeometry) ) {
  16915. var vertices = geometry.vertices;
  16916. var faces = geometry.faces;
  16917. var numEdges = 0;
  16918. // allocate maximal size
  16919. var edges = new Uint32Array( 6 * faces.length );
  16920. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  16921. var face = faces[ i ];
  16922. for ( var j = 0; j < 3; j ++ ) {
  16923. edge[ 0 ] = face[ keys[ j ] ];
  16924. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  16925. edge.sort( sortFunction );
  16926. var key = edge.toString();
  16927. if ( hash[ key ] === undefined ) {
  16928. edges[ 2 * numEdges ] = edge[ 0 ];
  16929. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  16930. hash[ key ] = true;
  16931. numEdges ++;
  16932. }
  16933. }
  16934. }
  16935. var coords = new Float32Array( numEdges * 2 * 3 );
  16936. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  16937. for ( var j = 0; j < 2; j ++ ) {
  16938. var vertex = vertices[ edges [ 2 * i + j ] ];
  16939. var index = 6 * i + 3 * j;
  16940. coords[ index + 0 ] = vertex.x;
  16941. coords[ index + 1 ] = vertex.y;
  16942. coords[ index + 2 ] = vertex.z;
  16943. }
  16944. }
  16945. this.addAttribute( 'position', new BufferAttribute( coords, 3 ) );
  16946. } else if ( (geometry && geometry.isBufferGeometry) ) {
  16947. if ( geometry.index !== null ) {
  16948. // Indexed BufferGeometry
  16949. var indices = geometry.index.array;
  16950. var vertices = geometry.attributes.position;
  16951. var groups = geometry.groups;
  16952. var numEdges = 0;
  16953. if ( groups.length === 0 ) {
  16954. geometry.addGroup( 0, indices.length );
  16955. }
  16956. // allocate maximal size
  16957. var edges = new Uint32Array( 2 * indices.length );
  16958. for ( var o = 0, ol = groups.length; o < ol; ++ o ) {
  16959. var group = groups[ o ];
  16960. var start = group.start;
  16961. var count = group.count;
  16962. for ( var i = start, il = start + count; i < il; i += 3 ) {
  16963. for ( var j = 0; j < 3; j ++ ) {
  16964. edge[ 0 ] = indices[ i + j ];
  16965. edge[ 1 ] = indices[ i + ( j + 1 ) % 3 ];
  16966. edge.sort( sortFunction );
  16967. var key = edge.toString();
  16968. if ( hash[ key ] === undefined ) {
  16969. edges[ 2 * numEdges ] = edge[ 0 ];
  16970. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  16971. hash[ key ] = true;
  16972. numEdges ++;
  16973. }
  16974. }
  16975. }
  16976. }
  16977. var coords = new Float32Array( numEdges * 2 * 3 );
  16978. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  16979. for ( var j = 0; j < 2; j ++ ) {
  16980. var index = 6 * i + 3 * j;
  16981. var index2 = edges[ 2 * i + j ];
  16982. coords[ index + 0 ] = vertices.getX( index2 );
  16983. coords[ index + 1 ] = vertices.getY( index2 );
  16984. coords[ index + 2 ] = vertices.getZ( index2 );
  16985. }
  16986. }
  16987. this.addAttribute( 'position', new BufferAttribute( coords, 3 ) );
  16988. } else {
  16989. // non-indexed BufferGeometry
  16990. var vertices = geometry.attributes.position.array;
  16991. var numEdges = vertices.length / 3;
  16992. var numTris = numEdges / 3;
  16993. var coords = new Float32Array( numEdges * 2 * 3 );
  16994. for ( var i = 0, l = numTris; i < l; i ++ ) {
  16995. for ( var j = 0; j < 3; j ++ ) {
  16996. var index = 18 * i + 6 * j;
  16997. var index1 = 9 * i + 3 * j;
  16998. coords[ index + 0 ] = vertices[ index1 ];
  16999. coords[ index + 1 ] = vertices[ index1 + 1 ];
  17000. coords[ index + 2 ] = vertices[ index1 + 2 ];
  17001. var index2 = 9 * i + 3 * ( ( j + 1 ) % 3 );
  17002. coords[ index + 3 ] = vertices[ index2 ];
  17003. coords[ index + 4 ] = vertices[ index2 + 1 ];
  17004. coords[ index + 5 ] = vertices[ index2 + 2 ];
  17005. }
  17006. }
  17007. this.addAttribute( 'position', new BufferAttribute( coords, 3 ) );
  17008. }
  17009. }
  17010. }
  17011. WireframeGeometry.prototype = Object.create( BufferGeometry.prototype );
  17012. WireframeGeometry.prototype.constructor = WireframeGeometry;
  17013. /**
  17014. * @author zz85 / https://github.com/zz85
  17015. * Parametric Surfaces Geometry
  17016. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  17017. *
  17018. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements );
  17019. *
  17020. */
  17021. function ParametricGeometry( func, slices, stacks ) {
  17022. Geometry.call( this );
  17023. this.type = 'ParametricGeometry';
  17024. this.parameters = {
  17025. func: func,
  17026. slices: slices,
  17027. stacks: stacks
  17028. };
  17029. var verts = this.vertices;
  17030. var faces = this.faces;
  17031. var uvs = this.faceVertexUvs[ 0 ];
  17032. var i, j, p;
  17033. var u, v;
  17034. var sliceCount = slices + 1;
  17035. for ( i = 0; i <= stacks; i ++ ) {
  17036. v = i / stacks;
  17037. for ( j = 0; j <= slices; j ++ ) {
  17038. u = j / slices;
  17039. p = func( u, v );
  17040. verts.push( p );
  17041. }
  17042. }
  17043. var a, b, c, d;
  17044. var uva, uvb, uvc, uvd;
  17045. for ( i = 0; i < stacks; i ++ ) {
  17046. for ( j = 0; j < slices; j ++ ) {
  17047. a = i * sliceCount + j;
  17048. b = i * sliceCount + j + 1;
  17049. c = ( i + 1 ) * sliceCount + j + 1;
  17050. d = ( i + 1 ) * sliceCount + j;
  17051. uva = new Vector2( j / slices, i / stacks );
  17052. uvb = new Vector2( ( j + 1 ) / slices, i / stacks );
  17053. uvc = new Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  17054. uvd = new Vector2( j / slices, ( i + 1 ) / stacks );
  17055. faces.push( new Face3( a, b, d ) );
  17056. uvs.push( [ uva, uvb, uvd ] );
  17057. faces.push( new Face3( b, c, d ) );
  17058. uvs.push( [ uvb.clone(), uvc, uvd.clone() ] );
  17059. }
  17060. }
  17061. // console.log(this);
  17062. // magic bullet
  17063. // var diff = this.mergeVertices();
  17064. // console.log('removed ', diff, ' vertices by merging');
  17065. this.computeFaceNormals();
  17066. this.computeVertexNormals();
  17067. }
  17068. ParametricGeometry.prototype = Object.create( Geometry.prototype );
  17069. ParametricGeometry.prototype.constructor = ParametricGeometry;
  17070. /**
  17071. * @author clockworkgeek / https://github.com/clockworkgeek
  17072. * @author timothypratley / https://github.com/timothypratley
  17073. * @author WestLangley / http://github.com/WestLangley
  17074. */
  17075. function PolyhedronGeometry( vertices, indices, radius, detail ) {
  17076. Geometry.call( this );
  17077. this.type = 'PolyhedronGeometry';
  17078. this.parameters = {
  17079. vertices: vertices,
  17080. indices: indices,
  17081. radius: radius,
  17082. detail: detail
  17083. };
  17084. radius = radius || 1;
  17085. detail = detail || 0;
  17086. var that = this;
  17087. for ( var i = 0, l = vertices.length; i < l; i += 3 ) {
  17088. prepare( new Vector3( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] ) );
  17089. }
  17090. var p = this.vertices;
  17091. var faces = [];
  17092. for ( var i = 0, j = 0, l = indices.length; i < l; i += 3, j ++ ) {
  17093. var v1 = p[ indices[ i ] ];
  17094. var v2 = p[ indices[ i + 1 ] ];
  17095. var v3 = p[ indices[ i + 2 ] ];
  17096. faces[ j ] = new Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  17097. }
  17098. var centroid = new Vector3();
  17099. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  17100. subdivide( faces[ i ], detail );
  17101. }
  17102. // Handle case when face straddles the seam
  17103. for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) {
  17104. var uvs = this.faceVertexUvs[ 0 ][ i ];
  17105. var x0 = uvs[ 0 ].x;
  17106. var x1 = uvs[ 1 ].x;
  17107. var x2 = uvs[ 2 ].x;
  17108. var max = Math.max( x0, x1, x2 );
  17109. var min = Math.min( x0, x1, x2 );
  17110. if ( max > 0.9 && min < 0.1 ) {
  17111. // 0.9 is somewhat arbitrary
  17112. if ( x0 < 0.2 ) uvs[ 0 ].x += 1;
  17113. if ( x1 < 0.2 ) uvs[ 1 ].x += 1;
  17114. if ( x2 < 0.2 ) uvs[ 2 ].x += 1;
  17115. }
  17116. }
  17117. // Apply radius
  17118. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  17119. this.vertices[ i ].multiplyScalar( radius );
  17120. }
  17121. // Merge vertices
  17122. this.mergeVertices();
  17123. this.computeFaceNormals();
  17124. this.boundingSphere = new Sphere( new Vector3(), radius );
  17125. // Project vector onto sphere's surface
  17126. function prepare( vector ) {
  17127. var vertex = vector.normalize().clone();
  17128. vertex.index = that.vertices.push( vertex ) - 1;
  17129. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  17130. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  17131. var v = inclination( vector ) / Math.PI + 0.5;
  17132. vertex.uv = new Vector2( u, 1 - v );
  17133. return vertex;
  17134. }
  17135. // Approximate a curved face with recursively sub-divided triangles.
  17136. function make( v1, v2, v3 ) {
  17137. var face = new Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  17138. that.faces.push( face );
  17139. centroid.copy( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  17140. var azi = azimuth( centroid );
  17141. that.faceVertexUvs[ 0 ].push( [
  17142. correctUV( v1.uv, v1, azi ),
  17143. correctUV( v2.uv, v2, azi ),
  17144. correctUV( v3.uv, v3, azi )
  17145. ] );
  17146. }
  17147. // Analytically subdivide a face to the required detail level.
  17148. function subdivide( face, detail ) {
  17149. var cols = Math.pow( 2, detail );
  17150. var a = prepare( that.vertices[ face.a ] );
  17151. var b = prepare( that.vertices[ face.b ] );
  17152. var c = prepare( that.vertices[ face.c ] );
  17153. var v = [];
  17154. // Construct all of the vertices for this subdivision.
  17155. for ( var i = 0 ; i <= cols; i ++ ) {
  17156. v[ i ] = [];
  17157. var aj = prepare( a.clone().lerp( c, i / cols ) );
  17158. var bj = prepare( b.clone().lerp( c, i / cols ) );
  17159. var rows = cols - i;
  17160. for ( var j = 0; j <= rows; j ++ ) {
  17161. if ( j === 0 && i === cols ) {
  17162. v[ i ][ j ] = aj;
  17163. } else {
  17164. v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) );
  17165. }
  17166. }
  17167. }
  17168. // Construct all of the faces.
  17169. for ( var i = 0; i < cols ; i ++ ) {
  17170. for ( var j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  17171. var k = Math.floor( j / 2 );
  17172. if ( j % 2 === 0 ) {
  17173. make(
  17174. v[ i ][ k + 1 ],
  17175. v[ i + 1 ][ k ],
  17176. v[ i ][ k ]
  17177. );
  17178. } else {
  17179. make(
  17180. v[ i ][ k + 1 ],
  17181. v[ i + 1 ][ k + 1 ],
  17182. v[ i + 1 ][ k ]
  17183. );
  17184. }
  17185. }
  17186. }
  17187. }
  17188. // Angle around the Y axis, counter-clockwise when looking from above.
  17189. function azimuth( vector ) {
  17190. return Math.atan2( vector.z, - vector.x );
  17191. }
  17192. // Angle above the XZ plane.
  17193. function inclination( vector ) {
  17194. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  17195. }
  17196. // Texture fixing helper. Spheres have some odd behaviours.
  17197. function correctUV( uv, vector, azimuth ) {
  17198. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new Vector2( uv.x - 1, uv.y );
  17199. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  17200. return uv.clone();
  17201. }
  17202. }
  17203. PolyhedronGeometry.prototype = Object.create( Geometry.prototype );
  17204. PolyhedronGeometry.prototype.constructor = PolyhedronGeometry;
  17205. /**
  17206. * @author timothypratley / https://github.com/timothypratley
  17207. */
  17208. function TetrahedronGeometry( radius, detail ) {
  17209. var vertices = [
  17210. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  17211. ];
  17212. var indices = [
  17213. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  17214. ];
  17215. PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  17216. this.type = 'TetrahedronGeometry';
  17217. this.parameters = {
  17218. radius: radius,
  17219. detail: detail
  17220. };
  17221. }
  17222. TetrahedronGeometry.prototype = Object.create( PolyhedronGeometry.prototype );
  17223. TetrahedronGeometry.prototype.constructor = TetrahedronGeometry;
  17224. /**
  17225. * @author timothypratley / https://github.com/timothypratley
  17226. */
  17227. function OctahedronGeometry( radius, detail ) {
  17228. var vertices = [
  17229. 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  17230. ];
  17231. var indices = [
  17232. 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2
  17233. ];
  17234. PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  17235. this.type = 'OctahedronGeometry';
  17236. this.parameters = {
  17237. radius: radius,
  17238. detail: detail
  17239. };
  17240. }
  17241. OctahedronGeometry.prototype = Object.create( PolyhedronGeometry.prototype );
  17242. OctahedronGeometry.prototype.constructor = OctahedronGeometry;
  17243. /**
  17244. * @author timothypratley / https://github.com/timothypratley
  17245. */
  17246. function IcosahedronGeometry( radius, detail ) {
  17247. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  17248. var vertices = [
  17249. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  17250. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  17251. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  17252. ];
  17253. var indices = [
  17254. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  17255. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  17256. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  17257. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  17258. ];
  17259. PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  17260. this.type = 'IcosahedronGeometry';
  17261. this.parameters = {
  17262. radius: radius,
  17263. detail: detail
  17264. };
  17265. }
  17266. IcosahedronGeometry.prototype = Object.create( PolyhedronGeometry.prototype );
  17267. IcosahedronGeometry.prototype.constructor = IcosahedronGeometry;
  17268. /**
  17269. * @author Abe Pazos / https://hamoid.com
  17270. */
  17271. function DodecahedronGeometry( radius, detail ) {
  17272. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  17273. var r = 1 / t;
  17274. var vertices = [
  17275. // (±1, ±1, ±1)
  17276. - 1, - 1, - 1, - 1, - 1, 1,
  17277. - 1, 1, - 1, - 1, 1, 1,
  17278. 1, - 1, - 1, 1, - 1, 1,
  17279. 1, 1, - 1, 1, 1, 1,
  17280. // (0, ±1/φ, ±φ)
  17281. 0, - r, - t, 0, - r, t,
  17282. 0, r, - t, 0, r, t,
  17283. // (±1/φ, ±φ, 0)
  17284. - r, - t, 0, - r, t, 0,
  17285. r, - t, 0, r, t, 0,
  17286. // (±φ, 0, ±1/φ)
  17287. - t, 0, - r, t, 0, - r,
  17288. - t, 0, r, t, 0, r
  17289. ];
  17290. var indices = [
  17291. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  17292. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  17293. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  17294. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  17295. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  17296. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  17297. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  17298. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  17299. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  17300. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  17301. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  17302. 1, 12, 14, 1, 14, 5, 1, 5, 9
  17303. ];
  17304. PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  17305. this.type = 'DodecahedronGeometry';
  17306. this.parameters = {
  17307. radius: radius,
  17308. detail: detail
  17309. };
  17310. }
  17311. DodecahedronGeometry.prototype = Object.create( PolyhedronGeometry.prototype );
  17312. DodecahedronGeometry.prototype.constructor = DodecahedronGeometry;
  17313. /**
  17314. * @author WestLangley / https://github.com/WestLangley
  17315. * @author zz85 / https://github.com/zz85
  17316. * @author miningold / https://github.com/miningold
  17317. * @author jonobr1 / https://github.com/jonobr1
  17318. *
  17319. * Modified from the TorusKnotGeometry by @oosmoxiecode
  17320. *
  17321. * Creates a tube which extrudes along a 3d spline
  17322. *
  17323. * Uses parallel transport frames as described in
  17324. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  17325. */
  17326. function TubeGeometry( path, segments, radius, radialSegments, closed, taper ) {
  17327. Geometry.call( this );
  17328. this.type = 'TubeGeometry';
  17329. this.parameters = {
  17330. path: path,
  17331. segments: segments,
  17332. radius: radius,
  17333. radialSegments: radialSegments,
  17334. closed: closed,
  17335. taper: taper
  17336. };
  17337. segments = segments || 64;
  17338. radius = radius || 1;
  17339. radialSegments = radialSegments || 8;
  17340. closed = closed || false;
  17341. taper = taper || TubeGeometry.NoTaper;
  17342. var grid = [];
  17343. var scope = this,
  17344. tangent,
  17345. normal,
  17346. binormal,
  17347. numpoints = segments + 1,
  17348. u, v, r,
  17349. cx, cy,
  17350. pos, pos2 = new Vector3(),
  17351. i, j,
  17352. ip, jp,
  17353. a, b, c, d,
  17354. uva, uvb, uvc, uvd;
  17355. var frames = new TubeGeometry.FrenetFrames( path, segments, closed ),
  17356. tangents = frames.tangents,
  17357. normals = frames.normals,
  17358. binormals = frames.binormals;
  17359. // proxy internals
  17360. this.tangents = tangents;
  17361. this.normals = normals;
  17362. this.binormals = binormals;
  17363. function vert( x, y, z ) {
  17364. return scope.vertices.push( new Vector3( x, y, z ) ) - 1;
  17365. }
  17366. // construct the grid
  17367. for ( i = 0; i < numpoints; i ++ ) {
  17368. grid[ i ] = [];
  17369. u = i / ( numpoints - 1 );
  17370. pos = path.getPointAt( u );
  17371. tangent = tangents[ i ];
  17372. normal = normals[ i ];
  17373. binormal = binormals[ i ];
  17374. r = radius * taper( u );
  17375. for ( j = 0; j < radialSegments; j ++ ) {
  17376. v = j / radialSegments * 2 * Math.PI;
  17377. cx = - r * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  17378. cy = r * Math.sin( v );
  17379. pos2.copy( pos );
  17380. pos2.x += cx * normal.x + cy * binormal.x;
  17381. pos2.y += cx * normal.y + cy * binormal.y;
  17382. pos2.z += cx * normal.z + cy * binormal.z;
  17383. grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  17384. }
  17385. }
  17386. // construct the mesh
  17387. for ( i = 0; i < segments; i ++ ) {
  17388. for ( j = 0; j < radialSegments; j ++ ) {
  17389. ip = ( closed ) ? ( i + 1 ) % segments : i + 1;
  17390. jp = ( j + 1 ) % radialSegments;
  17391. a = grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  17392. b = grid[ ip ][ j ];
  17393. c = grid[ ip ][ jp ];
  17394. d = grid[ i ][ jp ];
  17395. uva = new Vector2( i / segments, j / radialSegments );
  17396. uvb = new Vector2( ( i + 1 ) / segments, j / radialSegments );
  17397. uvc = new Vector2( ( i + 1 ) / segments, ( j + 1 ) / radialSegments );
  17398. uvd = new Vector2( i / segments, ( j + 1 ) / radialSegments );
  17399. this.faces.push( new Face3( a, b, d ) );
  17400. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  17401. this.faces.push( new Face3( b, c, d ) );
  17402. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  17403. }
  17404. }
  17405. this.computeFaceNormals();
  17406. this.computeVertexNormals();
  17407. }
  17408. TubeGeometry.prototype = Object.create( Geometry.prototype );
  17409. TubeGeometry.prototype.constructor = TubeGeometry;
  17410. TubeGeometry.NoTaper = function ( u ) {
  17411. return 1;
  17412. };
  17413. TubeGeometry.SinusoidalTaper = function ( u ) {
  17414. return Math.sin( Math.PI * u );
  17415. };
  17416. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  17417. TubeGeometry.FrenetFrames = function ( path, segments, closed ) {
  17418. var normal = new Vector3(),
  17419. tangents = [],
  17420. normals = [],
  17421. binormals = [],
  17422. vec = new Vector3(),
  17423. mat = new Matrix4(),
  17424. numpoints = segments + 1,
  17425. theta,
  17426. smallest,
  17427. tx, ty, tz,
  17428. i, u;
  17429. // expose internals
  17430. this.tangents = tangents;
  17431. this.normals = normals;
  17432. this.binormals = binormals;
  17433. // compute the tangent vectors for each segment on the path
  17434. for ( i = 0; i < numpoints; i ++ ) {
  17435. u = i / ( numpoints - 1 );
  17436. tangents[ i ] = path.getTangentAt( u );
  17437. tangents[ i ].normalize();
  17438. }
  17439. initialNormal3();
  17440. /*
  17441. function initialNormal1(lastBinormal) {
  17442. // fixed start binormal. Has dangers of 0 vectors
  17443. normals[ 0 ] = new THREE.Vector3();
  17444. binormals[ 0 ] = new THREE.Vector3();
  17445. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  17446. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  17447. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  17448. }
  17449. function initialNormal2() {
  17450. // This uses the Frenet-Serret formula for deriving binormal
  17451. var t2 = path.getTangentAt( epsilon );
  17452. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  17453. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  17454. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  17455. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  17456. }
  17457. */
  17458. function initialNormal3() {
  17459. // select an initial normal vector perpendicular to the first tangent vector,
  17460. // and in the direction of the smallest tangent xyz component
  17461. normals[ 0 ] = new Vector3();
  17462. binormals[ 0 ] = new Vector3();
  17463. smallest = Number.MAX_VALUE;
  17464. tx = Math.abs( tangents[ 0 ].x );
  17465. ty = Math.abs( tangents[ 0 ].y );
  17466. tz = Math.abs( tangents[ 0 ].z );
  17467. if ( tx <= smallest ) {
  17468. smallest = tx;
  17469. normal.set( 1, 0, 0 );
  17470. }
  17471. if ( ty <= smallest ) {
  17472. smallest = ty;
  17473. normal.set( 0, 1, 0 );
  17474. }
  17475. if ( tz <= smallest ) {
  17476. normal.set( 0, 0, 1 );
  17477. }
  17478. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  17479. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  17480. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  17481. }
  17482. // compute the slowly-varying normal and binormal vectors for each segment on the path
  17483. for ( i = 1; i < numpoints; i ++ ) {
  17484. normals[ i ] = normals[ i - 1 ].clone();
  17485. binormals[ i ] = binormals[ i - 1 ].clone();
  17486. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  17487. if ( vec.length() > Number.EPSILON ) {
  17488. vec.normalize();
  17489. theta = Math.acos( exports.Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  17490. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  17491. }
  17492. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  17493. }
  17494. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  17495. if ( closed ) {
  17496. theta = Math.acos( exports.Math.clamp( normals[ 0 ].dot( normals[ numpoints - 1 ] ), - 1, 1 ) );
  17497. theta /= ( numpoints - 1 );
  17498. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints - 1 ] ) ) > 0 ) {
  17499. theta = - theta;
  17500. }
  17501. for ( i = 1; i < numpoints; i ++ ) {
  17502. // twist a little...
  17503. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  17504. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  17505. }
  17506. }
  17507. };
  17508. /**
  17509. * @author Mugen87 / https://github.com/Mugen87
  17510. *
  17511. * see: http://www.blackpawn.com/texts/pqtorus/
  17512. */
  17513. function TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) {
  17514. BufferGeometry.call( this );
  17515. this.type = 'TorusKnotBufferGeometry';
  17516. this.parameters = {
  17517. radius: radius,
  17518. tube: tube,
  17519. tubularSegments: tubularSegments,
  17520. radialSegments: radialSegments,
  17521. p: p,
  17522. q: q
  17523. };
  17524. radius = radius || 100;
  17525. tube = tube || 40;
  17526. tubularSegments = Math.floor( tubularSegments ) || 64;
  17527. radialSegments = Math.floor( radialSegments ) || 8;
  17528. p = p || 2;
  17529. q = q || 3;
  17530. // used to calculate buffer length
  17531. var vertexCount = ( ( radialSegments + 1 ) * ( tubularSegments + 1 ) );
  17532. var indexCount = radialSegments * tubularSegments * 2 * 3;
  17533. // buffers
  17534. var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 );
  17535. var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  17536. var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  17537. var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  17538. // helper variables
  17539. var i, j, index = 0, indexOffset = 0;
  17540. var vertex = new Vector3();
  17541. var normal = new Vector3();
  17542. var uv = new Vector2();
  17543. var P1 = new Vector3();
  17544. var P2 = new Vector3();
  17545. var B = new Vector3();
  17546. var T = new Vector3();
  17547. var N = new Vector3();
  17548. // generate vertices, normals and uvs
  17549. for ( i = 0; i <= tubularSegments; ++ i ) {
  17550. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  17551. var u = i / tubularSegments * p * Math.PI * 2;
  17552. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  17553. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  17554. calculatePositionOnCurve( u, p, q, radius, P1 );
  17555. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  17556. // calculate orthonormal basis
  17557. T.subVectors( P2, P1 );
  17558. N.addVectors( P2, P1 );
  17559. B.crossVectors( T, N );
  17560. N.crossVectors( B, T );
  17561. // normalize B, N. T can be ignored, we don't use it
  17562. B.normalize();
  17563. N.normalize();
  17564. for ( j = 0; j <= radialSegments; ++ j ) {
  17565. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  17566. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  17567. var v = j / radialSegments * Math.PI * 2;
  17568. var cx = - tube * Math.cos( v );
  17569. var cy = tube * Math.sin( v );
  17570. // now calculate the final vertex position.
  17571. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  17572. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  17573. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  17574. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  17575. // vertex
  17576. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  17577. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  17578. normal.subVectors( vertex, P1 ).normalize();
  17579. normals.setXYZ( index, normal.x, normal.y, normal.z );
  17580. // uv
  17581. uv.x = i / tubularSegments;
  17582. uv.y = j / radialSegments;
  17583. uvs.setXY( index, uv.x, uv.y );
  17584. // increase index
  17585. index ++;
  17586. }
  17587. }
  17588. // generate indices
  17589. for ( j = 1; j <= tubularSegments; j ++ ) {
  17590. for ( i = 1; i <= radialSegments; i ++ ) {
  17591. // indices
  17592. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  17593. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  17594. var c = ( radialSegments + 1 ) * j + i;
  17595. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  17596. // face one
  17597. indices.setX( indexOffset, a ); indexOffset++;
  17598. indices.setX( indexOffset, b ); indexOffset++;
  17599. indices.setX( indexOffset, d ); indexOffset++;
  17600. // face two
  17601. indices.setX( indexOffset, b ); indexOffset++;
  17602. indices.setX( indexOffset, c ); indexOffset++;
  17603. indices.setX( indexOffset, d ); indexOffset++;
  17604. }
  17605. }
  17606. // build geometry
  17607. this.setIndex( indices );
  17608. this.addAttribute( 'position', vertices );
  17609. this.addAttribute( 'normal', normals );
  17610. this.addAttribute( 'uv', uvs );
  17611. // this function calculates the current position on the torus curve
  17612. function calculatePositionOnCurve( u, p, q, radius, position ) {
  17613. var cu = Math.cos( u );
  17614. var su = Math.sin( u );
  17615. var quOverP = q / p * u;
  17616. var cs = Math.cos( quOverP );
  17617. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  17618. position.y = radius * ( 2 + cs ) * su * 0.5;
  17619. position.z = radius * Math.sin( quOverP ) * 0.5;
  17620. }
  17621. }
  17622. TorusKnotBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  17623. TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry;
  17624. /**
  17625. * @author oosmoxiecode
  17626. */
  17627. function TorusKnotGeometry( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) {
  17628. Geometry.call( this );
  17629. this.type = 'TorusKnotGeometry';
  17630. this.parameters = {
  17631. radius: radius,
  17632. tube: tube,
  17633. tubularSegments: tubularSegments,
  17634. radialSegments: radialSegments,
  17635. p: p,
  17636. q: q
  17637. };
  17638. if( heightScale !== undefined ) console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' );
  17639. this.fromBufferGeometry( new TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) );
  17640. this.mergeVertices();
  17641. }
  17642. TorusKnotGeometry.prototype = Object.create( Geometry.prototype );
  17643. TorusKnotGeometry.prototype.constructor = TorusKnotGeometry;
  17644. /**
  17645. * @author Mugen87 / https://github.com/Mugen87
  17646. */
  17647. function TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  17648. BufferGeometry.call( this );
  17649. this.type = 'TorusBufferGeometry';
  17650. this.parameters = {
  17651. radius: radius,
  17652. tube: tube,
  17653. radialSegments: radialSegments,
  17654. tubularSegments: tubularSegments,
  17655. arc: arc
  17656. };
  17657. radius = radius || 100;
  17658. tube = tube || 40;
  17659. radialSegments = Math.floor( radialSegments ) || 8;
  17660. tubularSegments = Math.floor( tubularSegments ) || 6;
  17661. arc = arc || Math.PI * 2;
  17662. // used to calculate buffer length
  17663. var vertexCount = ( ( radialSegments + 1 ) * ( tubularSegments + 1 ) );
  17664. var indexCount = radialSegments * tubularSegments * 2 * 3;
  17665. // buffers
  17666. var indices = new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount );
  17667. var vertices = new Float32Array( vertexCount * 3 );
  17668. var normals = new Float32Array( vertexCount * 3 );
  17669. var uvs = new Float32Array( vertexCount * 2 );
  17670. // offset variables
  17671. var vertexBufferOffset = 0;
  17672. var uvBufferOffset = 0;
  17673. var indexBufferOffset = 0;
  17674. // helper variables
  17675. var center = new Vector3();
  17676. var vertex = new Vector3();
  17677. var normal = new Vector3();
  17678. var j, i;
  17679. // generate vertices, normals and uvs
  17680. for ( j = 0; j <= radialSegments; j ++ ) {
  17681. for ( i = 0; i <= tubularSegments; i ++ ) {
  17682. var u = i / tubularSegments * arc;
  17683. var v = j / radialSegments * Math.PI * 2;
  17684. // vertex
  17685. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  17686. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  17687. vertex.z = tube * Math.sin( v );
  17688. vertices[ vertexBufferOffset ] = vertex.x;
  17689. vertices[ vertexBufferOffset + 1 ] = vertex.y;
  17690. vertices[ vertexBufferOffset + 2 ] = vertex.z;
  17691. // this vector is used to calculate the normal
  17692. center.x = radius * Math.cos( u );
  17693. center.y = radius * Math.sin( u );
  17694. // normal
  17695. normal.subVectors( vertex, center ).normalize();
  17696. normals[ vertexBufferOffset ] = normal.x;
  17697. normals[ vertexBufferOffset + 1 ] = normal.y;
  17698. normals[ vertexBufferOffset + 2 ] = normal.z;
  17699. // uv
  17700. uvs[ uvBufferOffset ] = i / tubularSegments;
  17701. uvs[ uvBufferOffset + 1 ] = j / radialSegments;
  17702. // update offsets
  17703. vertexBufferOffset += 3;
  17704. uvBufferOffset += 2;
  17705. }
  17706. }
  17707. // generate indices
  17708. for ( j = 1; j <= radialSegments; j ++ ) {
  17709. for ( i = 1; i <= tubularSegments; i ++ ) {
  17710. // indices
  17711. var a = ( tubularSegments + 1 ) * j + i - 1;
  17712. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  17713. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  17714. var d = ( tubularSegments + 1 ) * j + i;
  17715. // face one
  17716. indices[ indexBufferOffset ] = a;
  17717. indices[ indexBufferOffset + 1 ] = b;
  17718. indices[ indexBufferOffset + 2 ] = d;
  17719. // face two
  17720. indices[ indexBufferOffset + 3 ] = b;
  17721. indices[ indexBufferOffset + 4 ] = c;
  17722. indices[ indexBufferOffset + 5 ] = d;
  17723. // update offset
  17724. indexBufferOffset += 6;
  17725. }
  17726. }
  17727. // build geometry
  17728. this.setIndex( new BufferAttribute( indices, 1 ) );
  17729. this.addAttribute( 'position', new BufferAttribute( vertices, 3 ) );
  17730. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) );
  17731. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) );
  17732. }
  17733. TorusBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  17734. TorusBufferGeometry.prototype.constructor = TorusBufferGeometry;
  17735. /**
  17736. * @author oosmoxiecode
  17737. * @author mrdoob / http://mrdoob.com/
  17738. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  17739. */
  17740. function TorusGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  17741. Geometry.call( this );
  17742. this.type = 'TorusGeometry';
  17743. this.parameters = {
  17744. radius: radius,
  17745. tube: tube,
  17746. radialSegments: radialSegments,
  17747. tubularSegments: tubularSegments,
  17748. arc: arc
  17749. };
  17750. this.fromBufferGeometry( new TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) );
  17751. }
  17752. TorusGeometry.prototype = Object.create( Geometry.prototype );
  17753. TorusGeometry.prototype.constructor = TorusGeometry;
  17754. /**
  17755. * @author zz85 / http://www.lab4games.net/zz85/blog
  17756. */
  17757. exports.ShapeUtils = {
  17758. // calculate area of the contour polygon
  17759. area: function ( contour ) {
  17760. var n = contour.length;
  17761. var a = 0.0;
  17762. for ( var p = n - 1, q = 0; q < n; p = q ++ ) {
  17763. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  17764. }
  17765. return a * 0.5;
  17766. },
  17767. triangulate: ( function () {
  17768. /**
  17769. * This code is a quick port of code written in C++ which was submitted to
  17770. * flipcode.com by John W. Ratcliff // July 22, 2000
  17771. * See original code and more information here:
  17772. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  17773. *
  17774. * ported to actionscript by Zevan Rosser
  17775. * www.actionsnippet.com
  17776. *
  17777. * ported to javascript by Joshua Koo
  17778. * http://www.lab4games.net/zz85/blog
  17779. *
  17780. */
  17781. function snip( contour, u, v, w, n, verts ) {
  17782. var p;
  17783. var ax, ay, bx, by;
  17784. var cx, cy, px, py;
  17785. ax = contour[ verts[ u ] ].x;
  17786. ay = contour[ verts[ u ] ].y;
  17787. bx = contour[ verts[ v ] ].x;
  17788. by = contour[ verts[ v ] ].y;
  17789. cx = contour[ verts[ w ] ].x;
  17790. cy = contour[ verts[ w ] ].y;
  17791. if ( Number.EPSILON > ( ( ( bx - ax ) * ( cy - ay ) ) - ( ( by - ay ) * ( cx - ax ) ) ) ) return false;
  17792. var aX, aY, bX, bY, cX, cY;
  17793. var apx, apy, bpx, bpy, cpx, cpy;
  17794. var cCROSSap, bCROSScp, aCROSSbp;
  17795. aX = cx - bx; aY = cy - by;
  17796. bX = ax - cx; bY = ay - cy;
  17797. cX = bx - ax; cY = by - ay;
  17798. for ( p = 0; p < n; p ++ ) {
  17799. px = contour[ verts[ p ] ].x;
  17800. py = contour[ verts[ p ] ].y;
  17801. if ( ( ( px === ax ) && ( py === ay ) ) ||
  17802. ( ( px === bx ) && ( py === by ) ) ||
  17803. ( ( px === cx ) && ( py === cy ) ) ) continue;
  17804. apx = px - ax; apy = py - ay;
  17805. bpx = px - bx; bpy = py - by;
  17806. cpx = px - cx; cpy = py - cy;
  17807. // see if p is inside triangle abc
  17808. aCROSSbp = aX * bpy - aY * bpx;
  17809. cCROSSap = cX * apy - cY * apx;
  17810. bCROSScp = bX * cpy - bY * cpx;
  17811. if ( ( aCROSSbp >= - Number.EPSILON ) && ( bCROSScp >= - Number.EPSILON ) && ( cCROSSap >= - Number.EPSILON ) ) return false;
  17812. }
  17813. return true;
  17814. }
  17815. // takes in an contour array and returns
  17816. return function triangulate( contour, indices ) {
  17817. var n = contour.length;
  17818. if ( n < 3 ) return null;
  17819. var result = [],
  17820. verts = [],
  17821. vertIndices = [];
  17822. /* we want a counter-clockwise polygon in verts */
  17823. var u, v, w;
  17824. if ( exports.ShapeUtils.area( contour ) > 0.0 ) {
  17825. for ( v = 0; v < n; v ++ ) verts[ v ] = v;
  17826. } else {
  17827. for ( v = 0; v < n; v ++ ) verts[ v ] = ( n - 1 ) - v;
  17828. }
  17829. var nv = n;
  17830. /* remove nv - 2 vertices, creating 1 triangle every time */
  17831. var count = 2 * nv; /* error detection */
  17832. for ( v = nv - 1; nv > 2; ) {
  17833. /* if we loop, it is probably a non-simple polygon */
  17834. if ( ( count -- ) <= 0 ) {
  17835. //** Triangulate: ERROR - probable bad polygon!
  17836. //throw ( "Warning, unable to triangulate polygon!" );
  17837. //return null;
  17838. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  17839. console.warn( 'THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()' );
  17840. if ( indices ) return vertIndices;
  17841. return result;
  17842. }
  17843. /* three consecutive vertices in current polygon, <u,v,w> */
  17844. u = v; if ( nv <= u ) u = 0; /* previous */
  17845. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  17846. w = v + 1; if ( nv <= w ) w = 0; /* next */
  17847. if ( snip( contour, u, v, w, nv, verts ) ) {
  17848. var a, b, c, s, t;
  17849. /* true names of the vertices */
  17850. a = verts[ u ];
  17851. b = verts[ v ];
  17852. c = verts[ w ];
  17853. /* output Triangle */
  17854. result.push( [ contour[ a ],
  17855. contour[ b ],
  17856. contour[ c ] ] );
  17857. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  17858. /* remove v from the remaining polygon */
  17859. for ( s = v, t = v + 1; t < nv; s ++, t ++ ) {
  17860. verts[ s ] = verts[ t ];
  17861. }
  17862. nv --;
  17863. /* reset error detection counter */
  17864. count = 2 * nv;
  17865. }
  17866. }
  17867. if ( indices ) return vertIndices;
  17868. return result;
  17869. }
  17870. } )(),
  17871. triangulateShape: function ( contour, holes ) {
  17872. function removeDupEndPts(points) {
  17873. var l = points.length;
  17874. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  17875. points.pop();
  17876. }
  17877. }
  17878. removeDupEndPts( contour );
  17879. holes.forEach( removeDupEndPts );
  17880. function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) {
  17881. // inOtherPt needs to be collinear to the inSegment
  17882. if ( inSegPt1.x !== inSegPt2.x ) {
  17883. if ( inSegPt1.x < inSegPt2.x ) {
  17884. return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) );
  17885. } else {
  17886. return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) );
  17887. }
  17888. } else {
  17889. if ( inSegPt1.y < inSegPt2.y ) {
  17890. return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) );
  17891. } else {
  17892. return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) );
  17893. }
  17894. }
  17895. }
  17896. function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) {
  17897. var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y;
  17898. var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y;
  17899. var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x;
  17900. var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y;
  17901. var limit = seg1dy * seg2dx - seg1dx * seg2dy;
  17902. var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy;
  17903. if ( Math.abs( limit ) > Number.EPSILON ) {
  17904. // not parallel
  17905. var perpSeg2;
  17906. if ( limit > 0 ) {
  17907. if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return [];
  17908. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  17909. if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return [];
  17910. } else {
  17911. if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return [];
  17912. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  17913. if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return [];
  17914. }
  17915. // i.e. to reduce rounding errors
  17916. // intersection at endpoint of segment#1?
  17917. if ( perpSeg2 === 0 ) {
  17918. if ( ( inExcludeAdjacentSegs ) &&
  17919. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  17920. return [ inSeg1Pt1 ];
  17921. }
  17922. if ( perpSeg2 === limit ) {
  17923. if ( ( inExcludeAdjacentSegs ) &&
  17924. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  17925. return [ inSeg1Pt2 ];
  17926. }
  17927. // intersection at endpoint of segment#2?
  17928. if ( perpSeg1 === 0 ) return [ inSeg2Pt1 ];
  17929. if ( perpSeg1 === limit ) return [ inSeg2Pt2 ];
  17930. // return real intersection point
  17931. var factorSeg1 = perpSeg2 / limit;
  17932. return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx,
  17933. y: inSeg1Pt1.y + factorSeg1 * seg1dy } ];
  17934. } else {
  17935. // parallel or collinear
  17936. if ( ( perpSeg1 !== 0 ) ||
  17937. ( seg2dy * seg1seg2dx !== seg2dx * seg1seg2dy ) ) return [];
  17938. // they are collinear or degenerate
  17939. var seg1Pt = ( ( seg1dx === 0 ) && ( seg1dy === 0 ) ); // segment1 is just a point?
  17940. var seg2Pt = ( ( seg2dx === 0 ) && ( seg2dy === 0 ) ); // segment2 is just a point?
  17941. // both segments are points
  17942. if ( seg1Pt && seg2Pt ) {
  17943. if ( ( inSeg1Pt1.x !== inSeg2Pt1.x ) ||
  17944. ( inSeg1Pt1.y !== inSeg2Pt1.y ) ) return []; // they are distinct points
  17945. return [ inSeg1Pt1 ]; // they are the same point
  17946. }
  17947. // segment#1 is a single point
  17948. if ( seg1Pt ) {
  17949. if ( ! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2
  17950. return [ inSeg1Pt1 ];
  17951. }
  17952. // segment#2 is a single point
  17953. if ( seg2Pt ) {
  17954. if ( ! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1
  17955. return [ inSeg2Pt1 ];
  17956. }
  17957. // they are collinear segments, which might overlap
  17958. var seg1min, seg1max, seg1minVal, seg1maxVal;
  17959. var seg2min, seg2max, seg2minVal, seg2maxVal;
  17960. if ( seg1dx !== 0 ) {
  17961. // the segments are NOT on a vertical line
  17962. if ( inSeg1Pt1.x < inSeg1Pt2.x ) {
  17963. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x;
  17964. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x;
  17965. } else {
  17966. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x;
  17967. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x;
  17968. }
  17969. if ( inSeg2Pt1.x < inSeg2Pt2.x ) {
  17970. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x;
  17971. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x;
  17972. } else {
  17973. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x;
  17974. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x;
  17975. }
  17976. } else {
  17977. // the segments are on a vertical line
  17978. if ( inSeg1Pt1.y < inSeg1Pt2.y ) {
  17979. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y;
  17980. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y;
  17981. } else {
  17982. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y;
  17983. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y;
  17984. }
  17985. if ( inSeg2Pt1.y < inSeg2Pt2.y ) {
  17986. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y;
  17987. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y;
  17988. } else {
  17989. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y;
  17990. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y;
  17991. }
  17992. }
  17993. if ( seg1minVal <= seg2minVal ) {
  17994. if ( seg1maxVal < seg2minVal ) return [];
  17995. if ( seg1maxVal === seg2minVal ) {
  17996. if ( inExcludeAdjacentSegs ) return [];
  17997. return [ seg2min ];
  17998. }
  17999. if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ];
  18000. return [ seg2min, seg2max ];
  18001. } else {
  18002. if ( seg1minVal > seg2maxVal ) return [];
  18003. if ( seg1minVal === seg2maxVal ) {
  18004. if ( inExcludeAdjacentSegs ) return [];
  18005. return [ seg1min ];
  18006. }
  18007. if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ];
  18008. return [ seg1min, seg2max ];
  18009. }
  18010. }
  18011. }
  18012. function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) {
  18013. // The order of legs is important
  18014. // translation of all points, so that Vertex is at (0,0)
  18015. var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y;
  18016. var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y;
  18017. var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y;
  18018. // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg.
  18019. var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX;
  18020. var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX;
  18021. if ( Math.abs( from2toAngle ) > Number.EPSILON ) {
  18022. // angle != 180 deg.
  18023. var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX;
  18024. // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle );
  18025. if ( from2toAngle > 0 ) {
  18026. // main angle < 180 deg.
  18027. return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) );
  18028. } else {
  18029. // main angle > 180 deg.
  18030. return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) );
  18031. }
  18032. } else {
  18033. // angle == 180 deg.
  18034. // console.log( "from2to: 180 deg., from2other: " + from2otherAngle );
  18035. return ( from2otherAngle > 0 );
  18036. }
  18037. }
  18038. function removeHoles( contour, holes ) {
  18039. var shape = contour.concat(); // work on this shape
  18040. var hole;
  18041. function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) {
  18042. // Check if hole point lies within angle around shape point
  18043. var lastShapeIdx = shape.length - 1;
  18044. var prevShapeIdx = inShapeIdx - 1;
  18045. if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx;
  18046. var nextShapeIdx = inShapeIdx + 1;
  18047. if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0;
  18048. var insideAngle = isPointInsideAngle( shape[ inShapeIdx ], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[ inHoleIdx ] );
  18049. if ( ! insideAngle ) {
  18050. // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y );
  18051. return false;
  18052. }
  18053. // Check if shape point lies within angle around hole point
  18054. var lastHoleIdx = hole.length - 1;
  18055. var prevHoleIdx = inHoleIdx - 1;
  18056. if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx;
  18057. var nextHoleIdx = inHoleIdx + 1;
  18058. if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0;
  18059. insideAngle = isPointInsideAngle( hole[ inHoleIdx ], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[ inShapeIdx ] );
  18060. if ( ! insideAngle ) {
  18061. // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y );
  18062. return false;
  18063. }
  18064. return true;
  18065. }
  18066. function intersectsShapeEdge( inShapePt, inHolePt ) {
  18067. // checks for intersections with shape edges
  18068. var sIdx, nextIdx, intersection;
  18069. for ( sIdx = 0; sIdx < shape.length; sIdx ++ ) {
  18070. nextIdx = sIdx + 1; nextIdx %= shape.length;
  18071. intersection = intersect_segments_2D( inShapePt, inHolePt, shape[ sIdx ], shape[ nextIdx ], true );
  18072. if ( intersection.length > 0 ) return true;
  18073. }
  18074. return false;
  18075. }
  18076. var indepHoles = [];
  18077. function intersectsHoleEdge( inShapePt, inHolePt ) {
  18078. // checks for intersections with hole edges
  18079. var ihIdx, chkHole,
  18080. hIdx, nextIdx, intersection;
  18081. for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx ++ ) {
  18082. chkHole = holes[ indepHoles[ ihIdx ]];
  18083. for ( hIdx = 0; hIdx < chkHole.length; hIdx ++ ) {
  18084. nextIdx = hIdx + 1; nextIdx %= chkHole.length;
  18085. intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[ hIdx ], chkHole[ nextIdx ], true );
  18086. if ( intersection.length > 0 ) return true;
  18087. }
  18088. }
  18089. return false;
  18090. }
  18091. var holeIndex, shapeIndex,
  18092. shapePt, holePt,
  18093. holeIdx, cutKey, failedCuts = [],
  18094. tmpShape1, tmpShape2,
  18095. tmpHole1, tmpHole2;
  18096. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  18097. indepHoles.push( h );
  18098. }
  18099. var minShapeIndex = 0;
  18100. var counter = indepHoles.length * 2;
  18101. while ( indepHoles.length > 0 ) {
  18102. counter --;
  18103. if ( counter < 0 ) {
  18104. console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" );
  18105. break;
  18106. }
  18107. // search for shape-vertex and hole-vertex,
  18108. // which can be connected without intersections
  18109. for ( shapeIndex = minShapeIndex; shapeIndex < shape.length; shapeIndex ++ ) {
  18110. shapePt = shape[ shapeIndex ];
  18111. holeIndex = - 1;
  18112. // search for hole which can be reached without intersections
  18113. for ( var h = 0; h < indepHoles.length; h ++ ) {
  18114. holeIdx = indepHoles[ h ];
  18115. // prevent multiple checks
  18116. cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx;
  18117. if ( failedCuts[ cutKey ] !== undefined ) continue;
  18118. hole = holes[ holeIdx ];
  18119. for ( var h2 = 0; h2 < hole.length; h2 ++ ) {
  18120. holePt = hole[ h2 ];
  18121. if ( ! isCutLineInsideAngles( shapeIndex, h2 ) ) continue;
  18122. if ( intersectsShapeEdge( shapePt, holePt ) ) continue;
  18123. if ( intersectsHoleEdge( shapePt, holePt ) ) continue;
  18124. holeIndex = h2;
  18125. indepHoles.splice( h, 1 );
  18126. tmpShape1 = shape.slice( 0, shapeIndex + 1 );
  18127. tmpShape2 = shape.slice( shapeIndex );
  18128. tmpHole1 = hole.slice( holeIndex );
  18129. tmpHole2 = hole.slice( 0, holeIndex + 1 );
  18130. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  18131. minShapeIndex = shapeIndex;
  18132. // Debug only, to show the selected cuts
  18133. // glob_CutLines.push( [ shapePt, holePt ] );
  18134. break;
  18135. }
  18136. if ( holeIndex >= 0 ) break; // hole-vertex found
  18137. failedCuts[ cutKey ] = true; // remember failure
  18138. }
  18139. if ( holeIndex >= 0 ) break; // hole-vertex found
  18140. }
  18141. }
  18142. return shape; /* shape with no holes */
  18143. }
  18144. var i, il, f, face,
  18145. key, index,
  18146. allPointsMap = {};
  18147. // 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.
  18148. var allpoints = contour.concat();
  18149. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  18150. Array.prototype.push.apply( allpoints, holes[ h ] );
  18151. }
  18152. //console.log( "allpoints",allpoints, allpoints.length );
  18153. // prepare all points map
  18154. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  18155. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  18156. if ( allPointsMap[ key ] !== undefined ) {
  18157. console.warn( "THREE.ShapeUtils: Duplicate point", key, i );
  18158. }
  18159. allPointsMap[ key ] = i;
  18160. }
  18161. // remove holes by cutting paths to holes and adding them to the shape
  18162. var shapeWithoutHoles = removeHoles( contour, holes );
  18163. var triangles = exports.ShapeUtils.triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape
  18164. //console.log( "triangles",triangles, triangles.length );
  18165. // check all face vertices against all points map
  18166. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  18167. face = triangles[ i ];
  18168. for ( f = 0; f < 3; f ++ ) {
  18169. key = face[ f ].x + ":" + face[ f ].y;
  18170. index = allPointsMap[ key ];
  18171. if ( index !== undefined ) {
  18172. face[ f ] = index;
  18173. }
  18174. }
  18175. }
  18176. return triangles.concat();
  18177. },
  18178. isClockWise: function ( pts ) {
  18179. return exports.ShapeUtils.area( pts ) < 0;
  18180. },
  18181. // Bezier Curves formulas obtained from
  18182. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  18183. // Quad Bezier Functions
  18184. b2: ( function () {
  18185. function b2p0( t, p ) {
  18186. var k = 1 - t;
  18187. return k * k * p;
  18188. }
  18189. function b2p1( t, p ) {
  18190. return 2 * ( 1 - t ) * t * p;
  18191. }
  18192. function b2p2( t, p ) {
  18193. return t * t * p;
  18194. }
  18195. return function b2( t, p0, p1, p2 ) {
  18196. return b2p0( t, p0 ) + b2p1( t, p1 ) + b2p2( t, p2 );
  18197. };
  18198. } )(),
  18199. // Cubic Bezier Functions
  18200. b3: ( function () {
  18201. function b3p0( t, p ) {
  18202. var k = 1 - t;
  18203. return k * k * k * p;
  18204. }
  18205. function b3p1( t, p ) {
  18206. var k = 1 - t;
  18207. return 3 * k * k * t * p;
  18208. }
  18209. function b3p2( t, p ) {
  18210. var k = 1 - t;
  18211. return 3 * k * t * t * p;
  18212. }
  18213. function b3p3( t, p ) {
  18214. return t * t * t * p;
  18215. }
  18216. return function b3( t, p0, p1, p2, p3 ) {
  18217. return b3p0( t, p0 ) + b3p1( t, p1 ) + b3p2( t, p2 ) + b3p3( t, p3 );
  18218. };
  18219. } )()
  18220. };
  18221. /**
  18222. * @author zz85 / http://www.lab4games.net/zz85/blog
  18223. *
  18224. * Creates extruded geometry from a path shape.
  18225. *
  18226. * parameters = {
  18227. *
  18228. * curveSegments: <int>, // number of points on the curves
  18229. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  18230. * amount: <int>, // Depth to extrude the shape
  18231. *
  18232. * bevelEnabled: <bool>, // turn on bevel
  18233. * bevelThickness: <float>, // how deep into the original shape bevel goes
  18234. * bevelSize: <float>, // how far from shape outline is bevel
  18235. * bevelSegments: <int>, // number of bevel layers
  18236. *
  18237. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  18238. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  18239. *
  18240. * uvGenerator: <Object> // object that provides UV generator functions
  18241. *
  18242. * }
  18243. **/
  18244. function ExtrudeGeometry( shapes, options ) {
  18245. if ( typeof( shapes ) === "undefined" ) {
  18246. shapes = [];
  18247. return;
  18248. }
  18249. Geometry.call( this );
  18250. this.type = 'ExtrudeGeometry';
  18251. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  18252. this.addShapeList( shapes, options );
  18253. this.computeFaceNormals();
  18254. // can't really use automatic vertex normals
  18255. // as then front and back sides get smoothed too
  18256. // should do separate smoothing just for sides
  18257. //this.computeVertexNormals();
  18258. //console.log( "took", ( Date.now() - startTime ) );
  18259. }
  18260. ExtrudeGeometry.prototype = Object.create( Geometry.prototype );
  18261. ExtrudeGeometry.prototype.constructor = ExtrudeGeometry;
  18262. ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18263. var sl = shapes.length;
  18264. for ( var s = 0; s < sl; s ++ ) {
  18265. var shape = shapes[ s ];
  18266. this.addShape( shape, options );
  18267. }
  18268. };
  18269. ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  18270. var amount = options.amount !== undefined ? options.amount : 100;
  18271. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  18272. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  18273. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18274. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  18275. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18276. var steps = options.steps !== undefined ? options.steps : 1;
  18277. var extrudePath = options.extrudePath;
  18278. var extrudePts, extrudeByPath = false;
  18279. // Use default WorldUVGenerator if no UV generators are specified.
  18280. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : ExtrudeGeometry.WorldUVGenerator;
  18281. var splineTube, binormal, normal, position2;
  18282. if ( extrudePath ) {
  18283. extrudePts = extrudePath.getSpacedPoints( steps );
  18284. extrudeByPath = true;
  18285. bevelEnabled = false; // bevels not supported for path extrusion
  18286. // SETUP TNB variables
  18287. // Reuse TNB from TubeGeomtry for now.
  18288. // TODO1 - have a .isClosed in spline?
  18289. splineTube = options.frames !== undefined ? options.frames : new TubeGeometry.FrenetFrames( extrudePath, steps, false );
  18290. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18291. binormal = new Vector3();
  18292. normal = new Vector3();
  18293. position2 = new Vector3();
  18294. }
  18295. // Safeguards if bevels are not enabled
  18296. if ( ! bevelEnabled ) {
  18297. bevelSegments = 0;
  18298. bevelThickness = 0;
  18299. bevelSize = 0;
  18300. }
  18301. // Variables initialization
  18302. var ahole, h, hl; // looping of holes
  18303. var scope = this;
  18304. var shapesOffset = this.vertices.length;
  18305. var shapePoints = shape.extractPoints( curveSegments );
  18306. var vertices = shapePoints.shape;
  18307. var holes = shapePoints.holes;
  18308. var reverse = ! exports.ShapeUtils.isClockWise( vertices );
  18309. if ( reverse ) {
  18310. vertices = vertices.reverse();
  18311. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18312. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18313. ahole = holes[ h ];
  18314. if ( exports.ShapeUtils.isClockWise( ahole ) ) {
  18315. holes[ h ] = ahole.reverse();
  18316. }
  18317. }
  18318. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  18319. }
  18320. var faces = exports.ShapeUtils.triangulateShape( vertices, holes );
  18321. /* Vertices */
  18322. var contour = vertices; // vertices has all points but contour has only points of circumference
  18323. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18324. ahole = holes[ h ];
  18325. vertices = vertices.concat( ahole );
  18326. }
  18327. function scalePt2( pt, vec, size ) {
  18328. if ( ! vec ) console.error( "THREE.ExtrudeGeometry: vec does not exist" );
  18329. return vec.clone().multiplyScalar( size ).add( pt );
  18330. }
  18331. var b, bs, t, z,
  18332. vert, vlen = vertices.length,
  18333. face, flen = faces.length;
  18334. // Find directions for point movement
  18335. function getBevelVec( inPt, inPrev, inNext ) {
  18336. // computes for inPt the corresponding point inPt' on a new contour
  18337. // shifted by 1 unit (length of normalized vector) to the left
  18338. // if we walk along contour clockwise, this new contour is outside the old one
  18339. //
  18340. // inPt' is the intersection of the two lines parallel to the two
  18341. // adjacent edges of inPt at a distance of 1 unit on the left side.
  18342. var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt
  18343. // good reading for geometry algorithms (here: line-line intersection)
  18344. // http://geomalgorithms.com/a05-_intersect-1.html
  18345. var v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y;
  18346. var v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y;
  18347. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  18348. // check for collinear edges
  18349. var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  18350. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  18351. // not collinear
  18352. // length of vectors for normalizing
  18353. var v_prev_len = Math.sqrt( v_prev_lensq );
  18354. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  18355. // shift adjacent points by unit vectors to the left
  18356. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  18357. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  18358. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  18359. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  18360. // scaling factor for v_prev to intersection point
  18361. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  18362. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  18363. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  18364. // vector from inPt to intersection point
  18365. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  18366. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  18367. // Don't normalize!, otherwise sharp corners become ugly
  18368. // but prevent crazy spikes
  18369. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  18370. if ( v_trans_lensq <= 2 ) {
  18371. return new Vector2( v_trans_x, v_trans_y );
  18372. } else {
  18373. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  18374. }
  18375. } else {
  18376. // handle special case of collinear edges
  18377. var direction_eq = false; // assumes: opposite
  18378. if ( v_prev_x > Number.EPSILON ) {
  18379. if ( v_next_x > Number.EPSILON ) {
  18380. direction_eq = true;
  18381. }
  18382. } else {
  18383. if ( v_prev_x < - Number.EPSILON ) {
  18384. if ( v_next_x < - Number.EPSILON ) {
  18385. direction_eq = true;
  18386. }
  18387. } else {
  18388. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  18389. direction_eq = true;
  18390. }
  18391. }
  18392. }
  18393. if ( direction_eq ) {
  18394. // console.log("Warning: lines are a straight sequence");
  18395. v_trans_x = - v_prev_y;
  18396. v_trans_y = v_prev_x;
  18397. shrink_by = Math.sqrt( v_prev_lensq );
  18398. } else {
  18399. // console.log("Warning: lines are a straight spike");
  18400. v_trans_x = v_prev_x;
  18401. v_trans_y = v_prev_y;
  18402. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  18403. }
  18404. }
  18405. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  18406. }
  18407. var contourMovements = [];
  18408. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18409. if ( j === il ) j = 0;
  18410. if ( k === il ) k = 0;
  18411. // (j)---(i)---(k)
  18412. // console.log('i,j,k', i, j , k)
  18413. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  18414. }
  18415. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  18416. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18417. ahole = holes[ h ];
  18418. oneHoleMovements = [];
  18419. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18420. if ( j === il ) j = 0;
  18421. if ( k === il ) k = 0;
  18422. // (j)---(i)---(k)
  18423. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  18424. }
  18425. holesMovements.push( oneHoleMovements );
  18426. verticesMovements = verticesMovements.concat( oneHoleMovements );
  18427. }
  18428. // Loop bevelSegments, 1 for the front, 1 for the back
  18429. for ( b = 0; b < bevelSegments; b ++ ) {
  18430. //for ( b = bevelSegments; b > 0; b -- ) {
  18431. t = b / bevelSegments;
  18432. z = bevelThickness * Math.cos( t * Math.PI / 2 );
  18433. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  18434. // contract shape
  18435. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18436. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18437. v( vert.x, vert.y, - z );
  18438. }
  18439. // expand holes
  18440. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18441. ahole = holes[ h ];
  18442. oneHoleMovements = holesMovements[ h ];
  18443. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  18444. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18445. v( vert.x, vert.y, - z );
  18446. }
  18447. }
  18448. }
  18449. bs = bevelSize;
  18450. // Back facing vertices
  18451. for ( i = 0; i < vlen; i ++ ) {
  18452. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18453. if ( ! extrudeByPath ) {
  18454. v( vert.x, vert.y, 0 );
  18455. } else {
  18456. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  18457. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  18458. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  18459. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  18460. v( position2.x, position2.y, position2.z );
  18461. }
  18462. }
  18463. // Add stepped vertices...
  18464. // Including front facing vertices
  18465. var s;
  18466. for ( s = 1; s <= steps; s ++ ) {
  18467. for ( i = 0; i < vlen; i ++ ) {
  18468. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18469. if ( ! extrudeByPath ) {
  18470. v( vert.x, vert.y, amount / steps * s );
  18471. } else {
  18472. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  18473. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  18474. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  18475. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  18476. v( position2.x, position2.y, position2.z );
  18477. }
  18478. }
  18479. }
  18480. // Add bevel segments planes
  18481. //for ( b = 1; b <= bevelSegments; b ++ ) {
  18482. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  18483. t = b / bevelSegments;
  18484. z = bevelThickness * Math.cos ( t * Math.PI / 2 );
  18485. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  18486. // contract shape
  18487. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18488. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18489. v( vert.x, vert.y, amount + z );
  18490. }
  18491. // expand holes
  18492. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18493. ahole = holes[ h ];
  18494. oneHoleMovements = holesMovements[ h ];
  18495. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  18496. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18497. if ( ! extrudeByPath ) {
  18498. v( vert.x, vert.y, amount + z );
  18499. } else {
  18500. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  18501. }
  18502. }
  18503. }
  18504. }
  18505. /* Faces */
  18506. // Top and bottom faces
  18507. buildLidFaces();
  18508. // Sides faces
  18509. buildSideFaces();
  18510. ///// Internal functions
  18511. function buildLidFaces() {
  18512. if ( bevelEnabled ) {
  18513. var layer = 0; // steps + 1
  18514. var offset = vlen * layer;
  18515. // Bottom faces
  18516. for ( i = 0; i < flen; i ++ ) {
  18517. face = faces[ i ];
  18518. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  18519. }
  18520. layer = steps + bevelSegments * 2;
  18521. offset = vlen * layer;
  18522. // Top faces
  18523. for ( i = 0; i < flen; i ++ ) {
  18524. face = faces[ i ];
  18525. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  18526. }
  18527. } else {
  18528. // Bottom faces
  18529. for ( i = 0; i < flen; i ++ ) {
  18530. face = faces[ i ];
  18531. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  18532. }
  18533. // Top faces
  18534. for ( i = 0; i < flen; i ++ ) {
  18535. face = faces[ i ];
  18536. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  18537. }
  18538. }
  18539. }
  18540. // Create faces for the z-sides of the shape
  18541. function buildSideFaces() {
  18542. var layeroffset = 0;
  18543. sidewalls( contour, layeroffset );
  18544. layeroffset += contour.length;
  18545. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18546. ahole = holes[ h ];
  18547. sidewalls( ahole, layeroffset );
  18548. //, true
  18549. layeroffset += ahole.length;
  18550. }
  18551. }
  18552. function sidewalls( contour, layeroffset ) {
  18553. var j, k;
  18554. i = contour.length;
  18555. while ( -- i >= 0 ) {
  18556. j = i;
  18557. k = i - 1;
  18558. if ( k < 0 ) k = contour.length - 1;
  18559. //console.log('b', i,j, i-1, k,vertices.length);
  18560. var s = 0, sl = steps + bevelSegments * 2;
  18561. for ( s = 0; s < sl; s ++ ) {
  18562. var slen1 = vlen * s;
  18563. var slen2 = vlen * ( s + 1 );
  18564. var a = layeroffset + j + slen1,
  18565. b = layeroffset + k + slen1,
  18566. c = layeroffset + k + slen2,
  18567. d = layeroffset + j + slen2;
  18568. f4( a, b, c, d, contour, s, sl, j, k );
  18569. }
  18570. }
  18571. }
  18572. function v( x, y, z ) {
  18573. scope.vertices.push( new Vector3( x, y, z ) );
  18574. }
  18575. function f3( a, b, c ) {
  18576. a += shapesOffset;
  18577. b += shapesOffset;
  18578. c += shapesOffset;
  18579. scope.faces.push( new Face3( a, b, c, null, null, 0 ) );
  18580. var uvs = uvgen.generateTopUV( scope, a, b, c );
  18581. scope.faceVertexUvs[ 0 ].push( uvs );
  18582. }
  18583. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  18584. a += shapesOffset;
  18585. b += shapesOffset;
  18586. c += shapesOffset;
  18587. d += shapesOffset;
  18588. scope.faces.push( new Face3( a, b, d, null, null, 1 ) );
  18589. scope.faces.push( new Face3( b, c, d, null, null, 1 ) );
  18590. var uvs = uvgen.generateSideWallUV( scope, a, b, c, d );
  18591. scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] );
  18592. scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] );
  18593. }
  18594. };
  18595. ExtrudeGeometry.WorldUVGenerator = {
  18596. generateTopUV: function ( geometry, indexA, indexB, indexC ) {
  18597. var vertices = geometry.vertices;
  18598. var a = vertices[ indexA ];
  18599. var b = vertices[ indexB ];
  18600. var c = vertices[ indexC ];
  18601. return [
  18602. new Vector2( a.x, a.y ),
  18603. new Vector2( b.x, b.y ),
  18604. new Vector2( c.x, c.y )
  18605. ];
  18606. },
  18607. generateSideWallUV: function ( geometry, indexA, indexB, indexC, indexD ) {
  18608. var vertices = geometry.vertices;
  18609. var a = vertices[ indexA ];
  18610. var b = vertices[ indexB ];
  18611. var c = vertices[ indexC ];
  18612. var d = vertices[ indexD ];
  18613. if ( Math.abs( a.y - b.y ) < 0.01 ) {
  18614. return [
  18615. new Vector2( a.x, 1 - a.z ),
  18616. new Vector2( b.x, 1 - b.z ),
  18617. new Vector2( c.x, 1 - c.z ),
  18618. new Vector2( d.x, 1 - d.z )
  18619. ];
  18620. } else {
  18621. return [
  18622. new Vector2( a.y, 1 - a.z ),
  18623. new Vector2( b.y, 1 - b.z ),
  18624. new Vector2( c.y, 1 - c.z ),
  18625. new Vector2( d.y, 1 - d.z )
  18626. ];
  18627. }
  18628. }
  18629. };
  18630. /**
  18631. * @author zz85 / http://www.lab4games.net/zz85/blog
  18632. * @author alteredq / http://alteredqualia.com/
  18633. *
  18634. * Text = 3D Text
  18635. *
  18636. * parameters = {
  18637. * font: <THREE.Font>, // font
  18638. *
  18639. * size: <float>, // size of the text
  18640. * height: <float>, // thickness to extrude text
  18641. * curveSegments: <int>, // number of points on the curves
  18642. *
  18643. * bevelEnabled: <bool>, // turn on bevel
  18644. * bevelThickness: <float>, // how deep into text bevel goes
  18645. * bevelSize: <float> // how far from text outline is bevel
  18646. * }
  18647. */
  18648. function TextGeometry( text, parameters ) {
  18649. parameters = parameters || {};
  18650. var font = parameters.font;
  18651. if ( (font && font.isFont) === false ) {
  18652. console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' );
  18653. return new Geometry();
  18654. }
  18655. var shapes = font.generateShapes( text, parameters.size, parameters.curveSegments );
  18656. // translate parameters to ExtrudeGeometry API
  18657. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  18658. // defaults
  18659. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  18660. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  18661. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  18662. ExtrudeGeometry.call( this, shapes, parameters );
  18663. this.type = 'TextGeometry';
  18664. }
  18665. TextGeometry.prototype = Object.create( ExtrudeGeometry.prototype );
  18666. TextGeometry.prototype.constructor = TextGeometry;
  18667. /**
  18668. * @author benaadams / https://twitter.com/ben_a_adams
  18669. * based on THREE.SphereGeometry
  18670. */
  18671. function SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  18672. BufferGeometry.call( this );
  18673. this.type = 'SphereBufferGeometry';
  18674. this.parameters = {
  18675. radius: radius,
  18676. widthSegments: widthSegments,
  18677. heightSegments: heightSegments,
  18678. phiStart: phiStart,
  18679. phiLength: phiLength,
  18680. thetaStart: thetaStart,
  18681. thetaLength: thetaLength
  18682. };
  18683. radius = radius || 50;
  18684. widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  18685. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  18686. phiStart = phiStart !== undefined ? phiStart : 0;
  18687. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  18688. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18689. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  18690. var thetaEnd = thetaStart + thetaLength;
  18691. var vertexCount = ( ( widthSegments + 1 ) * ( heightSegments + 1 ) );
  18692. var positions = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  18693. var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  18694. var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  18695. var index = 0, vertices = [], normal = new Vector3();
  18696. for ( var y = 0; y <= heightSegments; y ++ ) {
  18697. var verticesRow = [];
  18698. var v = y / heightSegments;
  18699. for ( var x = 0; x <= widthSegments; x ++ ) {
  18700. var u = x / widthSegments;
  18701. var px = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  18702. var py = radius * Math.cos( thetaStart + v * thetaLength );
  18703. var pz = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  18704. normal.set( px, py, pz ).normalize();
  18705. positions.setXYZ( index, px, py, pz );
  18706. normals.setXYZ( index, normal.x, normal.y, normal.z );
  18707. uvs.setXY( index, u, 1 - v );
  18708. verticesRow.push( index );
  18709. index ++;
  18710. }
  18711. vertices.push( verticesRow );
  18712. }
  18713. var indices = [];
  18714. for ( var y = 0; y < heightSegments; y ++ ) {
  18715. for ( var x = 0; x < widthSegments; x ++ ) {
  18716. var v1 = vertices[ y ][ x + 1 ];
  18717. var v2 = vertices[ y ][ x ];
  18718. var v3 = vertices[ y + 1 ][ x ];
  18719. var v4 = vertices[ y + 1 ][ x + 1 ];
  18720. if ( y !== 0 || thetaStart > 0 ) indices.push( v1, v2, v4 );
  18721. if ( y !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( v2, v3, v4 );
  18722. }
  18723. }
  18724. this.setIndex( new ( positions.count > 65535 ? Uint32Attribute : Uint16Attribute )( indices, 1 ) );
  18725. this.addAttribute( 'position', positions );
  18726. this.addAttribute( 'normal', normals );
  18727. this.addAttribute( 'uv', uvs );
  18728. this.boundingSphere = new Sphere( new Vector3(), radius );
  18729. }
  18730. SphereBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  18731. SphereBufferGeometry.prototype.constructor = SphereBufferGeometry;
  18732. /**
  18733. * @author mrdoob / http://mrdoob.com/
  18734. */
  18735. function SphereGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  18736. Geometry.call( this );
  18737. this.type = 'SphereGeometry';
  18738. this.parameters = {
  18739. radius: radius,
  18740. widthSegments: widthSegments,
  18741. heightSegments: heightSegments,
  18742. phiStart: phiStart,
  18743. phiLength: phiLength,
  18744. thetaStart: thetaStart,
  18745. thetaLength: thetaLength
  18746. };
  18747. this.fromBufferGeometry( new SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) );
  18748. }
  18749. SphereGeometry.prototype = Object.create( Geometry.prototype );
  18750. SphereGeometry.prototype.constructor = SphereGeometry;
  18751. /**
  18752. * @author Mugen87 / https://github.com/Mugen87
  18753. */
  18754. function RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  18755. BufferGeometry.call( this );
  18756. this.type = 'RingBufferGeometry';
  18757. this.parameters = {
  18758. innerRadius: innerRadius,
  18759. outerRadius: outerRadius,
  18760. thetaSegments: thetaSegments,
  18761. phiSegments: phiSegments,
  18762. thetaStart: thetaStart,
  18763. thetaLength: thetaLength
  18764. };
  18765. innerRadius = innerRadius || 20;
  18766. outerRadius = outerRadius || 50;
  18767. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18768. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  18769. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  18770. phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 1;
  18771. // these are used to calculate buffer length
  18772. var vertexCount = ( thetaSegments + 1 ) * ( phiSegments + 1 );
  18773. var indexCount = thetaSegments * phiSegments * 2 * 3;
  18774. // buffers
  18775. var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 );
  18776. var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  18777. var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  18778. var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  18779. // some helper variables
  18780. var index = 0, indexOffset = 0, segment;
  18781. var radius = innerRadius;
  18782. var radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  18783. var vertex = new Vector3();
  18784. var uv = new Vector2();
  18785. var j, i;
  18786. // generate vertices, normals and uvs
  18787. // values are generate from the inside of the ring to the outside
  18788. for ( j = 0; j <= phiSegments; j ++ ) {
  18789. for ( i = 0; i <= thetaSegments; i ++ ) {
  18790. segment = thetaStart + i / thetaSegments * thetaLength;
  18791. // vertex
  18792. vertex.x = radius * Math.cos( segment );
  18793. vertex.y = radius * Math.sin( segment );
  18794. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  18795. // normal
  18796. normals.setXYZ( index, 0, 0, 1 );
  18797. // uv
  18798. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  18799. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  18800. uvs.setXY( index, uv.x, uv.y );
  18801. // increase index
  18802. index++;
  18803. }
  18804. // increase the radius for next row of vertices
  18805. radius += radiusStep;
  18806. }
  18807. // generate indices
  18808. for ( j = 0; j < phiSegments; j ++ ) {
  18809. var thetaSegmentLevel = j * ( thetaSegments + 1 );
  18810. for ( i = 0; i < thetaSegments; i ++ ) {
  18811. segment = i + thetaSegmentLevel;
  18812. // indices
  18813. var a = segment;
  18814. var b = segment + thetaSegments + 1;
  18815. var c = segment + thetaSegments + 2;
  18816. var d = segment + 1;
  18817. // face one
  18818. indices.setX( indexOffset, a ); indexOffset++;
  18819. indices.setX( indexOffset, b ); indexOffset++;
  18820. indices.setX( indexOffset, c ); indexOffset++;
  18821. // face two
  18822. indices.setX( indexOffset, a ); indexOffset++;
  18823. indices.setX( indexOffset, c ); indexOffset++;
  18824. indices.setX( indexOffset, d ); indexOffset++;
  18825. }
  18826. }
  18827. // build geometry
  18828. this.setIndex( indices );
  18829. this.addAttribute( 'position', vertices );
  18830. this.addAttribute( 'normal', normals );
  18831. this.addAttribute( 'uv', uvs );
  18832. }
  18833. RingBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  18834. RingBufferGeometry.prototype.constructor = RingBufferGeometry;
  18835. /**
  18836. * @author Kaleb Murphy
  18837. */
  18838. function RingGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  18839. Geometry.call( this );
  18840. this.type = 'RingGeometry';
  18841. this.parameters = {
  18842. innerRadius: innerRadius,
  18843. outerRadius: outerRadius,
  18844. thetaSegments: thetaSegments,
  18845. phiSegments: phiSegments,
  18846. thetaStart: thetaStart,
  18847. thetaLength: thetaLength
  18848. };
  18849. this.fromBufferGeometry( new RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) );
  18850. }
  18851. RingGeometry.prototype = Object.create( Geometry.prototype );
  18852. RingGeometry.prototype.constructor = RingGeometry;
  18853. /**
  18854. * @author mrdoob / http://mrdoob.com/
  18855. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  18856. */
  18857. function PlaneGeometry( width, height, widthSegments, heightSegments ) {
  18858. Geometry.call( this );
  18859. this.type = 'PlaneGeometry';
  18860. this.parameters = {
  18861. width: width,
  18862. height: height,
  18863. widthSegments: widthSegments,
  18864. heightSegments: heightSegments
  18865. };
  18866. this.fromBufferGeometry( new PlaneBufferGeometry( width, height, widthSegments, heightSegments ) );
  18867. }
  18868. PlaneGeometry.prototype = Object.create( Geometry.prototype );
  18869. PlaneGeometry.prototype.constructor = PlaneGeometry;
  18870. /**
  18871. * @author Mugen87 / https://github.com/Mugen87
  18872. */
  18873. // points - to create a closed torus, one must use a set of points
  18874. // like so: [ a, b, c, d, a ], see first is the same as last.
  18875. // segments - the number of circumference segments to create
  18876. // phiStart - the starting radian
  18877. // phiLength - the radian (0 to 2PI) range of the lathed section
  18878. // 2PI is a closed lathe, less than 2PI is a portion.
  18879. function LatheBufferGeometry( points, segments, phiStart, phiLength ) {
  18880. BufferGeometry.call( this );
  18881. this.type = 'LatheBufferGeometry';
  18882. this.parameters = {
  18883. points: points,
  18884. segments: segments,
  18885. phiStart: phiStart,
  18886. phiLength: phiLength
  18887. };
  18888. segments = Math.floor( segments ) || 12;
  18889. phiStart = phiStart || 0;
  18890. phiLength = phiLength || Math.PI * 2;
  18891. // clamp phiLength so it's in range of [ 0, 2PI ]
  18892. phiLength = exports.Math.clamp( phiLength, 0, Math.PI * 2 );
  18893. // these are used to calculate buffer length
  18894. var vertexCount = ( segments + 1 ) * points.length;
  18895. var indexCount = segments * points.length * 2 * 3;
  18896. // buffers
  18897. var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 );
  18898. var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  18899. var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  18900. // helper variables
  18901. var index = 0, indexOffset = 0, base;
  18902. var inverseSegments = 1.0 / segments;
  18903. var vertex = new Vector3();
  18904. var uv = new Vector2();
  18905. var i, j;
  18906. // generate vertices and uvs
  18907. for ( i = 0; i <= segments; i ++ ) {
  18908. var phi = phiStart + i * inverseSegments * phiLength;
  18909. var sin = Math.sin( phi );
  18910. var cos = Math.cos( phi );
  18911. for ( j = 0; j <= ( points.length - 1 ); j ++ ) {
  18912. // vertex
  18913. vertex.x = points[ j ].x * sin;
  18914. vertex.y = points[ j ].y;
  18915. vertex.z = points[ j ].x * cos;
  18916. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  18917. // uv
  18918. uv.x = i / segments;
  18919. uv.y = j / ( points.length - 1 );
  18920. uvs.setXY( index, uv.x, uv.y );
  18921. // increase index
  18922. index ++;
  18923. }
  18924. }
  18925. // generate indices
  18926. for ( i = 0; i < segments; i ++ ) {
  18927. for ( j = 0; j < ( points.length - 1 ); j ++ ) {
  18928. base = j + i * points.length;
  18929. // indices
  18930. var a = base;
  18931. var b = base + points.length;
  18932. var c = base + points.length + 1;
  18933. var d = base + 1;
  18934. // face one
  18935. indices.setX( indexOffset, a ); indexOffset++;
  18936. indices.setX( indexOffset, b ); indexOffset++;
  18937. indices.setX( indexOffset, d ); indexOffset++;
  18938. // face two
  18939. indices.setX( indexOffset, b ); indexOffset++;
  18940. indices.setX( indexOffset, c ); indexOffset++;
  18941. indices.setX( indexOffset, d ); indexOffset++;
  18942. }
  18943. }
  18944. // build geometry
  18945. this.setIndex( indices );
  18946. this.addAttribute( 'position', vertices );
  18947. this.addAttribute( 'uv', uvs );
  18948. // generate normals
  18949. this.computeVertexNormals();
  18950. // if the geometry is closed, we need to average the normals along the seam.
  18951. // because the corresponding vertices are identical (but still have different UVs).
  18952. if( phiLength === Math.PI * 2 ) {
  18953. var normals = this.attributes.normal.array;
  18954. var n1 = new Vector3();
  18955. var n2 = new Vector3();
  18956. var n = new Vector3();
  18957. // this is the buffer offset for the last line of vertices
  18958. base = segments * points.length * 3;
  18959. for( i = 0, j = 0; i < points.length; i ++, j += 3 ) {
  18960. // select the normal of the vertex in the first line
  18961. n1.x = normals[ j + 0 ];
  18962. n1.y = normals[ j + 1 ];
  18963. n1.z = normals[ j + 2 ];
  18964. // select the normal of the vertex in the last line
  18965. n2.x = normals[ base + j + 0 ];
  18966. n2.y = normals[ base + j + 1 ];
  18967. n2.z = normals[ base + j + 2 ];
  18968. // average normals
  18969. n.addVectors( n1, n2 ).normalize();
  18970. // assign the new values to both normals
  18971. normals[ j + 0 ] = normals[ base + j + 0 ] = n.x;
  18972. normals[ j + 1 ] = normals[ base + j + 1 ] = n.y;
  18973. normals[ j + 2 ] = normals[ base + j + 2 ] = n.z;
  18974. } // next row
  18975. }
  18976. }
  18977. LatheBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  18978. LatheBufferGeometry.prototype.constructor = LatheBufferGeometry;
  18979. /**
  18980. * @author astrodud / http://astrodud.isgreat.org/
  18981. * @author zz85 / https://github.com/zz85
  18982. * @author bhouston / http://clara.io
  18983. */
  18984. // points - to create a closed torus, one must use a set of points
  18985. // like so: [ a, b, c, d, a ], see first is the same as last.
  18986. // segments - the number of circumference segments to create
  18987. // phiStart - the starting radian
  18988. // phiLength - the radian (0 to 2PI) range of the lathed section
  18989. // 2PI is a closed lathe, less than 2PI is a portion.
  18990. function LatheGeometry( points, segments, phiStart, phiLength ) {
  18991. Geometry.call( this );
  18992. this.type = 'LatheGeometry';
  18993. this.parameters = {
  18994. points: points,
  18995. segments: segments,
  18996. phiStart: phiStart,
  18997. phiLength: phiLength
  18998. };
  18999. this.fromBufferGeometry( new LatheBufferGeometry( points, segments, phiStart, phiLength ) );
  19000. this.mergeVertices();
  19001. }
  19002. LatheGeometry.prototype = Object.create( Geometry.prototype );
  19003. LatheGeometry.prototype.constructor = LatheGeometry;
  19004. /**
  19005. * @author jonobr1 / http://jonobr1.com
  19006. *
  19007. * Creates a one-sided polygonal geometry from a path shape. Similar to
  19008. * ExtrudeGeometry.
  19009. *
  19010. * parameters = {
  19011. *
  19012. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  19013. *
  19014. * material: <int> // material index for front and back faces
  19015. * uvGenerator: <Object> // object that provides UV generator functions
  19016. *
  19017. * }
  19018. **/
  19019. function ShapeGeometry( shapes, options ) {
  19020. Geometry.call( this );
  19021. this.type = 'ShapeGeometry';
  19022. if ( Array.isArray( shapes ) === false ) shapes = [ shapes ];
  19023. this.addShapeList( shapes, options );
  19024. this.computeFaceNormals();
  19025. }
  19026. ShapeGeometry.prototype = Object.create( Geometry.prototype );
  19027. ShapeGeometry.prototype.constructor = ShapeGeometry;
  19028. /**
  19029. * Add an array of shapes to THREE.ShapeGeometry.
  19030. */
  19031. ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19032. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  19033. this.addShape( shapes[ i ], options );
  19034. }
  19035. return this;
  19036. };
  19037. /**
  19038. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  19039. */
  19040. ShapeGeometry.prototype.addShape = function ( shape, options ) {
  19041. if ( options === undefined ) options = {};
  19042. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19043. var material = options.material;
  19044. var uvgen = options.UVGenerator === undefined ? ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  19045. //
  19046. var i, l, hole;
  19047. var shapesOffset = this.vertices.length;
  19048. var shapePoints = shape.extractPoints( curveSegments );
  19049. var vertices = shapePoints.shape;
  19050. var holes = shapePoints.holes;
  19051. var reverse = ! exports.ShapeUtils.isClockWise( vertices );
  19052. if ( reverse ) {
  19053. vertices = vertices.reverse();
  19054. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  19055. for ( i = 0, l = holes.length; i < l; i ++ ) {
  19056. hole = holes[ i ];
  19057. if ( exports.ShapeUtils.isClockWise( hole ) ) {
  19058. holes[ i ] = hole.reverse();
  19059. }
  19060. }
  19061. reverse = false;
  19062. }
  19063. var faces = exports.ShapeUtils.triangulateShape( vertices, holes );
  19064. // Vertices
  19065. for ( i = 0, l = holes.length; i < l; i ++ ) {
  19066. hole = holes[ i ];
  19067. vertices = vertices.concat( hole );
  19068. }
  19069. //
  19070. var vert, vlen = vertices.length;
  19071. var face, flen = faces.length;
  19072. for ( i = 0; i < vlen; i ++ ) {
  19073. vert = vertices[ i ];
  19074. this.vertices.push( new Vector3( vert.x, vert.y, 0 ) );
  19075. }
  19076. for ( i = 0; i < flen; i ++ ) {
  19077. face = faces[ i ];
  19078. var a = face[ 0 ] + shapesOffset;
  19079. var b = face[ 1 ] + shapesOffset;
  19080. var c = face[ 2 ] + shapesOffset;
  19081. this.faces.push( new Face3( a, b, c, null, null, material ) );
  19082. this.faceVertexUvs[ 0 ].push( uvgen.generateTopUV( this, a, b, c ) );
  19083. }
  19084. };
  19085. /**
  19086. * @author WestLangley / http://github.com/WestLangley
  19087. */
  19088. function EdgesGeometry( geometry, thresholdAngle ) {
  19089. BufferGeometry.call( this );
  19090. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  19091. var thresholdDot = Math.cos( exports.Math.DEG2RAD * thresholdAngle );
  19092. var edge = [ 0, 0 ], hash = {};
  19093. function sortFunction( a, b ) {
  19094. return a - b;
  19095. }
  19096. var keys = [ 'a', 'b', 'c' ];
  19097. var geometry2;
  19098. if ( (geometry && geometry.isBufferGeometry) ) {
  19099. geometry2 = new Geometry();
  19100. geometry2.fromBufferGeometry( geometry );
  19101. } else {
  19102. geometry2 = geometry.clone();
  19103. }
  19104. geometry2.mergeVertices();
  19105. geometry2.computeFaceNormals();
  19106. var vertices = geometry2.vertices;
  19107. var faces = geometry2.faces;
  19108. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  19109. var face = faces[ i ];
  19110. for ( var j = 0; j < 3; j ++ ) {
  19111. edge[ 0 ] = face[ keys[ j ] ];
  19112. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  19113. edge.sort( sortFunction );
  19114. var key = edge.toString();
  19115. if ( hash[ key ] === undefined ) {
  19116. hash[ key ] = { vert1: edge[ 0 ], vert2: edge[ 1 ], face1: i, face2: undefined };
  19117. } else {
  19118. hash[ key ].face2 = i;
  19119. }
  19120. }
  19121. }
  19122. var coords = [];
  19123. for ( var key in hash ) {
  19124. var h = hash[ key ];
  19125. if ( h.face2 === undefined || faces[ h.face1 ].normal.dot( faces[ h.face2 ].normal ) <= thresholdDot ) {
  19126. var vertex = vertices[ h.vert1 ];
  19127. coords.push( vertex.x );
  19128. coords.push( vertex.y );
  19129. coords.push( vertex.z );
  19130. vertex = vertices[ h.vert2 ];
  19131. coords.push( vertex.x );
  19132. coords.push( vertex.y );
  19133. coords.push( vertex.z );
  19134. }
  19135. }
  19136. this.addAttribute( 'position', new BufferAttribute( new Float32Array( coords ), 3 ) );
  19137. }
  19138. EdgesGeometry.prototype = Object.create( BufferGeometry.prototype );
  19139. EdgesGeometry.prototype.constructor = EdgesGeometry;
  19140. /**
  19141. * @author Mugen87 / https://github.com/Mugen87
  19142. */
  19143. function CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  19144. BufferGeometry.call( this );
  19145. this.type = 'CylinderBufferGeometry';
  19146. this.parameters = {
  19147. radiusTop: radiusTop,
  19148. radiusBottom: radiusBottom,
  19149. height: height,
  19150. radialSegments: radialSegments,
  19151. heightSegments: heightSegments,
  19152. openEnded: openEnded,
  19153. thetaStart: thetaStart,
  19154. thetaLength: thetaLength
  19155. };
  19156. var scope = this;
  19157. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  19158. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  19159. height = height !== undefined ? height : 100;
  19160. radialSegments = Math.floor( radialSegments ) || 8;
  19161. heightSegments = Math.floor( heightSegments ) || 1;
  19162. openEnded = openEnded !== undefined ? openEnded : false;
  19163. thetaStart = thetaStart !== undefined ? thetaStart : 0.0;
  19164. thetaLength = thetaLength !== undefined ? thetaLength : 2.0 * Math.PI;
  19165. // used to calculate buffer length
  19166. var nbCap = 0;
  19167. if ( openEnded === false ) {
  19168. if ( radiusTop > 0 ) nbCap ++;
  19169. if ( radiusBottom > 0 ) nbCap ++;
  19170. }
  19171. var vertexCount = calculateVertexCount();
  19172. var indexCount = calculateIndexCount();
  19173. // buffers
  19174. var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ), 1 );
  19175. var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  19176. var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  19177. var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  19178. // helper variables
  19179. var index = 0,
  19180. indexOffset = 0,
  19181. indexArray = [],
  19182. halfHeight = height / 2;
  19183. // group variables
  19184. var groupStart = 0;
  19185. // generate geometry
  19186. generateTorso();
  19187. if ( openEnded === false ) {
  19188. if ( radiusTop > 0 ) generateCap( true );
  19189. if ( radiusBottom > 0 ) generateCap( false );
  19190. }
  19191. // build geometry
  19192. this.setIndex( indices );
  19193. this.addAttribute( 'position', vertices );
  19194. this.addAttribute( 'normal', normals );
  19195. this.addAttribute( 'uv', uvs );
  19196. // helper functions
  19197. function calculateVertexCount() {
  19198. var count = ( radialSegments + 1 ) * ( heightSegments + 1 );
  19199. if ( openEnded === false ) {
  19200. count += ( ( radialSegments + 1 ) * nbCap ) + ( radialSegments * nbCap );
  19201. }
  19202. return count;
  19203. }
  19204. function calculateIndexCount() {
  19205. var count = radialSegments * heightSegments * 2 * 3;
  19206. if ( openEnded === false ) {
  19207. count += radialSegments * nbCap * 3;
  19208. }
  19209. return count;
  19210. }
  19211. function generateTorso() {
  19212. var x, y;
  19213. var normal = new Vector3();
  19214. var vertex = new Vector3();
  19215. var groupCount = 0;
  19216. // this will be used to calculate the normal
  19217. var tanTheta = ( radiusBottom - radiusTop ) / height;
  19218. // generate vertices, normals and uvs
  19219. for ( y = 0; y <= heightSegments; y ++ ) {
  19220. var indexRow = [];
  19221. var v = y / heightSegments;
  19222. // calculate the radius of the current row
  19223. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  19224. for ( x = 0; x <= radialSegments; x ++ ) {
  19225. var u = x / radialSegments;
  19226. // vertex
  19227. vertex.x = radius * Math.sin( u * thetaLength + thetaStart );
  19228. vertex.y = - v * height + halfHeight;
  19229. vertex.z = radius * Math.cos( u * thetaLength + thetaStart );
  19230. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  19231. // normal
  19232. normal.copy( vertex );
  19233. // handle special case if radiusTop/radiusBottom is zero
  19234. if ( ( radiusTop === 0 && y === 0 ) || ( radiusBottom === 0 && y === heightSegments ) ) {
  19235. normal.x = Math.sin( u * thetaLength + thetaStart );
  19236. normal.z = Math.cos( u * thetaLength + thetaStart );
  19237. }
  19238. normal.setY( Math.sqrt( normal.x * normal.x + normal.z * normal.z ) * tanTheta ).normalize();
  19239. normals.setXYZ( index, normal.x, normal.y, normal.z );
  19240. // uv
  19241. uvs.setXY( index, u, 1 - v );
  19242. // save index of vertex in respective row
  19243. indexRow.push( index );
  19244. // increase index
  19245. index ++;
  19246. }
  19247. // now save vertices of the row in our index array
  19248. indexArray.push( indexRow );
  19249. }
  19250. // generate indices
  19251. for ( x = 0; x < radialSegments; x ++ ) {
  19252. for ( y = 0; y < heightSegments; y ++ ) {
  19253. // we use the index array to access the correct indices
  19254. var i1 = indexArray[ y ][ x ];
  19255. var i2 = indexArray[ y + 1 ][ x ];
  19256. var i3 = indexArray[ y + 1 ][ x + 1 ];
  19257. var i4 = indexArray[ y ][ x + 1 ];
  19258. // face one
  19259. indices.setX( indexOffset, i1 ); indexOffset ++;
  19260. indices.setX( indexOffset, i2 ); indexOffset ++;
  19261. indices.setX( indexOffset, i4 ); indexOffset ++;
  19262. // face two
  19263. indices.setX( indexOffset, i2 ); indexOffset ++;
  19264. indices.setX( indexOffset, i3 ); indexOffset ++;
  19265. indices.setX( indexOffset, i4 ); indexOffset ++;
  19266. // update counters
  19267. groupCount += 6;
  19268. }
  19269. }
  19270. // add a group to the geometry. this will ensure multi material support
  19271. scope.addGroup( groupStart, groupCount, 0 );
  19272. // calculate new start value for groups
  19273. groupStart += groupCount;
  19274. }
  19275. function generateCap( top ) {
  19276. var x, centerIndexStart, centerIndexEnd;
  19277. var uv = new Vector2();
  19278. var vertex = new Vector3();
  19279. var groupCount = 0;
  19280. var radius = ( top === true ) ? radiusTop : radiusBottom;
  19281. var sign = ( top === true ) ? 1 : - 1;
  19282. // save the index of the first center vertex
  19283. centerIndexStart = index;
  19284. // first we generate the center vertex data of the cap.
  19285. // because the geometry needs one set of uvs per face,
  19286. // we must generate a center vertex per face/segment
  19287. for ( x = 1; x <= radialSegments; x ++ ) {
  19288. // vertex
  19289. vertices.setXYZ( index, 0, halfHeight * sign, 0 );
  19290. // normal
  19291. normals.setXYZ( index, 0, sign, 0 );
  19292. // uv
  19293. uv.x = 0.5;
  19294. uv.y = 0.5;
  19295. uvs.setXY( index, uv.x, uv.y );
  19296. // increase index
  19297. index ++;
  19298. }
  19299. // save the index of the last center vertex
  19300. centerIndexEnd = index;
  19301. // now we generate the surrounding vertices, normals and uvs
  19302. for ( x = 0; x <= radialSegments; x ++ ) {
  19303. var u = x / radialSegments;
  19304. var theta = u * thetaLength + thetaStart;
  19305. var cosTheta = Math.cos( theta );
  19306. var sinTheta = Math.sin( theta );
  19307. // vertex
  19308. vertex.x = radius * sinTheta;
  19309. vertex.y = halfHeight * sign;
  19310. vertex.z = radius * cosTheta;
  19311. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  19312. // normal
  19313. normals.setXYZ( index, 0, sign, 0 );
  19314. // uv
  19315. uv.x = ( cosTheta * 0.5 ) + 0.5;
  19316. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  19317. uvs.setXY( index, uv.x, uv.y );
  19318. // increase index
  19319. index ++;
  19320. }
  19321. // generate indices
  19322. for ( x = 0; x < radialSegments; x ++ ) {
  19323. var c = centerIndexStart + x;
  19324. var i = centerIndexEnd + x;
  19325. if ( top === true ) {
  19326. // face top
  19327. indices.setX( indexOffset, i ); indexOffset ++;
  19328. indices.setX( indexOffset, i + 1 ); indexOffset ++;
  19329. indices.setX( indexOffset, c ); indexOffset ++;
  19330. } else {
  19331. // face bottom
  19332. indices.setX( indexOffset, i + 1 ); indexOffset ++;
  19333. indices.setX( indexOffset, i ); indexOffset ++;
  19334. indices.setX( indexOffset, c ); indexOffset ++;
  19335. }
  19336. // update counters
  19337. groupCount += 3;
  19338. }
  19339. // add a group to the geometry. this will ensure multi material support
  19340. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  19341. // calculate new start value for groups
  19342. groupStart += groupCount;
  19343. }
  19344. }
  19345. CylinderBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  19346. CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry;
  19347. /**
  19348. * @author mrdoob / http://mrdoob.com/
  19349. */
  19350. function CylinderGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  19351. Geometry.call( this );
  19352. this.type = 'CylinderGeometry';
  19353. this.parameters = {
  19354. radiusTop: radiusTop,
  19355. radiusBottom: radiusBottom,
  19356. height: height,
  19357. radialSegments: radialSegments,
  19358. heightSegments: heightSegments,
  19359. openEnded: openEnded,
  19360. thetaStart: thetaStart,
  19361. thetaLength: thetaLength
  19362. };
  19363. this.fromBufferGeometry( new CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) );
  19364. this.mergeVertices();
  19365. }
  19366. CylinderGeometry.prototype = Object.create( Geometry.prototype );
  19367. CylinderGeometry.prototype.constructor = CylinderGeometry;
  19368. /**
  19369. * @author abelnation / http://github.com/abelnation
  19370. */
  19371. function ConeGeometry(
  19372. radius, height,
  19373. radialSegments, heightSegments,
  19374. openEnded, thetaStart, thetaLength ) {
  19375. CylinderGeometry.call( this,
  19376. 0, radius, height,
  19377. radialSegments, heightSegments,
  19378. openEnded, thetaStart, thetaLength );
  19379. this.type = 'ConeGeometry';
  19380. this.parameters = {
  19381. radius: radius,
  19382. height: height,
  19383. radialSegments: radialSegments,
  19384. heightSegments: heightSegments,
  19385. openEnded: openEnded,
  19386. thetaStart: thetaStart,
  19387. thetaLength: thetaLength
  19388. };
  19389. }
  19390. ConeGeometry.prototype = Object.create( CylinderGeometry.prototype );
  19391. ConeGeometry.prototype.constructor = ConeGeometry;
  19392. /*
  19393. * @author: abelnation / http://github.com/abelnation
  19394. */
  19395. function ConeBufferGeometry(
  19396. radius, height,
  19397. radialSegments, heightSegments,
  19398. openEnded, thetaStart, thetaLength ) {
  19399. CylinderBufferGeometry.call( this,
  19400. 0, radius, height,
  19401. radialSegments, heightSegments,
  19402. openEnded, thetaStart, thetaLength );
  19403. this.type = 'ConeBufferGeometry';
  19404. this.parameters = {
  19405. radius: radius,
  19406. height: height,
  19407. radialSegments: radialSegments,
  19408. heightSegments: heightSegments,
  19409. thetaStart: thetaStart,
  19410. thetaLength: thetaLength
  19411. };
  19412. }
  19413. ConeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  19414. ConeBufferGeometry.prototype.constructor = ConeBufferGeometry;
  19415. /**
  19416. * @author benaadams / https://twitter.com/ben_a_adams
  19417. */
  19418. function CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) {
  19419. BufferGeometry.call( this );
  19420. this.type = 'CircleBufferGeometry';
  19421. this.parameters = {
  19422. radius: radius,
  19423. segments: segments,
  19424. thetaStart: thetaStart,
  19425. thetaLength: thetaLength
  19426. };
  19427. radius = radius || 50;
  19428. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  19429. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19430. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19431. var vertices = segments + 2;
  19432. var positions = new Float32Array( vertices * 3 );
  19433. var normals = new Float32Array( vertices * 3 );
  19434. var uvs = new Float32Array( vertices * 2 );
  19435. // center data is already zero, but need to set a few extras
  19436. normals[ 2 ] = 1.0;
  19437. uvs[ 0 ] = 0.5;
  19438. uvs[ 1 ] = 0.5;
  19439. for ( var s = 0, i = 3, ii = 2 ; s <= segments; s ++, i += 3, ii += 2 ) {
  19440. var segment = thetaStart + s / segments * thetaLength;
  19441. positions[ i ] = radius * Math.cos( segment );
  19442. positions[ i + 1 ] = radius * Math.sin( segment );
  19443. normals[ i + 2 ] = 1; // normal z
  19444. uvs[ ii ] = ( positions[ i ] / radius + 1 ) / 2;
  19445. uvs[ ii + 1 ] = ( positions[ i + 1 ] / radius + 1 ) / 2;
  19446. }
  19447. var indices = [];
  19448. for ( var i = 1; i <= segments; i ++ ) {
  19449. indices.push( i, i + 1, 0 );
  19450. }
  19451. this.setIndex( new BufferAttribute( new Uint16Array( indices ), 1 ) );
  19452. this.addAttribute( 'position', new BufferAttribute( positions, 3 ) );
  19453. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) );
  19454. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) );
  19455. this.boundingSphere = new Sphere( new Vector3(), radius );
  19456. }
  19457. CircleBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  19458. CircleBufferGeometry.prototype.constructor = CircleBufferGeometry;
  19459. /**
  19460. * @author hughes
  19461. */
  19462. function CircleGeometry( radius, segments, thetaStart, thetaLength ) {
  19463. Geometry.call( this );
  19464. this.type = 'CircleGeometry';
  19465. this.parameters = {
  19466. radius: radius,
  19467. segments: segments,
  19468. thetaStart: thetaStart,
  19469. thetaLength: thetaLength
  19470. };
  19471. this.fromBufferGeometry( new CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) );
  19472. }
  19473. CircleGeometry.prototype = Object.create( Geometry.prototype );
  19474. CircleGeometry.prototype.constructor = CircleGeometry;
  19475. /**
  19476. * @author mrdoob / http://mrdoob.com/
  19477. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  19478. */
  19479. function BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  19480. Geometry.call( this );
  19481. this.type = 'BoxGeometry';
  19482. this.parameters = {
  19483. width: width,
  19484. height: height,
  19485. depth: depth,
  19486. widthSegments: widthSegments,
  19487. heightSegments: heightSegments,
  19488. depthSegments: depthSegments
  19489. };
  19490. this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) );
  19491. this.mergeVertices();
  19492. }
  19493. BoxGeometry.prototype = Object.create( Geometry.prototype );
  19494. BoxGeometry.prototype.constructor = BoxGeometry;
  19495. var Geometries = Object.freeze({
  19496. WireframeGeometry: WireframeGeometry,
  19497. ParametricGeometry: ParametricGeometry,
  19498. TetrahedronGeometry: TetrahedronGeometry,
  19499. OctahedronGeometry: OctahedronGeometry,
  19500. IcosahedronGeometry: IcosahedronGeometry,
  19501. DodecahedronGeometry: DodecahedronGeometry,
  19502. PolyhedronGeometry: PolyhedronGeometry,
  19503. TubeGeometry: TubeGeometry,
  19504. TorusKnotGeometry: TorusKnotGeometry,
  19505. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  19506. TorusGeometry: TorusGeometry,
  19507. TorusBufferGeometry: TorusBufferGeometry,
  19508. TextGeometry: TextGeometry,
  19509. SphereBufferGeometry: SphereBufferGeometry,
  19510. SphereGeometry: SphereGeometry,
  19511. RingGeometry: RingGeometry,
  19512. RingBufferGeometry: RingBufferGeometry,
  19513. PlaneBufferGeometry: PlaneBufferGeometry,
  19514. PlaneGeometry: PlaneGeometry,
  19515. LatheGeometry: LatheGeometry,
  19516. LatheBufferGeometry: LatheBufferGeometry,
  19517. ShapeGeometry: ShapeGeometry,
  19518. ExtrudeGeometry: ExtrudeGeometry,
  19519. EdgesGeometry: EdgesGeometry,
  19520. ConeGeometry: ConeGeometry,
  19521. ConeBufferGeometry: ConeBufferGeometry,
  19522. CylinderGeometry: CylinderGeometry,
  19523. CylinderBufferGeometry: CylinderBufferGeometry,
  19524. CircleBufferGeometry: CircleBufferGeometry,
  19525. CircleGeometry: CircleGeometry,
  19526. BoxBufferGeometry: BoxBufferGeometry,
  19527. BoxGeometry: BoxGeometry
  19528. });
  19529. /**
  19530. * @author mrdoob / http://mrdoob.com/
  19531. */
  19532. function ObjectLoader ( manager ) {
  19533. this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager;
  19534. this.texturePath = '';
  19535. }
  19536. Object.assign( ObjectLoader.prototype, {
  19537. load: function ( url, onLoad, onProgress, onError ) {
  19538. if ( this.texturePath === '' ) {
  19539. this.texturePath = url.substring( 0, url.lastIndexOf( '/' ) + 1 );
  19540. }
  19541. var scope = this;
  19542. var loader = new XHRLoader( scope.manager );
  19543. loader.load( url, function ( text ) {
  19544. scope.parse( JSON.parse( text ), onLoad );
  19545. }, onProgress, onError );
  19546. },
  19547. setTexturePath: function ( value ) {
  19548. this.texturePath = value;
  19549. },
  19550. setCrossOrigin: function ( value ) {
  19551. this.crossOrigin = value;
  19552. },
  19553. parse: function ( json, onLoad ) {
  19554. var geometries = this.parseGeometries( json.geometries );
  19555. var images = this.parseImages( json.images, function () {
  19556. if ( onLoad !== undefined ) onLoad( object );
  19557. } );
  19558. var textures = this.parseTextures( json.textures, images );
  19559. var materials = this.parseMaterials( json.materials, textures );
  19560. var object = this.parseObject( json.object, geometries, materials );
  19561. if ( json.animations ) {
  19562. object.animations = this.parseAnimations( json.animations );
  19563. }
  19564. if ( json.images === undefined || json.images.length === 0 ) {
  19565. if ( onLoad !== undefined ) onLoad( object );
  19566. }
  19567. return object;
  19568. },
  19569. parseGeometries: function ( json ) {
  19570. var geometries = {};
  19571. if ( json !== undefined ) {
  19572. var geometryLoader = new JSONLoader();
  19573. var bufferGeometryLoader = new BufferGeometryLoader();
  19574. for ( var i = 0, l = json.length; i < l; i ++ ) {
  19575. var geometry;
  19576. var data = json[ i ];
  19577. switch ( data.type ) {
  19578. case 'PlaneGeometry':
  19579. case 'PlaneBufferGeometry':
  19580. geometry = new Geometries[ data.type ](
  19581. data.width,
  19582. data.height,
  19583. data.widthSegments,
  19584. data.heightSegments
  19585. );
  19586. break;
  19587. case 'BoxGeometry':
  19588. case 'BoxBufferGeometry':
  19589. case 'CubeGeometry': // backwards compatible
  19590. geometry = new Geometries[ data.type ](
  19591. data.width,
  19592. data.height,
  19593. data.depth,
  19594. data.widthSegments,
  19595. data.heightSegments,
  19596. data.depthSegments
  19597. );
  19598. break;
  19599. case 'CircleGeometry':
  19600. case 'CircleBufferGeometry':
  19601. geometry = new Geometries[ data.type ](
  19602. data.radius,
  19603. data.segments,
  19604. data.thetaStart,
  19605. data.thetaLength
  19606. );
  19607. break;
  19608. case 'CylinderGeometry':
  19609. case 'CylinderBufferGeometry':
  19610. geometry = new Geometries[ data.type ](
  19611. data.radiusTop,
  19612. data.radiusBottom,
  19613. data.height,
  19614. data.radialSegments,
  19615. data.heightSegments,
  19616. data.openEnded,
  19617. data.thetaStart,
  19618. data.thetaLength
  19619. );
  19620. break;
  19621. case 'ConeGeometry':
  19622. case 'ConeBufferGeometry':
  19623. geometry = new Geometries[ data.type ](
  19624. data.radius,
  19625. data.height,
  19626. data.radialSegments,
  19627. data.heightSegments,
  19628. data.openEnded,
  19629. data.thetaStart,
  19630. data.thetaLength
  19631. );
  19632. break;
  19633. case 'SphereGeometry':
  19634. case 'SphereBufferGeometry':
  19635. geometry = new Geometries[ data.type ](
  19636. data.radius,
  19637. data.widthSegments,
  19638. data.heightSegments,
  19639. data.phiStart,
  19640. data.phiLength,
  19641. data.thetaStart,
  19642. data.thetaLength
  19643. );
  19644. break;
  19645. case 'DodecahedronGeometry':
  19646. case 'IcosahedronGeometry':
  19647. case 'OctahedronGeometry':
  19648. case 'TetrahedronGeometry':
  19649. geometry = new Geometries[ data.type ](
  19650. data.radius,
  19651. data.detail
  19652. );
  19653. break;
  19654. case 'RingGeometry':
  19655. case 'RingBufferGeometry':
  19656. geometry = new Geometries[ data.type ](
  19657. data.innerRadius,
  19658. data.outerRadius,
  19659. data.thetaSegments,
  19660. data.phiSegments,
  19661. data.thetaStart,
  19662. data.thetaLength
  19663. );
  19664. break;
  19665. case 'TorusGeometry':
  19666. case 'TorusBufferGeometry':
  19667. geometry = new Geometries[ data.type ](
  19668. data.radius,
  19669. data.tube,
  19670. data.radialSegments,
  19671. data.tubularSegments,
  19672. data.arc
  19673. );
  19674. break;
  19675. case 'TorusKnotGeometry':
  19676. case 'TorusKnotBufferGeometry':
  19677. geometry = new Geometries[ data.type ](
  19678. data.radius,
  19679. data.tube,
  19680. data.tubularSegments,
  19681. data.radialSegments,
  19682. data.p,
  19683. data.q
  19684. );
  19685. break;
  19686. case 'LatheGeometry':
  19687. case 'LatheBufferGeometry':
  19688. geometry = new Geometries[ data.type ](
  19689. data.points,
  19690. data.segments,
  19691. data.phiStart,
  19692. data.phiLength
  19693. );
  19694. break;
  19695. case 'BufferGeometry':
  19696. geometry = bufferGeometryLoader.parse( data );
  19697. break;
  19698. case 'Geometry':
  19699. geometry = geometryLoader.parse( data.data, this.texturePath ).geometry;
  19700. break;
  19701. default:
  19702. console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' );
  19703. continue;
  19704. }
  19705. geometry.uuid = data.uuid;
  19706. if ( data.name !== undefined ) geometry.name = data.name;
  19707. geometries[ data.uuid ] = geometry;
  19708. }
  19709. }
  19710. return geometries;
  19711. },
  19712. parseMaterials: function ( json, textures ) {
  19713. var materials = {};
  19714. if ( json !== undefined ) {
  19715. var loader = new MaterialLoader();
  19716. loader.setTextures( textures );
  19717. for ( var i = 0, l = json.length; i < l; i ++ ) {
  19718. var material = loader.parse( json[ i ] );
  19719. materials[ material.uuid ] = material;
  19720. }
  19721. }
  19722. return materials;
  19723. },
  19724. parseAnimations: function ( json ) {
  19725. var animations = [];
  19726. for ( var i = 0; i < json.length; i ++ ) {
  19727. var clip = AnimationClip.parse( json[ i ] );
  19728. animations.push( clip );
  19729. }
  19730. return animations;
  19731. },
  19732. parseImages: function ( json, onLoad ) {
  19733. var scope = this;
  19734. var images = {};
  19735. function loadImage( url ) {
  19736. scope.manager.itemStart( url );
  19737. return loader.load( url, function () {
  19738. scope.manager.itemEnd( url );
  19739. }, undefined, function () {
  19740. scope.manager.itemError( url );
  19741. } );
  19742. }
  19743. if ( json !== undefined && json.length > 0 ) {
  19744. var manager = new LoadingManager( onLoad );
  19745. var loader = new ImageLoader( manager );
  19746. loader.setCrossOrigin( this.crossOrigin );
  19747. for ( var i = 0, l = json.length; i < l; i ++ ) {
  19748. var image = json[ i ];
  19749. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.texturePath + image.url;
  19750. images[ image.uuid ] = loadImage( path );
  19751. }
  19752. }
  19753. return images;
  19754. },
  19755. parseTextures: function ( json, images ) {
  19756. function parseConstant( value, type ) {
  19757. if ( typeof( value ) === 'number' ) return value;
  19758. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  19759. return type[ value ];
  19760. }
  19761. var textures = {};
  19762. if ( json !== undefined ) {
  19763. for ( var i = 0, l = json.length; i < l; i ++ ) {
  19764. var data = json[ i ];
  19765. if ( data.image === undefined ) {
  19766. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  19767. }
  19768. if ( images[ data.image ] === undefined ) {
  19769. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  19770. }
  19771. var texture = new Texture( images[ data.image ] );
  19772. texture.needsUpdate = true;
  19773. texture.uuid = data.uuid;
  19774. if ( data.name !== undefined ) texture.name = data.name;
  19775. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TextureMapping );
  19776. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  19777. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  19778. if ( data.wrap !== undefined ) {
  19779. texture.wrapS = parseConstant( data.wrap[ 0 ], TextureWrapping );
  19780. texture.wrapT = parseConstant( data.wrap[ 1 ], TextureWrapping );
  19781. }
  19782. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TextureFilter );
  19783. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TextureFilter );
  19784. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  19785. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  19786. textures[ data.uuid ] = texture;
  19787. }
  19788. }
  19789. return textures;
  19790. },
  19791. parseObject: function () {
  19792. var matrix = new Matrix4();
  19793. return function parseObject( data, geometries, materials ) {
  19794. var object;
  19795. function getGeometry( name ) {
  19796. if ( geometries[ name ] === undefined ) {
  19797. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  19798. }
  19799. return geometries[ name ];
  19800. }
  19801. function getMaterial( name ) {
  19802. if ( name === undefined ) return undefined;
  19803. if ( materials[ name ] === undefined ) {
  19804. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  19805. }
  19806. return materials[ name ];
  19807. }
  19808. switch ( data.type ) {
  19809. case 'Scene':
  19810. object = new Scene();
  19811. if ( data.background !== undefined ) {
  19812. if ( Number.isInteger( data.background ) ) {
  19813. object.background = new Color( data.background );
  19814. }
  19815. }
  19816. if ( data.fog !== undefined ) {
  19817. if ( data.fog.type === 'Fog' ) {
  19818. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  19819. } else if ( data.fog.type === 'FogExp2' ) {
  19820. object.fog = new FogExp2( data.fog.color, data.fog.density );
  19821. }
  19822. }
  19823. break;
  19824. case 'PerspectiveCamera':
  19825. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  19826. if ( data.focus !== undefined ) object.focus = data.focus;
  19827. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  19828. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  19829. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  19830. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  19831. break;
  19832. case 'OrthographicCamera':
  19833. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  19834. break;
  19835. case 'AmbientLight':
  19836. object = new AmbientLight( data.color, data.intensity );
  19837. break;
  19838. case 'DirectionalLight':
  19839. object = new DirectionalLight( data.color, data.intensity );
  19840. break;
  19841. case 'PointLight':
  19842. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  19843. break;
  19844. case 'SpotLight':
  19845. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  19846. break;
  19847. case 'HemisphereLight':
  19848. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  19849. break;
  19850. case 'Mesh':
  19851. var geometry = getGeometry( data.geometry );
  19852. var material = getMaterial( data.material );
  19853. if ( geometry.bones && geometry.bones.length > 0 ) {
  19854. object = new SkinnedMesh( geometry, material );
  19855. } else {
  19856. object = new Mesh( geometry, material );
  19857. }
  19858. break;
  19859. case 'LOD':
  19860. object = new LOD();
  19861. break;
  19862. case 'Line':
  19863. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode );
  19864. break;
  19865. case 'LineSegments':
  19866. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  19867. break;
  19868. case 'PointCloud':
  19869. case 'Points':
  19870. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  19871. break;
  19872. case 'Sprite':
  19873. object = new Sprite( getMaterial( data.material ) );
  19874. break;
  19875. case 'Group':
  19876. object = new Group();
  19877. break;
  19878. default:
  19879. object = new Object3D();
  19880. }
  19881. object.uuid = data.uuid;
  19882. if ( data.name !== undefined ) object.name = data.name;
  19883. if ( data.matrix !== undefined ) {
  19884. matrix.fromArray( data.matrix );
  19885. matrix.decompose( object.position, object.quaternion, object.scale );
  19886. } else {
  19887. if ( data.position !== undefined ) object.position.fromArray( data.position );
  19888. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  19889. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  19890. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  19891. }
  19892. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  19893. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  19894. if ( data.shadow ) {
  19895. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  19896. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  19897. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  19898. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  19899. }
  19900. if ( data.visible !== undefined ) object.visible = data.visible;
  19901. if ( data.userData !== undefined ) object.userData = data.userData;
  19902. if ( data.children !== undefined ) {
  19903. for ( var child in data.children ) {
  19904. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  19905. }
  19906. }
  19907. if ( data.type === 'LOD' ) {
  19908. var levels = data.levels;
  19909. for ( var l = 0; l < levels.length; l ++ ) {
  19910. var level = levels[ l ];
  19911. var child = object.getObjectByProperty( 'uuid', level.object );
  19912. if ( child !== undefined ) {
  19913. object.addLevel( child, level.distance );
  19914. }
  19915. }
  19916. }
  19917. return object;
  19918. };
  19919. }()
  19920. } );
  19921. /**
  19922. * @author zz85 / http://www.lab4games.net/zz85/blog
  19923. * Extensible curve object
  19924. *
  19925. * Some common of Curve methods
  19926. * .getPoint(t), getTangent(t)
  19927. * .getPointAt(u), getTangentAt(u)
  19928. * .getPoints(), .getSpacedPoints()
  19929. * .getLength()
  19930. * .updateArcLengths()
  19931. *
  19932. * This following classes subclasses THREE.Curve:
  19933. *
  19934. * -- 2d classes --
  19935. * THREE.LineCurve
  19936. * THREE.QuadraticBezierCurve
  19937. * THREE.CubicBezierCurve
  19938. * THREE.SplineCurve
  19939. * THREE.ArcCurve
  19940. * THREE.EllipseCurve
  19941. *
  19942. * -- 3d classes --
  19943. * THREE.LineCurve3
  19944. * THREE.QuadraticBezierCurve3
  19945. * THREE.CubicBezierCurve3
  19946. * THREE.SplineCurve3
  19947. *
  19948. * A series of curves can be represented as a THREE.CurvePath
  19949. *
  19950. **/
  19951. /**************************************************************
  19952. * Abstract Curve base class
  19953. **************************************************************/
  19954. function Curve() {}
  19955. Curve.prototype = {
  19956. constructor: Curve,
  19957. // Virtual base class method to overwrite and implement in subclasses
  19958. // - t [0 .. 1]
  19959. getPoint: function ( t ) {
  19960. console.warn( "THREE.Curve: Warning, getPoint() not implemented!" );
  19961. return null;
  19962. },
  19963. // Get point at relative position in curve according to arc length
  19964. // - u [0 .. 1]
  19965. getPointAt: function ( u ) {
  19966. var t = this.getUtoTmapping( u );
  19967. return this.getPoint( t );
  19968. },
  19969. // Get sequence of points using getPoint( t )
  19970. getPoints: function ( divisions ) {
  19971. if ( ! divisions ) divisions = 5;
  19972. var points = [];
  19973. for ( var d = 0; d <= divisions; d ++ ) {
  19974. points.push( this.getPoint( d / divisions ) );
  19975. }
  19976. return points;
  19977. },
  19978. // Get sequence of points using getPointAt( u )
  19979. getSpacedPoints: function ( divisions ) {
  19980. if ( ! divisions ) divisions = 5;
  19981. var points = [];
  19982. for ( var d = 0; d <= divisions; d ++ ) {
  19983. points.push( this.getPointAt( d / divisions ) );
  19984. }
  19985. return points;
  19986. },
  19987. // Get total curve arc length
  19988. getLength: function () {
  19989. var lengths = this.getLengths();
  19990. return lengths[ lengths.length - 1 ];
  19991. },
  19992. // Get list of cumulative segment lengths
  19993. getLengths: function ( divisions ) {
  19994. if ( ! divisions ) divisions = ( this.__arcLengthDivisions ) ? ( this.__arcLengthDivisions ) : 200;
  19995. if ( this.cacheArcLengths
  19996. && ( this.cacheArcLengths.length === divisions + 1 )
  19997. && ! this.needsUpdate ) {
  19998. //console.log( "cached", this.cacheArcLengths );
  19999. return this.cacheArcLengths;
  20000. }
  20001. this.needsUpdate = false;
  20002. var cache = [];
  20003. var current, last = this.getPoint( 0 );
  20004. var p, sum = 0;
  20005. cache.push( 0 );
  20006. for ( p = 1; p <= divisions; p ++ ) {
  20007. current = this.getPoint ( p / divisions );
  20008. sum += current.distanceTo( last );
  20009. cache.push( sum );
  20010. last = current;
  20011. }
  20012. this.cacheArcLengths = cache;
  20013. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  20014. },
  20015. updateArcLengths: function() {
  20016. this.needsUpdate = true;
  20017. this.getLengths();
  20018. },
  20019. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  20020. getUtoTmapping: function ( u, distance ) {
  20021. var arcLengths = this.getLengths();
  20022. var i = 0, il = arcLengths.length;
  20023. var targetArcLength; // The targeted u distance value to get
  20024. if ( distance ) {
  20025. targetArcLength = distance;
  20026. } else {
  20027. targetArcLength = u * arcLengths[ il - 1 ];
  20028. }
  20029. //var time = Date.now();
  20030. // binary search for the index with largest value smaller than target u distance
  20031. var low = 0, high = il - 1, comparison;
  20032. while ( low <= high ) {
  20033. 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
  20034. comparison = arcLengths[ i ] - targetArcLength;
  20035. if ( comparison < 0 ) {
  20036. low = i + 1;
  20037. } else if ( comparison > 0 ) {
  20038. high = i - 1;
  20039. } else {
  20040. high = i;
  20041. break;
  20042. // DONE
  20043. }
  20044. }
  20045. i = high;
  20046. //console.log('b' , i, low, high, Date.now()- time);
  20047. if ( arcLengths[ i ] === targetArcLength ) {
  20048. var t = i / ( il - 1 );
  20049. return t;
  20050. }
  20051. // we could get finer grain at lengths, or use simple interpolation between two points
  20052. var lengthBefore = arcLengths[ i ];
  20053. var lengthAfter = arcLengths[ i + 1 ];
  20054. var segmentLength = lengthAfter - lengthBefore;
  20055. // determine where we are between the 'before' and 'after' points
  20056. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  20057. // add that fractional amount to t
  20058. var t = ( i + segmentFraction ) / ( il - 1 );
  20059. return t;
  20060. },
  20061. // Returns a unit vector tangent at t
  20062. // In case any sub curve does not implement its tangent derivation,
  20063. // 2 points a small delta apart will be used to find its gradient
  20064. // which seems to give a reasonable approximation
  20065. getTangent: function( t ) {
  20066. var delta = 0.0001;
  20067. var t1 = t - delta;
  20068. var t2 = t + delta;
  20069. // Capping in case of danger
  20070. if ( t1 < 0 ) t1 = 0;
  20071. if ( t2 > 1 ) t2 = 1;
  20072. var pt1 = this.getPoint( t1 );
  20073. var pt2 = this.getPoint( t2 );
  20074. var vec = pt2.clone().sub( pt1 );
  20075. return vec.normalize();
  20076. },
  20077. getTangentAt: function ( u ) {
  20078. var t = this.getUtoTmapping( u );
  20079. return this.getTangent( t );
  20080. }
  20081. };
  20082. // TODO: Transformation for Curves?
  20083. /**************************************************************
  20084. * 3D Curves
  20085. **************************************************************/
  20086. // A Factory method for creating new curve subclasses
  20087. Curve.create = function ( constructor, getPointFunc ) {
  20088. constructor.prototype = Object.create( Curve.prototype );
  20089. constructor.prototype.constructor = constructor;
  20090. constructor.prototype.getPoint = getPointFunc;
  20091. return constructor;
  20092. };
  20093. /**************************************************************
  20094. * Line
  20095. **************************************************************/
  20096. function LineCurve( v1, v2 ) {
  20097. this.v1 = v1;
  20098. this.v2 = v2;
  20099. }
  20100. LineCurve.prototype = Object.create( Curve.prototype );
  20101. LineCurve.prototype.constructor = LineCurve;
  20102. LineCurve.prototype.isLineCurve = true;
  20103. LineCurve.prototype.getPoint = function ( t ) {
  20104. if ( t === 1 ) {
  20105. return this.v2.clone();
  20106. }
  20107. var point = this.v2.clone().sub( this.v1 );
  20108. point.multiplyScalar( t ).add( this.v1 );
  20109. return point;
  20110. };
  20111. // Line curve is linear, so we can overwrite default getPointAt
  20112. LineCurve.prototype.getPointAt = function ( u ) {
  20113. return this.getPoint( u );
  20114. };
  20115. LineCurve.prototype.getTangent = function( t ) {
  20116. var tangent = this.v2.clone().sub( this.v1 );
  20117. return tangent.normalize();
  20118. };
  20119. /**
  20120. * @author zz85 / http://www.lab4games.net/zz85/blog
  20121. *
  20122. **/
  20123. /**************************************************************
  20124. * Curved Path - a curve path is simply a array of connected
  20125. * curves, but retains the api of a curve
  20126. **************************************************************/
  20127. function CurvePath() {
  20128. this.curves = [];
  20129. this.autoClose = false; // Automatically closes the path
  20130. }
  20131. CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), {
  20132. constructor: CurvePath,
  20133. add: function ( curve ) {
  20134. this.curves.push( curve );
  20135. },
  20136. closePath: function () {
  20137. // Add a line curve if start and end of lines are not connected
  20138. var startPoint = this.curves[ 0 ].getPoint( 0 );
  20139. var endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  20140. if ( ! startPoint.equals( endPoint ) ) {
  20141. this.curves.push( new LineCurve( endPoint, startPoint ) );
  20142. }
  20143. },
  20144. // To get accurate point with reference to
  20145. // entire path distance at time t,
  20146. // following has to be done:
  20147. // 1. Length of each sub path have to be known
  20148. // 2. Locate and identify type of curve
  20149. // 3. Get t for the curve
  20150. // 4. Return curve.getPointAt(t')
  20151. getPoint: function ( t ) {
  20152. var d = t * this.getLength();
  20153. var curveLengths = this.getCurveLengths();
  20154. var i = 0;
  20155. // To think about boundaries points.
  20156. while ( i < curveLengths.length ) {
  20157. if ( curveLengths[ i ] >= d ) {
  20158. var diff = curveLengths[ i ] - d;
  20159. var curve = this.curves[ i ];
  20160. var segmentLength = curve.getLength();
  20161. var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  20162. return curve.getPointAt( u );
  20163. }
  20164. i ++;
  20165. }
  20166. return null;
  20167. // loop where sum != 0, sum > d , sum+1 <d
  20168. },
  20169. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  20170. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  20171. // getPoint() depends on getLength
  20172. getLength: function () {
  20173. var lens = this.getCurveLengths();
  20174. return lens[ lens.length - 1 ];
  20175. },
  20176. // cacheLengths must be recalculated.
  20177. updateArcLengths: function () {
  20178. this.needsUpdate = true;
  20179. this.cacheLengths = null;
  20180. this.getLengths();
  20181. },
  20182. // Compute lengths and cache them
  20183. // We cannot overwrite getLengths() because UtoT mapping uses it.
  20184. getCurveLengths: function () {
  20185. // We use cache values if curves and cache array are same length
  20186. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  20187. return this.cacheLengths;
  20188. }
  20189. // Get length of sub-curve
  20190. // Push sums into cached array
  20191. var lengths = [], sums = 0;
  20192. for ( var i = 0, l = this.curves.length; i < l; i ++ ) {
  20193. sums += this.curves[ i ].getLength();
  20194. lengths.push( sums );
  20195. }
  20196. this.cacheLengths = lengths;
  20197. return lengths;
  20198. },
  20199. getSpacedPoints: function ( divisions ) {
  20200. if ( ! divisions ) divisions = 40;
  20201. var points = [];
  20202. for ( var i = 0; i <= divisions; i ++ ) {
  20203. points.push( this.getPoint( i / divisions ) );
  20204. }
  20205. if ( this.autoClose ) {
  20206. points.push( points[ 0 ] );
  20207. }
  20208. return points;
  20209. },
  20210. getPoints: function ( divisions ) {
  20211. divisions = divisions || 12;
  20212. var points = [], last;
  20213. for ( var i = 0, curves = this.curves; i < curves.length; i ++ ) {
  20214. var curve = curves[ i ];
  20215. var resolution = (curve && curve.isEllipseCurve) ? divisions * 2
  20216. : (curve && curve.isLineCurve) ? 1
  20217. : (curve && curve.isSplineCurve) ? divisions * curve.points.length
  20218. : divisions;
  20219. var pts = curve.getPoints( resolution );
  20220. for ( var j = 0; j < pts.length; j++ ) {
  20221. var point = pts[ j ];
  20222. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  20223. points.push( point );
  20224. last = point;
  20225. }
  20226. }
  20227. if ( this.autoClose && points.length > 1 && !points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  20228. points.push( points[ 0 ] );
  20229. }
  20230. return points;
  20231. },
  20232. /**************************************************************
  20233. * Create Geometries Helpers
  20234. **************************************************************/
  20235. /// Generate geometry from path points (for Line or Points objects)
  20236. createPointsGeometry: function ( divisions ) {
  20237. var pts = this.getPoints( divisions );
  20238. return this.createGeometry( pts );
  20239. },
  20240. // Generate geometry from equidistant sampling along the path
  20241. createSpacedPointsGeometry: function ( divisions ) {
  20242. var pts = this.getSpacedPoints( divisions );
  20243. return this.createGeometry( pts );
  20244. },
  20245. createGeometry: function ( points ) {
  20246. var geometry = new Geometry();
  20247. for ( var i = 0, l = points.length; i < l; i ++ ) {
  20248. var point = points[ i ];
  20249. geometry.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );
  20250. }
  20251. return geometry;
  20252. }
  20253. } );
  20254. /**************************************************************
  20255. * Ellipse curve
  20256. **************************************************************/
  20257. function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  20258. this.aX = aX;
  20259. this.aY = aY;
  20260. this.xRadius = xRadius;
  20261. this.yRadius = yRadius;
  20262. this.aStartAngle = aStartAngle;
  20263. this.aEndAngle = aEndAngle;
  20264. this.aClockwise = aClockwise;
  20265. this.aRotation = aRotation || 0;
  20266. }
  20267. EllipseCurve.prototype = Object.create( Curve.prototype );
  20268. EllipseCurve.prototype.constructor = EllipseCurve;
  20269. EllipseCurve.prototype.isEllipseCurve = true;
  20270. EllipseCurve.prototype.getPoint = function( t ) {
  20271. var twoPi = Math.PI * 2;
  20272. var deltaAngle = this.aEndAngle - this.aStartAngle;
  20273. var samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  20274. // ensures that deltaAngle is 0 .. 2 PI
  20275. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  20276. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  20277. if ( deltaAngle < Number.EPSILON ) {
  20278. if ( samePoints ) {
  20279. deltaAngle = 0;
  20280. } else {
  20281. deltaAngle = twoPi;
  20282. }
  20283. }
  20284. if ( this.aClockwise === true && ! samePoints ) {
  20285. if ( deltaAngle === twoPi ) {
  20286. deltaAngle = - twoPi;
  20287. } else {
  20288. deltaAngle = deltaAngle - twoPi;
  20289. }
  20290. }
  20291. var angle = this.aStartAngle + t * deltaAngle;
  20292. var x = this.aX + this.xRadius * Math.cos( angle );
  20293. var y = this.aY + this.yRadius * Math.sin( angle );
  20294. if ( this.aRotation !== 0 ) {
  20295. var cos = Math.cos( this.aRotation );
  20296. var sin = Math.sin( this.aRotation );
  20297. var tx = x - this.aX;
  20298. var ty = y - this.aY;
  20299. // Rotate the point about the center of the ellipse.
  20300. x = tx * cos - ty * sin + this.aX;
  20301. y = tx * sin + ty * cos + this.aY;
  20302. }
  20303. return new Vector2( x, y );
  20304. };
  20305. /**
  20306. * @author zz85 / http://www.lab4games.net/zz85/blog
  20307. */
  20308. exports.CurveUtils = {
  20309. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  20310. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  20311. },
  20312. // Puay Bing, thanks for helping with this derivative!
  20313. tangentCubicBezier: function ( t, p0, p1, p2, p3 ) {
  20314. return - 3 * p0 * ( 1 - t ) * ( 1 - t ) +
  20315. 3 * p1 * ( 1 - t ) * ( 1 - t ) - 6 * t * p1 * ( 1 - t ) +
  20316. 6 * t * p2 * ( 1 - t ) - 3 * t * t * p2 +
  20317. 3 * t * t * p3;
  20318. },
  20319. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  20320. // To check if my formulas are correct
  20321. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  20322. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  20323. var h01 = - 6 * t * t + 6 * t; // − 2t3 + 3t2
  20324. var h11 = 3 * t * t - 2 * t; // t3 − t2
  20325. return h00 + h10 + h01 + h11;
  20326. },
  20327. // Catmull-Rom
  20328. interpolate: function( p0, p1, p2, p3, t ) {
  20329. var v0 = ( p2 - p0 ) * 0.5;
  20330. var v1 = ( p3 - p1 ) * 0.5;
  20331. var t2 = t * t;
  20332. var t3 = t * t2;
  20333. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  20334. }
  20335. };
  20336. /**************************************************************
  20337. * Spline curve
  20338. **************************************************************/
  20339. function SplineCurve( points /* array of Vector2 */ ) {
  20340. this.points = ( points === undefined ) ? [] : points;
  20341. }
  20342. SplineCurve.prototype = Object.create( Curve.prototype );
  20343. SplineCurve.prototype.constructor = SplineCurve;
  20344. SplineCurve.prototype.isSplineCurve = true;
  20345. SplineCurve.prototype.getPoint = function ( t ) {
  20346. var points = this.points;
  20347. var point = ( points.length - 1 ) * t;
  20348. var intPoint = Math.floor( point );
  20349. var weight = point - intPoint;
  20350. var point0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  20351. var point1 = points[ intPoint ];
  20352. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  20353. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  20354. var interpolate = exports.CurveUtils.interpolate;
  20355. return new Vector2(
  20356. interpolate( point0.x, point1.x, point2.x, point3.x, weight ),
  20357. interpolate( point0.y, point1.y, point2.y, point3.y, weight )
  20358. );
  20359. };
  20360. /**************************************************************
  20361. * Cubic Bezier curve
  20362. **************************************************************/
  20363. function CubicBezierCurve( v0, v1, v2, v3 ) {
  20364. this.v0 = v0;
  20365. this.v1 = v1;
  20366. this.v2 = v2;
  20367. this.v3 = v3;
  20368. }
  20369. CubicBezierCurve.prototype = Object.create( Curve.prototype );
  20370. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  20371. CubicBezierCurve.prototype.getPoint = function ( t ) {
  20372. var b3 = exports.ShapeUtils.b3;
  20373. return new Vector2(
  20374. b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ),
  20375. b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y )
  20376. );
  20377. };
  20378. CubicBezierCurve.prototype.getTangent = function( t ) {
  20379. var tangentCubicBezier = exports.CurveUtils.tangentCubicBezier;
  20380. return new Vector2(
  20381. tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ),
  20382. tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y )
  20383. ).normalize();
  20384. };
  20385. /**************************************************************
  20386. * Quadratic Bezier curve
  20387. **************************************************************/
  20388. function QuadraticBezierCurve( v0, v1, v2 ) {
  20389. this.v0 = v0;
  20390. this.v1 = v1;
  20391. this.v2 = v2;
  20392. }
  20393. QuadraticBezierCurve.prototype = Object.create( Curve.prototype );
  20394. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  20395. QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  20396. var b2 = exports.ShapeUtils.b2;
  20397. return new Vector2(
  20398. b2( t, this.v0.x, this.v1.x, this.v2.x ),
  20399. b2( t, this.v0.y, this.v1.y, this.v2.y )
  20400. );
  20401. };
  20402. QuadraticBezierCurve.prototype.getTangent = function( t ) {
  20403. var tangentQuadraticBezier = exports.CurveUtils.tangentQuadraticBezier;
  20404. return new Vector2(
  20405. tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x ),
  20406. tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y )
  20407. ).normalize();
  20408. };
  20409. var PathPrototype = Object.assign( Object.create( CurvePath.prototype ), {
  20410. fromPoints: function ( vectors ) {
  20411. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  20412. for ( var i = 1, l = vectors.length; i < l; i ++ ) {
  20413. this.lineTo( vectors[ i ].x, vectors[ i ].y );
  20414. }
  20415. },
  20416. moveTo: function ( x, y ) {
  20417. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  20418. },
  20419. lineTo: function ( x, y ) {
  20420. var curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  20421. this.curves.push( curve );
  20422. this.currentPoint.set( x, y );
  20423. },
  20424. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  20425. var curve = new QuadraticBezierCurve(
  20426. this.currentPoint.clone(),
  20427. new Vector2( aCPx, aCPy ),
  20428. new Vector2( aX, aY )
  20429. );
  20430. this.curves.push( curve );
  20431. this.currentPoint.set( aX, aY );
  20432. },
  20433. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  20434. var curve = new CubicBezierCurve(
  20435. this.currentPoint.clone(),
  20436. new Vector2( aCP1x, aCP1y ),
  20437. new Vector2( aCP2x, aCP2y ),
  20438. new Vector2( aX, aY )
  20439. );
  20440. this.curves.push( curve );
  20441. this.currentPoint.set( aX, aY );
  20442. },
  20443. splineThru: function ( pts /*Array of Vector*/ ) {
  20444. var npts = [ this.currentPoint.clone() ].concat( pts );
  20445. var curve = new SplineCurve( npts );
  20446. this.curves.push( curve );
  20447. this.currentPoint.copy( pts[ pts.length - 1 ] );
  20448. },
  20449. arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  20450. var x0 = this.currentPoint.x;
  20451. var y0 = this.currentPoint.y;
  20452. this.absarc( aX + x0, aY + y0, aRadius,
  20453. aStartAngle, aEndAngle, aClockwise );
  20454. },
  20455. absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  20456. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  20457. },
  20458. ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  20459. var x0 = this.currentPoint.x;
  20460. var y0 = this.currentPoint.y;
  20461. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  20462. },
  20463. absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  20464. var curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  20465. if ( this.curves.length > 0 ) {
  20466. // if a previous curve is present, attempt to join
  20467. var firstPoint = curve.getPoint( 0 );
  20468. if ( ! firstPoint.equals( this.currentPoint ) ) {
  20469. this.lineTo( firstPoint.x, firstPoint.y );
  20470. }
  20471. }
  20472. this.curves.push( curve );
  20473. var lastPoint = curve.getPoint( 1 );
  20474. this.currentPoint.copy( lastPoint );
  20475. }
  20476. } );
  20477. /**
  20478. * @author zz85 / http://www.lab4games.net/zz85/blog
  20479. * Defines a 2d shape plane using paths.
  20480. **/
  20481. // STEP 1 Create a path.
  20482. // STEP 2 Turn path into shape.
  20483. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  20484. // STEP 3a - Extract points from each shape, turn to vertices
  20485. // STEP 3b - Triangulate each shape, add faces.
  20486. function Shape() {
  20487. Path.apply( this, arguments );
  20488. this.holes = [];
  20489. }
  20490. Shape.prototype = Object.assign( Object.create( PathPrototype ), {
  20491. constructor: Shape,
  20492. // Convenience method to return ExtrudeGeometry
  20493. extrude: function ( options ) {
  20494. return new ExtrudeGeometry( this, options );
  20495. },
  20496. // Convenience method to return ShapeGeometry
  20497. makeGeometry: function ( options ) {
  20498. return new ShapeGeometry( this, options );
  20499. },
  20500. getPointsHoles: function ( divisions ) {
  20501. var holesPts = [];
  20502. for ( var i = 0, l = this.holes.length; i < l; i ++ ) {
  20503. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  20504. }
  20505. return holesPts;
  20506. },
  20507. // Get points of shape and holes (keypoints based on segments parameter)
  20508. extractAllPoints: function ( divisions ) {
  20509. return {
  20510. shape: this.getPoints( divisions ),
  20511. holes: this.getPointsHoles( divisions )
  20512. };
  20513. },
  20514. extractPoints: function ( divisions ) {
  20515. return this.extractAllPoints( divisions );
  20516. }
  20517. } );
  20518. /**
  20519. * @author zz85 / http://www.lab4games.net/zz85/blog
  20520. * Creates free form 2d path using series of points, lines or curves.
  20521. *
  20522. **/
  20523. function Path( points ) {
  20524. CurvePath.call( this );
  20525. this.currentPoint = new Vector2();
  20526. if ( points ) {
  20527. this.fromPoints( points );
  20528. }
  20529. }
  20530. Path.prototype = PathPrototype;
  20531. PathPrototype.constructor = Path;
  20532. // minimal class for proxing functions to Path. Replaces old "extractSubpaths()"
  20533. function ShapePath() {
  20534. this.subPaths = [];
  20535. this.currentPath = null;
  20536. }
  20537. ShapePath.prototype = {
  20538. moveTo: function ( x, y ) {
  20539. this.currentPath = new Path();
  20540. this.subPaths.push(this.currentPath);
  20541. this.currentPath.moveTo( x, y );
  20542. },
  20543. lineTo: function ( x, y ) {
  20544. this.currentPath.lineTo( x, y );
  20545. },
  20546. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  20547. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  20548. },
  20549. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  20550. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  20551. },
  20552. splineThru: function ( pts ) {
  20553. this.currentPath.splineThru( pts );
  20554. },
  20555. toShapes: function ( isCCW, noHoles ) {
  20556. function toShapesNoHoles( inSubpaths ) {
  20557. var shapes = [];
  20558. for ( var i = 0, l = inSubpaths.length; i < l; i ++ ) {
  20559. var tmpPath = inSubpaths[ i ];
  20560. var tmpShape = new Shape();
  20561. tmpShape.curves = tmpPath.curves;
  20562. shapes.push( tmpShape );
  20563. }
  20564. return shapes;
  20565. }
  20566. function isPointInsidePolygon( inPt, inPolygon ) {
  20567. var polyLen = inPolygon.length;
  20568. // inPt on polygon contour => immediate success or
  20569. // toggling of inside/outside at every single! intersection point of an edge
  20570. // with the horizontal line through inPt, left of inPt
  20571. // not counting lowerY endpoints of edges and whole edges on that line
  20572. var inside = false;
  20573. for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  20574. var edgeLowPt = inPolygon[ p ];
  20575. var edgeHighPt = inPolygon[ q ];
  20576. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  20577. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  20578. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  20579. // not parallel
  20580. if ( edgeDy < 0 ) {
  20581. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  20582. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  20583. }
  20584. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  20585. if ( inPt.y === edgeLowPt.y ) {
  20586. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  20587. // continue; // no intersection or edgeLowPt => doesn't count !!!
  20588. } else {
  20589. var perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  20590. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  20591. if ( perpEdge < 0 ) continue;
  20592. inside = ! inside; // true intersection left of inPt
  20593. }
  20594. } else {
  20595. // parallel or collinear
  20596. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  20597. // edge lies on the same horizontal line as inPt
  20598. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  20599. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  20600. // continue;
  20601. }
  20602. }
  20603. return inside;
  20604. }
  20605. var isClockWise = exports.ShapeUtils.isClockWise;
  20606. var subPaths = this.subPaths;
  20607. if ( subPaths.length === 0 ) return [];
  20608. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  20609. var solid, tmpPath, tmpShape, shapes = [];
  20610. if ( subPaths.length === 1 ) {
  20611. tmpPath = subPaths[ 0 ];
  20612. tmpShape = new Shape();
  20613. tmpShape.curves = tmpPath.curves;
  20614. shapes.push( tmpShape );
  20615. return shapes;
  20616. }
  20617. var holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  20618. holesFirst = isCCW ? ! holesFirst : holesFirst;
  20619. // console.log("Holes first", holesFirst);
  20620. var betterShapeHoles = [];
  20621. var newShapes = [];
  20622. var newShapeHoles = [];
  20623. var mainIdx = 0;
  20624. var tmpPoints;
  20625. newShapes[ mainIdx ] = undefined;
  20626. newShapeHoles[ mainIdx ] = [];
  20627. for ( var i = 0, l = subPaths.length; i < l; i ++ ) {
  20628. tmpPath = subPaths[ i ];
  20629. tmpPoints = tmpPath.getPoints();
  20630. solid = isClockWise( tmpPoints );
  20631. solid = isCCW ? ! solid : solid;
  20632. if ( solid ) {
  20633. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  20634. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  20635. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  20636. if ( holesFirst ) mainIdx ++;
  20637. newShapeHoles[ mainIdx ] = [];
  20638. //console.log('cw', i);
  20639. } else {
  20640. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  20641. //console.log('ccw', i);
  20642. }
  20643. }
  20644. // only Holes? -> probably all Shapes with wrong orientation
  20645. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  20646. if ( newShapes.length > 1 ) {
  20647. var ambiguous = false;
  20648. var toChange = [];
  20649. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  20650. betterShapeHoles[ sIdx ] = [];
  20651. }
  20652. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  20653. var sho = newShapeHoles[ sIdx ];
  20654. for ( var hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  20655. var ho = sho[ hIdx ];
  20656. var hole_unassigned = true;
  20657. for ( var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  20658. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  20659. if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  20660. if ( hole_unassigned ) {
  20661. hole_unassigned = false;
  20662. betterShapeHoles[ s2Idx ].push( ho );
  20663. } else {
  20664. ambiguous = true;
  20665. }
  20666. }
  20667. }
  20668. if ( hole_unassigned ) {
  20669. betterShapeHoles[ sIdx ].push( ho );
  20670. }
  20671. }
  20672. }
  20673. // console.log("ambiguous: ", ambiguous);
  20674. if ( toChange.length > 0 ) {
  20675. // console.log("to change: ", toChange);
  20676. if ( ! ambiguous ) newShapeHoles = betterShapeHoles;
  20677. }
  20678. }
  20679. var tmpHoles;
  20680. for ( var i = 0, il = newShapes.length; i < il; i ++ ) {
  20681. tmpShape = newShapes[ i ].s;
  20682. shapes.push( tmpShape );
  20683. tmpHoles = newShapeHoles[ i ];
  20684. for ( var j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  20685. tmpShape.holes.push( tmpHoles[ j ].h );
  20686. }
  20687. }
  20688. //console.log("shape", shapes);
  20689. return shapes;
  20690. }
  20691. }
  20692. /**
  20693. * @author zz85 / http://www.lab4games.net/zz85/blog
  20694. * @author mrdoob / http://mrdoob.com/
  20695. */
  20696. function Font( data ) {
  20697. this.data = data;
  20698. }
  20699. Object.assign( Font.prototype, {
  20700. isFont: true,
  20701. generateShapes: function ( text, size, divisions ) {
  20702. function createPaths( text ) {
  20703. var chars = String( text ).split( '' );
  20704. var scale = size / data.resolution;
  20705. var offset = 0;
  20706. var paths = [];
  20707. for ( var i = 0; i < chars.length; i ++ ) {
  20708. var ret = createPath( chars[ i ], scale, offset );
  20709. offset += ret.offset;
  20710. paths.push( ret.path );
  20711. }
  20712. return paths;
  20713. }
  20714. function createPath( c, scale, offset ) {
  20715. var glyph = data.glyphs[ c ] || data.glyphs[ '?' ];
  20716. if ( ! glyph ) return;
  20717. var path = new ShapePath();
  20718. var pts = [], b2 = exports.ShapeUtils.b2, b3 = exports.ShapeUtils.b3;
  20719. var x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2, laste;
  20720. if ( glyph.o ) {
  20721. var outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  20722. for ( var i = 0, l = outline.length; i < l; ) {
  20723. var action = outline[ i ++ ];
  20724. switch ( action ) {
  20725. case 'm': // moveTo
  20726. x = outline[ i ++ ] * scale + offset;
  20727. y = outline[ i ++ ] * scale;
  20728. path.moveTo( x, y );
  20729. break;
  20730. case 'l': // lineTo
  20731. x = outline[ i ++ ] * scale + offset;
  20732. y = outline[ i ++ ] * scale;
  20733. path.lineTo( x, y );
  20734. break;
  20735. case 'q': // quadraticCurveTo
  20736. cpx = outline[ i ++ ] * scale + offset;
  20737. cpy = outline[ i ++ ] * scale;
  20738. cpx1 = outline[ i ++ ] * scale + offset;
  20739. cpy1 = outline[ i ++ ] * scale;
  20740. path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
  20741. laste = pts[ pts.length - 1 ];
  20742. if ( laste ) {
  20743. cpx0 = laste.x;
  20744. cpy0 = laste.y;
  20745. for ( var i2 = 1; i2 <= divisions; i2 ++ ) {
  20746. var t = i2 / divisions;
  20747. b2( t, cpx0, cpx1, cpx );
  20748. b2( t, cpy0, cpy1, cpy );
  20749. }
  20750. }
  20751. break;
  20752. case 'b': // bezierCurveTo
  20753. cpx = outline[ i ++ ] * scale + offset;
  20754. cpy = outline[ i ++ ] * scale;
  20755. cpx1 = outline[ i ++ ] * scale + offset;
  20756. cpy1 = outline[ i ++ ] * scale;
  20757. cpx2 = outline[ i ++ ] * scale + offset;
  20758. cpy2 = outline[ i ++ ] * scale;
  20759. path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
  20760. laste = pts[ pts.length - 1 ];
  20761. if ( laste ) {
  20762. cpx0 = laste.x;
  20763. cpy0 = laste.y;
  20764. for ( var i2 = 1; i2 <= divisions; i2 ++ ) {
  20765. var t = i2 / divisions;
  20766. b3( t, cpx0, cpx1, cpx2, cpx );
  20767. b3( t, cpy0, cpy1, cpy2, cpy );
  20768. }
  20769. }
  20770. break;
  20771. }
  20772. }
  20773. }
  20774. return { offset: glyph.ha * scale, path: path };
  20775. }
  20776. //
  20777. if ( size === undefined ) size = 100;
  20778. if ( divisions === undefined ) divisions = 4;
  20779. var data = this.data;
  20780. var paths = createPaths( text );
  20781. var shapes = [];
  20782. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  20783. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  20784. }
  20785. return shapes;
  20786. }
  20787. } );
  20788. /**
  20789. * @author mrdoob / http://mrdoob.com/
  20790. */
  20791. function FontLoader( manager ) {
  20792. this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager;
  20793. }
  20794. Object.assign( FontLoader.prototype, {
  20795. load: function ( url, onLoad, onProgress, onError ) {
  20796. var scope = this;
  20797. var loader = new XHRLoader( this.manager );
  20798. loader.load( url, function ( text ) {
  20799. var json;
  20800. try {
  20801. json = JSON.parse( text );
  20802. } catch ( e ) {
  20803. console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' );
  20804. json = JSON.parse( text.substring( 65, text.length - 2 ) );
  20805. }
  20806. var font = scope.parse( json );
  20807. if ( onLoad ) onLoad( font );
  20808. }, onProgress, onError );
  20809. },
  20810. parse: function ( json ) {
  20811. return new Font( json );
  20812. }
  20813. } );
  20814. var context;
  20815. function getAudioContext() {
  20816. if ( context === undefined ) {
  20817. context = new ( window.AudioContext || window.webkitAudioContext )();
  20818. }
  20819. return context;
  20820. }
  20821. /**
  20822. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  20823. */
  20824. function AudioLoader( manager ) {
  20825. this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager;
  20826. }
  20827. Object.assign( AudioLoader.prototype, {
  20828. load: function ( url, onLoad, onProgress, onError ) {
  20829. var loader = new XHRLoader( this.manager );
  20830. loader.setResponseType( 'arraybuffer' );
  20831. loader.load( url, function ( buffer ) {
  20832. var context = getAudioContext();
  20833. context.decodeAudioData( buffer, function ( audioBuffer ) {
  20834. onLoad( audioBuffer );
  20835. } );
  20836. }, onProgress, onError );
  20837. }
  20838. } );
  20839. /**
  20840. * @author mrdoob / http://mrdoob.com/
  20841. */
  20842. function StereoCamera() {
  20843. this.type = 'StereoCamera';
  20844. this.aspect = 1;
  20845. this.eyeSep = 0.064;
  20846. this.cameraL = new PerspectiveCamera();
  20847. this.cameraL.layers.enable( 1 );
  20848. this.cameraL.matrixAutoUpdate = false;
  20849. this.cameraR = new PerspectiveCamera();
  20850. this.cameraR.layers.enable( 2 );
  20851. this.cameraR.matrixAutoUpdate = false;
  20852. }
  20853. Object.assign( StereoCamera.prototype, {
  20854. update: ( function () {
  20855. var focus, fov, aspect, near, far;
  20856. var eyeRight = new Matrix4();
  20857. var eyeLeft = new Matrix4();
  20858. return function update( camera ) {
  20859. var needsUpdate = focus !== camera.focus || fov !== camera.fov ||
  20860. aspect !== camera.aspect * this.aspect || near !== camera.near ||
  20861. far !== camera.far;
  20862. if ( needsUpdate ) {
  20863. focus = camera.focus;
  20864. fov = camera.fov;
  20865. aspect = camera.aspect * this.aspect;
  20866. near = camera.near;
  20867. far = camera.far;
  20868. // Off-axis stereoscopic effect based on
  20869. // http://paulbourke.net/stereographics/stereorender/
  20870. var projectionMatrix = camera.projectionMatrix.clone();
  20871. var eyeSep = this.eyeSep / 2;
  20872. var eyeSepOnProjection = eyeSep * near / focus;
  20873. var ymax = near * Math.tan( exports.Math.DEG2RAD * fov * 0.5 );
  20874. var xmin, xmax;
  20875. // translate xOffset
  20876. eyeLeft.elements[ 12 ] = - eyeSep;
  20877. eyeRight.elements[ 12 ] = eyeSep;
  20878. // for left eye
  20879. xmin = - ymax * aspect + eyeSepOnProjection;
  20880. xmax = ymax * aspect + eyeSepOnProjection;
  20881. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  20882. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  20883. this.cameraL.projectionMatrix.copy( projectionMatrix );
  20884. // for right eye
  20885. xmin = - ymax * aspect - eyeSepOnProjection;
  20886. xmax = ymax * aspect - eyeSepOnProjection;
  20887. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  20888. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  20889. this.cameraR.projectionMatrix.copy( projectionMatrix );
  20890. }
  20891. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( eyeLeft );
  20892. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( eyeRight );
  20893. };
  20894. } )()
  20895. } );
  20896. /**
  20897. * Camera for rendering cube maps
  20898. * - renders scene into axis-aligned cube
  20899. *
  20900. * @author alteredq / http://alteredqualia.com/
  20901. */
  20902. function CubeCamera( near, far, cubeResolution ) {
  20903. Object3D.call( this );
  20904. this.type = 'CubeCamera';
  20905. var fov = 90, aspect = 1;
  20906. var cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  20907. cameraPX.up.set( 0, - 1, 0 );
  20908. cameraPX.lookAt( new Vector3( 1, 0, 0 ) );
  20909. this.add( cameraPX );
  20910. var cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  20911. cameraNX.up.set( 0, - 1, 0 );
  20912. cameraNX.lookAt( new Vector3( - 1, 0, 0 ) );
  20913. this.add( cameraNX );
  20914. var cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  20915. cameraPY.up.set( 0, 0, 1 );
  20916. cameraPY.lookAt( new Vector3( 0, 1, 0 ) );
  20917. this.add( cameraPY );
  20918. var cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  20919. cameraNY.up.set( 0, 0, - 1 );
  20920. cameraNY.lookAt( new Vector3( 0, - 1, 0 ) );
  20921. this.add( cameraNY );
  20922. var cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  20923. cameraPZ.up.set( 0, - 1, 0 );
  20924. cameraPZ.lookAt( new Vector3( 0, 0, 1 ) );
  20925. this.add( cameraPZ );
  20926. var cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  20927. cameraNZ.up.set( 0, - 1, 0 );
  20928. cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) );
  20929. this.add( cameraNZ );
  20930. var options = { format: RGBFormat, magFilter: LinearFilter, minFilter: LinearFilter };
  20931. this.renderTarget = new WebGLRenderTargetCube( cubeResolution, cubeResolution, options );
  20932. this.updateCubeMap = function ( renderer, scene ) {
  20933. if ( this.parent === null ) this.updateMatrixWorld();
  20934. var renderTarget = this.renderTarget;
  20935. var generateMipmaps = renderTarget.texture.generateMipmaps;
  20936. renderTarget.texture.generateMipmaps = false;
  20937. renderTarget.activeCubeFace = 0;
  20938. renderer.render( scene, cameraPX, renderTarget );
  20939. renderTarget.activeCubeFace = 1;
  20940. renderer.render( scene, cameraNX, renderTarget );
  20941. renderTarget.activeCubeFace = 2;
  20942. renderer.render( scene, cameraPY, renderTarget );
  20943. renderTarget.activeCubeFace = 3;
  20944. renderer.render( scene, cameraNY, renderTarget );
  20945. renderTarget.activeCubeFace = 4;
  20946. renderer.render( scene, cameraPZ, renderTarget );
  20947. renderTarget.texture.generateMipmaps = generateMipmaps;
  20948. renderTarget.activeCubeFace = 5;
  20949. renderer.render( scene, cameraNZ, renderTarget );
  20950. renderer.setRenderTarget( null );
  20951. };
  20952. }
  20953. CubeCamera.prototype = Object.create( Object3D.prototype );
  20954. CubeCamera.prototype.constructor = CubeCamera;
  20955. function AudioListener() {
  20956. Object3D.call( this );
  20957. this.type = 'AudioListener';
  20958. this.context = getAudioContext();
  20959. this.gain = this.context.createGain();
  20960. this.gain.connect( this.context.destination );
  20961. this.filter = null;
  20962. }
  20963. AudioListener.prototype = Object.assign( Object.create( Object3D.prototype ), {
  20964. constructor: AudioListener,
  20965. getInput: function () {
  20966. return this.gain;
  20967. },
  20968. removeFilter: function ( ) {
  20969. if ( this.filter !== null ) {
  20970. this.gain.disconnect( this.filter );
  20971. this.filter.disconnect( this.context.destination );
  20972. this.gain.connect( this.context.destination );
  20973. this.filter = null;
  20974. }
  20975. },
  20976. getFilter: function () {
  20977. return this.filter;
  20978. },
  20979. setFilter: function ( value ) {
  20980. if ( this.filter !== null ) {
  20981. this.gain.disconnect( this.filter );
  20982. this.filter.disconnect( this.context.destination );
  20983. } else {
  20984. this.gain.disconnect( this.context.destination );
  20985. }
  20986. this.filter = value;
  20987. this.gain.connect( this.filter );
  20988. this.filter.connect( this.context.destination );
  20989. },
  20990. getMasterVolume: function () {
  20991. return this.gain.gain.value;
  20992. },
  20993. setMasterVolume: function ( value ) {
  20994. this.gain.gain.value = value;
  20995. },
  20996. updateMatrixWorld: ( function () {
  20997. var position = new Vector3();
  20998. var quaternion = new Quaternion();
  20999. var scale = new Vector3();
  21000. var orientation = new Vector3();
  21001. return function updateMatrixWorld( force ) {
  21002. Object3D.prototype.updateMatrixWorld.call( this, force );
  21003. var listener = this.context.listener;
  21004. var up = this.up;
  21005. this.matrixWorld.decompose( position, quaternion, scale );
  21006. orientation.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  21007. listener.setPosition( position.x, position.y, position.z );
  21008. listener.setOrientation( orientation.x, orientation.y, orientation.z, up.x, up.y, up.z );
  21009. };
  21010. } )()
  21011. } );
  21012. function Audio( listener ) {
  21013. Object3D.call( this );
  21014. this.type = 'Audio';
  21015. this.context = listener.context;
  21016. this.source = this.context.createBufferSource();
  21017. this.source.onended = this.onEnded.bind( this );
  21018. this.gain = this.context.createGain();
  21019. this.gain.connect( listener.getInput() );
  21020. this.autoplay = false;
  21021. this.startTime = 0;
  21022. this.playbackRate = 1;
  21023. this.isPlaying = false;
  21024. this.hasPlaybackControl = true;
  21025. this.sourceType = 'empty';
  21026. this.filters = [];
  21027. }
  21028. Audio.prototype = Object.assign( Object.create( Object3D.prototype ), {
  21029. constructor: Audio,
  21030. getOutput: function () {
  21031. return this.gain;
  21032. },
  21033. setNodeSource: function ( audioNode ) {
  21034. this.hasPlaybackControl = false;
  21035. this.sourceType = 'audioNode';
  21036. this.source = audioNode;
  21037. this.connect();
  21038. return this;
  21039. },
  21040. setBuffer: function ( audioBuffer ) {
  21041. this.source.buffer = audioBuffer;
  21042. this.sourceType = 'buffer';
  21043. if ( this.autoplay ) this.play();
  21044. return this;
  21045. },
  21046. play: function () {
  21047. if ( this.isPlaying === true ) {
  21048. console.warn( 'THREE.Audio: Audio is already playing.' );
  21049. return;
  21050. }
  21051. if ( this.hasPlaybackControl === false ) {
  21052. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21053. return;
  21054. }
  21055. var source = this.context.createBufferSource();
  21056. source.buffer = this.source.buffer;
  21057. source.loop = this.source.loop;
  21058. source.onended = this.source.onended;
  21059. source.start( 0, this.startTime );
  21060. source.playbackRate.value = this.playbackRate;
  21061. this.isPlaying = true;
  21062. this.source = source;
  21063. return this.connect();
  21064. },
  21065. pause: function () {
  21066. if ( this.hasPlaybackControl === false ) {
  21067. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21068. return;
  21069. }
  21070. this.source.stop();
  21071. this.startTime = this.context.currentTime;
  21072. this.isPlaying = false;
  21073. return this;
  21074. },
  21075. stop: function () {
  21076. if ( this.hasPlaybackControl === false ) {
  21077. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21078. return;
  21079. }
  21080. this.source.stop();
  21081. this.startTime = 0;
  21082. this.isPlaying = false;
  21083. return this;
  21084. },
  21085. connect: function () {
  21086. if ( this.filters.length > 0 ) {
  21087. this.source.connect( this.filters[ 0 ] );
  21088. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  21089. this.filters[ i - 1 ].connect( this.filters[ i ] );
  21090. }
  21091. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  21092. } else {
  21093. this.source.connect( this.getOutput() );
  21094. }
  21095. return this;
  21096. },
  21097. disconnect: function () {
  21098. if ( this.filters.length > 0 ) {
  21099. this.source.disconnect( this.filters[ 0 ] );
  21100. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  21101. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  21102. }
  21103. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  21104. } else {
  21105. this.source.disconnect( this.getOutput() );
  21106. }
  21107. return this;
  21108. },
  21109. getFilters: function () {
  21110. return this.filters;
  21111. },
  21112. setFilters: function ( value ) {
  21113. if ( ! value ) value = [];
  21114. if ( this.isPlaying === true ) {
  21115. this.disconnect();
  21116. this.filters = value;
  21117. this.connect();
  21118. } else {
  21119. this.filters = value;
  21120. }
  21121. return this;
  21122. },
  21123. getFilter: function () {
  21124. return this.getFilters()[ 0 ];
  21125. },
  21126. setFilter: function ( filter ) {
  21127. return this.setFilters( filter ? [ filter ] : [] );
  21128. },
  21129. setPlaybackRate: function ( value ) {
  21130. if ( this.hasPlaybackControl === false ) {
  21131. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21132. return;
  21133. }
  21134. this.playbackRate = value;
  21135. if ( this.isPlaying === true ) {
  21136. this.source.playbackRate.value = this.playbackRate;
  21137. }
  21138. return this;
  21139. },
  21140. getPlaybackRate: function () {
  21141. return this.playbackRate;
  21142. },
  21143. onEnded: function () {
  21144. this.isPlaying = false;
  21145. },
  21146. getLoop: function () {
  21147. if ( this.hasPlaybackControl === false ) {
  21148. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21149. return false;
  21150. }
  21151. return this.source.loop;
  21152. },
  21153. setLoop: function ( value ) {
  21154. if ( this.hasPlaybackControl === false ) {
  21155. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21156. return;
  21157. }
  21158. this.source.loop = value;
  21159. },
  21160. getVolume: function () {
  21161. return this.gain.gain.value;
  21162. },
  21163. setVolume: function ( value ) {
  21164. this.gain.gain.value = value;
  21165. return this;
  21166. }
  21167. } );
  21168. function PositionalAudio( listener ) {
  21169. Audio.call( this, listener );
  21170. this.panner = this.context.createPanner();
  21171. this.panner.connect( this.gain );
  21172. }
  21173. PositionalAudio.prototype = Object.assign( Object.create( Audio.prototype ), {
  21174. constructor: PositionalAudio,
  21175. getOutput: function () {
  21176. return this.panner;
  21177. },
  21178. getRefDistance: function () {
  21179. return this.panner.refDistance;
  21180. },
  21181. setRefDistance: function ( value ) {
  21182. this.panner.refDistance = value;
  21183. },
  21184. getRolloffFactor: function () {
  21185. return this.panner.rolloffFactor;
  21186. },
  21187. setRolloffFactor: function ( value ) {
  21188. this.panner.rolloffFactor = value;
  21189. },
  21190. getDistanceModel: function () {
  21191. return this.panner.distanceModel;
  21192. },
  21193. setDistanceModel: function ( value ) {
  21194. this.panner.distanceModel = value;
  21195. },
  21196. getMaxDistance: function () {
  21197. return this.panner.maxDistance;
  21198. },
  21199. setMaxDistance: function ( value ) {
  21200. this.panner.maxDistance = value;
  21201. },
  21202. updateMatrixWorld: ( function () {
  21203. var position = new Vector3();
  21204. return function updateMatrixWorld( force ) {
  21205. Object3D.prototype.updateMatrixWorld.call( this, force );
  21206. position.setFromMatrixPosition( this.matrixWorld );
  21207. this.panner.setPosition( position.x, position.y, position.z );
  21208. };
  21209. } )()
  21210. } );
  21211. /**
  21212. * @author mrdoob / http://mrdoob.com/
  21213. */
  21214. function AudioAnalyser( audio, fftSize ) {
  21215. this.analyser = audio.context.createAnalyser();
  21216. this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048;
  21217. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  21218. audio.getOutput().connect( this.analyser );
  21219. }
  21220. Object.assign( AudioAnalyser.prototype, {
  21221. getFrequencyData: function () {
  21222. this.analyser.getByteFrequencyData( this.data );
  21223. return this.data;
  21224. },
  21225. getAverageFrequency: function () {
  21226. var value = 0, data = this.getFrequencyData();
  21227. for ( var i = 0; i < data.length; i ++ ) {
  21228. value += data[ i ];
  21229. }
  21230. return value / data.length;
  21231. }
  21232. } );
  21233. /**
  21234. *
  21235. * Buffered scene graph property that allows weighted accumulation.
  21236. *
  21237. *
  21238. * @author Ben Houston / http://clara.io/
  21239. * @author David Sarno / http://lighthaus.us/
  21240. * @author tschw
  21241. */
  21242. function PropertyMixer( binding, typeName, valueSize ) {
  21243. this.binding = binding;
  21244. this.valueSize = valueSize;
  21245. var bufferType = Float64Array,
  21246. mixFunction;
  21247. switch ( typeName ) {
  21248. case 'quaternion': mixFunction = this._slerp; break;
  21249. case 'string':
  21250. case 'bool':
  21251. bufferType = Array, mixFunction = this._select; break;
  21252. default: mixFunction = this._lerp;
  21253. }
  21254. this.buffer = new bufferType( valueSize * 4 );
  21255. // layout: [ incoming | accu0 | accu1 | orig ]
  21256. //
  21257. // interpolators can use .buffer as their .result
  21258. // the data then goes to 'incoming'
  21259. //
  21260. // 'accu0' and 'accu1' are used frame-interleaved for
  21261. // the cumulative result and are compared to detect
  21262. // changes
  21263. //
  21264. // 'orig' stores the original state of the property
  21265. this._mixBufferRegion = mixFunction;
  21266. this.cumulativeWeight = 0;
  21267. this.useCount = 0;
  21268. this.referenceCount = 0;
  21269. }
  21270. PropertyMixer.prototype = {
  21271. constructor: PropertyMixer,
  21272. // accumulate data in the 'incoming' region into 'accu<i>'
  21273. accumulate: function( accuIndex, weight ) {
  21274. // note: happily accumulating nothing when weight = 0, the caller knows
  21275. // the weight and shouldn't have made the call in the first place
  21276. var buffer = this.buffer,
  21277. stride = this.valueSize,
  21278. offset = accuIndex * stride + stride,
  21279. currentWeight = this.cumulativeWeight;
  21280. if ( currentWeight === 0 ) {
  21281. // accuN := incoming * weight
  21282. for ( var i = 0; i !== stride; ++ i ) {
  21283. buffer[ offset + i ] = buffer[ i ];
  21284. }
  21285. currentWeight = weight;
  21286. } else {
  21287. // accuN := accuN + incoming * weight
  21288. currentWeight += weight;
  21289. var mix = weight / currentWeight;
  21290. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  21291. }
  21292. this.cumulativeWeight = currentWeight;
  21293. },
  21294. // apply the state of 'accu<i>' to the binding when accus differ
  21295. apply: function( accuIndex ) {
  21296. var stride = this.valueSize,
  21297. buffer = this.buffer,
  21298. offset = accuIndex * stride + stride,
  21299. weight = this.cumulativeWeight,
  21300. binding = this.binding;
  21301. this.cumulativeWeight = 0;
  21302. if ( weight < 1 ) {
  21303. // accuN := accuN + original * ( 1 - cumulativeWeight )
  21304. var originalValueOffset = stride * 3;
  21305. this._mixBufferRegion(
  21306. buffer, offset, originalValueOffset, 1 - weight, stride );
  21307. }
  21308. for ( var i = stride, e = stride + stride; i !== e; ++ i ) {
  21309. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  21310. // value has changed -> update scene graph
  21311. binding.setValue( buffer, offset );
  21312. break;
  21313. }
  21314. }
  21315. },
  21316. // remember the state of the bound property and copy it to both accus
  21317. saveOriginalState: function() {
  21318. var binding = this.binding;
  21319. var buffer = this.buffer,
  21320. stride = this.valueSize,
  21321. originalValueOffset = stride * 3;
  21322. binding.getValue( buffer, originalValueOffset );
  21323. // accu[0..1] := orig -- initially detect changes against the original
  21324. for ( var i = stride, e = originalValueOffset; i !== e; ++ i ) {
  21325. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  21326. }
  21327. this.cumulativeWeight = 0;
  21328. },
  21329. // apply the state previously taken via 'saveOriginalState' to the binding
  21330. restoreOriginalState: function() {
  21331. var originalValueOffset = this.valueSize * 3;
  21332. this.binding.setValue( this.buffer, originalValueOffset );
  21333. },
  21334. // mix functions
  21335. _select: function( buffer, dstOffset, srcOffset, t, stride ) {
  21336. if ( t >= 0.5 ) {
  21337. for ( var i = 0; i !== stride; ++ i ) {
  21338. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  21339. }
  21340. }
  21341. },
  21342. _slerp: function( buffer, dstOffset, srcOffset, t, stride ) {
  21343. Quaternion.slerpFlat( buffer, dstOffset,
  21344. buffer, dstOffset, buffer, srcOffset, t );
  21345. },
  21346. _lerp: function( buffer, dstOffset, srcOffset, t, stride ) {
  21347. var s = 1 - t;
  21348. for ( var i = 0; i !== stride; ++ i ) {
  21349. var j = dstOffset + i;
  21350. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  21351. }
  21352. }
  21353. };
  21354. /**
  21355. *
  21356. * A reference to a real property in the scene graph.
  21357. *
  21358. *
  21359. * @author Ben Houston / http://clara.io/
  21360. * @author David Sarno / http://lighthaus.us/
  21361. * @author tschw
  21362. */
  21363. function PropertyBinding( rootNode, path, parsedPath ) {
  21364. this.path = path;
  21365. this.parsedPath = parsedPath ||
  21366. PropertyBinding.parseTrackName( path );
  21367. this.node = PropertyBinding.findNode(
  21368. rootNode, this.parsedPath.nodeName ) || rootNode;
  21369. this.rootNode = rootNode;
  21370. }
  21371. PropertyBinding.prototype = {
  21372. constructor: PropertyBinding,
  21373. getValue: function getValue_unbound( targetArray, offset ) {
  21374. this.bind();
  21375. this.getValue( targetArray, offset );
  21376. // Note: This class uses a State pattern on a per-method basis:
  21377. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  21378. // prototype version of these methods with one that represents
  21379. // the bound state. When the property is not found, the methods
  21380. // become no-ops.
  21381. },
  21382. setValue: function getValue_unbound( sourceArray, offset ) {
  21383. this.bind();
  21384. this.setValue( sourceArray, offset );
  21385. },
  21386. // create getter / setter pair for a property in the scene graph
  21387. bind: function() {
  21388. var targetObject = this.node,
  21389. parsedPath = this.parsedPath,
  21390. objectName = parsedPath.objectName,
  21391. propertyName = parsedPath.propertyName,
  21392. propertyIndex = parsedPath.propertyIndex;
  21393. if ( ! targetObject ) {
  21394. targetObject = PropertyBinding.findNode(
  21395. this.rootNode, parsedPath.nodeName ) || this.rootNode;
  21396. this.node = targetObject;
  21397. }
  21398. // set fail state so we can just 'return' on error
  21399. this.getValue = this._getValue_unavailable;
  21400. this.setValue = this._setValue_unavailable;
  21401. // ensure there is a value node
  21402. if ( ! targetObject ) {
  21403. console.error( " trying to update node for track: " + this.path + " but it wasn't found." );
  21404. return;
  21405. }
  21406. if ( objectName ) {
  21407. var objectIndex = parsedPath.objectIndex;
  21408. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  21409. switch ( objectName ) {
  21410. case 'materials':
  21411. if ( ! targetObject.material ) {
  21412. console.error( ' can not bind to material as node does not have a material', this );
  21413. return;
  21414. }
  21415. if ( ! targetObject.material.materials ) {
  21416. console.error( ' can not bind to material.materials as node.material does not have a materials array', this );
  21417. return;
  21418. }
  21419. targetObject = targetObject.material.materials;
  21420. break;
  21421. case 'bones':
  21422. if ( ! targetObject.skeleton ) {
  21423. console.error( ' can not bind to bones as node does not have a skeleton', this );
  21424. return;
  21425. }
  21426. // potential future optimization: skip this if propertyIndex is already an integer
  21427. // and convert the integer string to a true integer.
  21428. targetObject = targetObject.skeleton.bones;
  21429. // support resolving morphTarget names into indices.
  21430. for ( var i = 0; i < targetObject.length; i ++ ) {
  21431. if ( targetObject[ i ].name === objectIndex ) {
  21432. objectIndex = i;
  21433. break;
  21434. }
  21435. }
  21436. break;
  21437. default:
  21438. if ( targetObject[ objectName ] === undefined ) {
  21439. console.error( ' can not bind to objectName of node, undefined', this );
  21440. return;
  21441. }
  21442. targetObject = targetObject[ objectName ];
  21443. }
  21444. if ( objectIndex !== undefined ) {
  21445. if ( targetObject[ objectIndex ] === undefined ) {
  21446. console.error( " trying to bind to objectIndex of objectName, but is undefined:", this, targetObject );
  21447. return;
  21448. }
  21449. targetObject = targetObject[ objectIndex ];
  21450. }
  21451. }
  21452. // resolve property
  21453. var nodeProperty = targetObject[ propertyName ];
  21454. if ( nodeProperty === undefined ) {
  21455. var nodeName = parsedPath.nodeName;
  21456. console.error( " trying to update property for track: " + nodeName +
  21457. '.' + propertyName + " but it wasn't found.", targetObject );
  21458. return;
  21459. }
  21460. // determine versioning scheme
  21461. var versioning = this.Versioning.None;
  21462. if ( targetObject.needsUpdate !== undefined ) { // material
  21463. versioning = this.Versioning.NeedsUpdate;
  21464. this.targetObject = targetObject;
  21465. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  21466. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  21467. this.targetObject = targetObject;
  21468. }
  21469. // determine how the property gets bound
  21470. var bindingType = this.BindingType.Direct;
  21471. if ( propertyIndex !== undefined ) {
  21472. // access a sub element of the property array (only primitives are supported right now)
  21473. if ( propertyName === "morphTargetInfluences" ) {
  21474. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  21475. // support resolving morphTarget names into indices.
  21476. if ( ! targetObject.geometry ) {
  21477. console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry', this );
  21478. return;
  21479. }
  21480. if ( ! targetObject.geometry.morphTargets ) {
  21481. console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry.morphTargets', this );
  21482. return;
  21483. }
  21484. for ( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) {
  21485. if ( targetObject.geometry.morphTargets[ i ].name === propertyIndex ) {
  21486. propertyIndex = i;
  21487. break;
  21488. }
  21489. }
  21490. }
  21491. bindingType = this.BindingType.ArrayElement;
  21492. this.resolvedProperty = nodeProperty;
  21493. this.propertyIndex = propertyIndex;
  21494. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  21495. // must use copy for Object3D.Euler/Quaternion
  21496. bindingType = this.BindingType.HasFromToArray;
  21497. this.resolvedProperty = nodeProperty;
  21498. } else if ( nodeProperty.length !== undefined ) {
  21499. bindingType = this.BindingType.EntireArray;
  21500. this.resolvedProperty = nodeProperty;
  21501. } else {
  21502. this.propertyName = propertyName;
  21503. }
  21504. // select getter / setter
  21505. this.getValue = this.GetterByBindingType[ bindingType ];
  21506. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  21507. },
  21508. unbind: function() {
  21509. this.node = null;
  21510. // back to the prototype version of getValue / setValue
  21511. // note: avoiding to mutate the shape of 'this' via 'delete'
  21512. this.getValue = this._getValue_unbound;
  21513. this.setValue = this._setValue_unbound;
  21514. }
  21515. };
  21516. Object.assign( PropertyBinding.prototype, { // prototype, continued
  21517. // these are used to "bind" a nonexistent property
  21518. _getValue_unavailable: function() {},
  21519. _setValue_unavailable: function() {},
  21520. // initial state of these methods that calls 'bind'
  21521. _getValue_unbound: PropertyBinding.prototype.getValue,
  21522. _setValue_unbound: PropertyBinding.prototype.setValue,
  21523. BindingType: {
  21524. Direct: 0,
  21525. EntireArray: 1,
  21526. ArrayElement: 2,
  21527. HasFromToArray: 3
  21528. },
  21529. Versioning: {
  21530. None: 0,
  21531. NeedsUpdate: 1,
  21532. MatrixWorldNeedsUpdate: 2
  21533. },
  21534. GetterByBindingType: [
  21535. function getValue_direct( buffer, offset ) {
  21536. buffer[ offset ] = this.node[ this.propertyName ];
  21537. },
  21538. function getValue_array( buffer, offset ) {
  21539. var source = this.resolvedProperty;
  21540. for ( var i = 0, n = source.length; i !== n; ++ i ) {
  21541. buffer[ offset ++ ] = source[ i ];
  21542. }
  21543. },
  21544. function getValue_arrayElement( buffer, offset ) {
  21545. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  21546. },
  21547. function getValue_toArray( buffer, offset ) {
  21548. this.resolvedProperty.toArray( buffer, offset );
  21549. }
  21550. ],
  21551. SetterByBindingTypeAndVersioning: [
  21552. [
  21553. // Direct
  21554. function setValue_direct( buffer, offset ) {
  21555. this.node[ this.propertyName ] = buffer[ offset ];
  21556. },
  21557. function setValue_direct_setNeedsUpdate( buffer, offset ) {
  21558. this.node[ this.propertyName ] = buffer[ offset ];
  21559. this.targetObject.needsUpdate = true;
  21560. },
  21561. function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  21562. this.node[ this.propertyName ] = buffer[ offset ];
  21563. this.targetObject.matrixWorldNeedsUpdate = true;
  21564. }
  21565. ], [
  21566. // EntireArray
  21567. function setValue_array( buffer, offset ) {
  21568. var dest = this.resolvedProperty;
  21569. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  21570. dest[ i ] = buffer[ offset ++ ];
  21571. }
  21572. },
  21573. function setValue_array_setNeedsUpdate( buffer, offset ) {
  21574. var dest = this.resolvedProperty;
  21575. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  21576. dest[ i ] = buffer[ offset ++ ];
  21577. }
  21578. this.targetObject.needsUpdate = true;
  21579. },
  21580. function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  21581. var dest = this.resolvedProperty;
  21582. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  21583. dest[ i ] = buffer[ offset ++ ];
  21584. }
  21585. this.targetObject.matrixWorldNeedsUpdate = true;
  21586. }
  21587. ], [
  21588. // ArrayElement
  21589. function setValue_arrayElement( buffer, offset ) {
  21590. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  21591. },
  21592. function setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  21593. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  21594. this.targetObject.needsUpdate = true;
  21595. },
  21596. function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  21597. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  21598. this.targetObject.matrixWorldNeedsUpdate = true;
  21599. }
  21600. ], [
  21601. // HasToFromArray
  21602. function setValue_fromArray( buffer, offset ) {
  21603. this.resolvedProperty.fromArray( buffer, offset );
  21604. },
  21605. function setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  21606. this.resolvedProperty.fromArray( buffer, offset );
  21607. this.targetObject.needsUpdate = true;
  21608. },
  21609. function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  21610. this.resolvedProperty.fromArray( buffer, offset );
  21611. this.targetObject.matrixWorldNeedsUpdate = true;
  21612. }
  21613. ]
  21614. ]
  21615. } );
  21616. PropertyBinding.Composite =
  21617. function( targetGroup, path, optionalParsedPath ) {
  21618. var parsedPath = optionalParsedPath ||
  21619. PropertyBinding.parseTrackName( path );
  21620. this._targetGroup = targetGroup;
  21621. this._bindings = targetGroup.subscribe_( path, parsedPath );
  21622. };
  21623. PropertyBinding.Composite.prototype = {
  21624. constructor: PropertyBinding.Composite,
  21625. getValue: function( array, offset ) {
  21626. this.bind(); // bind all binding
  21627. var firstValidIndex = this._targetGroup.nCachedObjects_,
  21628. binding = this._bindings[ firstValidIndex ];
  21629. // and only call .getValue on the first
  21630. if ( binding !== undefined ) binding.getValue( array, offset );
  21631. },
  21632. setValue: function( array, offset ) {
  21633. var bindings = this._bindings;
  21634. for ( var i = this._targetGroup.nCachedObjects_,
  21635. n = bindings.length; i !== n; ++ i ) {
  21636. bindings[ i ].setValue( array, offset );
  21637. }
  21638. },
  21639. bind: function() {
  21640. var bindings = this._bindings;
  21641. for ( var i = this._targetGroup.nCachedObjects_,
  21642. n = bindings.length; i !== n; ++ i ) {
  21643. bindings[ i ].bind();
  21644. }
  21645. },
  21646. unbind: function() {
  21647. var bindings = this._bindings;
  21648. for ( var i = this._targetGroup.nCachedObjects_,
  21649. n = bindings.length; i !== n; ++ i ) {
  21650. bindings[ i ].unbind();
  21651. }
  21652. }
  21653. };
  21654. PropertyBinding.create = function( root, path, parsedPath ) {
  21655. if ( ! ( (root && root.isAnimationObjectGroup) ) ) {
  21656. return new PropertyBinding( root, path, parsedPath );
  21657. } else {
  21658. return new PropertyBinding.Composite( root, path, parsedPath );
  21659. }
  21660. };
  21661. PropertyBinding.parseTrackName = function( trackName ) {
  21662. // matches strings in the form of:
  21663. // nodeName.property
  21664. // nodeName.property[accessor]
  21665. // nodeName.material.property[accessor]
  21666. // uuid.property[accessor]
  21667. // uuid.objectName[objectIndex].propertyName[propertyIndex]
  21668. // parentName/nodeName.property
  21669. // parentName/parentName/nodeName.property[index]
  21670. // .bone[Armature.DEF_cog].position
  21671. // created and tested via https://regex101.com/#javascript
  21672. var re = /^((?:\w+\/)*)(\w+)?(?:\.(\w+)(?:\[(.+)\])?)?\.(\w+)(?:\[(.+)\])?$/;
  21673. var matches = re.exec( trackName );
  21674. if ( ! matches ) {
  21675. throw new Error( "cannot parse trackName at all: " + trackName );
  21676. }
  21677. var results = {
  21678. // directoryName: matches[ 1 ], // (tschw) currently unused
  21679. nodeName: matches[ 2 ], // allowed to be null, specified root node.
  21680. objectName: matches[ 3 ],
  21681. objectIndex: matches[ 4 ],
  21682. propertyName: matches[ 5 ],
  21683. propertyIndex: matches[ 6 ] // allowed to be null, specifies that the whole property is set.
  21684. };
  21685. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  21686. throw new Error( "can not parse propertyName from trackName: " + trackName );
  21687. }
  21688. return results;
  21689. };
  21690. PropertyBinding.findNode = function( root, nodeName ) {
  21691. if ( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  21692. return root;
  21693. }
  21694. // search into skeleton bones.
  21695. if ( root.skeleton ) {
  21696. var searchSkeleton = function( skeleton ) {
  21697. for( var i = 0; i < skeleton.bones.length; i ++ ) {
  21698. var bone = skeleton.bones[ i ];
  21699. if ( bone.name === nodeName ) {
  21700. return bone;
  21701. }
  21702. }
  21703. return null;
  21704. };
  21705. var bone = searchSkeleton( root.skeleton );
  21706. if ( bone ) {
  21707. return bone;
  21708. }
  21709. }
  21710. // search into node subtree.
  21711. if ( root.children ) {
  21712. var searchNodeSubtree = function( children ) {
  21713. for( var i = 0; i < children.length; i ++ ) {
  21714. var childNode = children[ i ];
  21715. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  21716. return childNode;
  21717. }
  21718. var result = searchNodeSubtree( childNode.children );
  21719. if ( result ) return result;
  21720. }
  21721. return null;
  21722. };
  21723. var subTreeNode = searchNodeSubtree( root.children );
  21724. if ( subTreeNode ) {
  21725. return subTreeNode;
  21726. }
  21727. }
  21728. return null;
  21729. };
  21730. /**
  21731. *
  21732. * A group of objects that receives a shared animation state.
  21733. *
  21734. * Usage:
  21735. *
  21736. * - Add objects you would otherwise pass as 'root' to the
  21737. * constructor or the .clipAction method of AnimationMixer.
  21738. *
  21739. * - Instead pass this object as 'root'.
  21740. *
  21741. * - You can also add and remove objects later when the mixer
  21742. * is running.
  21743. *
  21744. * Note:
  21745. *
  21746. * Objects of this class appear as one object to the mixer,
  21747. * so cache control of the individual objects must be done
  21748. * on the group.
  21749. *
  21750. * Limitation:
  21751. *
  21752. * - The animated properties must be compatible among the
  21753. * all objects in the group.
  21754. *
  21755. * - A single property can either be controlled through a
  21756. * target group or directly, but not both.
  21757. *
  21758. * @author tschw
  21759. */
  21760. function AnimationObjectGroup( var_args ) {
  21761. this.uuid = exports.Math.generateUUID();
  21762. // cached objects followed by the active ones
  21763. this._objects = Array.prototype.slice.call( arguments );
  21764. this.nCachedObjects_ = 0; // threshold
  21765. // note: read by PropertyBinding.Composite
  21766. var indices = {};
  21767. this._indicesByUUID = indices; // for bookkeeping
  21768. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  21769. indices[ arguments[ i ].uuid ] = i;
  21770. }
  21771. this._paths = []; // inside: string
  21772. this._parsedPaths = []; // inside: { we don't care, here }
  21773. this._bindings = []; // inside: Array< PropertyBinding >
  21774. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  21775. var scope = this;
  21776. this.stats = {
  21777. objects: {
  21778. get total() { return scope._objects.length; },
  21779. get inUse() { return this.total - scope.nCachedObjects_; }
  21780. },
  21781. get bindingsPerObject() { return scope._bindings.length; }
  21782. };
  21783. }
  21784. AnimationObjectGroup.prototype = {
  21785. constructor: AnimationObjectGroup,
  21786. isAnimationObjectGroup: true,
  21787. add: function( var_args ) {
  21788. var objects = this._objects,
  21789. nObjects = objects.length,
  21790. nCachedObjects = this.nCachedObjects_,
  21791. indicesByUUID = this._indicesByUUID,
  21792. paths = this._paths,
  21793. parsedPaths = this._parsedPaths,
  21794. bindings = this._bindings,
  21795. nBindings = bindings.length;
  21796. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  21797. var object = arguments[ i ],
  21798. uuid = object.uuid,
  21799. index = indicesByUUID[ uuid ];
  21800. if ( index === undefined ) {
  21801. // unknown object -> add it to the ACTIVE region
  21802. index = nObjects ++;
  21803. indicesByUUID[ uuid ] = index;
  21804. objects.push( object );
  21805. // accounting is done, now do the same for all bindings
  21806. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  21807. bindings[ j ].push(
  21808. new PropertyBinding(
  21809. object, paths[ j ], parsedPaths[ j ] ) );
  21810. }
  21811. } else if ( index < nCachedObjects ) {
  21812. var knownObject = objects[ index ];
  21813. // move existing object to the ACTIVE region
  21814. var firstActiveIndex = -- nCachedObjects,
  21815. lastCachedObject = objects[ firstActiveIndex ];
  21816. indicesByUUID[ lastCachedObject.uuid ] = index;
  21817. objects[ index ] = lastCachedObject;
  21818. indicesByUUID[ uuid ] = firstActiveIndex;
  21819. objects[ firstActiveIndex ] = object;
  21820. // accounting is done, now do the same for all bindings
  21821. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  21822. var bindingsForPath = bindings[ j ],
  21823. lastCached = bindingsForPath[ firstActiveIndex ],
  21824. binding = bindingsForPath[ index ];
  21825. bindingsForPath[ index ] = lastCached;
  21826. if ( binding === undefined ) {
  21827. // since we do not bother to create new bindings
  21828. // for objects that are cached, the binding may
  21829. // or may not exist
  21830. binding = new PropertyBinding(
  21831. object, paths[ j ], parsedPaths[ j ] );
  21832. }
  21833. bindingsForPath[ firstActiveIndex ] = binding;
  21834. }
  21835. } else if ( objects[ index ] !== knownObject) {
  21836. console.error( "Different objects with the same UUID " +
  21837. "detected. Clean the caches or recreate your " +
  21838. "infrastructure when reloading scenes..." );
  21839. } // else the object is already where we want it to be
  21840. } // for arguments
  21841. this.nCachedObjects_ = nCachedObjects;
  21842. },
  21843. remove: function( var_args ) {
  21844. var objects = this._objects,
  21845. nCachedObjects = this.nCachedObjects_,
  21846. indicesByUUID = this._indicesByUUID,
  21847. bindings = this._bindings,
  21848. nBindings = bindings.length;
  21849. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  21850. var object = arguments[ i ],
  21851. uuid = object.uuid,
  21852. index = indicesByUUID[ uuid ];
  21853. if ( index !== undefined && index >= nCachedObjects ) {
  21854. // move existing object into the CACHED region
  21855. var lastCachedIndex = nCachedObjects ++,
  21856. firstActiveObject = objects[ lastCachedIndex ];
  21857. indicesByUUID[ firstActiveObject.uuid ] = index;
  21858. objects[ index ] = firstActiveObject;
  21859. indicesByUUID[ uuid ] = lastCachedIndex;
  21860. objects[ lastCachedIndex ] = object;
  21861. // accounting is done, now do the same for all bindings
  21862. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  21863. var bindingsForPath = bindings[ j ],
  21864. firstActive = bindingsForPath[ lastCachedIndex ],
  21865. binding = bindingsForPath[ index ];
  21866. bindingsForPath[ index ] = firstActive;
  21867. bindingsForPath[ lastCachedIndex ] = binding;
  21868. }
  21869. }
  21870. } // for arguments
  21871. this.nCachedObjects_ = nCachedObjects;
  21872. },
  21873. // remove & forget
  21874. uncache: function( var_args ) {
  21875. var objects = this._objects,
  21876. nObjects = objects.length,
  21877. nCachedObjects = this.nCachedObjects_,
  21878. indicesByUUID = this._indicesByUUID,
  21879. bindings = this._bindings,
  21880. nBindings = bindings.length;
  21881. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  21882. var object = arguments[ i ],
  21883. uuid = object.uuid,
  21884. index = indicesByUUID[ uuid ];
  21885. if ( index !== undefined ) {
  21886. delete indicesByUUID[ uuid ];
  21887. if ( index < nCachedObjects ) {
  21888. // object is cached, shrink the CACHED region
  21889. var firstActiveIndex = -- nCachedObjects,
  21890. lastCachedObject = objects[ firstActiveIndex ],
  21891. lastIndex = -- nObjects,
  21892. lastObject = objects[ lastIndex ];
  21893. // last cached object takes this object's place
  21894. indicesByUUID[ lastCachedObject.uuid ] = index;
  21895. objects[ index ] = lastCachedObject;
  21896. // last object goes to the activated slot and pop
  21897. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  21898. objects[ firstActiveIndex ] = lastObject;
  21899. objects.pop();
  21900. // accounting is done, now do the same for all bindings
  21901. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  21902. var bindingsForPath = bindings[ j ],
  21903. lastCached = bindingsForPath[ firstActiveIndex ],
  21904. last = bindingsForPath[ lastIndex ];
  21905. bindingsForPath[ index ] = lastCached;
  21906. bindingsForPath[ firstActiveIndex ] = last;
  21907. bindingsForPath.pop();
  21908. }
  21909. } else {
  21910. // object is active, just swap with the last and pop
  21911. var lastIndex = -- nObjects,
  21912. lastObject = objects[ lastIndex ];
  21913. indicesByUUID[ lastObject.uuid ] = index;
  21914. objects[ index ] = lastObject;
  21915. objects.pop();
  21916. // accounting is done, now do the same for all bindings
  21917. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  21918. var bindingsForPath = bindings[ j ];
  21919. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  21920. bindingsForPath.pop();
  21921. }
  21922. } // cached or active
  21923. } // if object is known
  21924. } // for arguments
  21925. this.nCachedObjects_ = nCachedObjects;
  21926. },
  21927. // Internal interface used by befriended PropertyBinding.Composite:
  21928. subscribe_: function( path, parsedPath ) {
  21929. // returns an array of bindings for the given path that is changed
  21930. // according to the contained objects in the group
  21931. var indicesByPath = this._bindingsIndicesByPath,
  21932. index = indicesByPath[ path ],
  21933. bindings = this._bindings;
  21934. if ( index !== undefined ) return bindings[ index ];
  21935. var paths = this._paths,
  21936. parsedPaths = this._parsedPaths,
  21937. objects = this._objects,
  21938. nObjects = objects.length,
  21939. nCachedObjects = this.nCachedObjects_,
  21940. bindingsForPath = new Array( nObjects );
  21941. index = bindings.length;
  21942. indicesByPath[ path ] = index;
  21943. paths.push( path );
  21944. parsedPaths.push( parsedPath );
  21945. bindings.push( bindingsForPath );
  21946. for ( var i = nCachedObjects,
  21947. n = objects.length; i !== n; ++ i ) {
  21948. var object = objects[ i ];
  21949. bindingsForPath[ i ] =
  21950. new PropertyBinding( object, path, parsedPath );
  21951. }
  21952. return bindingsForPath;
  21953. },
  21954. unsubscribe_: function( path ) {
  21955. // tells the group to forget about a property path and no longer
  21956. // update the array previously obtained with 'subscribe_'
  21957. var indicesByPath = this._bindingsIndicesByPath,
  21958. index = indicesByPath[ path ];
  21959. if ( index !== undefined ) {
  21960. var paths = this._paths,
  21961. parsedPaths = this._parsedPaths,
  21962. bindings = this._bindings,
  21963. lastBindingsIndex = bindings.length - 1,
  21964. lastBindings = bindings[ lastBindingsIndex ],
  21965. lastBindingsPath = path[ lastBindingsIndex ];
  21966. indicesByPath[ lastBindingsPath ] = index;
  21967. bindings[ index ] = lastBindings;
  21968. bindings.pop();
  21969. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  21970. parsedPaths.pop();
  21971. paths[ index ] = paths[ lastBindingsIndex ];
  21972. paths.pop();
  21973. }
  21974. }
  21975. };
  21976. /**
  21977. *
  21978. * Action provided by AnimationMixer for scheduling clip playback on specific
  21979. * objects.
  21980. *
  21981. * @author Ben Houston / http://clara.io/
  21982. * @author David Sarno / http://lighthaus.us/
  21983. * @author tschw
  21984. *
  21985. */
  21986. function AnimationAction( mixer, clip, localRoot ) {
  21987. this._mixer = mixer;
  21988. this._clip = clip;
  21989. this._localRoot = localRoot || null;
  21990. var tracks = clip.tracks,
  21991. nTracks = tracks.length,
  21992. interpolants = new Array( nTracks );
  21993. var interpolantSettings = {
  21994. endingStart: ZeroCurvatureEnding,
  21995. endingEnd: ZeroCurvatureEnding
  21996. };
  21997. for ( var i = 0; i !== nTracks; ++ i ) {
  21998. var interpolant = tracks[ i ].createInterpolant( null );
  21999. interpolants[ i ] = interpolant;
  22000. interpolant.settings = interpolantSettings;
  22001. }
  22002. this._interpolantSettings = interpolantSettings;
  22003. this._interpolants = interpolants; // bound by the mixer
  22004. // inside: PropertyMixer (managed by the mixer)
  22005. this._propertyBindings = new Array( nTracks );
  22006. this._cacheIndex = null; // for the memory manager
  22007. this._byClipCacheIndex = null; // for the memory manager
  22008. this._timeScaleInterpolant = null;
  22009. this._weightInterpolant = null;
  22010. this.loop = LoopRepeat;
  22011. this._loopCount = -1;
  22012. // global mixer time when the action is to be started
  22013. // it's set back to 'null' upon start of the action
  22014. this._startTime = null;
  22015. // scaled local time of the action
  22016. // gets clamped or wrapped to 0..clip.duration according to loop
  22017. this.time = 0;
  22018. this.timeScale = 1;
  22019. this._effectiveTimeScale = 1;
  22020. this.weight = 1;
  22021. this._effectiveWeight = 1;
  22022. this.repetitions = Infinity; // no. of repetitions when looping
  22023. this.paused = false; // false -> zero effective time scale
  22024. this.enabled = true; // true -> zero effective weight
  22025. this.clampWhenFinished = false; // keep feeding the last frame?
  22026. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  22027. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  22028. };
  22029. AnimationAction.prototype = {
  22030. constructor: AnimationAction,
  22031. // State & Scheduling
  22032. play: function() {
  22033. this._mixer._activateAction( this );
  22034. return this;
  22035. },
  22036. stop: function() {
  22037. this._mixer._deactivateAction( this );
  22038. return this.reset();
  22039. },
  22040. reset: function() {
  22041. this.paused = false;
  22042. this.enabled = true;
  22043. this.time = 0; // restart clip
  22044. this._loopCount = -1; // forget previous loops
  22045. this._startTime = null; // forget scheduling
  22046. return this.stopFading().stopWarping();
  22047. },
  22048. isRunning: function() {
  22049. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  22050. this._startTime === null && this._mixer._isActiveAction( this );
  22051. },
  22052. // return true when play has been called
  22053. isScheduled: function() {
  22054. return this._mixer._isActiveAction( this );
  22055. },
  22056. startAt: function( time ) {
  22057. this._startTime = time;
  22058. return this;
  22059. },
  22060. setLoop: function( mode, repetitions ) {
  22061. this.loop = mode;
  22062. this.repetitions = repetitions;
  22063. return this;
  22064. },
  22065. // Weight
  22066. // set the weight stopping any scheduled fading
  22067. // although .enabled = false yields an effective weight of zero, this
  22068. // method does *not* change .enabled, because it would be confusing
  22069. setEffectiveWeight: function( weight ) {
  22070. this.weight = weight;
  22071. // note: same logic as when updated at runtime
  22072. this._effectiveWeight = this.enabled ? weight : 0;
  22073. return this.stopFading();
  22074. },
  22075. // return the weight considering fading and .enabled
  22076. getEffectiveWeight: function() {
  22077. return this._effectiveWeight;
  22078. },
  22079. fadeIn: function( duration ) {
  22080. return this._scheduleFading( duration, 0, 1 );
  22081. },
  22082. fadeOut: function( duration ) {
  22083. return this._scheduleFading( duration, 1, 0 );
  22084. },
  22085. crossFadeFrom: function( fadeOutAction, duration, warp ) {
  22086. fadeOutAction.fadeOut( duration );
  22087. this.fadeIn( duration );
  22088. if( warp ) {
  22089. var fadeInDuration = this._clip.duration,
  22090. fadeOutDuration = fadeOutAction._clip.duration,
  22091. startEndRatio = fadeOutDuration / fadeInDuration,
  22092. endStartRatio = fadeInDuration / fadeOutDuration;
  22093. fadeOutAction.warp( 1.0, startEndRatio, duration );
  22094. this.warp( endStartRatio, 1.0, duration );
  22095. }
  22096. return this;
  22097. },
  22098. crossFadeTo: function( fadeInAction, duration, warp ) {
  22099. return fadeInAction.crossFadeFrom( this, duration, warp );
  22100. },
  22101. stopFading: function() {
  22102. var weightInterpolant = this._weightInterpolant;
  22103. if ( weightInterpolant !== null ) {
  22104. this._weightInterpolant = null;
  22105. this._mixer._takeBackControlInterpolant( weightInterpolant );
  22106. }
  22107. return this;
  22108. },
  22109. // Time Scale Control
  22110. // set the weight stopping any scheduled warping
  22111. // although .paused = true yields an effective time scale of zero, this
  22112. // method does *not* change .paused, because it would be confusing
  22113. setEffectiveTimeScale: function( timeScale ) {
  22114. this.timeScale = timeScale;
  22115. this._effectiveTimeScale = this.paused ? 0 :timeScale;
  22116. return this.stopWarping();
  22117. },
  22118. // return the time scale considering warping and .paused
  22119. getEffectiveTimeScale: function() {
  22120. return this._effectiveTimeScale;
  22121. },
  22122. setDuration: function( duration ) {
  22123. this.timeScale = this._clip.duration / duration;
  22124. return this.stopWarping();
  22125. },
  22126. syncWith: function( action ) {
  22127. this.time = action.time;
  22128. this.timeScale = action.timeScale;
  22129. return this.stopWarping();
  22130. },
  22131. halt: function( duration ) {
  22132. return this.warp( this._effectiveTimeScale, 0, duration );
  22133. },
  22134. warp: function( startTimeScale, endTimeScale, duration ) {
  22135. var mixer = this._mixer, now = mixer.time,
  22136. interpolant = this._timeScaleInterpolant,
  22137. timeScale = this.timeScale;
  22138. if ( interpolant === null ) {
  22139. interpolant = mixer._lendControlInterpolant(),
  22140. this._timeScaleInterpolant = interpolant;
  22141. }
  22142. var times = interpolant.parameterPositions,
  22143. values = interpolant.sampleValues;
  22144. times[ 0 ] = now;
  22145. times[ 1 ] = now + duration;
  22146. values[ 0 ] = startTimeScale / timeScale;
  22147. values[ 1 ] = endTimeScale / timeScale;
  22148. return this;
  22149. },
  22150. stopWarping: function() {
  22151. var timeScaleInterpolant = this._timeScaleInterpolant;
  22152. if ( timeScaleInterpolant !== null ) {
  22153. this._timeScaleInterpolant = null;
  22154. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  22155. }
  22156. return this;
  22157. },
  22158. // Object Accessors
  22159. getMixer: function() {
  22160. return this._mixer;
  22161. },
  22162. getClip: function() {
  22163. return this._clip;
  22164. },
  22165. getRoot: function() {
  22166. return this._localRoot || this._mixer._root;
  22167. },
  22168. // Interna
  22169. _update: function( time, deltaTime, timeDirection, accuIndex ) {
  22170. // called by the mixer
  22171. var startTime = this._startTime;
  22172. if ( startTime !== null ) {
  22173. // check for scheduled start of action
  22174. var timeRunning = ( time - startTime ) * timeDirection;
  22175. if ( timeRunning < 0 || timeDirection === 0 ) {
  22176. return; // yet to come / don't decide when delta = 0
  22177. }
  22178. // start
  22179. this._startTime = null; // unschedule
  22180. deltaTime = timeDirection * timeRunning;
  22181. }
  22182. // apply time scale and advance time
  22183. deltaTime *= this._updateTimeScale( time );
  22184. var clipTime = this._updateTime( deltaTime );
  22185. // note: _updateTime may disable the action resulting in
  22186. // an effective weight of 0
  22187. var weight = this._updateWeight( time );
  22188. if ( weight > 0 ) {
  22189. var interpolants = this._interpolants;
  22190. var propertyMixers = this._propertyBindings;
  22191. for ( var j = 0, m = interpolants.length; j !== m; ++ j ) {
  22192. interpolants[ j ].evaluate( clipTime );
  22193. propertyMixers[ j ].accumulate( accuIndex, weight );
  22194. }
  22195. }
  22196. },
  22197. _updateWeight: function( time ) {
  22198. var weight = 0;
  22199. if ( this.enabled ) {
  22200. weight = this.weight;
  22201. var interpolant = this._weightInterpolant;
  22202. if ( interpolant !== null ) {
  22203. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  22204. weight *= interpolantValue;
  22205. if ( time > interpolant.parameterPositions[ 1 ] ) {
  22206. this.stopFading();
  22207. if ( interpolantValue === 0 ) {
  22208. // faded out, disable
  22209. this.enabled = false;
  22210. }
  22211. }
  22212. }
  22213. }
  22214. this._effectiveWeight = weight;
  22215. return weight;
  22216. },
  22217. _updateTimeScale: function( time ) {
  22218. var timeScale = 0;
  22219. if ( ! this.paused ) {
  22220. timeScale = this.timeScale;
  22221. var interpolant = this._timeScaleInterpolant;
  22222. if ( interpolant !== null ) {
  22223. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  22224. timeScale *= interpolantValue;
  22225. if ( time > interpolant.parameterPositions[ 1 ] ) {
  22226. this.stopWarping();
  22227. if ( timeScale === 0 ) {
  22228. // motion has halted, pause
  22229. this.paused = true;
  22230. } else {
  22231. // warp done - apply final time scale
  22232. this.timeScale = timeScale;
  22233. }
  22234. }
  22235. }
  22236. }
  22237. this._effectiveTimeScale = timeScale;
  22238. return timeScale;
  22239. },
  22240. _updateTime: function( deltaTime ) {
  22241. var time = this.time + deltaTime;
  22242. if ( deltaTime === 0 ) return time;
  22243. var duration = this._clip.duration,
  22244. loop = this.loop,
  22245. loopCount = this._loopCount;
  22246. if ( loop === LoopOnce ) {
  22247. if ( loopCount === -1 ) {
  22248. // just started
  22249. this.loopCount = 0;
  22250. this._setEndings( true, true, false );
  22251. }
  22252. handle_stop: {
  22253. if ( time >= duration ) {
  22254. time = duration;
  22255. } else if ( time < 0 ) {
  22256. time = 0;
  22257. } else break handle_stop;
  22258. if ( this.clampWhenFinished ) this.paused = true;
  22259. else this.enabled = false;
  22260. this._mixer.dispatchEvent( {
  22261. type: 'finished', action: this,
  22262. direction: deltaTime < 0 ? -1 : 1
  22263. } );
  22264. }
  22265. } else { // repetitive Repeat or PingPong
  22266. var pingPong = ( loop === LoopPingPong );
  22267. if ( loopCount === -1 ) {
  22268. // just started
  22269. if ( deltaTime >= 0 ) {
  22270. loopCount = 0;
  22271. this._setEndings(
  22272. true, this.repetitions === 0, pingPong );
  22273. } else {
  22274. // when looping in reverse direction, the initial
  22275. // transition through zero counts as a repetition,
  22276. // so leave loopCount at -1
  22277. this._setEndings(
  22278. this.repetitions === 0, true, pingPong );
  22279. }
  22280. }
  22281. if ( time >= duration || time < 0 ) {
  22282. // wrap around
  22283. var loopDelta = Math.floor( time / duration ); // signed
  22284. time -= duration * loopDelta;
  22285. loopCount += Math.abs( loopDelta );
  22286. var pending = this.repetitions - loopCount;
  22287. if ( pending < 0 ) {
  22288. // have to stop (switch state, clamp time, fire event)
  22289. if ( this.clampWhenFinished ) this.paused = true;
  22290. else this.enabled = false;
  22291. time = deltaTime > 0 ? duration : 0;
  22292. this._mixer.dispatchEvent( {
  22293. type: 'finished', action: this,
  22294. direction: deltaTime > 0 ? 1 : -1
  22295. } );
  22296. } else {
  22297. // keep running
  22298. if ( pending === 0 ) {
  22299. // entering the last round
  22300. var atStart = deltaTime < 0;
  22301. this._setEndings( atStart, ! atStart, pingPong );
  22302. } else {
  22303. this._setEndings( false, false, pingPong );
  22304. }
  22305. this._loopCount = loopCount;
  22306. this._mixer.dispatchEvent( {
  22307. type: 'loop', action: this, loopDelta: loopDelta
  22308. } );
  22309. }
  22310. }
  22311. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  22312. // invert time for the "pong round"
  22313. this.time = time;
  22314. return duration - time;
  22315. }
  22316. }
  22317. this.time = time;
  22318. return time;
  22319. },
  22320. _setEndings: function( atStart, atEnd, pingPong ) {
  22321. var settings = this._interpolantSettings;
  22322. if ( pingPong ) {
  22323. settings.endingStart = ZeroSlopeEnding;
  22324. settings.endingEnd = ZeroSlopeEnding;
  22325. } else {
  22326. // assuming for LoopOnce atStart == atEnd == true
  22327. if ( atStart ) {
  22328. settings.endingStart = this.zeroSlopeAtStart ?
  22329. ZeroSlopeEnding : ZeroCurvatureEnding;
  22330. } else {
  22331. settings.endingStart = WrapAroundEnding;
  22332. }
  22333. if ( atEnd ) {
  22334. settings.endingEnd = this.zeroSlopeAtEnd ?
  22335. ZeroSlopeEnding : ZeroCurvatureEnding;
  22336. } else {
  22337. settings.endingEnd = WrapAroundEnding;
  22338. }
  22339. }
  22340. },
  22341. _scheduleFading: function( duration, weightNow, weightThen ) {
  22342. var mixer = this._mixer, now = mixer.time,
  22343. interpolant = this._weightInterpolant;
  22344. if ( interpolant === null ) {
  22345. interpolant = mixer._lendControlInterpolant(),
  22346. this._weightInterpolant = interpolant;
  22347. }
  22348. var times = interpolant.parameterPositions,
  22349. values = interpolant.sampleValues;
  22350. times[ 0 ] = now; values[ 0 ] = weightNow;
  22351. times[ 1 ] = now + duration; values[ 1 ] = weightThen;
  22352. return this;
  22353. }
  22354. };
  22355. /**
  22356. *
  22357. * Player for AnimationClips.
  22358. *
  22359. *
  22360. * @author Ben Houston / http://clara.io/
  22361. * @author David Sarno / http://lighthaus.us/
  22362. * @author tschw
  22363. */
  22364. function AnimationMixer( root ) {
  22365. this._root = root;
  22366. this._initMemoryManager();
  22367. this._accuIndex = 0;
  22368. this.time = 0;
  22369. this.timeScale = 1.0;
  22370. }
  22371. Object.assign( AnimationMixer.prototype, EventDispatcher.prototype, {
  22372. // return an action for a clip optionally using a custom root target
  22373. // object (this method allocates a lot of dynamic memory in case a
  22374. // previously unknown clip/root combination is specified)
  22375. clipAction: function( clip, optionalRoot ) {
  22376. var root = optionalRoot || this._root,
  22377. rootUuid = root.uuid,
  22378. clipObject = typeof clip === 'string' ?
  22379. AnimationClip.findByName( root, clip ) : clip,
  22380. clipUuid = clipObject !== null ? clipObject.uuid : clip,
  22381. actionsForClip = this._actionsByClip[ clipUuid ],
  22382. prototypeAction = null;
  22383. if ( actionsForClip !== undefined ) {
  22384. var existingAction =
  22385. actionsForClip.actionByRoot[ rootUuid ];
  22386. if ( existingAction !== undefined ) {
  22387. return existingAction;
  22388. }
  22389. // we know the clip, so we don't have to parse all
  22390. // the bindings again but can just copy
  22391. prototypeAction = actionsForClip.knownActions[ 0 ];
  22392. // also, take the clip from the prototype action
  22393. if ( clipObject === null )
  22394. clipObject = prototypeAction._clip;
  22395. }
  22396. // clip must be known when specified via string
  22397. if ( clipObject === null ) return null;
  22398. // allocate all resources required to run it
  22399. var newAction = new AnimationAction( this, clipObject, optionalRoot );
  22400. this._bindAction( newAction, prototypeAction );
  22401. // and make the action known to the memory manager
  22402. this._addInactiveAction( newAction, clipUuid, rootUuid );
  22403. return newAction;
  22404. },
  22405. // get an existing action
  22406. existingAction: function( clip, optionalRoot ) {
  22407. var root = optionalRoot || this._root,
  22408. rootUuid = root.uuid,
  22409. clipObject = typeof clip === 'string' ?
  22410. AnimationClip.findByName( root, clip ) : clip,
  22411. clipUuid = clipObject ? clipObject.uuid : clip,
  22412. actionsForClip = this._actionsByClip[ clipUuid ];
  22413. if ( actionsForClip !== undefined ) {
  22414. return actionsForClip.actionByRoot[ rootUuid ] || null;
  22415. }
  22416. return null;
  22417. },
  22418. // deactivates all previously scheduled actions
  22419. stopAllAction: function() {
  22420. var actions = this._actions,
  22421. nActions = this._nActiveActions,
  22422. bindings = this._bindings,
  22423. nBindings = this._nActiveBindings;
  22424. this._nActiveActions = 0;
  22425. this._nActiveBindings = 0;
  22426. for ( var i = 0; i !== nActions; ++ i ) {
  22427. actions[ i ].reset();
  22428. }
  22429. for ( var i = 0; i !== nBindings; ++ i ) {
  22430. bindings[ i ].useCount = 0;
  22431. }
  22432. return this;
  22433. },
  22434. // advance the time and update apply the animation
  22435. update: function( deltaTime ) {
  22436. deltaTime *= this.timeScale;
  22437. var actions = this._actions,
  22438. nActions = this._nActiveActions,
  22439. time = this.time += deltaTime,
  22440. timeDirection = Math.sign( deltaTime ),
  22441. accuIndex = this._accuIndex ^= 1;
  22442. // run active actions
  22443. for ( var i = 0; i !== nActions; ++ i ) {
  22444. var action = actions[ i ];
  22445. if ( action.enabled ) {
  22446. action._update( time, deltaTime, timeDirection, accuIndex );
  22447. }
  22448. }
  22449. // update scene graph
  22450. var bindings = this._bindings,
  22451. nBindings = this._nActiveBindings;
  22452. for ( var i = 0; i !== nBindings; ++ i ) {
  22453. bindings[ i ].apply( accuIndex );
  22454. }
  22455. return this;
  22456. },
  22457. // return this mixer's root target object
  22458. getRoot: function() {
  22459. return this._root;
  22460. },
  22461. // free all resources specific to a particular clip
  22462. uncacheClip: function( clip ) {
  22463. var actions = this._actions,
  22464. clipUuid = clip.uuid,
  22465. actionsByClip = this._actionsByClip,
  22466. actionsForClip = actionsByClip[ clipUuid ];
  22467. if ( actionsForClip !== undefined ) {
  22468. // note: just calling _removeInactiveAction would mess up the
  22469. // iteration state and also require updating the state we can
  22470. // just throw away
  22471. var actionsToRemove = actionsForClip.knownActions;
  22472. for ( var i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  22473. var action = actionsToRemove[ i ];
  22474. this._deactivateAction( action );
  22475. var cacheIndex = action._cacheIndex,
  22476. lastInactiveAction = actions[ actions.length - 1 ];
  22477. action._cacheIndex = null;
  22478. action._byClipCacheIndex = null;
  22479. lastInactiveAction._cacheIndex = cacheIndex;
  22480. actions[ cacheIndex ] = lastInactiveAction;
  22481. actions.pop();
  22482. this._removeInactiveBindingsForAction( action );
  22483. }
  22484. delete actionsByClip[ clipUuid ];
  22485. }
  22486. },
  22487. // free all resources specific to a particular root target object
  22488. uncacheRoot: function( root ) {
  22489. var rootUuid = root.uuid,
  22490. actionsByClip = this._actionsByClip;
  22491. for ( var clipUuid in actionsByClip ) {
  22492. var actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  22493. action = actionByRoot[ rootUuid ];
  22494. if ( action !== undefined ) {
  22495. this._deactivateAction( action );
  22496. this._removeInactiveAction( action );
  22497. }
  22498. }
  22499. var bindingsByRoot = this._bindingsByRootAndName,
  22500. bindingByName = bindingsByRoot[ rootUuid ];
  22501. if ( bindingByName !== undefined ) {
  22502. for ( var trackName in bindingByName ) {
  22503. var binding = bindingByName[ trackName ];
  22504. binding.restoreOriginalState();
  22505. this._removeInactiveBinding( binding );
  22506. }
  22507. }
  22508. },
  22509. // remove a targeted clip from the cache
  22510. uncacheAction: function( clip, optionalRoot ) {
  22511. var action = this.existingAction( clip, optionalRoot );
  22512. if ( action !== null ) {
  22513. this._deactivateAction( action );
  22514. this._removeInactiveAction( action );
  22515. }
  22516. }
  22517. } );
  22518. // Implementation details:
  22519. Object.assign( AnimationMixer.prototype, {
  22520. _bindAction: function( action, prototypeAction ) {
  22521. var root = action._localRoot || this._root,
  22522. tracks = action._clip.tracks,
  22523. nTracks = tracks.length,
  22524. bindings = action._propertyBindings,
  22525. interpolants = action._interpolants,
  22526. rootUuid = root.uuid,
  22527. bindingsByRoot = this._bindingsByRootAndName,
  22528. bindingsByName = bindingsByRoot[ rootUuid ];
  22529. if ( bindingsByName === undefined ) {
  22530. bindingsByName = {};
  22531. bindingsByRoot[ rootUuid ] = bindingsByName;
  22532. }
  22533. for ( var i = 0; i !== nTracks; ++ i ) {
  22534. var track = tracks[ i ],
  22535. trackName = track.name,
  22536. binding = bindingsByName[ trackName ];
  22537. if ( binding !== undefined ) {
  22538. bindings[ i ] = binding;
  22539. } else {
  22540. binding = bindings[ i ];
  22541. if ( binding !== undefined ) {
  22542. // existing binding, make sure the cache knows
  22543. if ( binding._cacheIndex === null ) {
  22544. ++ binding.referenceCount;
  22545. this._addInactiveBinding( binding, rootUuid, trackName );
  22546. }
  22547. continue;
  22548. }
  22549. var path = prototypeAction && prototypeAction.
  22550. _propertyBindings[ i ].binding.parsedPath;
  22551. binding = new PropertyMixer(
  22552. PropertyBinding.create( root, trackName, path ),
  22553. track.ValueTypeName, track.getValueSize() );
  22554. ++ binding.referenceCount;
  22555. this._addInactiveBinding( binding, rootUuid, trackName );
  22556. bindings[ i ] = binding;
  22557. }
  22558. interpolants[ i ].resultBuffer = binding.buffer;
  22559. }
  22560. },
  22561. _activateAction: function( action ) {
  22562. if ( ! this._isActiveAction( action ) ) {
  22563. if ( action._cacheIndex === null ) {
  22564. // this action has been forgotten by the cache, but the user
  22565. // appears to be still using it -> rebind
  22566. var rootUuid = ( action._localRoot || this._root ).uuid,
  22567. clipUuid = action._clip.uuid,
  22568. actionsForClip = this._actionsByClip[ clipUuid ];
  22569. this._bindAction( action,
  22570. actionsForClip && actionsForClip.knownActions[ 0 ] );
  22571. this._addInactiveAction( action, clipUuid, rootUuid );
  22572. }
  22573. var bindings = action._propertyBindings;
  22574. // increment reference counts / sort out state
  22575. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  22576. var binding = bindings[ i ];
  22577. if ( binding.useCount ++ === 0 ) {
  22578. this._lendBinding( binding );
  22579. binding.saveOriginalState();
  22580. }
  22581. }
  22582. this._lendAction( action );
  22583. }
  22584. },
  22585. _deactivateAction: function( action ) {
  22586. if ( this._isActiveAction( action ) ) {
  22587. var bindings = action._propertyBindings;
  22588. // decrement reference counts / sort out state
  22589. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  22590. var binding = bindings[ i ];
  22591. if ( -- binding.useCount === 0 ) {
  22592. binding.restoreOriginalState();
  22593. this._takeBackBinding( binding );
  22594. }
  22595. }
  22596. this._takeBackAction( action );
  22597. }
  22598. },
  22599. // Memory manager
  22600. _initMemoryManager: function() {
  22601. this._actions = []; // 'nActiveActions' followed by inactive ones
  22602. this._nActiveActions = 0;
  22603. this._actionsByClip = {};
  22604. // inside:
  22605. // {
  22606. // knownActions: Array< AnimationAction > - used as prototypes
  22607. // actionByRoot: AnimationAction - lookup
  22608. // }
  22609. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  22610. this._nActiveBindings = 0;
  22611. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  22612. this._controlInterpolants = []; // same game as above
  22613. this._nActiveControlInterpolants = 0;
  22614. var scope = this;
  22615. this.stats = {
  22616. actions: {
  22617. get total() { return scope._actions.length; },
  22618. get inUse() { return scope._nActiveActions; }
  22619. },
  22620. bindings: {
  22621. get total() { return scope._bindings.length; },
  22622. get inUse() { return scope._nActiveBindings; }
  22623. },
  22624. controlInterpolants: {
  22625. get total() { return scope._controlInterpolants.length; },
  22626. get inUse() { return scope._nActiveControlInterpolants; }
  22627. }
  22628. };
  22629. },
  22630. // Memory management for AnimationAction objects
  22631. _isActiveAction: function( action ) {
  22632. var index = action._cacheIndex;
  22633. return index !== null && index < this._nActiveActions;
  22634. },
  22635. _addInactiveAction: function( action, clipUuid, rootUuid ) {
  22636. var actions = this._actions,
  22637. actionsByClip = this._actionsByClip,
  22638. actionsForClip = actionsByClip[ clipUuid ];
  22639. if ( actionsForClip === undefined ) {
  22640. actionsForClip = {
  22641. knownActions: [ action ],
  22642. actionByRoot: {}
  22643. };
  22644. action._byClipCacheIndex = 0;
  22645. actionsByClip[ clipUuid ] = actionsForClip;
  22646. } else {
  22647. var knownActions = actionsForClip.knownActions;
  22648. action._byClipCacheIndex = knownActions.length;
  22649. knownActions.push( action );
  22650. }
  22651. action._cacheIndex = actions.length;
  22652. actions.push( action );
  22653. actionsForClip.actionByRoot[ rootUuid ] = action;
  22654. },
  22655. _removeInactiveAction: function( action ) {
  22656. var actions = this._actions,
  22657. lastInactiveAction = actions[ actions.length - 1 ],
  22658. cacheIndex = action._cacheIndex;
  22659. lastInactiveAction._cacheIndex = cacheIndex;
  22660. actions[ cacheIndex ] = lastInactiveAction;
  22661. actions.pop();
  22662. action._cacheIndex = null;
  22663. var clipUuid = action._clip.uuid,
  22664. actionsByClip = this._actionsByClip,
  22665. actionsForClip = actionsByClip[ clipUuid ],
  22666. knownActionsForClip = actionsForClip.knownActions,
  22667. lastKnownAction =
  22668. knownActionsForClip[ knownActionsForClip.length - 1 ],
  22669. byClipCacheIndex = action._byClipCacheIndex;
  22670. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  22671. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  22672. knownActionsForClip.pop();
  22673. action._byClipCacheIndex = null;
  22674. var actionByRoot = actionsForClip.actionByRoot,
  22675. rootUuid = ( actions._localRoot || this._root ).uuid;
  22676. delete actionByRoot[ rootUuid ];
  22677. if ( knownActionsForClip.length === 0 ) {
  22678. delete actionsByClip[ clipUuid ];
  22679. }
  22680. this._removeInactiveBindingsForAction( action );
  22681. },
  22682. _removeInactiveBindingsForAction: function( action ) {
  22683. var bindings = action._propertyBindings;
  22684. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  22685. var binding = bindings[ i ];
  22686. if ( -- binding.referenceCount === 0 ) {
  22687. this._removeInactiveBinding( binding );
  22688. }
  22689. }
  22690. },
  22691. _lendAction: function( action ) {
  22692. // [ active actions | inactive actions ]
  22693. // [ active actions >| inactive actions ]
  22694. // s a
  22695. // <-swap->
  22696. // a s
  22697. var actions = this._actions,
  22698. prevIndex = action._cacheIndex,
  22699. lastActiveIndex = this._nActiveActions ++,
  22700. firstInactiveAction = actions[ lastActiveIndex ];
  22701. action._cacheIndex = lastActiveIndex;
  22702. actions[ lastActiveIndex ] = action;
  22703. firstInactiveAction._cacheIndex = prevIndex;
  22704. actions[ prevIndex ] = firstInactiveAction;
  22705. },
  22706. _takeBackAction: function( action ) {
  22707. // [ active actions | inactive actions ]
  22708. // [ active actions |< inactive actions ]
  22709. // a s
  22710. // <-swap->
  22711. // s a
  22712. var actions = this._actions,
  22713. prevIndex = action._cacheIndex,
  22714. firstInactiveIndex = -- this._nActiveActions,
  22715. lastActiveAction = actions[ firstInactiveIndex ];
  22716. action._cacheIndex = firstInactiveIndex;
  22717. actions[ firstInactiveIndex ] = action;
  22718. lastActiveAction._cacheIndex = prevIndex;
  22719. actions[ prevIndex ] = lastActiveAction;
  22720. },
  22721. // Memory management for PropertyMixer objects
  22722. _addInactiveBinding: function( binding, rootUuid, trackName ) {
  22723. var bindingsByRoot = this._bindingsByRootAndName,
  22724. bindingByName = bindingsByRoot[ rootUuid ],
  22725. bindings = this._bindings;
  22726. if ( bindingByName === undefined ) {
  22727. bindingByName = {};
  22728. bindingsByRoot[ rootUuid ] = bindingByName;
  22729. }
  22730. bindingByName[ trackName ] = binding;
  22731. binding._cacheIndex = bindings.length;
  22732. bindings.push( binding );
  22733. },
  22734. _removeInactiveBinding: function( binding ) {
  22735. var bindings = this._bindings,
  22736. propBinding = binding.binding,
  22737. rootUuid = propBinding.rootNode.uuid,
  22738. trackName = propBinding.path,
  22739. bindingsByRoot = this._bindingsByRootAndName,
  22740. bindingByName = bindingsByRoot[ rootUuid ],
  22741. lastInactiveBinding = bindings[ bindings.length - 1 ],
  22742. cacheIndex = binding._cacheIndex;
  22743. lastInactiveBinding._cacheIndex = cacheIndex;
  22744. bindings[ cacheIndex ] = lastInactiveBinding;
  22745. bindings.pop();
  22746. delete bindingByName[ trackName ];
  22747. remove_empty_map: {
  22748. for ( var _ in bindingByName ) break remove_empty_map;
  22749. delete bindingsByRoot[ rootUuid ];
  22750. }
  22751. },
  22752. _lendBinding: function( binding ) {
  22753. var bindings = this._bindings,
  22754. prevIndex = binding._cacheIndex,
  22755. lastActiveIndex = this._nActiveBindings ++,
  22756. firstInactiveBinding = bindings[ lastActiveIndex ];
  22757. binding._cacheIndex = lastActiveIndex;
  22758. bindings[ lastActiveIndex ] = binding;
  22759. firstInactiveBinding._cacheIndex = prevIndex;
  22760. bindings[ prevIndex ] = firstInactiveBinding;
  22761. },
  22762. _takeBackBinding: function( binding ) {
  22763. var bindings = this._bindings,
  22764. prevIndex = binding._cacheIndex,
  22765. firstInactiveIndex = -- this._nActiveBindings,
  22766. lastActiveBinding = bindings[ firstInactiveIndex ];
  22767. binding._cacheIndex = firstInactiveIndex;
  22768. bindings[ firstInactiveIndex ] = binding;
  22769. lastActiveBinding._cacheIndex = prevIndex;
  22770. bindings[ prevIndex ] = lastActiveBinding;
  22771. },
  22772. // Memory management of Interpolants for weight and time scale
  22773. _lendControlInterpolant: function() {
  22774. var interpolants = this._controlInterpolants,
  22775. lastActiveIndex = this._nActiveControlInterpolants ++,
  22776. interpolant = interpolants[ lastActiveIndex ];
  22777. if ( interpolant === undefined ) {
  22778. interpolant = new LinearInterpolant(
  22779. new Float32Array( 2 ), new Float32Array( 2 ),
  22780. 1, this._controlInterpolantsResultBuffer );
  22781. interpolant.__cacheIndex = lastActiveIndex;
  22782. interpolants[ lastActiveIndex ] = interpolant;
  22783. }
  22784. return interpolant;
  22785. },
  22786. _takeBackControlInterpolant: function( interpolant ) {
  22787. var interpolants = this._controlInterpolants,
  22788. prevIndex = interpolant.__cacheIndex,
  22789. firstInactiveIndex = -- this._nActiveControlInterpolants,
  22790. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  22791. interpolant.__cacheIndex = firstInactiveIndex;
  22792. interpolants[ firstInactiveIndex ] = interpolant;
  22793. lastActiveInterpolant.__cacheIndex = prevIndex;
  22794. interpolants[ prevIndex ] = lastActiveInterpolant;
  22795. },
  22796. _controlInterpolantsResultBuffer: new Float32Array( 1 )
  22797. } );
  22798. /**
  22799. * @author mrdoob / http://mrdoob.com/
  22800. */
  22801. function Uniform( value ) {
  22802. if ( typeof value === 'string' ) {
  22803. console.warn( 'THREE.Uniform: Type parameter is no longer needed.' );
  22804. value = arguments[ 1 ];
  22805. }
  22806. this.value = value;
  22807. this.dynamic = false;
  22808. }
  22809. Uniform.prototype = {
  22810. constructor: Uniform,
  22811. onUpdate: function ( callback ) {
  22812. this.dynamic = true;
  22813. this.onUpdateCallback = callback;
  22814. return this;
  22815. }
  22816. };
  22817. /**
  22818. * @author benaadams / https://twitter.com/ben_a_adams
  22819. */
  22820. function InstancedBufferGeometry() {
  22821. BufferGeometry.call( this );
  22822. this.type = 'InstancedBufferGeometry';
  22823. this.maxInstancedCount = undefined;
  22824. }
  22825. InstancedBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  22826. InstancedBufferGeometry.prototype.constructor = InstancedBufferGeometry;
  22827. InstancedBufferGeometry.prototype.isInstancedBufferGeometry = true;
  22828. InstancedBufferGeometry.prototype.addGroup = function ( start, count, instances ) {
  22829. this.groups.push( {
  22830. start: start,
  22831. count: count,
  22832. instances: instances
  22833. } );
  22834. };
  22835. InstancedBufferGeometry.prototype.copy = function ( source ) {
  22836. var index = source.index;
  22837. if ( index !== null ) {
  22838. this.setIndex( index.clone() );
  22839. }
  22840. var attributes = source.attributes;
  22841. for ( var name in attributes ) {
  22842. var attribute = attributes[ name ];
  22843. this.addAttribute( name, attribute.clone() );
  22844. }
  22845. var groups = source.groups;
  22846. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  22847. var group = groups[ i ];
  22848. this.addGroup( group.start, group.count, group.instances );
  22849. }
  22850. return this;
  22851. };
  22852. /**
  22853. * @author benaadams / https://twitter.com/ben_a_adams
  22854. */
  22855. function InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, normalized ) {
  22856. this.uuid = exports.Math.generateUUID();
  22857. this.data = interleavedBuffer;
  22858. this.itemSize = itemSize;
  22859. this.offset = offset;
  22860. this.normalized = normalized === true;
  22861. }
  22862. InterleavedBufferAttribute.prototype = {
  22863. constructor: InterleavedBufferAttribute,
  22864. isInterleavedBufferAttribute: true,
  22865. get length() {
  22866. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Please use .count.' );
  22867. return this.array.length;
  22868. },
  22869. get count() {
  22870. return this.data.count;
  22871. },
  22872. get array() {
  22873. return this.data.array;
  22874. },
  22875. setX: function ( index, x ) {
  22876. this.data.array[ index * this.data.stride + this.offset ] = x;
  22877. return this;
  22878. },
  22879. setY: function ( index, y ) {
  22880. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  22881. return this;
  22882. },
  22883. setZ: function ( index, z ) {
  22884. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  22885. return this;
  22886. },
  22887. setW: function ( index, w ) {
  22888. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  22889. return this;
  22890. },
  22891. getX: function ( index ) {
  22892. return this.data.array[ index * this.data.stride + this.offset ];
  22893. },
  22894. getY: function ( index ) {
  22895. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  22896. },
  22897. getZ: function ( index ) {
  22898. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  22899. },
  22900. getW: function ( index ) {
  22901. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  22902. },
  22903. setXY: function ( index, x, y ) {
  22904. index = index * this.data.stride + this.offset;
  22905. this.data.array[ index + 0 ] = x;
  22906. this.data.array[ index + 1 ] = y;
  22907. return this;
  22908. },
  22909. setXYZ: function ( index, x, y, z ) {
  22910. index = index * this.data.stride + this.offset;
  22911. this.data.array[ index + 0 ] = x;
  22912. this.data.array[ index + 1 ] = y;
  22913. this.data.array[ index + 2 ] = z;
  22914. return this;
  22915. },
  22916. setXYZW: function ( index, x, y, z, w ) {
  22917. index = index * this.data.stride + this.offset;
  22918. this.data.array[ index + 0 ] = x;
  22919. this.data.array[ index + 1 ] = y;
  22920. this.data.array[ index + 2 ] = z;
  22921. this.data.array[ index + 3 ] = w;
  22922. return this;
  22923. }
  22924. };
  22925. /**
  22926. * @author benaadams / https://twitter.com/ben_a_adams
  22927. */
  22928. function InterleavedBuffer( array, stride ) {
  22929. this.uuid = exports.Math.generateUUID();
  22930. this.array = array;
  22931. this.stride = stride;
  22932. this.dynamic = false;
  22933. this.updateRange = { offset: 0, count: - 1 };
  22934. this.version = 0;
  22935. }
  22936. InterleavedBuffer.prototype = {
  22937. constructor: InterleavedBuffer,
  22938. isInterleavedBuffer: true,
  22939. get length () {
  22940. return this.array.length;
  22941. },
  22942. get count () {
  22943. return this.array.length / this.stride;
  22944. },
  22945. set needsUpdate( value ) {
  22946. if ( value === true ) this.version ++;
  22947. },
  22948. setDynamic: function ( value ) {
  22949. this.dynamic = value;
  22950. return this;
  22951. },
  22952. copy: function ( source ) {
  22953. this.array = new source.array.constructor( source.array );
  22954. this.stride = source.stride;
  22955. this.dynamic = source.dynamic;
  22956. return this;
  22957. },
  22958. copyAt: function ( index1, attribute, index2 ) {
  22959. index1 *= this.stride;
  22960. index2 *= attribute.stride;
  22961. for ( var i = 0, l = this.stride; i < l; i ++ ) {
  22962. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  22963. }
  22964. return this;
  22965. },
  22966. set: function ( value, offset ) {
  22967. if ( offset === undefined ) offset = 0;
  22968. this.array.set( value, offset );
  22969. return this;
  22970. },
  22971. clone: function () {
  22972. return new this.constructor().copy( this );
  22973. }
  22974. };
  22975. /**
  22976. * @author benaadams / https://twitter.com/ben_a_adams
  22977. */
  22978. function InstancedInterleavedBuffer( array, stride, meshPerAttribute ) {
  22979. InterleavedBuffer.call( this, array, stride );
  22980. this.meshPerAttribute = meshPerAttribute || 1;
  22981. }
  22982. InstancedInterleavedBuffer.prototype = Object.create( InterleavedBuffer.prototype );
  22983. InstancedInterleavedBuffer.prototype.constructor = InstancedInterleavedBuffer;
  22984. InstancedInterleavedBuffer.prototype.isInstancedInterleavedBuffer = true;
  22985. InstancedInterleavedBuffer.prototype.copy = function ( source ) {
  22986. InterleavedBuffer.prototype.copy.call( this, source );
  22987. this.meshPerAttribute = source.meshPerAttribute;
  22988. return this;
  22989. };
  22990. /**
  22991. * @author benaadams / https://twitter.com/ben_a_adams
  22992. */
  22993. function InstancedBufferAttribute( array, itemSize, meshPerAttribute ) {
  22994. BufferAttribute.call( this, array, itemSize );
  22995. this.meshPerAttribute = meshPerAttribute || 1;
  22996. }
  22997. InstancedBufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  22998. InstancedBufferAttribute.prototype.constructor = InstancedBufferAttribute;
  22999. InstancedBufferAttribute.prototype.isInstancedBufferAttribute = true;
  23000. InstancedBufferAttribute.prototype.copy = function ( source ) {
  23001. BufferAttribute.prototype.copy.call( this, source );
  23002. this.meshPerAttribute = source.meshPerAttribute;
  23003. return this;
  23004. };
  23005. /**
  23006. * @author mrdoob / http://mrdoob.com/
  23007. * @author bhouston / http://clara.io/
  23008. * @author stephomi / http://stephaneginier.com/
  23009. */
  23010. function Raycaster( origin, direction, near, far ) {
  23011. this.ray = new Ray( origin, direction );
  23012. // direction is assumed to be normalized (for accurate distance calculations)
  23013. this.near = near || 0;
  23014. this.far = far || Infinity;
  23015. this.params = {
  23016. Mesh: {},
  23017. Line: {},
  23018. LOD: {},
  23019. Points: { threshold: 1 },
  23020. Sprite: {}
  23021. };
  23022. Object.defineProperties( this.params, {
  23023. PointCloud: {
  23024. get: function () {
  23025. console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' );
  23026. return this.Points;
  23027. }
  23028. }
  23029. } );
  23030. }
  23031. function ascSort( a, b ) {
  23032. return a.distance - b.distance;
  23033. }
  23034. function intersectObject( object, raycaster, intersects, recursive ) {
  23035. if ( object.visible === false ) return;
  23036. object.raycast( raycaster, intersects );
  23037. if ( recursive === true ) {
  23038. var children = object.children;
  23039. for ( var i = 0, l = children.length; i < l; i ++ ) {
  23040. intersectObject( children[ i ], raycaster, intersects, true );
  23041. }
  23042. }
  23043. }
  23044. //
  23045. Raycaster.prototype = {
  23046. constructor: Raycaster,
  23047. linePrecision: 1,
  23048. set: function ( origin, direction ) {
  23049. // direction is assumed to be normalized (for accurate distance calculations)
  23050. this.ray.set( origin, direction );
  23051. },
  23052. setFromCamera: function ( coords, camera ) {
  23053. if ( (camera && camera.isPerspectiveCamera) ) {
  23054. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  23055. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  23056. } else if ( (camera && camera.isOrthographicCamera) ) {
  23057. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  23058. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  23059. } else {
  23060. console.error( 'THREE.Raycaster: Unsupported camera type.' );
  23061. }
  23062. },
  23063. intersectObject: function ( object, recursive ) {
  23064. var intersects = [];
  23065. intersectObject( object, this, intersects, recursive );
  23066. intersects.sort( ascSort );
  23067. return intersects;
  23068. },
  23069. intersectObjects: function ( objects, recursive ) {
  23070. var intersects = [];
  23071. if ( Array.isArray( objects ) === false ) {
  23072. console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
  23073. return intersects;
  23074. }
  23075. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  23076. intersectObject( objects[ i ], this, intersects, recursive );
  23077. }
  23078. intersects.sort( ascSort );
  23079. return intersects;
  23080. }
  23081. };
  23082. /**
  23083. * @author alteredq / http://alteredqualia.com/
  23084. */
  23085. function Clock( autoStart ) {
  23086. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  23087. this.startTime = 0;
  23088. this.oldTime = 0;
  23089. this.elapsedTime = 0;
  23090. this.running = false;
  23091. }
  23092. Clock.prototype = {
  23093. constructor: Clock,
  23094. start: function () {
  23095. this.startTime = ( performance || Date ).now();
  23096. this.oldTime = this.startTime;
  23097. this.running = true;
  23098. },
  23099. stop: function () {
  23100. this.getElapsedTime();
  23101. this.running = false;
  23102. },
  23103. getElapsedTime: function () {
  23104. this.getDelta();
  23105. return this.elapsedTime;
  23106. },
  23107. getDelta: function () {
  23108. var diff = 0;
  23109. if ( this.autoStart && ! this.running ) {
  23110. this.start();
  23111. }
  23112. if ( this.running ) {
  23113. var newTime = ( performance || Date ).now();
  23114. diff = ( newTime - this.oldTime ) / 1000;
  23115. this.oldTime = newTime;
  23116. this.elapsedTime += diff;
  23117. }
  23118. return diff;
  23119. }
  23120. };
  23121. /**
  23122. * Spline from Tween.js, slightly optimized (and trashed)
  23123. * http://sole.github.com/tween.js/examples/05_spline.html
  23124. *
  23125. * @author mrdoob / http://mrdoob.com/
  23126. * @author alteredq / http://alteredqualia.com/
  23127. */
  23128. function Spline( points ) {
  23129. this.points = points;
  23130. var c = [], v3 = { x: 0, y: 0, z: 0 },
  23131. point, intPoint, weight, w2, w3,
  23132. pa, pb, pc, pd;
  23133. this.initFromArray = function ( a ) {
  23134. this.points = [];
  23135. for ( var i = 0; i < a.length; i ++ ) {
  23136. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  23137. }
  23138. };
  23139. this.getPoint = function ( k ) {
  23140. point = ( this.points.length - 1 ) * k;
  23141. intPoint = Math.floor( point );
  23142. weight = point - intPoint;
  23143. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  23144. c[ 1 ] = intPoint;
  23145. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  23146. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  23147. pa = this.points[ c[ 0 ] ];
  23148. pb = this.points[ c[ 1 ] ];
  23149. pc = this.points[ c[ 2 ] ];
  23150. pd = this.points[ c[ 3 ] ];
  23151. w2 = weight * weight;
  23152. w3 = weight * w2;
  23153. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  23154. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  23155. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  23156. return v3;
  23157. };
  23158. this.getControlPointsArray = function () {
  23159. var i, p, l = this.points.length,
  23160. coords = [];
  23161. for ( i = 0; i < l; i ++ ) {
  23162. p = this.points[ i ];
  23163. coords[ i ] = [ p.x, p.y, p.z ];
  23164. }
  23165. return coords;
  23166. };
  23167. // approximate length by summing linear segments
  23168. this.getLength = function ( nSubDivisions ) {
  23169. var i, index, nSamples, position,
  23170. point = 0, intPoint = 0, oldIntPoint = 0,
  23171. oldPosition = new Vector3(),
  23172. tmpVec = new Vector3(),
  23173. chunkLengths = [],
  23174. totalLength = 0;
  23175. // first point has 0 length
  23176. chunkLengths[ 0 ] = 0;
  23177. if ( ! nSubDivisions ) nSubDivisions = 100;
  23178. nSamples = this.points.length * nSubDivisions;
  23179. oldPosition.copy( this.points[ 0 ] );
  23180. for ( i = 1; i < nSamples; i ++ ) {
  23181. index = i / nSamples;
  23182. position = this.getPoint( index );
  23183. tmpVec.copy( position );
  23184. totalLength += tmpVec.distanceTo( oldPosition );
  23185. oldPosition.copy( position );
  23186. point = ( this.points.length - 1 ) * index;
  23187. intPoint = Math.floor( point );
  23188. if ( intPoint !== oldIntPoint ) {
  23189. chunkLengths[ intPoint ] = totalLength;
  23190. oldIntPoint = intPoint;
  23191. }
  23192. }
  23193. // last point ends with total length
  23194. chunkLengths[ chunkLengths.length ] = totalLength;
  23195. return { chunks: chunkLengths, total: totalLength };
  23196. };
  23197. this.reparametrizeByArcLength = function ( samplingCoef ) {
  23198. var i, j,
  23199. index, indexCurrent, indexNext,
  23200. realDistance,
  23201. sampling, position,
  23202. newpoints = [],
  23203. tmpVec = new Vector3(),
  23204. sl = this.getLength();
  23205. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  23206. for ( i = 1; i < this.points.length; i ++ ) {
  23207. //tmpVec.copy( this.points[ i - 1 ] );
  23208. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  23209. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  23210. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  23211. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  23212. indexNext = i / ( this.points.length - 1 );
  23213. for ( j = 1; j < sampling - 1; j ++ ) {
  23214. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  23215. position = this.getPoint( index );
  23216. newpoints.push( tmpVec.copy( position ).clone() );
  23217. }
  23218. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  23219. }
  23220. this.points = newpoints;
  23221. };
  23222. // Catmull-Rom
  23223. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  23224. var v0 = ( p2 - p0 ) * 0.5,
  23225. v1 = ( p3 - p1 ) * 0.5;
  23226. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  23227. }
  23228. }
  23229. /**
  23230. * @author bhouston / http://clara.io
  23231. * @author WestLangley / http://github.com/WestLangley
  23232. *
  23233. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  23234. *
  23235. * The poles (phi) are at the positive and negative y axis.
  23236. * The equator starts at positive z.
  23237. */
  23238. function Spherical( radius, phi, theta ) {
  23239. this.radius = ( radius !== undefined ) ? radius : 1.0;
  23240. this.phi = ( phi !== undefined ) ? phi : 0; // up / down towards top and bottom pole
  23241. this.theta = ( theta !== undefined ) ? theta : 0; // around the equator of the sphere
  23242. return this;
  23243. }
  23244. Spherical.prototype = {
  23245. constructor: Spherical,
  23246. set: function ( radius, phi, theta ) {
  23247. this.radius = radius;
  23248. this.phi = phi;
  23249. this.theta = theta;
  23250. return this;
  23251. },
  23252. clone: function () {
  23253. return new this.constructor().copy( this );
  23254. },
  23255. copy: function ( other ) {
  23256. this.radius.copy( other.radius );
  23257. this.phi.copy( other.phi );
  23258. this.theta.copy( other.theta );
  23259. return this;
  23260. },
  23261. // restrict phi to be betwee EPS and PI-EPS
  23262. makeSafe: function() {
  23263. var EPS = 0.000001;
  23264. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  23265. return this;
  23266. },
  23267. setFromVector3: function( vec3 ) {
  23268. this.radius = vec3.length();
  23269. if ( this.radius === 0 ) {
  23270. this.theta = 0;
  23271. this.phi = 0;
  23272. } else {
  23273. this.theta = Math.atan2( vec3.x, vec3.z ); // equator angle around y-up axis
  23274. this.phi = Math.acos( exports.Math.clamp( vec3.y / this.radius, - 1, 1 ) ); // polar angle
  23275. }
  23276. return this;
  23277. },
  23278. };
  23279. /**
  23280. * @author alteredq / http://alteredqualia.com/
  23281. */
  23282. function MorphBlendMesh( geometry, material ) {
  23283. Mesh.call( this, geometry, material );
  23284. this.animationsMap = {};
  23285. this.animationsList = [];
  23286. // prepare default animation
  23287. // (all frames played together in 1 second)
  23288. var numFrames = this.geometry.morphTargets.length;
  23289. var name = "__default";
  23290. var startFrame = 0;
  23291. var endFrame = numFrames - 1;
  23292. var fps = numFrames / 1;
  23293. this.createAnimation( name, startFrame, endFrame, fps );
  23294. this.setAnimationWeight( name, 1 );
  23295. }
  23296. MorphBlendMesh.prototype = Object.create( Mesh.prototype );
  23297. MorphBlendMesh.prototype.constructor = MorphBlendMesh;
  23298. MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  23299. var animation = {
  23300. start: start,
  23301. end: end,
  23302. length: end - start + 1,
  23303. fps: fps,
  23304. duration: ( end - start ) / fps,
  23305. lastFrame: 0,
  23306. currentFrame: 0,
  23307. active: false,
  23308. time: 0,
  23309. direction: 1,
  23310. weight: 1,
  23311. directionBackwards: false,
  23312. mirroredLoop: false
  23313. };
  23314. this.animationsMap[ name ] = animation;
  23315. this.animationsList.push( animation );
  23316. };
  23317. MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  23318. var pattern = /([a-z]+)_?(\d+)/i;
  23319. var firstAnimation, frameRanges = {};
  23320. var geometry = this.geometry;
  23321. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  23322. var morph = geometry.morphTargets[ i ];
  23323. var chunks = morph.name.match( pattern );
  23324. if ( chunks && chunks.length > 1 ) {
  23325. var name = chunks[ 1 ];
  23326. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: - Infinity };
  23327. var range = frameRanges[ name ];
  23328. if ( i < range.start ) range.start = i;
  23329. if ( i > range.end ) range.end = i;
  23330. if ( ! firstAnimation ) firstAnimation = name;
  23331. }
  23332. }
  23333. for ( var name in frameRanges ) {
  23334. var range = frameRanges[ name ];
  23335. this.createAnimation( name, range.start, range.end, fps );
  23336. }
  23337. this.firstAnimation = firstAnimation;
  23338. };
  23339. MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  23340. var animation = this.animationsMap[ name ];
  23341. if ( animation ) {
  23342. animation.direction = 1;
  23343. animation.directionBackwards = false;
  23344. }
  23345. };
  23346. MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  23347. var animation = this.animationsMap[ name ];
  23348. if ( animation ) {
  23349. animation.direction = - 1;
  23350. animation.directionBackwards = true;
  23351. }
  23352. };
  23353. MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  23354. var animation = this.animationsMap[ name ];
  23355. if ( animation ) {
  23356. animation.fps = fps;
  23357. animation.duration = ( animation.end - animation.start ) / animation.fps;
  23358. }
  23359. };
  23360. MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  23361. var animation = this.animationsMap[ name ];
  23362. if ( animation ) {
  23363. animation.duration = duration;
  23364. animation.fps = ( animation.end - animation.start ) / animation.duration;
  23365. }
  23366. };
  23367. MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  23368. var animation = this.animationsMap[ name ];
  23369. if ( animation ) {
  23370. animation.weight = weight;
  23371. }
  23372. };
  23373. MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  23374. var animation = this.animationsMap[ name ];
  23375. if ( animation ) {
  23376. animation.time = time;
  23377. }
  23378. };
  23379. MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  23380. var time = 0;
  23381. var animation = this.animationsMap[ name ];
  23382. if ( animation ) {
  23383. time = animation.time;
  23384. }
  23385. return time;
  23386. };
  23387. MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  23388. var duration = - 1;
  23389. var animation = this.animationsMap[ name ];
  23390. if ( animation ) {
  23391. duration = animation.duration;
  23392. }
  23393. return duration;
  23394. };
  23395. MorphBlendMesh.prototype.playAnimation = function ( name ) {
  23396. var animation = this.animationsMap[ name ];
  23397. if ( animation ) {
  23398. animation.time = 0;
  23399. animation.active = true;
  23400. } else {
  23401. console.warn( "THREE.MorphBlendMesh: animation[" + name + "] undefined in .playAnimation()" );
  23402. }
  23403. };
  23404. MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  23405. var animation = this.animationsMap[ name ];
  23406. if ( animation ) {
  23407. animation.active = false;
  23408. }
  23409. };
  23410. MorphBlendMesh.prototype.update = function ( delta ) {
  23411. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  23412. var animation = this.animationsList[ i ];
  23413. if ( ! animation.active ) continue;
  23414. var frameTime = animation.duration / animation.length;
  23415. animation.time += animation.direction * delta;
  23416. if ( animation.mirroredLoop ) {
  23417. if ( animation.time > animation.duration || animation.time < 0 ) {
  23418. animation.direction *= - 1;
  23419. if ( animation.time > animation.duration ) {
  23420. animation.time = animation.duration;
  23421. animation.directionBackwards = true;
  23422. }
  23423. if ( animation.time < 0 ) {
  23424. animation.time = 0;
  23425. animation.directionBackwards = false;
  23426. }
  23427. }
  23428. } else {
  23429. animation.time = animation.time % animation.duration;
  23430. if ( animation.time < 0 ) animation.time += animation.duration;
  23431. }
  23432. var keyframe = animation.start + exports.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  23433. var weight = animation.weight;
  23434. if ( keyframe !== animation.currentFrame ) {
  23435. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  23436. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  23437. this.morphTargetInfluences[ keyframe ] = 0;
  23438. animation.lastFrame = animation.currentFrame;
  23439. animation.currentFrame = keyframe;
  23440. }
  23441. var mix = ( animation.time % frameTime ) / frameTime;
  23442. if ( animation.directionBackwards ) mix = 1 - mix;
  23443. if ( animation.currentFrame !== animation.lastFrame ) {
  23444. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  23445. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  23446. } else {
  23447. this.morphTargetInfluences[ animation.currentFrame ] = weight;
  23448. }
  23449. }
  23450. };
  23451. /**
  23452. * @author alteredq / http://alteredqualia.com/
  23453. */
  23454. function ImmediateRenderObject( material ) {
  23455. Object3D.call( this );
  23456. this.material = material;
  23457. this.render = function ( renderCallback ) {};
  23458. }
  23459. ImmediateRenderObject.prototype = Object.create( Object3D.prototype );
  23460. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  23461. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  23462. /**
  23463. * @author mrdoob / http://mrdoob.com/
  23464. */
  23465. function WireframeHelper( object, hex ) {
  23466. var color = ( hex !== undefined ) ? hex : 0xffffff;
  23467. LineSegments.call( this, new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: color } ) );
  23468. this.matrix = object.matrixWorld;
  23469. this.matrixAutoUpdate = false;
  23470. }
  23471. WireframeHelper.prototype = Object.create( LineSegments.prototype );
  23472. WireframeHelper.prototype.constructor = WireframeHelper;
  23473. /**
  23474. * @author mrdoob / http://mrdoob.com/
  23475. * @author WestLangley / http://github.com/WestLangley
  23476. */
  23477. function VertexNormalsHelper( object, size, hex, linewidth ) {
  23478. this.object = object;
  23479. this.size = ( size !== undefined ) ? size : 1;
  23480. var color = ( hex !== undefined ) ? hex : 0xff0000;
  23481. var width = ( linewidth !== undefined ) ? linewidth : 1;
  23482. //
  23483. var nNormals = 0;
  23484. var objGeometry = this.object.geometry;
  23485. if ( (objGeometry && objGeometry.isGeometry) ) {
  23486. nNormals = objGeometry.faces.length * 3;
  23487. } else if ( (objGeometry && objGeometry.isBufferGeometry) ) {
  23488. nNormals = objGeometry.attributes.normal.count;
  23489. }
  23490. //
  23491. var geometry = new BufferGeometry();
  23492. var positions = new Float32Attribute( nNormals * 2 * 3, 3 );
  23493. geometry.addAttribute( 'position', positions );
  23494. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  23495. //
  23496. this.matrixAutoUpdate = false;
  23497. this.update();
  23498. }
  23499. VertexNormalsHelper.prototype = Object.create( LineSegments.prototype );
  23500. VertexNormalsHelper.prototype.constructor = VertexNormalsHelper;
  23501. VertexNormalsHelper.prototype.update = ( function () {
  23502. var v1 = new Vector3();
  23503. var v2 = new Vector3();
  23504. var normalMatrix = new Matrix3();
  23505. return function update() {
  23506. var keys = [ 'a', 'b', 'c' ];
  23507. this.object.updateMatrixWorld( true );
  23508. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  23509. var matrixWorld = this.object.matrixWorld;
  23510. var position = this.geometry.attributes.position;
  23511. //
  23512. var objGeometry = this.object.geometry;
  23513. if ( (objGeometry && objGeometry.isGeometry) ) {
  23514. var vertices = objGeometry.vertices;
  23515. var faces = objGeometry.faces;
  23516. var idx = 0;
  23517. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  23518. var face = faces[ i ];
  23519. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  23520. var vertex = vertices[ face[ keys[ j ] ] ];
  23521. var normal = face.vertexNormals[ j ];
  23522. v1.copy( vertex ).applyMatrix4( matrixWorld );
  23523. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  23524. position.setXYZ( idx, v1.x, v1.y, v1.z );
  23525. idx = idx + 1;
  23526. position.setXYZ( idx, v2.x, v2.y, v2.z );
  23527. idx = idx + 1;
  23528. }
  23529. }
  23530. } else if ( (objGeometry && objGeometry.isBufferGeometry) ) {
  23531. var objPos = objGeometry.attributes.position;
  23532. var objNorm = objGeometry.attributes.normal;
  23533. var idx = 0;
  23534. // for simplicity, ignore index and drawcalls, and render every normal
  23535. for ( var j = 0, jl = objPos.count; j < jl; j ++ ) {
  23536. v1.set( objPos.getX( j ), objPos.getY( j ), objPos.getZ( j ) ).applyMatrix4( matrixWorld );
  23537. v2.set( objNorm.getX( j ), objNorm.getY( j ), objNorm.getZ( j ) );
  23538. v2.applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  23539. position.setXYZ( idx, v1.x, v1.y, v1.z );
  23540. idx = idx + 1;
  23541. position.setXYZ( idx, v2.x, v2.y, v2.z );
  23542. idx = idx + 1;
  23543. }
  23544. }
  23545. position.needsUpdate = true;
  23546. return this;
  23547. };
  23548. }() );
  23549. /**
  23550. * @author alteredq / http://alteredqualia.com/
  23551. * @author mrdoob / http://mrdoob.com/
  23552. * @author WestLangley / http://github.com/WestLangley
  23553. */
  23554. function SpotLightHelper( light ) {
  23555. Object3D.call( this );
  23556. this.light = light;
  23557. this.light.updateMatrixWorld();
  23558. this.matrix = light.matrixWorld;
  23559. this.matrixAutoUpdate = false;
  23560. var geometry = new BufferGeometry();
  23561. var positions = [
  23562. 0, 0, 0, 0, 0, 1,
  23563. 0, 0, 0, 1, 0, 1,
  23564. 0, 0, 0, - 1, 0, 1,
  23565. 0, 0, 0, 0, 1, 1,
  23566. 0, 0, 0, 0, - 1, 1
  23567. ];
  23568. for ( var i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  23569. var p1 = ( i / l ) * Math.PI * 2;
  23570. var p2 = ( j / l ) * Math.PI * 2;
  23571. positions.push(
  23572. Math.cos( p1 ), Math.sin( p1 ), 1,
  23573. Math.cos( p2 ), Math.sin( p2 ), 1
  23574. );
  23575. }
  23576. geometry.addAttribute( 'position', new Float32Attribute( positions, 3 ) );
  23577. var material = new LineBasicMaterial( { fog: false } );
  23578. this.cone = new LineSegments( geometry, material );
  23579. this.add( this.cone );
  23580. this.update();
  23581. }
  23582. SpotLightHelper.prototype = Object.create( Object3D.prototype );
  23583. SpotLightHelper.prototype.constructor = SpotLightHelper;
  23584. SpotLightHelper.prototype.dispose = function () {
  23585. this.cone.geometry.dispose();
  23586. this.cone.material.dispose();
  23587. };
  23588. SpotLightHelper.prototype.update = function () {
  23589. var vector = new Vector3();
  23590. var vector2 = new Vector3();
  23591. return function update() {
  23592. var coneLength = this.light.distance ? this.light.distance : 1000;
  23593. var coneWidth = coneLength * Math.tan( this.light.angle );
  23594. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  23595. vector.setFromMatrixPosition( this.light.matrixWorld );
  23596. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  23597. this.cone.lookAt( vector2.sub( vector ) );
  23598. this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  23599. };
  23600. }();
  23601. /**
  23602. * @author Sean Griffin / http://twitter.com/sgrif
  23603. * @author Michael Guerrero / http://realitymeltdown.com
  23604. * @author mrdoob / http://mrdoob.com/
  23605. * @author ikerr / http://verold.com
  23606. */
  23607. function SkeletonHelper( object ) {
  23608. this.bones = this.getBoneList( object );
  23609. var geometry = new Geometry();
  23610. for ( var i = 0; i < this.bones.length; i ++ ) {
  23611. var bone = this.bones[ i ];
  23612. if ( (bone.parent && bone.parent.isBone) ) {
  23613. geometry.vertices.push( new Vector3() );
  23614. geometry.vertices.push( new Vector3() );
  23615. geometry.colors.push( new Color( 0, 0, 1 ) );
  23616. geometry.colors.push( new Color( 0, 1, 0 ) );
  23617. }
  23618. }
  23619. geometry.dynamic = true;
  23620. var material = new LineBasicMaterial( { vertexColors: VertexColors, depthTest: false, depthWrite: false, transparent: true } );
  23621. LineSegments.call( this, geometry, material );
  23622. this.root = object;
  23623. this.matrix = object.matrixWorld;
  23624. this.matrixAutoUpdate = false;
  23625. this.update();
  23626. }
  23627. SkeletonHelper.prototype = Object.create( LineSegments.prototype );
  23628. SkeletonHelper.prototype.constructor = SkeletonHelper;
  23629. SkeletonHelper.prototype.getBoneList = function( object ) {
  23630. var boneList = [];
  23631. if ( (object && object.isBone) ) {
  23632. boneList.push( object );
  23633. }
  23634. for ( var i = 0; i < object.children.length; i ++ ) {
  23635. boneList.push.apply( boneList, this.getBoneList( object.children[ i ] ) );
  23636. }
  23637. return boneList;
  23638. };
  23639. SkeletonHelper.prototype.update = function () {
  23640. var geometry = this.geometry;
  23641. var matrixWorldInv = new Matrix4().getInverse( this.root.matrixWorld );
  23642. var boneMatrix = new Matrix4();
  23643. var j = 0;
  23644. for ( var i = 0; i < this.bones.length; i ++ ) {
  23645. var bone = this.bones[ i ];
  23646. if ( (bone.parent && bone.parent.isBone) ) {
  23647. boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld );
  23648. geometry.vertices[ j ].setFromMatrixPosition( boneMatrix );
  23649. boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld );
  23650. geometry.vertices[ j + 1 ].setFromMatrixPosition( boneMatrix );
  23651. j += 2;
  23652. }
  23653. }
  23654. geometry.verticesNeedUpdate = true;
  23655. geometry.computeBoundingSphere();
  23656. };
  23657. /**
  23658. * @author alteredq / http://alteredqualia.com/
  23659. * @author mrdoob / http://mrdoob.com/
  23660. */
  23661. function PointLightHelper( light, sphereSize ) {
  23662. this.light = light;
  23663. this.light.updateMatrixWorld();
  23664. var geometry = new SphereBufferGeometry( sphereSize, 4, 2 );
  23665. var material = new MeshBasicMaterial( { wireframe: true, fog: false } );
  23666. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  23667. Mesh.call( this, geometry, material );
  23668. this.matrix = this.light.matrixWorld;
  23669. this.matrixAutoUpdate = false;
  23670. /*
  23671. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  23672. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  23673. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  23674. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  23675. var d = light.distance;
  23676. if ( d === 0.0 ) {
  23677. this.lightDistance.visible = false;
  23678. } else {
  23679. this.lightDistance.scale.set( d, d, d );
  23680. }
  23681. this.add( this.lightDistance );
  23682. */
  23683. }
  23684. PointLightHelper.prototype = Object.create( Mesh.prototype );
  23685. PointLightHelper.prototype.constructor = PointLightHelper;
  23686. PointLightHelper.prototype.dispose = function () {
  23687. this.geometry.dispose();
  23688. this.material.dispose();
  23689. };
  23690. PointLightHelper.prototype.update = function () {
  23691. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  23692. /*
  23693. var d = this.light.distance;
  23694. if ( d === 0.0 ) {
  23695. this.lightDistance.visible = false;
  23696. } else {
  23697. this.lightDistance.visible = true;
  23698. this.lightDistance.scale.set( d, d, d );
  23699. }
  23700. */
  23701. };
  23702. /**
  23703. * @author alteredq / http://alteredqualia.com/
  23704. * @author mrdoob / http://mrdoob.com/
  23705. */
  23706. function HemisphereLightHelper( light, sphereSize ) {
  23707. Object3D.call( this );
  23708. this.light = light;
  23709. this.light.updateMatrixWorld();
  23710. this.matrix = light.matrixWorld;
  23711. this.matrixAutoUpdate = false;
  23712. this.colors = [ new Color(), new Color() ];
  23713. var geometry = new SphereGeometry( sphereSize, 4, 2 );
  23714. geometry.rotateX( - Math.PI / 2 );
  23715. for ( var i = 0, il = 8; i < il; i ++ ) {
  23716. geometry.faces[ i ].color = this.colors[ i < 4 ? 0 : 1 ];
  23717. }
  23718. var material = new MeshBasicMaterial( { vertexColors: FaceColors, wireframe: true } );
  23719. this.lightSphere = new Mesh( geometry, material );
  23720. this.add( this.lightSphere );
  23721. this.update();
  23722. }
  23723. HemisphereLightHelper.prototype = Object.create( Object3D.prototype );
  23724. HemisphereLightHelper.prototype.constructor = HemisphereLightHelper;
  23725. HemisphereLightHelper.prototype.dispose = function () {
  23726. this.lightSphere.geometry.dispose();
  23727. this.lightSphere.material.dispose();
  23728. };
  23729. HemisphereLightHelper.prototype.update = function () {
  23730. var vector = new Vector3();
  23731. return function update() {
  23732. this.colors[ 0 ].copy( this.light.color ).multiplyScalar( this.light.intensity );
  23733. this.colors[ 1 ].copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  23734. this.lightSphere.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  23735. this.lightSphere.geometry.colorsNeedUpdate = true;
  23736. };
  23737. }();
  23738. /**
  23739. * @author mrdoob / http://mrdoob.com/
  23740. */
  23741. function GridHelper( size, divisions, color1, color2 ) {
  23742. divisions = divisions || 1;
  23743. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  23744. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  23745. var center = divisions / 2;
  23746. var step = ( size * 2 ) / divisions;
  23747. var vertices = [], colors = [];
  23748. for ( var i = 0, j = 0, k = - size; i <= divisions; i ++, k += step ) {
  23749. vertices.push( - size, 0, k, size, 0, k );
  23750. vertices.push( k, 0, - size, k, 0, size );
  23751. var color = i === center ? color1 : color2;
  23752. color.toArray( colors, j ); j += 3;
  23753. color.toArray( colors, j ); j += 3;
  23754. color.toArray( colors, j ); j += 3;
  23755. color.toArray( colors, j ); j += 3;
  23756. }
  23757. var geometry = new BufferGeometry();
  23758. geometry.addAttribute( 'position', new Float32Attribute( vertices, 3 ) );
  23759. geometry.addAttribute( 'color', new Float32Attribute( colors, 3 ) );
  23760. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  23761. LineSegments.call( this, geometry, material );
  23762. }
  23763. GridHelper.prototype = Object.create( LineSegments.prototype );
  23764. GridHelper.prototype.constructor = GridHelper;
  23765. GridHelper.prototype.setColors = function () {
  23766. console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' );
  23767. };
  23768. /**
  23769. * @author mrdoob / http://mrdoob.com/
  23770. * @author WestLangley / http://github.com/WestLangley
  23771. */
  23772. function FaceNormalsHelper( object, size, hex, linewidth ) {
  23773. // FaceNormalsHelper only supports THREE.Geometry
  23774. this.object = object;
  23775. this.size = ( size !== undefined ) ? size : 1;
  23776. var color = ( hex !== undefined ) ? hex : 0xffff00;
  23777. var width = ( linewidth !== undefined ) ? linewidth : 1;
  23778. //
  23779. var nNormals = 0;
  23780. var objGeometry = this.object.geometry;
  23781. if ( (objGeometry && objGeometry.isGeometry) ) {
  23782. nNormals = objGeometry.faces.length;
  23783. } else {
  23784. console.warn( 'THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.' );
  23785. }
  23786. //
  23787. var geometry = new BufferGeometry();
  23788. var positions = new Float32Attribute( nNormals * 2 * 3, 3 );
  23789. geometry.addAttribute( 'position', positions );
  23790. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  23791. //
  23792. this.matrixAutoUpdate = false;
  23793. this.update();
  23794. }
  23795. FaceNormalsHelper.prototype = Object.create( LineSegments.prototype );
  23796. FaceNormalsHelper.prototype.constructor = FaceNormalsHelper;
  23797. FaceNormalsHelper.prototype.update = ( function () {
  23798. var v1 = new Vector3();
  23799. var v2 = new Vector3();
  23800. var normalMatrix = new Matrix3();
  23801. return function update() {
  23802. this.object.updateMatrixWorld( true );
  23803. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  23804. var matrixWorld = this.object.matrixWorld;
  23805. var position = this.geometry.attributes.position;
  23806. //
  23807. var objGeometry = this.object.geometry;
  23808. var vertices = objGeometry.vertices;
  23809. var faces = objGeometry.faces;
  23810. var idx = 0;
  23811. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  23812. var face = faces[ i ];
  23813. var normal = face.normal;
  23814. v1.copy( vertices[ face.a ] )
  23815. .add( vertices[ face.b ] )
  23816. .add( vertices[ face.c ] )
  23817. .divideScalar( 3 )
  23818. .applyMatrix4( matrixWorld );
  23819. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  23820. position.setXYZ( idx, v1.x, v1.y, v1.z );
  23821. idx = idx + 1;
  23822. position.setXYZ( idx, v2.x, v2.y, v2.z );
  23823. idx = idx + 1;
  23824. }
  23825. position.needsUpdate = true;
  23826. return this;
  23827. };
  23828. }() );
  23829. /**
  23830. * @author WestLangley / http://github.com/WestLangley
  23831. * @param object THREE.Mesh whose geometry will be used
  23832. * @param hex line color
  23833. * @param thresholdAngle the minimum angle (in degrees),
  23834. * between the face normals of adjacent faces,
  23835. * that is required to render an edge. A value of 10 means
  23836. * an edge is only rendered if the angle is at least 10 degrees.
  23837. */
  23838. function EdgesHelper( object, hex, thresholdAngle ) {
  23839. var color = ( hex !== undefined ) ? hex : 0xffffff;
  23840. LineSegments.call( this, new EdgesGeometry( object.geometry, thresholdAngle ), new LineBasicMaterial( { color: color } ) );
  23841. this.matrix = object.matrixWorld;
  23842. this.matrixAutoUpdate = false;
  23843. }
  23844. EdgesHelper.prototype = Object.create( LineSegments.prototype );
  23845. EdgesHelper.prototype.constructor = EdgesHelper;
  23846. /**
  23847. * @author alteredq / http://alteredqualia.com/
  23848. * @author mrdoob / http://mrdoob.com/
  23849. * @author WestLangley / http://github.com/WestLangley
  23850. */
  23851. function DirectionalLightHelper( light, size ) {
  23852. Object3D.call( this );
  23853. this.light = light;
  23854. this.light.updateMatrixWorld();
  23855. this.matrix = light.matrixWorld;
  23856. this.matrixAutoUpdate = false;
  23857. if ( size === undefined ) size = 1;
  23858. var geometry = new BufferGeometry();
  23859. geometry.addAttribute( 'position', new Float32Attribute( [
  23860. - size, size, 0,
  23861. size, size, 0,
  23862. size, - size, 0,
  23863. - size, - size, 0,
  23864. - size, size, 0
  23865. ], 3 ) );
  23866. var material = new LineBasicMaterial( { fog: false } );
  23867. this.add( new Line( geometry, material ) );
  23868. geometry = new BufferGeometry();
  23869. geometry.addAttribute( 'position', new Float32Attribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  23870. this.add( new Line( geometry, material ));
  23871. this.update();
  23872. }
  23873. DirectionalLightHelper.prototype = Object.create( Object3D.prototype );
  23874. DirectionalLightHelper.prototype.constructor = DirectionalLightHelper;
  23875. DirectionalLightHelper.prototype.dispose = function () {
  23876. var lightPlane = this.children[ 0 ];
  23877. var targetLine = this.children[ 1 ];
  23878. lightPlane.geometry.dispose();
  23879. lightPlane.material.dispose();
  23880. targetLine.geometry.dispose();
  23881. targetLine.material.dispose();
  23882. };
  23883. DirectionalLightHelper.prototype.update = function () {
  23884. var v1 = new Vector3();
  23885. var v2 = new Vector3();
  23886. var v3 = new Vector3();
  23887. return function update() {
  23888. v1.setFromMatrixPosition( this.light.matrixWorld );
  23889. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  23890. v3.subVectors( v2, v1 );
  23891. var lightPlane = this.children[ 0 ];
  23892. var targetLine = this.children[ 1 ];
  23893. lightPlane.lookAt( v3 );
  23894. lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  23895. targetLine.lookAt( v3 );
  23896. targetLine.scale.z = v3.length();
  23897. };
  23898. }();
  23899. /**
  23900. * @author alteredq / http://alteredqualia.com/
  23901. *
  23902. * - shows frustum, line of sight and up of the camera
  23903. * - suitable for fast updates
  23904. * - based on frustum visualization in lightgl.js shadowmap example
  23905. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  23906. */
  23907. function CameraHelper( camera ) {
  23908. var geometry = new Geometry();
  23909. var material = new LineBasicMaterial( { color: 0xffffff, vertexColors: FaceColors } );
  23910. var pointMap = {};
  23911. // colors
  23912. var hexFrustum = 0xffaa00;
  23913. var hexCone = 0xff0000;
  23914. var hexUp = 0x00aaff;
  23915. var hexTarget = 0xffffff;
  23916. var hexCross = 0x333333;
  23917. // near
  23918. addLine( "n1", "n2", hexFrustum );
  23919. addLine( "n2", "n4", hexFrustum );
  23920. addLine( "n4", "n3", hexFrustum );
  23921. addLine( "n3", "n1", hexFrustum );
  23922. // far
  23923. addLine( "f1", "f2", hexFrustum );
  23924. addLine( "f2", "f4", hexFrustum );
  23925. addLine( "f4", "f3", hexFrustum );
  23926. addLine( "f3", "f1", hexFrustum );
  23927. // sides
  23928. addLine( "n1", "f1", hexFrustum );
  23929. addLine( "n2", "f2", hexFrustum );
  23930. addLine( "n3", "f3", hexFrustum );
  23931. addLine( "n4", "f4", hexFrustum );
  23932. // cone
  23933. addLine( "p", "n1", hexCone );
  23934. addLine( "p", "n2", hexCone );
  23935. addLine( "p", "n3", hexCone );
  23936. addLine( "p", "n4", hexCone );
  23937. // up
  23938. addLine( "u1", "u2", hexUp );
  23939. addLine( "u2", "u3", hexUp );
  23940. addLine( "u3", "u1", hexUp );
  23941. // target
  23942. addLine( "c", "t", hexTarget );
  23943. addLine( "p", "c", hexCross );
  23944. // cross
  23945. addLine( "cn1", "cn2", hexCross );
  23946. addLine( "cn3", "cn4", hexCross );
  23947. addLine( "cf1", "cf2", hexCross );
  23948. addLine( "cf3", "cf4", hexCross );
  23949. function addLine( a, b, hex ) {
  23950. addPoint( a, hex );
  23951. addPoint( b, hex );
  23952. }
  23953. function addPoint( id, hex ) {
  23954. geometry.vertices.push( new Vector3() );
  23955. geometry.colors.push( new Color( hex ) );
  23956. if ( pointMap[ id ] === undefined ) {
  23957. pointMap[ id ] = [];
  23958. }
  23959. pointMap[ id ].push( geometry.vertices.length - 1 );
  23960. }
  23961. LineSegments.call( this, geometry, material );
  23962. this.camera = camera;
  23963. if( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  23964. this.matrix = camera.matrixWorld;
  23965. this.matrixAutoUpdate = false;
  23966. this.pointMap = pointMap;
  23967. this.update();
  23968. }
  23969. CameraHelper.prototype = Object.create( LineSegments.prototype );
  23970. CameraHelper.prototype.constructor = CameraHelper;
  23971. CameraHelper.prototype.update = function () {
  23972. var geometry, pointMap;
  23973. var vector = new Vector3();
  23974. var camera = new Camera();
  23975. function setPoint( point, x, y, z ) {
  23976. vector.set( x, y, z ).unproject( camera );
  23977. var points = pointMap[ point ];
  23978. if ( points !== undefined ) {
  23979. for ( var i = 0, il = points.length; i < il; i ++ ) {
  23980. geometry.vertices[ points[ i ] ].copy( vector );
  23981. }
  23982. }
  23983. }
  23984. return function update() {
  23985. geometry = this.geometry;
  23986. pointMap = this.pointMap;
  23987. var w = 1, h = 1;
  23988. // we need just camera projection matrix
  23989. // world matrix must be identity
  23990. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  23991. // center / target
  23992. setPoint( "c", 0, 0, - 1 );
  23993. setPoint( "t", 0, 0, 1 );
  23994. // near
  23995. setPoint( "n1", - w, - h, - 1 );
  23996. setPoint( "n2", w, - h, - 1 );
  23997. setPoint( "n3", - w, h, - 1 );
  23998. setPoint( "n4", w, h, - 1 );
  23999. // far
  24000. setPoint( "f1", - w, - h, 1 );
  24001. setPoint( "f2", w, - h, 1 );
  24002. setPoint( "f3", - w, h, 1 );
  24003. setPoint( "f4", w, h, 1 );
  24004. // up
  24005. setPoint( "u1", w * 0.7, h * 1.1, - 1 );
  24006. setPoint( "u2", - w * 0.7, h * 1.1, - 1 );
  24007. setPoint( "u3", 0, h * 2, - 1 );
  24008. // cross
  24009. setPoint( "cf1", - w, 0, 1 );
  24010. setPoint( "cf2", w, 0, 1 );
  24011. setPoint( "cf3", 0, - h, 1 );
  24012. setPoint( "cf4", 0, h, 1 );
  24013. setPoint( "cn1", - w, 0, - 1 );
  24014. setPoint( "cn2", w, 0, - 1 );
  24015. setPoint( "cn3", 0, - h, - 1 );
  24016. setPoint( "cn4", 0, h, - 1 );
  24017. geometry.verticesNeedUpdate = true;
  24018. };
  24019. }();
  24020. /**
  24021. * @author WestLangley / http://github.com/WestLangley
  24022. */
  24023. // a helper to show the world-axis-aligned bounding box for an object
  24024. function BoundingBoxHelper( object, hex ) {
  24025. var color = ( hex !== undefined ) ? hex : 0x888888;
  24026. this.object = object;
  24027. this.box = new Box3();
  24028. Mesh.call( this, new BoxGeometry( 1, 1, 1 ), new MeshBasicMaterial( { color: color, wireframe: true } ) );
  24029. }
  24030. BoundingBoxHelper.prototype = Object.create( Mesh.prototype );
  24031. BoundingBoxHelper.prototype.constructor = BoundingBoxHelper;
  24032. BoundingBoxHelper.prototype.update = function () {
  24033. this.box.setFromObject( this.object );
  24034. this.box.size( this.scale );
  24035. this.box.center( this.position );
  24036. };
  24037. /**
  24038. * @author mrdoob / http://mrdoob.com/
  24039. */
  24040. function BoxHelper( object, color ) {
  24041. if ( color === undefined ) color = 0xffff00;
  24042. 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 ] );
  24043. var positions = new Float32Array( 8 * 3 );
  24044. var geometry = new BufferGeometry();
  24045. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  24046. geometry.addAttribute( 'position', new BufferAttribute( positions, 3 ) );
  24047. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  24048. if ( object !== undefined ) {
  24049. this.update( object );
  24050. }
  24051. }
  24052. BoxHelper.prototype = Object.create( LineSegments.prototype );
  24053. BoxHelper.prototype.constructor = BoxHelper;
  24054. BoxHelper.prototype.update = ( function () {
  24055. var box = new Box3();
  24056. return function update( object ) {
  24057. if ( (object && object.isBox3) ) {
  24058. box.copy( object );
  24059. } else {
  24060. box.setFromObject( object );
  24061. }
  24062. if ( box.isEmpty() ) return;
  24063. var min = box.min;
  24064. var max = box.max;
  24065. /*
  24066. 5____4
  24067. 1/___0/|
  24068. | 6__|_7
  24069. 2/___3/
  24070. 0: max.x, max.y, max.z
  24071. 1: min.x, max.y, max.z
  24072. 2: min.x, min.y, max.z
  24073. 3: max.x, min.y, max.z
  24074. 4: max.x, max.y, min.z
  24075. 5: min.x, max.y, min.z
  24076. 6: min.x, min.y, min.z
  24077. 7: max.x, min.y, min.z
  24078. */
  24079. var position = this.geometry.attributes.position;
  24080. var array = position.array;
  24081. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  24082. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  24083. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  24084. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  24085. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  24086. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  24087. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  24088. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  24089. position.needsUpdate = true;
  24090. this.geometry.computeBoundingSphere();
  24091. };
  24092. } )();
  24093. var lineGeometry = new BufferGeometry();
  24094. lineGeometry.addAttribute( 'position', new Float32Attribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  24095. var coneGeometry = new CylinderBufferGeometry( 0, 0.5, 1, 5, 1 );
  24096. coneGeometry.translate( 0, - 0.5, 0 );
  24097. function ArrowHelper( dir, origin, length, color, headLength, headWidth ) {
  24098. // dir is assumed to be normalized
  24099. Object3D.call( this );
  24100. if ( color === undefined ) color = 0xffff00;
  24101. if ( length === undefined ) length = 1;
  24102. if ( headLength === undefined ) headLength = 0.2 * length;
  24103. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  24104. this.position.copy( origin );
  24105. this.line = new Line( lineGeometry, new LineBasicMaterial( { color: color } ) );
  24106. this.line.matrixAutoUpdate = false;
  24107. this.add( this.line );
  24108. this.cone = new Mesh( coneGeometry, new MeshBasicMaterial( { color: color } ) );
  24109. this.cone.matrixAutoUpdate = false;
  24110. this.add( this.cone );
  24111. this.setDirection( dir );
  24112. this.setLength( length, headLength, headWidth );
  24113. }
  24114. ArrowHelper.prototype = Object.create( Object3D.prototype );
  24115. ArrowHelper.prototype.constructor = ArrowHelper;
  24116. ArrowHelper.prototype.setDirection = ( function () {
  24117. var axis = new Vector3();
  24118. var radians;
  24119. return function setDirection( dir ) {
  24120. // dir is assumed to be normalized
  24121. if ( dir.y > 0.99999 ) {
  24122. this.quaternion.set( 0, 0, 0, 1 );
  24123. } else if ( dir.y < - 0.99999 ) {
  24124. this.quaternion.set( 1, 0, 0, 0 );
  24125. } else {
  24126. axis.set( dir.z, 0, - dir.x ).normalize();
  24127. radians = Math.acos( dir.y );
  24128. this.quaternion.setFromAxisAngle( axis, radians );
  24129. }
  24130. };
  24131. }() );
  24132. ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  24133. if ( headLength === undefined ) headLength = 0.2 * length;
  24134. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  24135. this.line.scale.set( 1, Math.max( 0, length - headLength ), 1 );
  24136. this.line.updateMatrix();
  24137. this.cone.scale.set( headWidth, headLength, headWidth );
  24138. this.cone.position.y = length;
  24139. this.cone.updateMatrix();
  24140. };
  24141. ArrowHelper.prototype.setColor = function ( color ) {
  24142. this.line.material.color.copy( color );
  24143. this.cone.material.color.copy( color );
  24144. };
  24145. /**
  24146. * @author sroucheray / http://sroucheray.org/
  24147. * @author mrdoob / http://mrdoob.com/
  24148. */
  24149. function AxisHelper( size ) {
  24150. size = size || 1;
  24151. var vertices = new Float32Array( [
  24152. 0, 0, 0, size, 0, 0,
  24153. 0, 0, 0, 0, size, 0,
  24154. 0, 0, 0, 0, 0, size
  24155. ] );
  24156. var colors = new Float32Array( [
  24157. 1, 0, 0, 1, 0.6, 0,
  24158. 0, 1, 0, 0.6, 1, 0,
  24159. 0, 0, 1, 0, 0.6, 1
  24160. ] );
  24161. var geometry = new BufferGeometry();
  24162. geometry.addAttribute( 'position', new BufferAttribute( vertices, 3 ) );
  24163. geometry.addAttribute( 'color', new BufferAttribute( colors, 3 ) );
  24164. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  24165. LineSegments.call( this, geometry, material );
  24166. }
  24167. AxisHelper.prototype = Object.create( LineSegments.prototype );
  24168. AxisHelper.prototype.constructor = AxisHelper;
  24169. /**
  24170. * @author zz85 https://github.com/zz85
  24171. *
  24172. * Centripetal CatmullRom Curve - which is useful for avoiding
  24173. * cusps and self-intersections in non-uniform catmull rom curves.
  24174. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  24175. *
  24176. * curve.type accepts centripetal(default), chordal and catmullrom
  24177. * curve.tension is used for catmullrom which defaults to 0.5
  24178. */
  24179. exports.CatmullRomCurve3 = ( function() {
  24180. var
  24181. tmp = new Vector3(),
  24182. px = new CubicPoly(),
  24183. py = new CubicPoly(),
  24184. pz = new CubicPoly();
  24185. /*
  24186. Based on an optimized c++ solution in
  24187. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  24188. - http://ideone.com/NoEbVM
  24189. This CubicPoly class could be used for reusing some variables and calculations,
  24190. but for three.js curve use, it could be possible inlined and flatten into a single function call
  24191. which can be placed in CurveUtils.
  24192. */
  24193. function CubicPoly() {
  24194. }
  24195. /*
  24196. * Compute coefficients for a cubic polynomial
  24197. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  24198. * such that
  24199. * p(0) = x0, p(1) = x1
  24200. * and
  24201. * p'(0) = t0, p'(1) = t1.
  24202. */
  24203. CubicPoly.prototype.init = function( x0, x1, t0, t1 ) {
  24204. this.c0 = x0;
  24205. this.c1 = t0;
  24206. this.c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  24207. this.c3 = 2 * x0 - 2 * x1 + t0 + t1;
  24208. };
  24209. CubicPoly.prototype.initNonuniformCatmullRom = function( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  24210. // compute tangents when parameterized in [t1,t2]
  24211. var t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  24212. var t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  24213. // rescale tangents for parametrization in [0,1]
  24214. t1 *= dt1;
  24215. t2 *= dt1;
  24216. // initCubicPoly
  24217. this.init( x1, x2, t1, t2 );
  24218. };
  24219. // standard Catmull-Rom spline: interpolate between x1 and x2 with previous/following points x1/x4
  24220. CubicPoly.prototype.initCatmullRom = function( x0, x1, x2, x3, tension ) {
  24221. this.init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  24222. };
  24223. CubicPoly.prototype.calc = function( t ) {
  24224. var t2 = t * t;
  24225. var t3 = t2 * t;
  24226. return this.c0 + this.c1 * t + this.c2 * t2 + this.c3 * t3;
  24227. };
  24228. // Subclass Three.js curve
  24229. return Curve.create(
  24230. function ( p /* array of Vector3 */ ) {
  24231. this.points = p || [];
  24232. this.closed = false;
  24233. },
  24234. function ( t ) {
  24235. var points = this.points,
  24236. point, intPoint, weight, l;
  24237. l = points.length;
  24238. if ( l < 2 ) console.log( 'duh, you need at least 2 points' );
  24239. point = ( l - ( this.closed ? 0 : 1 ) ) * t;
  24240. intPoint = Math.floor( point );
  24241. weight = point - intPoint;
  24242. if ( this.closed ) {
  24243. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  24244. } else if ( weight === 0 && intPoint === l - 1 ) {
  24245. intPoint = l - 2;
  24246. weight = 1;
  24247. }
  24248. var p0, p1, p2, p3; // 4 points
  24249. if ( this.closed || intPoint > 0 ) {
  24250. p0 = points[ ( intPoint - 1 ) % l ];
  24251. } else {
  24252. // extrapolate first point
  24253. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  24254. p0 = tmp;
  24255. }
  24256. p1 = points[ intPoint % l ];
  24257. p2 = points[ ( intPoint + 1 ) % l ];
  24258. if ( this.closed || intPoint + 2 < l ) {
  24259. p3 = points[ ( intPoint + 2 ) % l ];
  24260. } else {
  24261. // extrapolate last point
  24262. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  24263. p3 = tmp;
  24264. }
  24265. if ( this.type === undefined || this.type === 'centripetal' || this.type === 'chordal' ) {
  24266. // init Centripetal / Chordal Catmull-Rom
  24267. var pow = this.type === 'chordal' ? 0.5 : 0.25;
  24268. var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  24269. var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  24270. var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  24271. // safety check for repeated points
  24272. if ( dt1 < 1e-4 ) dt1 = 1.0;
  24273. if ( dt0 < 1e-4 ) dt0 = dt1;
  24274. if ( dt2 < 1e-4 ) dt2 = dt1;
  24275. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  24276. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  24277. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  24278. } else if ( this.type === 'catmullrom' ) {
  24279. var tension = this.tension !== undefined ? this.tension : 0.5;
  24280. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, tension );
  24281. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, tension );
  24282. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, tension );
  24283. }
  24284. var v = new Vector3(
  24285. px.calc( weight ),
  24286. py.calc( weight ),
  24287. pz.calc( weight )
  24288. );
  24289. return v;
  24290. }
  24291. );
  24292. } )();
  24293. /**************************************************************
  24294. * Closed Spline 3D curve
  24295. **************************************************************/
  24296. function ClosedSplineCurve3( points ) {
  24297. console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Please use THREE.CatmullRomCurve3.' );
  24298. exports.CatmullRomCurve3.call( this, points );
  24299. this.type = 'catmullrom';
  24300. this.closed = true;
  24301. }
  24302. ClosedSplineCurve3.prototype = Object.create( exports.CatmullRomCurve3.prototype );
  24303. /**************************************************************
  24304. * Spline 3D curve
  24305. **************************************************************/
  24306. var SplineCurve3 = Curve.create(
  24307. function ( points /* array of Vector3 */ ) {
  24308. console.warn( 'THREE.SplineCurve3 will be deprecated. Please use THREE.CatmullRomCurve3' );
  24309. this.points = ( points === undefined ) ? [] : points;
  24310. },
  24311. function ( t ) {
  24312. var points = this.points;
  24313. var point = ( points.length - 1 ) * t;
  24314. var intPoint = Math.floor( point );
  24315. var weight = point - intPoint;
  24316. var point0 = points[ intPoint == 0 ? intPoint : intPoint - 1 ];
  24317. var point1 = points[ intPoint ];
  24318. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  24319. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  24320. var interpolate = exports.CurveUtils.interpolate;
  24321. return new Vector3(
  24322. interpolate( point0.x, point1.x, point2.x, point3.x, weight ),
  24323. interpolate( point0.y, point1.y, point2.y, point3.y, weight ),
  24324. interpolate( point0.z, point1.z, point2.z, point3.z, weight )
  24325. );
  24326. }
  24327. );
  24328. /**************************************************************
  24329. * Cubic Bezier 3D curve
  24330. **************************************************************/
  24331. exports.CubicBezierCurve3 = Curve.create(
  24332. function ( v0, v1, v2, v3 ) {
  24333. this.v0 = v0;
  24334. this.v1 = v1;
  24335. this.v2 = v2;
  24336. this.v3 = v3;
  24337. },
  24338. function ( t ) {
  24339. var b3 = exports.ShapeUtils.b3;
  24340. return new Vector3(
  24341. b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ),
  24342. b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ),
  24343. b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z )
  24344. );
  24345. }
  24346. );
  24347. /**************************************************************
  24348. * Quadratic Bezier 3D curve
  24349. **************************************************************/
  24350. exports.QuadraticBezierCurve3 = Curve.create(
  24351. function ( v0, v1, v2 ) {
  24352. this.v0 = v0;
  24353. this.v1 = v1;
  24354. this.v2 = v2;
  24355. },
  24356. function ( t ) {
  24357. var b2 = exports.ShapeUtils.b2;
  24358. return new Vector3(
  24359. b2( t, this.v0.x, this.v1.x, this.v2.x ),
  24360. b2( t, this.v0.y, this.v1.y, this.v2.y ),
  24361. b2( t, this.v0.z, this.v1.z, this.v2.z )
  24362. );
  24363. }
  24364. );
  24365. /**************************************************************
  24366. * Line3D
  24367. **************************************************************/
  24368. exports.LineCurve3 = Curve.create(
  24369. function ( v1, v2 ) {
  24370. this.v1 = v1;
  24371. this.v2 = v2;
  24372. },
  24373. function ( t ) {
  24374. if ( t === 1 ) {
  24375. return this.v2.clone();
  24376. }
  24377. var vector = new Vector3();
  24378. vector.subVectors( this.v2, this.v1 ); // diff
  24379. vector.multiplyScalar( t );
  24380. vector.add( this.v1 );
  24381. return vector;
  24382. }
  24383. );
  24384. /**************************************************************
  24385. * Arc curve
  24386. **************************************************************/
  24387. function ArcCurve( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24388. EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  24389. }
  24390. ArcCurve.prototype = Object.create( EllipseCurve.prototype );
  24391. ArcCurve.prototype.constructor = ArcCurve;
  24392. /**
  24393. * @author alteredq / http://alteredqualia.com/
  24394. */
  24395. exports.SceneUtils = {
  24396. createMultiMaterialObject: function ( geometry, materials ) {
  24397. var group = new Group();
  24398. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  24399. group.add( new Mesh( geometry, materials[ i ] ) );
  24400. }
  24401. return group;
  24402. },
  24403. detach: function ( child, parent, scene ) {
  24404. child.applyMatrix( parent.matrixWorld );
  24405. parent.remove( child );
  24406. scene.add( child );
  24407. },
  24408. attach: function ( child, scene, parent ) {
  24409. var matrixWorldInverse = new Matrix4();
  24410. matrixWorldInverse.getInverse( parent.matrixWorld );
  24411. child.applyMatrix( matrixWorldInverse );
  24412. scene.remove( child );
  24413. parent.add( child );
  24414. }
  24415. };
  24416. function Face4 ( a, b, c, d, normal, color, materialIndex ) {
  24417. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' );
  24418. return new Face3( a, b, c, normal, color, materialIndex );
  24419. }
  24420. var LineStrip = 0;
  24421. var LinePieces = 1;
  24422. function PointCloud ( geometry, material ) {
  24423. console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
  24424. return new Points( geometry, material );
  24425. }
  24426. function ParticleSystem ( geometry, material ) {
  24427. console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
  24428. return new Points( geometry, material );
  24429. }
  24430. function PointCloudMaterial ( parameters ) {
  24431. console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
  24432. return new PointsMaterial( parameters );
  24433. }
  24434. function ParticleBasicMaterial ( parameters ) {
  24435. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
  24436. return new PointsMaterial( parameters );
  24437. }
  24438. function ParticleSystemMaterial ( parameters ) {
  24439. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
  24440. return new PointsMaterial( parameters );
  24441. }
  24442. function Vertex ( x, y, z ) {
  24443. console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' );
  24444. return new Vector3( x, y, z );
  24445. }
  24446. //
  24447. Object.assign( Box2.prototype, {
  24448. empty: function () {
  24449. console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' );
  24450. return this.isEmpty();
  24451. },
  24452. isIntersectionBox: function ( box ) {
  24453. console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
  24454. return this.intersectsBox( box );
  24455. }
  24456. } );
  24457. Object.assign( Box3.prototype, {
  24458. empty: function () {
  24459. console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' );
  24460. return this.isEmpty();
  24461. },
  24462. isIntersectionBox: function ( box ) {
  24463. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  24464. return this.intersectsBox( box );
  24465. },
  24466. isIntersectionSphere: function ( sphere ) {
  24467. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  24468. return this.intersectsSphere( sphere );
  24469. }
  24470. } );
  24471. Object.assign( Matrix3.prototype, {
  24472. multiplyVector3: function ( vector ) {
  24473. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  24474. return vector.applyMatrix3( this );
  24475. },
  24476. multiplyVector3Array: function ( a ) {
  24477. console.warn( 'THREE.Matrix3: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  24478. return this.applyToVector3Array( a );
  24479. }
  24480. } );
  24481. Object.assign( Matrix4.prototype, {
  24482. extractPosition: function ( m ) {
  24483. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  24484. return this.copyPosition( m );
  24485. },
  24486. setRotationFromQuaternion: function ( q ) {
  24487. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  24488. return this.makeRotationFromQuaternion( q );
  24489. },
  24490. multiplyVector3: function ( vector ) {
  24491. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  24492. return vector.applyProjection( this );
  24493. },
  24494. multiplyVector4: function ( vector ) {
  24495. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  24496. return vector.applyMatrix4( this );
  24497. },
  24498. multiplyVector3Array: function ( a ) {
  24499. console.warn( 'THREE.Matrix4: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  24500. return this.applyToVector3Array( a );
  24501. },
  24502. rotateAxis: function ( v ) {
  24503. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  24504. v.transformDirection( this );
  24505. },
  24506. crossVector: function ( vector ) {
  24507. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  24508. return vector.applyMatrix4( this );
  24509. },
  24510. translate: function ( v ) {
  24511. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  24512. },
  24513. rotateX: function ( angle ) {
  24514. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  24515. },
  24516. rotateY: function ( angle ) {
  24517. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  24518. },
  24519. rotateZ: function ( angle ) {
  24520. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  24521. },
  24522. rotateByAxis: function ( axis, angle ) {
  24523. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  24524. }
  24525. } );
  24526. Object.assign( Plane.prototype, {
  24527. isIntersectionLine: function ( line ) {
  24528. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  24529. return this.intersectsLine( line );
  24530. }
  24531. } );
  24532. Object.assign( Quaternion.prototype, {
  24533. multiplyVector3: function ( vector ) {
  24534. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  24535. return vector.applyQuaternion( this );
  24536. }
  24537. } );
  24538. Object.assign( Ray.prototype, {
  24539. isIntersectionBox: function ( box ) {
  24540. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  24541. return this.intersectsBox( box );
  24542. },
  24543. isIntersectionPlane: function ( plane ) {
  24544. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  24545. return this.intersectsPlane( plane );
  24546. },
  24547. isIntersectionSphere: function ( sphere ) {
  24548. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  24549. return this.intersectsSphere( sphere );
  24550. }
  24551. } );
  24552. Object.assign( Vector3.prototype, {
  24553. setEulerFromRotationMatrix: function () {
  24554. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  24555. },
  24556. setEulerFromQuaternion: function () {
  24557. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  24558. },
  24559. getPositionFromMatrix: function ( m ) {
  24560. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  24561. return this.setFromMatrixPosition( m );
  24562. },
  24563. getScaleFromMatrix: function ( m ) {
  24564. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  24565. return this.setFromMatrixScale( m );
  24566. },
  24567. getColumnFromMatrix: function ( index, matrix ) {
  24568. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  24569. return this.setFromMatrixColumn( matrix, index );
  24570. }
  24571. } );
  24572. //
  24573. Object.assign( Object3D.prototype, {
  24574. getChildByName: function ( name ) {
  24575. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  24576. return this.getObjectByName( name );
  24577. },
  24578. renderDepth: function ( value ) {
  24579. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  24580. },
  24581. translate: function ( distance, axis ) {
  24582. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  24583. return this.translateOnAxis( axis, distance );
  24584. }
  24585. } );
  24586. Object.defineProperties( Object3D.prototype, {
  24587. eulerOrder: {
  24588. get: function () {
  24589. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  24590. return this.rotation.order;
  24591. },
  24592. set: function ( value ) {
  24593. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  24594. this.rotation.order = value;
  24595. }
  24596. },
  24597. useQuaternion: {
  24598. get: function () {
  24599. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  24600. },
  24601. set: function ( value ) {
  24602. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  24603. }
  24604. }
  24605. } );
  24606. Object.defineProperties( LOD.prototype, {
  24607. objects: {
  24608. get: function () {
  24609. console.warn( 'THREE.LOD: .objects has been renamed to .levels.' );
  24610. return this.levels;
  24611. }
  24612. }
  24613. } );
  24614. //
  24615. PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) {
  24616. console.warn( "THREE.PerspectiveCamera.setLens is deprecated. " +
  24617. "Use .setFocalLength and .filmGauge for a photographic setup." );
  24618. if ( filmGauge !== undefined ) this.filmGauge = filmGauge;
  24619. this.setFocalLength( focalLength );
  24620. };
  24621. //
  24622. Object.defineProperties( Light.prototype, {
  24623. onlyShadow: {
  24624. set: function ( value ) {
  24625. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  24626. }
  24627. },
  24628. shadowCameraFov: {
  24629. set: function ( value ) {
  24630. console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' );
  24631. this.shadow.camera.fov = value;
  24632. }
  24633. },
  24634. shadowCameraLeft: {
  24635. set: function ( value ) {
  24636. console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' );
  24637. this.shadow.camera.left = value;
  24638. }
  24639. },
  24640. shadowCameraRight: {
  24641. set: function ( value ) {
  24642. console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' );
  24643. this.shadow.camera.right = value;
  24644. }
  24645. },
  24646. shadowCameraTop: {
  24647. set: function ( value ) {
  24648. console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' );
  24649. this.shadow.camera.top = value;
  24650. }
  24651. },
  24652. shadowCameraBottom: {
  24653. set: function ( value ) {
  24654. console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' );
  24655. this.shadow.camera.bottom = value;
  24656. }
  24657. },
  24658. shadowCameraNear: {
  24659. set: function ( value ) {
  24660. console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' );
  24661. this.shadow.camera.near = value;
  24662. }
  24663. },
  24664. shadowCameraFar: {
  24665. set: function ( value ) {
  24666. console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' );
  24667. this.shadow.camera.far = value;
  24668. }
  24669. },
  24670. shadowCameraVisible: {
  24671. set: function ( value ) {
  24672. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );
  24673. }
  24674. },
  24675. shadowBias: {
  24676. set: function ( value ) {
  24677. console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' );
  24678. this.shadow.bias = value;
  24679. }
  24680. },
  24681. shadowDarkness: {
  24682. set: function ( value ) {
  24683. console.warn( 'THREE.Light: .shadowDarkness has been removed.' );
  24684. }
  24685. },
  24686. shadowMapWidth: {
  24687. set: function ( value ) {
  24688. console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' );
  24689. this.shadow.mapSize.width = value;
  24690. }
  24691. },
  24692. shadowMapHeight: {
  24693. set: function ( value ) {
  24694. console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' );
  24695. this.shadow.mapSize.height = value;
  24696. }
  24697. }
  24698. } );
  24699. //
  24700. Object.defineProperties( BufferAttribute.prototype, {
  24701. length: {
  24702. get: function () {
  24703. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Please use .count.' );
  24704. return this.array.length;
  24705. }
  24706. }
  24707. } );
  24708. Object.assign( BufferGeometry.prototype, {
  24709. addIndex: function ( index ) {
  24710. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  24711. this.setIndex( index );
  24712. },
  24713. addDrawCall: function ( start, count, indexOffset ) {
  24714. if ( indexOffset !== undefined ) {
  24715. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  24716. }
  24717. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  24718. this.addGroup( start, count );
  24719. },
  24720. clearDrawCalls: function () {
  24721. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  24722. this.clearGroups();
  24723. },
  24724. computeTangents: function () {
  24725. console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' );
  24726. },
  24727. computeOffsets: function () {
  24728. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );
  24729. }
  24730. } );
  24731. Object.defineProperties( BufferGeometry.prototype, {
  24732. drawcalls: {
  24733. get: function () {
  24734. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  24735. return this.groups;
  24736. }
  24737. },
  24738. offsets: {
  24739. get: function () {
  24740. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  24741. return this.groups;
  24742. }
  24743. }
  24744. } );
  24745. //
  24746. Object.defineProperties( Material.prototype, {
  24747. wrapAround: {
  24748. get: function () {
  24749. console.warn( 'THREE.' + this.type + ': .wrapAround has been removed.' );
  24750. },
  24751. set: function ( value ) {
  24752. console.warn( 'THREE.' + this.type + ': .wrapAround has been removed.' );
  24753. }
  24754. },
  24755. wrapRGB: {
  24756. get: function () {
  24757. console.warn( 'THREE.' + this.type + ': .wrapRGB has been removed.' );
  24758. return new Color();
  24759. }
  24760. }
  24761. } );
  24762. Object.defineProperties( MeshPhongMaterial.prototype, {
  24763. metal: {
  24764. get: function () {
  24765. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' );
  24766. return false;
  24767. },
  24768. set: function ( value ) {
  24769. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' );
  24770. }
  24771. }
  24772. } );
  24773. Object.defineProperties( ShaderMaterial.prototype, {
  24774. derivatives: {
  24775. get: function () {
  24776. console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  24777. return this.extensions.derivatives;
  24778. },
  24779. set: function ( value ) {
  24780. console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  24781. this.extensions.derivatives = value;
  24782. }
  24783. }
  24784. } );
  24785. //
  24786. EventDispatcher.prototype = Object.assign( Object.create( {
  24787. // Note: Extra base ensures these properties are not 'assign'ed.
  24788. constructor: EventDispatcher,
  24789. apply: function ( target ) {
  24790. console.warn( "THREE.EventDispatcher: .apply is deprecated, " +
  24791. "just inherit or Object.assign the prototype to mix-in." );
  24792. Object.assign( target, this );
  24793. }
  24794. } ), EventDispatcher.prototype );
  24795. //
  24796. Object.assign( WebGLRenderer.prototype, {
  24797. supportsFloatTextures: function () {
  24798. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  24799. return this.extensions.get( 'OES_texture_float' );
  24800. },
  24801. supportsHalfFloatTextures: function () {
  24802. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  24803. return this.extensions.get( 'OES_texture_half_float' );
  24804. },
  24805. supportsStandardDerivatives: function () {
  24806. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  24807. return this.extensions.get( 'OES_standard_derivatives' );
  24808. },
  24809. supportsCompressedTextureS3TC: function () {
  24810. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  24811. return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  24812. },
  24813. supportsCompressedTexturePVRTC: function () {
  24814. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  24815. return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  24816. },
  24817. supportsBlendMinMax: function () {
  24818. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  24819. return this.extensions.get( 'EXT_blend_minmax' );
  24820. },
  24821. supportsVertexTextures: function () {
  24822. return this.capabilities.vertexTextures;
  24823. },
  24824. supportsInstancedArrays: function () {
  24825. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  24826. return this.extensions.get( 'ANGLE_instanced_arrays' );
  24827. },
  24828. enableScissorTest: function ( boolean ) {
  24829. console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' );
  24830. this.setScissorTest( boolean );
  24831. },
  24832. initMaterial: function () {
  24833. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  24834. },
  24835. addPrePlugin: function () {
  24836. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  24837. },
  24838. addPostPlugin: function () {
  24839. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  24840. },
  24841. updateShadowMap: function () {
  24842. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  24843. }
  24844. } );
  24845. Object.defineProperties( WebGLRenderer.prototype, {
  24846. shadowMapEnabled: {
  24847. get: function () {
  24848. return this.shadowMap.enabled;
  24849. },
  24850. set: function ( value ) {
  24851. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  24852. this.shadowMap.enabled = value;
  24853. }
  24854. },
  24855. shadowMapType: {
  24856. get: function () {
  24857. return this.shadowMap.type;
  24858. },
  24859. set: function ( value ) {
  24860. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  24861. this.shadowMap.type = value;
  24862. }
  24863. },
  24864. shadowMapCullFace: {
  24865. get: function () {
  24866. return this.shadowMap.cullFace;
  24867. },
  24868. set: function ( value ) {
  24869. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace is now .shadowMap.cullFace.' );
  24870. this.shadowMap.cullFace = value;
  24871. }
  24872. }
  24873. } );
  24874. Object.defineProperties( WebGLShadowMap.prototype, {
  24875. cullFace: {
  24876. get: function () {
  24877. return this.renderReverseSided ? CullFaceFront : CullFaceBack;
  24878. },
  24879. set: function ( cullFace ) {
  24880. var value = ( cullFace !== CullFaceBack );
  24881. console.warn( "WebGLRenderer: .shadowMap.cullFace is deprecated. Set .shadowMap.renderReverseSided to " + value + "." );
  24882. this.renderReverseSided = value;
  24883. }
  24884. }
  24885. } );
  24886. //
  24887. Object.defineProperties( WebGLRenderTarget.prototype, {
  24888. wrapS: {
  24889. get: function () {
  24890. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  24891. return this.texture.wrapS;
  24892. },
  24893. set: function ( value ) {
  24894. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  24895. this.texture.wrapS = value;
  24896. }
  24897. },
  24898. wrapT: {
  24899. get: function () {
  24900. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  24901. return this.texture.wrapT;
  24902. },
  24903. set: function ( value ) {
  24904. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  24905. this.texture.wrapT = value;
  24906. }
  24907. },
  24908. magFilter: {
  24909. get: function () {
  24910. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  24911. return this.texture.magFilter;
  24912. },
  24913. set: function ( value ) {
  24914. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  24915. this.texture.magFilter = value;
  24916. }
  24917. },
  24918. minFilter: {
  24919. get: function () {
  24920. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  24921. return this.texture.minFilter;
  24922. },
  24923. set: function ( value ) {
  24924. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  24925. this.texture.minFilter = value;
  24926. }
  24927. },
  24928. anisotropy: {
  24929. get: function () {
  24930. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  24931. return this.texture.anisotropy;
  24932. },
  24933. set: function ( value ) {
  24934. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  24935. this.texture.anisotropy = value;
  24936. }
  24937. },
  24938. offset: {
  24939. get: function () {
  24940. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  24941. return this.texture.offset;
  24942. },
  24943. set: function ( value ) {
  24944. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  24945. this.texture.offset = value;
  24946. }
  24947. },
  24948. repeat: {
  24949. get: function () {
  24950. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  24951. return this.texture.repeat;
  24952. },
  24953. set: function ( value ) {
  24954. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  24955. this.texture.repeat = value;
  24956. }
  24957. },
  24958. format: {
  24959. get: function () {
  24960. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  24961. return this.texture.format;
  24962. },
  24963. set: function ( value ) {
  24964. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  24965. this.texture.format = value;
  24966. }
  24967. },
  24968. type: {
  24969. get: function () {
  24970. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  24971. return this.texture.type;
  24972. },
  24973. set: function ( value ) {
  24974. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  24975. this.texture.type = value;
  24976. }
  24977. },
  24978. generateMipmaps: {
  24979. get: function () {
  24980. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  24981. return this.texture.generateMipmaps;
  24982. },
  24983. set: function ( value ) {
  24984. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  24985. this.texture.generateMipmaps = value;
  24986. }
  24987. }
  24988. } );
  24989. //
  24990. Object.assign( Audio.prototype, {
  24991. load: function ( file ) {
  24992. console.warn( 'THREE.Audio: .load has been deprecated. Please use THREE.AudioLoader.' );
  24993. var scope = this;
  24994. var audioLoader = new AudioLoader();
  24995. audioLoader.load( file, function ( buffer ) {
  24996. scope.setBuffer( buffer );
  24997. } );
  24998. return this;
  24999. }
  25000. } );
  25001. Object.assign( AudioAnalyser.prototype, {
  25002. getData: function ( file ) {
  25003. console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' );
  25004. return this.getFrequencyData();
  25005. }
  25006. } );
  25007. //
  25008. var GeometryUtils = {
  25009. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  25010. console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  25011. var matrix;
  25012. if ( geometry2.isMesh ) {
  25013. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  25014. matrix = geometry2.matrix;
  25015. geometry2 = geometry2.geometry;
  25016. }
  25017. geometry1.merge( geometry2, matrix, materialIndexOffset );
  25018. },
  25019. center: function ( geometry ) {
  25020. console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
  25021. return geometry.center();
  25022. }
  25023. };
  25024. var ImageUtils = {
  25025. crossOrigin: undefined,
  25026. loadTexture: function ( url, mapping, onLoad, onError ) {
  25027. console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
  25028. var loader = new TextureLoader();
  25029. loader.setCrossOrigin( this.crossOrigin );
  25030. var texture = loader.load( url, onLoad, undefined, onError );
  25031. if ( mapping ) texture.mapping = mapping;
  25032. return texture;
  25033. },
  25034. loadTextureCube: function ( urls, mapping, onLoad, onError ) {
  25035. console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
  25036. var loader = new CubeTextureLoader();
  25037. loader.setCrossOrigin( this.crossOrigin );
  25038. var texture = loader.load( urls, onLoad, undefined, onError );
  25039. if ( mapping ) texture.mapping = mapping;
  25040. return texture;
  25041. },
  25042. loadCompressedTexture: function () {
  25043. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' );
  25044. },
  25045. loadCompressedTextureCube: function () {
  25046. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' );
  25047. }
  25048. };
  25049. //
  25050. function Projector () {
  25051. console.error( 'THREE.Projector has been moved to /examples/js/renderers/Projector.js.' );
  25052. this.projectVector = function ( vector, camera ) {
  25053. console.warn( 'THREE.Projector: .projectVector() is now vector.project().' );
  25054. vector.project( camera );
  25055. };
  25056. this.unprojectVector = function ( vector, camera ) {
  25057. console.warn( 'THREE.Projector: .unprojectVector() is now vector.unproject().' );
  25058. vector.unproject( camera );
  25059. };
  25060. this.pickingRay = function ( vector, camera ) {
  25061. console.error( 'THREE.Projector: .pickingRay() is now raycaster.setFromCamera().' );
  25062. };
  25063. }
  25064. //
  25065. function CanvasRenderer () {
  25066. console.error( 'THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js' );
  25067. this.domElement = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  25068. this.clear = function () {};
  25069. this.render = function () {};
  25070. this.setClearColor = function () {};
  25071. this.setSize = function () {};
  25072. }
  25073. Object.defineProperty( exports, 'AudioContext', {
  25074. get: function () {
  25075. return exports.getAudioContext();
  25076. }
  25077. });
  25078. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  25079. exports.WebGLRenderTarget = WebGLRenderTarget;
  25080. exports.WebGLRenderer = WebGLRenderer;
  25081. exports.ShaderLib = ShaderLib;
  25082. exports.UniformsLib = UniformsLib;
  25083. exports.ShaderChunk = ShaderChunk;
  25084. exports.FogExp2 = FogExp2;
  25085. exports.Fog = Fog;
  25086. exports.Scene = Scene;
  25087. exports.LensFlare = LensFlare;
  25088. exports.Sprite = Sprite;
  25089. exports.LOD = LOD;
  25090. exports.SkinnedMesh = SkinnedMesh;
  25091. exports.Skeleton = Skeleton;
  25092. exports.Bone = Bone;
  25093. exports.Mesh = Mesh;
  25094. exports.LineSegments = LineSegments;
  25095. exports.Line = Line;
  25096. exports.Points = Points;
  25097. exports.Group = Group;
  25098. exports.VideoTexture = VideoTexture;
  25099. exports.DataTexture = DataTexture;
  25100. exports.CompressedTexture = CompressedTexture;
  25101. exports.CubeTexture = CubeTexture;
  25102. exports.CanvasTexture = CanvasTexture;
  25103. exports.DepthTexture = DepthTexture;
  25104. exports.TextureIdCount = TextureIdCount;
  25105. exports.Texture = Texture;
  25106. exports.MaterialIdCount = MaterialIdCount;
  25107. exports.CompressedTextureLoader = CompressedTextureLoader;
  25108. exports.BinaryTextureLoader = BinaryTextureLoader;
  25109. exports.DataTextureLoader = DataTextureLoader;
  25110. exports.CubeTextureLoader = CubeTextureLoader;
  25111. exports.TextureLoader = TextureLoader;
  25112. exports.ObjectLoader = ObjectLoader;
  25113. exports.MaterialLoader = MaterialLoader;
  25114. exports.BufferGeometryLoader = BufferGeometryLoader;
  25115. exports.LoadingManager = LoadingManager;
  25116. exports.JSONLoader = JSONLoader;
  25117. exports.ImageLoader = ImageLoader;
  25118. exports.FontLoader = FontLoader;
  25119. exports.XHRLoader = XHRLoader;
  25120. exports.Loader = Loader;
  25121. exports.AudioLoader = AudioLoader;
  25122. exports.SpotLightShadow = SpotLightShadow;
  25123. exports.SpotLight = SpotLight;
  25124. exports.PointLight = PointLight;
  25125. exports.HemisphereLight = HemisphereLight;
  25126. exports.DirectionalLightShadow = DirectionalLightShadow;
  25127. exports.DirectionalLight = DirectionalLight;
  25128. exports.AmbientLight = AmbientLight;
  25129. exports.LightShadow = LightShadow;
  25130. exports.Light = Light;
  25131. exports.StereoCamera = StereoCamera;
  25132. exports.PerspectiveCamera = PerspectiveCamera;
  25133. exports.OrthographicCamera = OrthographicCamera;
  25134. exports.CubeCamera = CubeCamera;
  25135. exports.Camera = Camera;
  25136. exports.AudioListener = AudioListener;
  25137. exports.PositionalAudio = PositionalAudio;
  25138. exports.getAudioContext = getAudioContext;
  25139. exports.AudioAnalyser = AudioAnalyser;
  25140. exports.Audio = Audio;
  25141. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  25142. exports.StringKeyframeTrack = StringKeyframeTrack;
  25143. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  25144. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  25145. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  25146. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  25147. exports.PropertyMixer = PropertyMixer;
  25148. exports.PropertyBinding = PropertyBinding;
  25149. exports.KeyframeTrack = KeyframeTrack;
  25150. exports.AnimationObjectGroup = AnimationObjectGroup;
  25151. exports.AnimationMixer = AnimationMixer;
  25152. exports.AnimationClip = AnimationClip;
  25153. exports.Uniform = Uniform;
  25154. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  25155. exports.BufferGeometry = BufferGeometry;
  25156. exports.DirectGeometry = DirectGeometry;
  25157. exports.GeometryIdCount = GeometryIdCount;
  25158. exports.Geometry = Geometry;
  25159. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  25160. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  25161. exports.InterleavedBuffer = InterleavedBuffer;
  25162. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  25163. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  25164. exports.Float64Attribute = Float64Attribute;
  25165. exports.Float32Attribute = Float32Attribute;
  25166. exports.Uint32Attribute = Uint32Attribute;
  25167. exports.Int32Attribute = Int32Attribute;
  25168. exports.Uint16Attribute = Uint16Attribute;
  25169. exports.Int16Attribute = Int16Attribute;
  25170. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  25171. exports.Uint8Attribute = Uint8Attribute;
  25172. exports.Int8Attribute = Int8Attribute;
  25173. exports.BufferAttribute = BufferAttribute;
  25174. exports.Face3 = Face3;
  25175. exports.Object3DIdCount = Object3DIdCount;
  25176. exports.Object3D = Object3D;
  25177. exports.Raycaster = Raycaster;
  25178. exports.Layers = Layers;
  25179. exports.EventDispatcher = EventDispatcher;
  25180. exports.Clock = Clock;
  25181. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  25182. exports.LinearInterpolant = LinearInterpolant;
  25183. exports.DiscreteInterpolant = DiscreteInterpolant;
  25184. exports.CubicInterpolant = CubicInterpolant;
  25185. exports.Interpolant = Interpolant;
  25186. exports.Triangle = Triangle;
  25187. exports.Spline = Spline;
  25188. exports.Spherical = Spherical;
  25189. exports.Plane = Plane;
  25190. exports.Frustum = Frustum;
  25191. exports.Sphere = Sphere;
  25192. exports.Ray = Ray;
  25193. exports.Matrix4 = Matrix4;
  25194. exports.Matrix3 = Matrix3;
  25195. exports.Box3 = Box3;
  25196. exports.Box2 = Box2;
  25197. exports.Line3 = Line3;
  25198. exports.Euler = Euler;
  25199. exports.Vector4 = Vector4;
  25200. exports.Vector3 = Vector3;
  25201. exports.Vector2 = Vector2;
  25202. exports.Quaternion = Quaternion;
  25203. exports.Color = Color;
  25204. exports.MorphBlendMesh = MorphBlendMesh;
  25205. exports.ImmediateRenderObject = ImmediateRenderObject;
  25206. exports.WireframeHelper = WireframeHelper;
  25207. exports.VertexNormalsHelper = VertexNormalsHelper;
  25208. exports.SpotLightHelper = SpotLightHelper;
  25209. exports.SkeletonHelper = SkeletonHelper;
  25210. exports.PointLightHelper = PointLightHelper;
  25211. exports.HemisphereLightHelper = HemisphereLightHelper;
  25212. exports.GridHelper = GridHelper;
  25213. exports.FaceNormalsHelper = FaceNormalsHelper;
  25214. exports.EdgesHelper = EdgesHelper;
  25215. exports.DirectionalLightHelper = DirectionalLightHelper;
  25216. exports.CameraHelper = CameraHelper;
  25217. exports.BoundingBoxHelper = BoundingBoxHelper;
  25218. exports.BoxHelper = BoxHelper;
  25219. exports.ArrowHelper = ArrowHelper;
  25220. exports.AxisHelper = AxisHelper;
  25221. exports.ClosedSplineCurve3 = ClosedSplineCurve3;
  25222. exports.SplineCurve3 = SplineCurve3;
  25223. exports.ArcCurve = ArcCurve;
  25224. exports.EllipseCurve = EllipseCurve;
  25225. exports.SplineCurve = SplineCurve;
  25226. exports.CubicBezierCurve = CubicBezierCurve;
  25227. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  25228. exports.LineCurve = LineCurve;
  25229. exports.Shape = Shape;
  25230. exports.ShapePath = ShapePath;
  25231. exports.Path = Path;
  25232. exports.Font = Font;
  25233. exports.CurvePath = CurvePath;
  25234. exports.Curve = Curve;
  25235. exports.ShadowMaterial = ShadowMaterial;
  25236. exports.SpriteMaterial = SpriteMaterial;
  25237. exports.RawShaderMaterial = RawShaderMaterial;
  25238. exports.ShaderMaterial = ShaderMaterial;
  25239. exports.PointsMaterial = PointsMaterial;
  25240. exports.MultiMaterial = MultiMaterial;
  25241. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  25242. exports.MeshStandardMaterial = MeshStandardMaterial;
  25243. exports.MeshPhongMaterial = MeshPhongMaterial;
  25244. exports.MeshNormalMaterial = MeshNormalMaterial;
  25245. exports.MeshLambertMaterial = MeshLambertMaterial;
  25246. exports.MeshDepthMaterial = MeshDepthMaterial;
  25247. exports.MeshBasicMaterial = MeshBasicMaterial;
  25248. exports.LineDashedMaterial = LineDashedMaterial;
  25249. exports.LineBasicMaterial = LineBasicMaterial;
  25250. exports.Material = Material;
  25251. exports.WireframeGeometry = WireframeGeometry;
  25252. exports.ParametricGeometry = ParametricGeometry;
  25253. exports.TetrahedronGeometry = TetrahedronGeometry;
  25254. exports.OctahedronGeometry = OctahedronGeometry;
  25255. exports.IcosahedronGeometry = IcosahedronGeometry;
  25256. exports.DodecahedronGeometry = DodecahedronGeometry;
  25257. exports.PolyhedronGeometry = PolyhedronGeometry;
  25258. exports.TubeGeometry = TubeGeometry;
  25259. exports.TorusKnotGeometry = TorusKnotGeometry;
  25260. exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry;
  25261. exports.TorusGeometry = TorusGeometry;
  25262. exports.TorusBufferGeometry = TorusBufferGeometry;
  25263. exports.TextGeometry = TextGeometry;
  25264. exports.SphereBufferGeometry = SphereBufferGeometry;
  25265. exports.SphereGeometry = SphereGeometry;
  25266. exports.RingGeometry = RingGeometry;
  25267. exports.RingBufferGeometry = RingBufferGeometry;
  25268. exports.PlaneBufferGeometry = PlaneBufferGeometry;
  25269. exports.PlaneGeometry = PlaneGeometry;
  25270. exports.LatheGeometry = LatheGeometry;
  25271. exports.LatheBufferGeometry = LatheBufferGeometry;
  25272. exports.ShapeGeometry = ShapeGeometry;
  25273. exports.ExtrudeGeometry = ExtrudeGeometry;
  25274. exports.EdgesGeometry = EdgesGeometry;
  25275. exports.ConeGeometry = ConeGeometry;
  25276. exports.ConeBufferGeometry = ConeBufferGeometry;
  25277. exports.CylinderGeometry = CylinderGeometry;
  25278. exports.CylinderBufferGeometry = CylinderBufferGeometry;
  25279. exports.CircleBufferGeometry = CircleBufferGeometry;
  25280. exports.CircleGeometry = CircleGeometry;
  25281. exports.BoxBufferGeometry = BoxBufferGeometry;
  25282. exports.BoxGeometry = BoxGeometry;
  25283. exports.REVISION = REVISION;
  25284. exports.MOUSE = MOUSE;
  25285. exports.CullFaceNone = CullFaceNone;
  25286. exports.CullFaceBack = CullFaceBack;
  25287. exports.CullFaceFront = CullFaceFront;
  25288. exports.CullFaceFrontBack = CullFaceFrontBack;
  25289. exports.FrontFaceDirectionCW = FrontFaceDirectionCW;
  25290. exports.FrontFaceDirectionCCW = FrontFaceDirectionCCW;
  25291. exports.BasicShadowMap = BasicShadowMap;
  25292. exports.PCFShadowMap = PCFShadowMap;
  25293. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  25294. exports.FrontSide = FrontSide;
  25295. exports.BackSide = BackSide;
  25296. exports.DoubleSide = DoubleSide;
  25297. exports.FlatShading = FlatShading;
  25298. exports.SmoothShading = SmoothShading;
  25299. exports.NoColors = NoColors;
  25300. exports.FaceColors = FaceColors;
  25301. exports.VertexColors = VertexColors;
  25302. exports.NoBlending = NoBlending;
  25303. exports.NormalBlending = NormalBlending;
  25304. exports.AdditiveBlending = AdditiveBlending;
  25305. exports.SubtractiveBlending = SubtractiveBlending;
  25306. exports.MultiplyBlending = MultiplyBlending;
  25307. exports.CustomBlending = CustomBlending;
  25308. exports.BlendingMode = BlendingMode;
  25309. exports.AddEquation = AddEquation;
  25310. exports.SubtractEquation = SubtractEquation;
  25311. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  25312. exports.MinEquation = MinEquation;
  25313. exports.MaxEquation = MaxEquation;
  25314. exports.ZeroFactor = ZeroFactor;
  25315. exports.OneFactor = OneFactor;
  25316. exports.SrcColorFactor = SrcColorFactor;
  25317. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  25318. exports.SrcAlphaFactor = SrcAlphaFactor;
  25319. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  25320. exports.DstAlphaFactor = DstAlphaFactor;
  25321. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  25322. exports.DstColorFactor = DstColorFactor;
  25323. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  25324. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  25325. exports.NeverDepth = NeverDepth;
  25326. exports.AlwaysDepth = AlwaysDepth;
  25327. exports.LessDepth = LessDepth;
  25328. exports.LessEqualDepth = LessEqualDepth;
  25329. exports.EqualDepth = EqualDepth;
  25330. exports.GreaterEqualDepth = GreaterEqualDepth;
  25331. exports.GreaterDepth = GreaterDepth;
  25332. exports.NotEqualDepth = NotEqualDepth;
  25333. exports.MultiplyOperation = MultiplyOperation;
  25334. exports.MixOperation = MixOperation;
  25335. exports.AddOperation = AddOperation;
  25336. exports.NoToneMapping = NoToneMapping;
  25337. exports.LinearToneMapping = LinearToneMapping;
  25338. exports.ReinhardToneMapping = ReinhardToneMapping;
  25339. exports.Uncharted2ToneMapping = Uncharted2ToneMapping;
  25340. exports.CineonToneMapping = CineonToneMapping;
  25341. exports.UVMapping = UVMapping;
  25342. exports.CubeReflectionMapping = CubeReflectionMapping;
  25343. exports.CubeRefractionMapping = CubeRefractionMapping;
  25344. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  25345. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  25346. exports.SphericalReflectionMapping = SphericalReflectionMapping;
  25347. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  25348. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  25349. exports.TextureMapping = TextureMapping;
  25350. exports.RepeatWrapping = RepeatWrapping;
  25351. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  25352. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  25353. exports.TextureWrapping = TextureWrapping;
  25354. exports.NearestFilter = NearestFilter;
  25355. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  25356. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  25357. exports.LinearFilter = LinearFilter;
  25358. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  25359. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  25360. exports.TextureFilter = TextureFilter;
  25361. exports.UnsignedByteType = UnsignedByteType;
  25362. exports.ByteType = ByteType;
  25363. exports.ShortType = ShortType;
  25364. exports.UnsignedShortType = UnsignedShortType;
  25365. exports.IntType = IntType;
  25366. exports.UnsignedIntType = UnsignedIntType;
  25367. exports.FloatType = FloatType;
  25368. exports.HalfFloatType = HalfFloatType;
  25369. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  25370. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  25371. exports.UnsignedShort565Type = UnsignedShort565Type;
  25372. exports.UnsignedInt248Type = UnsignedInt248Type;
  25373. exports.AlphaFormat = AlphaFormat;
  25374. exports.RGBFormat = RGBFormat;
  25375. exports.RGBAFormat = RGBAFormat;
  25376. exports.LuminanceFormat = LuminanceFormat;
  25377. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  25378. exports.RGBEFormat = RGBEFormat;
  25379. exports.DepthFormat = DepthFormat;
  25380. exports.DepthStencilFormat = DepthStencilFormat;
  25381. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  25382. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  25383. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  25384. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  25385. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  25386. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  25387. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  25388. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  25389. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  25390. exports.LoopOnce = LoopOnce;
  25391. exports.LoopRepeat = LoopRepeat;
  25392. exports.LoopPingPong = LoopPingPong;
  25393. exports.InterpolateDiscrete = InterpolateDiscrete;
  25394. exports.InterpolateLinear = InterpolateLinear;
  25395. exports.InterpolateSmooth = InterpolateSmooth;
  25396. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  25397. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  25398. exports.WrapAroundEnding = WrapAroundEnding;
  25399. exports.TrianglesDrawMode = TrianglesDrawMode;
  25400. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  25401. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  25402. exports.LinearEncoding = LinearEncoding;
  25403. exports.sRGBEncoding = sRGBEncoding;
  25404. exports.GammaEncoding = GammaEncoding;
  25405. exports.RGBEEncoding = RGBEEncoding;
  25406. exports.LogLuvEncoding = LogLuvEncoding;
  25407. exports.RGBM7Encoding = RGBM7Encoding;
  25408. exports.RGBM16Encoding = RGBM16Encoding;
  25409. exports.RGBDEncoding = RGBDEncoding;
  25410. exports.BasicDepthPacking = BasicDepthPacking;
  25411. exports.RGBADepthPacking = RGBADepthPacking;
  25412. exports.CubeGeometry = BoxGeometry;
  25413. exports.Face4 = Face4;
  25414. exports.LineStrip = LineStrip;
  25415. exports.LinePieces = LinePieces;
  25416. exports.MeshFaceMaterial = MultiMaterial;
  25417. exports.PointCloud = PointCloud;
  25418. exports.Particle = Sprite;
  25419. exports.ParticleSystem = ParticleSystem;
  25420. exports.PointCloudMaterial = PointCloudMaterial;
  25421. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  25422. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  25423. exports.Vertex = Vertex;
  25424. exports.GeometryUtils = GeometryUtils;
  25425. exports.ImageUtils = ImageUtils;
  25426. exports.Projector = Projector;
  25427. exports.CanvasRenderer = CanvasRenderer;
  25428. Object.defineProperty(exports, '__esModule', { value: true });
  25429. })));