three.js 774 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842
  1. // File:src/Three.js
  2. /**
  3. * @author mrdoob / http://mrdoob.com/
  4. */
  5. var THREE = { REVISION: '72dev' };
  6. // browserify support
  7. if ( typeof module === 'object' ) {
  8. module.exports = THREE;
  9. }
  10. // polyfills
  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. // https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent.button
  18. THREE.MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2 };
  19. // GL STATE CONSTANTS
  20. THREE.CullFaceNone = 0;
  21. THREE.CullFaceBack = 1;
  22. THREE.CullFaceFront = 2;
  23. THREE.CullFaceFrontBack = 3;
  24. THREE.FrontFaceDirectionCW = 0;
  25. THREE.FrontFaceDirectionCCW = 1;
  26. // SHADOWING TYPES
  27. THREE.BasicShadowMap = 0;
  28. THREE.PCFShadowMap = 1;
  29. THREE.PCFSoftShadowMap = 2;
  30. // MATERIAL CONSTANTS
  31. // side
  32. THREE.FrontSide = 0;
  33. THREE.BackSide = 1;
  34. THREE.DoubleSide = 2;
  35. // shading
  36. THREE.NoShading = 0;
  37. THREE.FlatShading = 1;
  38. THREE.SmoothShading = 2;
  39. // colors
  40. THREE.NoColors = 0;
  41. THREE.FaceColors = 1;
  42. THREE.VertexColors = 2;
  43. // blending modes
  44. THREE.NoBlending = 0;
  45. THREE.NormalBlending = 1;
  46. THREE.AdditiveBlending = 2;
  47. THREE.SubtractiveBlending = 3;
  48. THREE.MultiplyBlending = 4;
  49. THREE.CustomBlending = 5;
  50. // custom blending equations
  51. // (numbers start from 100 not to clash with other
  52. // mappings to OpenGL constants defined in Texture.js)
  53. THREE.AddEquation = 100;
  54. THREE.SubtractEquation = 101;
  55. THREE.ReverseSubtractEquation = 102;
  56. THREE.MinEquation = 103;
  57. THREE.MaxEquation = 104;
  58. // custom blending destination factors
  59. THREE.ZeroFactor = 200;
  60. THREE.OneFactor = 201;
  61. THREE.SrcColorFactor = 202;
  62. THREE.OneMinusSrcColorFactor = 203;
  63. THREE.SrcAlphaFactor = 204;
  64. THREE.OneMinusSrcAlphaFactor = 205;
  65. THREE.DstAlphaFactor = 206;
  66. THREE.OneMinusDstAlphaFactor = 207;
  67. // custom blending source factors
  68. //THREE.ZeroFactor = 200;
  69. //THREE.OneFactor = 201;
  70. //THREE.SrcAlphaFactor = 204;
  71. //THREE.OneMinusSrcAlphaFactor = 205;
  72. //THREE.DstAlphaFactor = 206;
  73. //THREE.OneMinusDstAlphaFactor = 207;
  74. THREE.DstColorFactor = 208;
  75. THREE.OneMinusDstColorFactor = 209;
  76. THREE.SrcAlphaSaturateFactor = 210;
  77. // depth modes
  78. THREE.NeverDepth = 0;
  79. THREE.AlwaysDepth = 1;
  80. THREE.LessDepth = 2;
  81. THREE.LessEqualDepth = 3;
  82. THREE.EqualDepth = 4;
  83. THREE.GreaterEqualDepth = 5;
  84. THREE.GreaterDepth = 6;
  85. THREE.NotEqualDepth = 7;
  86. // TEXTURE CONSTANTS
  87. THREE.MultiplyOperation = 0;
  88. THREE.MixOperation = 1;
  89. THREE.AddOperation = 2;
  90. // Mapping modes
  91. THREE.UVMapping = 300;
  92. THREE.CubeReflectionMapping = 301;
  93. THREE.CubeRefractionMapping = 302;
  94. THREE.EquirectangularReflectionMapping = 303;
  95. THREE.EquirectangularRefractionMapping = 304;
  96. THREE.SphericalReflectionMapping = 305;
  97. // Wrapping modes
  98. THREE.RepeatWrapping = 1000;
  99. THREE.ClampToEdgeWrapping = 1001;
  100. THREE.MirroredRepeatWrapping = 1002;
  101. // Filters
  102. THREE.NearestFilter = 1003;
  103. THREE.NearestMipMapNearestFilter = 1004;
  104. THREE.NearestMipMapLinearFilter = 1005;
  105. THREE.LinearFilter = 1006;
  106. THREE.LinearMipMapNearestFilter = 1007;
  107. THREE.LinearMipMapLinearFilter = 1008;
  108. // Data types
  109. THREE.UnsignedByteType = 1009;
  110. THREE.ByteType = 1010;
  111. THREE.ShortType = 1011;
  112. THREE.UnsignedShortType = 1012;
  113. THREE.IntType = 1013;
  114. THREE.UnsignedIntType = 1014;
  115. THREE.FloatType = 1015;
  116. THREE.HalfFloatType = 1025;
  117. // Pixel types
  118. //THREE.UnsignedByteType = 1009;
  119. THREE.UnsignedShort4444Type = 1016;
  120. THREE.UnsignedShort5551Type = 1017;
  121. THREE.UnsignedShort565Type = 1018;
  122. // Pixel formats
  123. THREE.AlphaFormat = 1019;
  124. THREE.RGBFormat = 1020;
  125. THREE.RGBAFormat = 1021;
  126. THREE.LuminanceFormat = 1022;
  127. THREE.LuminanceAlphaFormat = 1023;
  128. // THREE.RGBEFormat handled as THREE.RGBAFormat in shaders
  129. THREE.RGBEFormat = THREE.RGBAFormat; //1024;
  130. // DDS / ST3C Compressed texture formats
  131. THREE.RGB_S3TC_DXT1_Format = 2001;
  132. THREE.RGBA_S3TC_DXT1_Format = 2002;
  133. THREE.RGBA_S3TC_DXT3_Format = 2003;
  134. THREE.RGBA_S3TC_DXT5_Format = 2004;
  135. // PVRTC compressed texture formats
  136. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  137. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  138. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  139. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  140. // DEPRECATED
  141. THREE.Projector = function () {
  142. console.error( 'THREE.Projector has been moved to /examples/js/renderers/Projector.js.' );
  143. this.projectVector = function ( vector, camera ) {
  144. console.warn( 'THREE.Projector: .projectVector() is now vector.project().' );
  145. vector.project( camera );
  146. };
  147. this.unprojectVector = function ( vector, camera ) {
  148. console.warn( 'THREE.Projector: .unprojectVector() is now vector.unproject().' );
  149. vector.unproject( camera );
  150. };
  151. this.pickingRay = function ( vector, camera ) {
  152. console.error( 'THREE.Projector: .pickingRay() is now raycaster.setFromCamera().' );
  153. };
  154. };
  155. THREE.CanvasRenderer = function () {
  156. console.error( 'THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js' );
  157. this.domElement = document.createElement( 'canvas' );
  158. this.clear = function () {};
  159. this.render = function () {};
  160. this.setClearColor = function () {};
  161. this.setSize = function () {};
  162. };
  163. // File:src/math/Color.js
  164. /**
  165. * @author mrdoob / http://mrdoob.com/
  166. */
  167. THREE.Color = function ( color ) {
  168. if ( arguments.length === 3 ) {
  169. return this.setRGB( arguments[ 0 ], arguments[ 1 ], arguments[ 2 ] );
  170. }
  171. return this.set( color )
  172. };
  173. THREE.Color.prototype = {
  174. constructor: THREE.Color,
  175. r: 1, g: 1, b: 1,
  176. set: function ( value ) {
  177. if ( value instanceof THREE.Color ) {
  178. this.copy( value );
  179. } else if ( typeof value === 'number' ) {
  180. this.setHex( value );
  181. } else if ( typeof value === 'string' ) {
  182. this.setStyle( value );
  183. }
  184. return this;
  185. },
  186. setHex: function ( hex ) {
  187. hex = Math.floor( hex );
  188. this.r = ( hex >> 16 & 255 ) / 255;
  189. this.g = ( hex >> 8 & 255 ) / 255;
  190. this.b = ( hex & 255 ) / 255;
  191. return this;
  192. },
  193. setRGB: function ( r, g, b ) {
  194. this.r = r;
  195. this.g = g;
  196. this.b = b;
  197. return this;
  198. },
  199. setHSL: function ( h, s, l ) {
  200. // h,s,l ranges are in 0.0 - 1.0
  201. if ( s === 0 ) {
  202. this.r = this.g = this.b = l;
  203. } else {
  204. var hue2rgb = function ( p, q, t ) {
  205. if ( t < 0 ) t += 1;
  206. if ( t > 1 ) t -= 1;
  207. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  208. if ( t < 1 / 2 ) return q;
  209. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  210. return p;
  211. };
  212. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  213. var q = ( 2 * l ) - p;
  214. this.r = hue2rgb( q, p, h + 1 / 3 );
  215. this.g = hue2rgb( q, p, h );
  216. this.b = hue2rgb( q, p, h - 1 / 3 );
  217. }
  218. return this;
  219. },
  220. setStyle: function ( style ) {
  221. // rgb(255,0,0)
  222. if ( /^rgb\((\d+), ?(\d+), ?(\d+)\)$/i.test( style ) ) {
  223. var color = /^rgb\((\d+), ?(\d+), ?(\d+)\)$/i.exec( style );
  224. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  225. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  226. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  227. return this;
  228. }
  229. // rgb(100%,0%,0%)
  230. if ( /^rgb\((\d+)\%, ?(\d+)\%, ?(\d+)\%\)$/i.test( style ) ) {
  231. var color = /^rgb\((\d+)\%, ?(\d+)\%, ?(\d+)\%\)$/i.exec( style );
  232. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  233. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  234. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  235. return this;
  236. }
  237. // #ff0000
  238. if ( /^\#([0-9a-f]{6})$/i.test( style ) ) {
  239. var color = /^\#([0-9a-f]{6})$/i.exec( style );
  240. this.setHex( parseInt( color[ 1 ], 16 ) );
  241. return this;
  242. }
  243. // #f00
  244. if ( /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.test( style ) ) {
  245. var color = /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec( style );
  246. this.setHex( parseInt( color[ 1 ] + color[ 1 ] + color[ 2 ] + color[ 2 ] + color[ 3 ] + color[ 3 ], 16 ) );
  247. return this;
  248. }
  249. // red
  250. if ( /^(\w+)$/i.test( style ) ) {
  251. this.setHex( THREE.ColorKeywords[ style ] );
  252. return this;
  253. }
  254. },
  255. copy: function ( color ) {
  256. this.r = color.r;
  257. this.g = color.g;
  258. this.b = color.b;
  259. return this;
  260. },
  261. copyGammaToLinear: function ( color, gammaFactor ) {
  262. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  263. this.r = Math.pow( color.r, gammaFactor );
  264. this.g = Math.pow( color.g, gammaFactor );
  265. this.b = Math.pow( color.b, gammaFactor );
  266. return this;
  267. },
  268. copyLinearToGamma: function ( color, gammaFactor ) {
  269. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  270. var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  271. this.r = Math.pow( color.r, safeInverse );
  272. this.g = Math.pow( color.g, safeInverse );
  273. this.b = Math.pow( color.b, safeInverse );
  274. return this;
  275. },
  276. convertGammaToLinear: function () {
  277. var r = this.r, g = this.g, b = this.b;
  278. this.r = r * r;
  279. this.g = g * g;
  280. this.b = b * b;
  281. return this;
  282. },
  283. convertLinearToGamma: function () {
  284. this.r = Math.sqrt( this.r );
  285. this.g = Math.sqrt( this.g );
  286. this.b = Math.sqrt( this.b );
  287. return this;
  288. },
  289. getHex: function () {
  290. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  291. },
  292. getHexString: function () {
  293. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  294. },
  295. getHSL: function ( optionalTarget ) {
  296. // h,s,l ranges are in 0.0 - 1.0
  297. var hsl = optionalTarget || { h: 0, s: 0, l: 0 };
  298. var r = this.r, g = this.g, b = this.b;
  299. var max = Math.max( r, g, b );
  300. var min = Math.min( r, g, b );
  301. var hue, saturation;
  302. var lightness = ( min + max ) / 2.0;
  303. if ( min === max ) {
  304. hue = 0;
  305. saturation = 0;
  306. } else {
  307. var delta = max - min;
  308. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  309. switch ( max ) {
  310. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  311. case g: hue = ( b - r ) / delta + 2; break;
  312. case b: hue = ( r - g ) / delta + 4; break;
  313. }
  314. hue /= 6;
  315. }
  316. hsl.h = hue;
  317. hsl.s = saturation;
  318. hsl.l = lightness;
  319. return hsl;
  320. },
  321. getStyle: function () {
  322. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  323. },
  324. offsetHSL: function ( h, s, l ) {
  325. var hsl = this.getHSL();
  326. hsl.h += h; hsl.s += s; hsl.l += l;
  327. this.setHSL( hsl.h, hsl.s, hsl.l );
  328. return this;
  329. },
  330. add: function ( color ) {
  331. this.r += color.r;
  332. this.g += color.g;
  333. this.b += color.b;
  334. return this;
  335. },
  336. addColors: function ( color1, color2 ) {
  337. this.r = color1.r + color2.r;
  338. this.g = color1.g + color2.g;
  339. this.b = color1.b + color2.b;
  340. return this;
  341. },
  342. addScalar: function ( s ) {
  343. this.r += s;
  344. this.g += s;
  345. this.b += s;
  346. return this;
  347. },
  348. multiply: function ( color ) {
  349. this.r *= color.r;
  350. this.g *= color.g;
  351. this.b *= color.b;
  352. return this;
  353. },
  354. multiplyScalar: function ( s ) {
  355. this.r *= s;
  356. this.g *= s;
  357. this.b *= s;
  358. return this;
  359. },
  360. lerp: function ( color, alpha ) {
  361. this.r += ( color.r - this.r ) * alpha;
  362. this.g += ( color.g - this.g ) * alpha;
  363. this.b += ( color.b - this.b ) * alpha;
  364. return this;
  365. },
  366. equals: function ( c ) {
  367. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  368. },
  369. fromArray: function ( array ) {
  370. this.r = array[ 0 ];
  371. this.g = array[ 1 ];
  372. this.b = array[ 2 ];
  373. return this;
  374. },
  375. toArray: function ( array, offset ) {
  376. if ( array === undefined ) array = [];
  377. if ( offset === undefined ) offset = 0;
  378. array[ offset ] = this.r;
  379. array[ offset + 1 ] = this.g;
  380. array[ offset + 2 ] = this.b;
  381. return array;
  382. },
  383. clone: function () {
  384. return new THREE.Color().setRGB( this.r, this.g, this.b );
  385. }
  386. };
  387. THREE.ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  388. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  389. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  390. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  391. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  392. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  393. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  394. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  395. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  396. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  397. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  398. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  399. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  400. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  401. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  402. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  403. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  404. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  405. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  406. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  407. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  408. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  409. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  410. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  411. // File:src/math/Quaternion.js
  412. /**
  413. * @author mikael emtinger / http://gomo.se/
  414. * @author alteredq / http://alteredqualia.com/
  415. * @author WestLangley / http://github.com/WestLangley
  416. * @author bhouston / http://exocortex.com
  417. */
  418. THREE.Quaternion = function ( x, y, z, w ) {
  419. this._x = x || 0;
  420. this._y = y || 0;
  421. this._z = z || 0;
  422. this._w = ( w !== undefined ) ? w : 1;
  423. };
  424. THREE.Quaternion.prototype = {
  425. constructor: THREE.Quaternion,
  426. _x: 0,_y: 0, _z: 0, _w: 0,
  427. get x () {
  428. return this._x;
  429. },
  430. set x ( value ) {
  431. this._x = value;
  432. this.onChangeCallback();
  433. },
  434. get y () {
  435. return this._y;
  436. },
  437. set y ( value ) {
  438. this._y = value;
  439. this.onChangeCallback();
  440. },
  441. get z () {
  442. return this._z;
  443. },
  444. set z ( value ) {
  445. this._z = value;
  446. this.onChangeCallback();
  447. },
  448. get w () {
  449. return this._w;
  450. },
  451. set w ( value ) {
  452. this._w = value;
  453. this.onChangeCallback();
  454. },
  455. set: function ( x, y, z, w ) {
  456. this._x = x;
  457. this._y = y;
  458. this._z = z;
  459. this._w = w;
  460. this.onChangeCallback();
  461. return this;
  462. },
  463. copy: function ( quaternion ) {
  464. this._x = quaternion.x;
  465. this._y = quaternion.y;
  466. this._z = quaternion.z;
  467. this._w = quaternion.w;
  468. this.onChangeCallback();
  469. return this;
  470. },
  471. setFromEuler: function ( euler, update ) {
  472. if ( euler instanceof THREE.Euler === false ) {
  473. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  474. }
  475. // http://www.mathworks.com/matlabcentral/fileexchange/
  476. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  477. // content/SpinCalc.m
  478. var c1 = Math.cos( euler._x / 2 );
  479. var c2 = Math.cos( euler._y / 2 );
  480. var c3 = Math.cos( euler._z / 2 );
  481. var s1 = Math.sin( euler._x / 2 );
  482. var s2 = Math.sin( euler._y / 2 );
  483. var s3 = Math.sin( euler._z / 2 );
  484. if ( euler.order === 'XYZ' ) {
  485. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  486. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  487. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  488. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  489. } else if ( euler.order === 'YXZ' ) {
  490. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  491. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  492. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  493. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  494. } else if ( euler.order === 'ZXY' ) {
  495. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  496. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  497. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  498. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  499. } else if ( euler.order === 'ZYX' ) {
  500. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  501. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  502. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  503. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  504. } else if ( euler.order === 'YZX' ) {
  505. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  506. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  507. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  508. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  509. } else if ( euler.order === 'XZY' ) {
  510. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  511. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  512. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  513. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  514. }
  515. if ( update !== false ) this.onChangeCallback();
  516. return this;
  517. },
  518. setFromAxisAngle: function ( axis, angle ) {
  519. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  520. // assumes axis is normalized
  521. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  522. this._x = axis.x * s;
  523. this._y = axis.y * s;
  524. this._z = axis.z * s;
  525. this._w = Math.cos( halfAngle );
  526. this.onChangeCallback();
  527. return this;
  528. },
  529. setFromRotationMatrix: function ( m ) {
  530. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  531. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  532. var te = m.elements,
  533. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  534. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  535. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  536. trace = m11 + m22 + m33,
  537. s;
  538. if ( trace > 0 ) {
  539. s = 0.5 / Math.sqrt( trace + 1.0 );
  540. this._w = 0.25 / s;
  541. this._x = ( m32 - m23 ) * s;
  542. this._y = ( m13 - m31 ) * s;
  543. this._z = ( m21 - m12 ) * s;
  544. } else if ( m11 > m22 && m11 > m33 ) {
  545. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  546. this._w = ( m32 - m23 ) / s;
  547. this._x = 0.25 * s;
  548. this._y = ( m12 + m21 ) / s;
  549. this._z = ( m13 + m31 ) / s;
  550. } else if ( m22 > m33 ) {
  551. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  552. this._w = ( m13 - m31 ) / s;
  553. this._x = ( m12 + m21 ) / s;
  554. this._y = 0.25 * s;
  555. this._z = ( m23 + m32 ) / s;
  556. } else {
  557. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  558. this._w = ( m21 - m12 ) / s;
  559. this._x = ( m13 + m31 ) / s;
  560. this._y = ( m23 + m32 ) / s;
  561. this._z = 0.25 * s;
  562. }
  563. this.onChangeCallback();
  564. return this;
  565. },
  566. setFromUnitVectors: function () {
  567. // http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final
  568. // assumes direction vectors vFrom and vTo are normalized
  569. var v1, r;
  570. var EPS = 0.000001;
  571. return function ( vFrom, vTo ) {
  572. if ( v1 === undefined ) v1 = new THREE.Vector3();
  573. r = vFrom.dot( vTo ) + 1;
  574. if ( r < EPS ) {
  575. r = 0;
  576. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  577. v1.set( - vFrom.y, vFrom.x, 0 );
  578. } else {
  579. v1.set( 0, - vFrom.z, vFrom.y );
  580. }
  581. } else {
  582. v1.crossVectors( vFrom, vTo );
  583. }
  584. this._x = v1.x;
  585. this._y = v1.y;
  586. this._z = v1.z;
  587. this._w = r;
  588. this.normalize();
  589. return this;
  590. }
  591. }(),
  592. inverse: function () {
  593. this.conjugate().normalize();
  594. return this;
  595. },
  596. conjugate: function () {
  597. this._x *= - 1;
  598. this._y *= - 1;
  599. this._z *= - 1;
  600. this.onChangeCallback();
  601. return this;
  602. },
  603. dot: function ( v ) {
  604. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  605. },
  606. lengthSq: function () {
  607. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  608. },
  609. length: function () {
  610. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  611. },
  612. normalize: function () {
  613. var l = this.length();
  614. if ( l === 0 ) {
  615. this._x = 0;
  616. this._y = 0;
  617. this._z = 0;
  618. this._w = 1;
  619. } else {
  620. l = 1 / l;
  621. this._x = this._x * l;
  622. this._y = this._y * l;
  623. this._z = this._z * l;
  624. this._w = this._w * l;
  625. }
  626. this.onChangeCallback();
  627. return this;
  628. },
  629. multiply: function ( q, p ) {
  630. if ( p !== undefined ) {
  631. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  632. return this.multiplyQuaternions( q, p );
  633. }
  634. return this.multiplyQuaternions( this, q );
  635. },
  636. multiplyQuaternions: function ( a, b ) {
  637. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  638. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  639. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  640. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  641. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  642. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  643. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  644. this.onChangeCallback();
  645. return this;
  646. },
  647. multiplyVector3: function ( vector ) {
  648. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  649. return vector.applyQuaternion( this );
  650. },
  651. slerp: function ( qb, t ) {
  652. if ( t === 0 ) return this;
  653. if ( t === 1 ) return this.copy( qb );
  654. var x = this._x, y = this._y, z = this._z, w = this._w;
  655. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  656. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  657. if ( cosHalfTheta < 0 ) {
  658. this._w = - qb._w;
  659. this._x = - qb._x;
  660. this._y = - qb._y;
  661. this._z = - qb._z;
  662. cosHalfTheta = - cosHalfTheta;
  663. } else {
  664. this.copy( qb );
  665. }
  666. if ( cosHalfTheta >= 1.0 ) {
  667. this._w = w;
  668. this._x = x;
  669. this._y = y;
  670. this._z = z;
  671. return this;
  672. }
  673. var halfTheta = Math.acos( cosHalfTheta );
  674. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  675. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  676. this._w = 0.5 * ( w + this._w );
  677. this._x = 0.5 * ( x + this._x );
  678. this._y = 0.5 * ( y + this._y );
  679. this._z = 0.5 * ( z + this._z );
  680. return this;
  681. }
  682. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  683. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  684. this._w = ( w * ratioA + this._w * ratioB );
  685. this._x = ( x * ratioA + this._x * ratioB );
  686. this._y = ( y * ratioA + this._y * ratioB );
  687. this._z = ( z * ratioA + this._z * ratioB );
  688. this.onChangeCallback();
  689. return this;
  690. },
  691. equals: function ( quaternion ) {
  692. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  693. },
  694. fromArray: function ( array, offset ) {
  695. if ( offset === undefined ) offset = 0;
  696. this._x = array[ offset ];
  697. this._y = array[ offset + 1 ];
  698. this._z = array[ offset + 2 ];
  699. this._w = array[ offset + 3 ];
  700. this.onChangeCallback();
  701. return this;
  702. },
  703. toArray: function ( array, offset ) {
  704. if ( array === undefined ) array = [];
  705. if ( offset === undefined ) offset = 0;
  706. array[ offset ] = this._x;
  707. array[ offset + 1 ] = this._y;
  708. array[ offset + 2 ] = this._z;
  709. array[ offset + 3 ] = this._w;
  710. return array;
  711. },
  712. onChange: function ( callback ) {
  713. this.onChangeCallback = callback;
  714. return this;
  715. },
  716. onChangeCallback: function () {},
  717. clone: function () {
  718. return new THREE.Quaternion( this._x, this._y, this._z, this._w );
  719. }
  720. };
  721. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  722. return qm.copy( qa ).slerp( qb, t );
  723. };
  724. // File:src/math/Vector2.js
  725. /**
  726. * @author mrdoob / http://mrdoob.com/
  727. * @author philogb / http://blog.thejit.org/
  728. * @author egraether / http://egraether.com/
  729. * @author zz85 / http://www.lab4games.net/zz85/blog
  730. */
  731. THREE.Vector2 = function ( x, y ) {
  732. this.x = x || 0;
  733. this.y = y || 0;
  734. };
  735. THREE.Vector2.prototype = {
  736. constructor: THREE.Vector2,
  737. set: function ( x, y ) {
  738. this.x = x;
  739. this.y = y;
  740. return this;
  741. },
  742. setX: function ( x ) {
  743. this.x = x;
  744. return this;
  745. },
  746. setY: function ( y ) {
  747. this.y = y;
  748. return this;
  749. },
  750. setComponent: function ( index, value ) {
  751. switch ( index ) {
  752. case 0: this.x = value; break;
  753. case 1: this.y = value; break;
  754. default: throw new Error( 'index is out of range: ' + index );
  755. }
  756. },
  757. getComponent: function ( index ) {
  758. switch ( index ) {
  759. case 0: return this.x;
  760. case 1: return this.y;
  761. default: throw new Error( 'index is out of range: ' + index );
  762. }
  763. },
  764. copy: function ( v ) {
  765. this.x = v.x;
  766. this.y = v.y;
  767. return this;
  768. },
  769. add: function ( v, w ) {
  770. if ( w !== undefined ) {
  771. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  772. return this.addVectors( v, w );
  773. }
  774. this.x += v.x;
  775. this.y += v.y;
  776. return this;
  777. },
  778. addScalar: function ( s ) {
  779. this.x += s;
  780. this.y += s;
  781. return this;
  782. },
  783. addVectors: function ( a, b ) {
  784. this.x = a.x + b.x;
  785. this.y = a.y + b.y;
  786. return this;
  787. },
  788. sub: function ( v, w ) {
  789. if ( w !== undefined ) {
  790. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  791. return this.subVectors( v, w );
  792. }
  793. this.x -= v.x;
  794. this.y -= v.y;
  795. return this;
  796. },
  797. subScalar: function ( s ) {
  798. this.x -= s;
  799. this.y -= s;
  800. return this;
  801. },
  802. subVectors: function ( a, b ) {
  803. this.x = a.x - b.x;
  804. this.y = a.y - b.y;
  805. return this;
  806. },
  807. multiply: function ( v ) {
  808. this.x *= v.x;
  809. this.y *= v.y;
  810. return this;
  811. },
  812. multiplyScalar: function ( s ) {
  813. this.x *= s;
  814. this.y *= s;
  815. return this;
  816. },
  817. divide: function ( v ) {
  818. this.x /= v.x;
  819. this.y /= v.y;
  820. return this;
  821. },
  822. divideScalar: function ( scalar ) {
  823. if ( scalar !== 0 ) {
  824. var invScalar = 1 / scalar;
  825. this.x *= invScalar;
  826. this.y *= invScalar;
  827. } else {
  828. this.x = 0;
  829. this.y = 0;
  830. }
  831. return this;
  832. },
  833. min: function ( v ) {
  834. if ( this.x > v.x ) {
  835. this.x = v.x;
  836. }
  837. if ( this.y > v.y ) {
  838. this.y = v.y;
  839. }
  840. return this;
  841. },
  842. max: function ( v ) {
  843. if ( this.x < v.x ) {
  844. this.x = v.x;
  845. }
  846. if ( this.y < v.y ) {
  847. this.y = v.y;
  848. }
  849. return this;
  850. },
  851. clamp: function ( min, max ) {
  852. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  853. if ( this.x < min.x ) {
  854. this.x = min.x;
  855. } else if ( this.x > max.x ) {
  856. this.x = max.x;
  857. }
  858. if ( this.y < min.y ) {
  859. this.y = min.y;
  860. } else if ( this.y > max.y ) {
  861. this.y = max.y;
  862. }
  863. return this;
  864. },
  865. clampScalar: ( function () {
  866. var min, max;
  867. return function ( minVal, maxVal ) {
  868. if ( min === undefined ) {
  869. min = new THREE.Vector2();
  870. max = new THREE.Vector2();
  871. }
  872. min.set( minVal, minVal );
  873. max.set( maxVal, maxVal );
  874. return this.clamp( min, max );
  875. };
  876. } )(),
  877. floor: function () {
  878. this.x = Math.floor( this.x );
  879. this.y = Math.floor( this.y );
  880. return this;
  881. },
  882. ceil: function () {
  883. this.x = Math.ceil( this.x );
  884. this.y = Math.ceil( this.y );
  885. return this;
  886. },
  887. round: function () {
  888. this.x = Math.round( this.x );
  889. this.y = Math.round( this.y );
  890. return this;
  891. },
  892. roundToZero: function () {
  893. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  894. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  895. return this;
  896. },
  897. negate: function () {
  898. this.x = - this.x;
  899. this.y = - this.y;
  900. return this;
  901. },
  902. dot: function ( v ) {
  903. return this.x * v.x + this.y * v.y;
  904. },
  905. lengthSq: function () {
  906. return this.x * this.x + this.y * this.y;
  907. },
  908. length: function () {
  909. return Math.sqrt( this.x * this.x + this.y * this.y );
  910. },
  911. normalize: function () {
  912. return this.divideScalar( this.length() );
  913. },
  914. distanceTo: function ( v ) {
  915. return Math.sqrt( this.distanceToSquared( v ) );
  916. },
  917. distanceToSquared: function ( v ) {
  918. var dx = this.x - v.x, dy = this.y - v.y;
  919. return dx * dx + dy * dy;
  920. },
  921. setLength: function ( l ) {
  922. var oldLength = this.length();
  923. if ( oldLength !== 0 && l !== oldLength ) {
  924. this.multiplyScalar( l / oldLength );
  925. }
  926. return this;
  927. },
  928. lerp: function ( v, alpha ) {
  929. this.x += ( v.x - this.x ) * alpha;
  930. this.y += ( v.y - this.y ) * alpha;
  931. return this;
  932. },
  933. lerpVectors: function ( v1, v2, alpha ) {
  934. this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  935. return this;
  936. },
  937. equals: function ( v ) {
  938. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  939. },
  940. fromArray: function ( array, offset ) {
  941. if ( offset === undefined ) offset = 0;
  942. this.x = array[ offset ];
  943. this.y = array[ offset + 1 ];
  944. return this;
  945. },
  946. toArray: function ( array, offset ) {
  947. if ( array === undefined ) array = [];
  948. if ( offset === undefined ) offset = 0;
  949. array[ offset ] = this.x;
  950. array[ offset + 1 ] = this.y;
  951. return array;
  952. },
  953. fromAttribute: function ( attribute, index, offset ) {
  954. if ( offset === undefined ) offset = 0;
  955. index = index * attribute.itemSize + offset;
  956. this.x = attribute.array[ index ];
  957. this.y = attribute.array[ index + 1 ];
  958. return this;
  959. },
  960. clone: function () {
  961. return new THREE.Vector2( this.x, this.y );
  962. }
  963. };
  964. // File:src/math/Vector3.js
  965. /**
  966. * @author mrdoob / http://mrdoob.com/
  967. * @author *kile / http://kile.stravaganza.org/
  968. * @author philogb / http://blog.thejit.org/
  969. * @author mikael emtinger / http://gomo.se/
  970. * @author egraether / http://egraether.com/
  971. * @author WestLangley / http://github.com/WestLangley
  972. */
  973. THREE.Vector3 = function ( x, y, z ) {
  974. this.x = x || 0;
  975. this.y = y || 0;
  976. this.z = z || 0;
  977. };
  978. THREE.Vector3.prototype = {
  979. constructor: THREE.Vector3,
  980. set: function ( x, y, z ) {
  981. this.x = x;
  982. this.y = y;
  983. this.z = z;
  984. return this;
  985. },
  986. setX: function ( x ) {
  987. this.x = x;
  988. return this;
  989. },
  990. setY: function ( y ) {
  991. this.y = y;
  992. return this;
  993. },
  994. setZ: function ( z ) {
  995. this.z = z;
  996. return this;
  997. },
  998. setComponent: function ( index, value ) {
  999. switch ( index ) {
  1000. case 0: this.x = value; break;
  1001. case 1: this.y = value; break;
  1002. case 2: this.z = value; break;
  1003. default: throw new Error( 'index is out of range: ' + index );
  1004. }
  1005. },
  1006. getComponent: function ( index ) {
  1007. switch ( index ) {
  1008. case 0: return this.x;
  1009. case 1: return this.y;
  1010. case 2: return this.z;
  1011. default: throw new Error( 'index is out of range: ' + index );
  1012. }
  1013. },
  1014. copy: function ( v ) {
  1015. this.x = v.x;
  1016. this.y = v.y;
  1017. this.z = v.z;
  1018. return this;
  1019. },
  1020. add: function ( v, w ) {
  1021. if ( w !== undefined ) {
  1022. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1023. return this.addVectors( v, w );
  1024. }
  1025. this.x += v.x;
  1026. this.y += v.y;
  1027. this.z += v.z;
  1028. return this;
  1029. },
  1030. addScalar: function ( s ) {
  1031. this.x += s;
  1032. this.y += s;
  1033. this.z += s;
  1034. return this;
  1035. },
  1036. addVectors: function ( a, b ) {
  1037. this.x = a.x + b.x;
  1038. this.y = a.y + b.y;
  1039. this.z = a.z + b.z;
  1040. return this;
  1041. },
  1042. sub: function ( v, w ) {
  1043. if ( w !== undefined ) {
  1044. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1045. return this.subVectors( v, w );
  1046. }
  1047. this.x -= v.x;
  1048. this.y -= v.y;
  1049. this.z -= v.z;
  1050. return this;
  1051. },
  1052. subScalar: function ( s ) {
  1053. this.x -= s;
  1054. this.y -= s;
  1055. this.z -= s;
  1056. return this;
  1057. },
  1058. subVectors: function ( a, b ) {
  1059. this.x = a.x - b.x;
  1060. this.y = a.y - b.y;
  1061. this.z = a.z - b.z;
  1062. return this;
  1063. },
  1064. multiply: function ( v, w ) {
  1065. if ( w !== undefined ) {
  1066. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  1067. return this.multiplyVectors( v, w );
  1068. }
  1069. this.x *= v.x;
  1070. this.y *= v.y;
  1071. this.z *= v.z;
  1072. return this;
  1073. },
  1074. multiplyScalar: function ( scalar ) {
  1075. this.x *= scalar;
  1076. this.y *= scalar;
  1077. this.z *= scalar;
  1078. return this;
  1079. },
  1080. multiplyVectors: function ( a, b ) {
  1081. this.x = a.x * b.x;
  1082. this.y = a.y * b.y;
  1083. this.z = a.z * b.z;
  1084. return this;
  1085. },
  1086. applyEuler: function () {
  1087. var quaternion;
  1088. return function ( euler ) {
  1089. if ( euler instanceof THREE.Euler === false ) {
  1090. console.error( 'THREE.Vector3: .applyEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  1091. }
  1092. if ( quaternion === undefined ) quaternion = new THREE.Quaternion();
  1093. this.applyQuaternion( quaternion.setFromEuler( euler ) );
  1094. return this;
  1095. };
  1096. }(),
  1097. applyAxisAngle: function () {
  1098. var quaternion;
  1099. return function ( axis, angle ) {
  1100. if ( quaternion === undefined ) quaternion = new THREE.Quaternion();
  1101. this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  1102. return this;
  1103. };
  1104. }(),
  1105. applyMatrix3: function ( m ) {
  1106. var x = this.x;
  1107. var y = this.y;
  1108. var z = this.z;
  1109. var e = m.elements;
  1110. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  1111. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  1112. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  1113. return this;
  1114. },
  1115. applyMatrix4: function ( m ) {
  1116. // input: THREE.Matrix4 affine matrix
  1117. var x = this.x, y = this.y, z = this.z;
  1118. var e = m.elements;
  1119. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ];
  1120. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ];
  1121. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ];
  1122. return this;
  1123. },
  1124. applyProjection: function ( m ) {
  1125. // input: THREE.Matrix4 projection matrix
  1126. var x = this.x, y = this.y, z = this.z;
  1127. var e = m.elements;
  1128. var d = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] ); // perspective divide
  1129. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * d;
  1130. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * d;
  1131. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * d;
  1132. return this;
  1133. },
  1134. applyQuaternion: function ( q ) {
  1135. var x = this.x;
  1136. var y = this.y;
  1137. var z = this.z;
  1138. var qx = q.x;
  1139. var qy = q.y;
  1140. var qz = q.z;
  1141. var qw = q.w;
  1142. // calculate quat * vector
  1143. var ix = qw * x + qy * z - qz * y;
  1144. var iy = qw * y + qz * x - qx * z;
  1145. var iz = qw * z + qx * y - qy * x;
  1146. var iw = - qx * x - qy * y - qz * z;
  1147. // calculate result * inverse quat
  1148. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  1149. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  1150. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  1151. return this;
  1152. },
  1153. project: function () {
  1154. var matrix;
  1155. return function ( camera ) {
  1156. if ( matrix === undefined ) matrix = new THREE.Matrix4();
  1157. matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) );
  1158. return this.applyProjection( matrix );
  1159. };
  1160. }(),
  1161. unproject: function () {
  1162. var matrix;
  1163. return function ( camera ) {
  1164. if ( matrix === undefined ) matrix = new THREE.Matrix4();
  1165. matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) );
  1166. return this.applyProjection( matrix );
  1167. };
  1168. }(),
  1169. transformDirection: function ( m ) {
  1170. // input: THREE.Matrix4 affine matrix
  1171. // vector interpreted as a direction
  1172. var x = this.x, y = this.y, z = this.z;
  1173. var e = m.elements;
  1174. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  1175. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  1176. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  1177. this.normalize();
  1178. return this;
  1179. },
  1180. divide: function ( v ) {
  1181. this.x /= v.x;
  1182. this.y /= v.y;
  1183. this.z /= v.z;
  1184. return this;
  1185. },
  1186. divideScalar: function ( scalar ) {
  1187. if ( scalar !== 0 ) {
  1188. var invScalar = 1 / scalar;
  1189. this.x *= invScalar;
  1190. this.y *= invScalar;
  1191. this.z *= invScalar;
  1192. } else {
  1193. this.x = 0;
  1194. this.y = 0;
  1195. this.z = 0;
  1196. }
  1197. return this;
  1198. },
  1199. min: function ( v ) {
  1200. if ( this.x > v.x ) {
  1201. this.x = v.x;
  1202. }
  1203. if ( this.y > v.y ) {
  1204. this.y = v.y;
  1205. }
  1206. if ( this.z > v.z ) {
  1207. this.z = v.z;
  1208. }
  1209. return this;
  1210. },
  1211. max: function ( v ) {
  1212. if ( this.x < v.x ) {
  1213. this.x = v.x;
  1214. }
  1215. if ( this.y < v.y ) {
  1216. this.y = v.y;
  1217. }
  1218. if ( this.z < v.z ) {
  1219. this.z = v.z;
  1220. }
  1221. return this;
  1222. },
  1223. clamp: function ( min, max ) {
  1224. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1225. if ( this.x < min.x ) {
  1226. this.x = min.x;
  1227. } else if ( this.x > max.x ) {
  1228. this.x = max.x;
  1229. }
  1230. if ( this.y < min.y ) {
  1231. this.y = min.y;
  1232. } else if ( this.y > max.y ) {
  1233. this.y = max.y;
  1234. }
  1235. if ( this.z < min.z ) {
  1236. this.z = min.z;
  1237. } else if ( this.z > max.z ) {
  1238. this.z = max.z;
  1239. }
  1240. return this;
  1241. },
  1242. clampScalar: ( function () {
  1243. var min, max;
  1244. return function ( minVal, maxVal ) {
  1245. if ( min === undefined ) {
  1246. min = new THREE.Vector3();
  1247. max = new THREE.Vector3();
  1248. }
  1249. min.set( minVal, minVal, minVal );
  1250. max.set( maxVal, maxVal, maxVal );
  1251. return this.clamp( min, max );
  1252. };
  1253. } )(),
  1254. floor: function () {
  1255. this.x = Math.floor( this.x );
  1256. this.y = Math.floor( this.y );
  1257. this.z = Math.floor( this.z );
  1258. return this;
  1259. },
  1260. ceil: function () {
  1261. this.x = Math.ceil( this.x );
  1262. this.y = Math.ceil( this.y );
  1263. this.z = Math.ceil( this.z );
  1264. return this;
  1265. },
  1266. round: function () {
  1267. this.x = Math.round( this.x );
  1268. this.y = Math.round( this.y );
  1269. this.z = Math.round( this.z );
  1270. return this;
  1271. },
  1272. roundToZero: function () {
  1273. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1274. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1275. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1276. return this;
  1277. },
  1278. negate: function () {
  1279. this.x = - this.x;
  1280. this.y = - this.y;
  1281. this.z = - this.z;
  1282. return this;
  1283. },
  1284. dot: function ( v ) {
  1285. return this.x * v.x + this.y * v.y + this.z * v.z;
  1286. },
  1287. lengthSq: function () {
  1288. return this.x * this.x + this.y * this.y + this.z * this.z;
  1289. },
  1290. length: function () {
  1291. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1292. },
  1293. lengthManhattan: function () {
  1294. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1295. },
  1296. normalize: function () {
  1297. return this.divideScalar( this.length() );
  1298. },
  1299. setLength: function ( l ) {
  1300. var oldLength = this.length();
  1301. if ( oldLength !== 0 && l !== oldLength ) {
  1302. this.multiplyScalar( l / oldLength );
  1303. }
  1304. return this;
  1305. },
  1306. lerp: function ( v, alpha ) {
  1307. this.x += ( v.x - this.x ) * alpha;
  1308. this.y += ( v.y - this.y ) * alpha;
  1309. this.z += ( v.z - this.z ) * alpha;
  1310. return this;
  1311. },
  1312. lerpVectors: function ( v1, v2, alpha ) {
  1313. this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1314. return this;
  1315. },
  1316. cross: function ( v, w ) {
  1317. if ( w !== undefined ) {
  1318. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1319. return this.crossVectors( v, w );
  1320. }
  1321. var x = this.x, y = this.y, z = this.z;
  1322. this.x = y * v.z - z * v.y;
  1323. this.y = z * v.x - x * v.z;
  1324. this.z = x * v.y - y * v.x;
  1325. return this;
  1326. },
  1327. crossVectors: function ( a, b ) {
  1328. var ax = a.x, ay = a.y, az = a.z;
  1329. var bx = b.x, by = b.y, bz = b.z;
  1330. this.x = ay * bz - az * by;
  1331. this.y = az * bx - ax * bz;
  1332. this.z = ax * by - ay * bx;
  1333. return this;
  1334. },
  1335. projectOnVector: function () {
  1336. var v1, dot;
  1337. return function ( vector ) {
  1338. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1339. v1.copy( vector ).normalize();
  1340. dot = this.dot( v1 );
  1341. return this.copy( v1 ).multiplyScalar( dot );
  1342. };
  1343. }(),
  1344. projectOnPlane: function () {
  1345. var v1;
  1346. return function ( planeNormal ) {
  1347. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1348. v1.copy( this ).projectOnVector( planeNormal );
  1349. return this.sub( v1 );
  1350. }
  1351. }(),
  1352. reflect: function () {
  1353. // reflect incident vector off plane orthogonal to normal
  1354. // normal is assumed to have unit length
  1355. var v1;
  1356. return function ( normal ) {
  1357. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1358. return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  1359. }
  1360. }(),
  1361. angleTo: function ( v ) {
  1362. var theta = this.dot( v ) / ( this.length() * v.length() );
  1363. // clamp, to handle numerical problems
  1364. return Math.acos( THREE.Math.clamp( theta, - 1, 1 ) );
  1365. },
  1366. distanceTo: function ( v ) {
  1367. return Math.sqrt( this.distanceToSquared( v ) );
  1368. },
  1369. distanceToSquared: function ( v ) {
  1370. var dx = this.x - v.x;
  1371. var dy = this.y - v.y;
  1372. var dz = this.z - v.z;
  1373. return dx * dx + dy * dy + dz * dz;
  1374. },
  1375. setEulerFromRotationMatrix: function ( m, order ) {
  1376. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  1377. },
  1378. setEulerFromQuaternion: function ( q, order ) {
  1379. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  1380. },
  1381. getPositionFromMatrix: function ( m ) {
  1382. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  1383. return this.setFromMatrixPosition( m );
  1384. },
  1385. getScaleFromMatrix: function ( m ) {
  1386. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  1387. return this.setFromMatrixScale( m );
  1388. },
  1389. getColumnFromMatrix: function ( index, matrix ) {
  1390. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  1391. return this.setFromMatrixColumn( index, matrix );
  1392. },
  1393. setFromMatrixPosition: function ( m ) {
  1394. this.x = m.elements[ 12 ];
  1395. this.y = m.elements[ 13 ];
  1396. this.z = m.elements[ 14 ];
  1397. return this;
  1398. },
  1399. setFromMatrixScale: function ( m ) {
  1400. var sx = this.set( m.elements[ 0 ], m.elements[ 1 ], m.elements[ 2 ] ).length();
  1401. var sy = this.set( m.elements[ 4 ], m.elements[ 5 ], m.elements[ 6 ] ).length();
  1402. var sz = this.set( m.elements[ 8 ], m.elements[ 9 ], m.elements[ 10 ] ).length();
  1403. this.x = sx;
  1404. this.y = sy;
  1405. this.z = sz;
  1406. return this;
  1407. },
  1408. setFromMatrixColumn: function ( index, matrix ) {
  1409. var offset = index * 4;
  1410. var me = matrix.elements;
  1411. this.x = me[ offset ];
  1412. this.y = me[ offset + 1 ];
  1413. this.z = me[ offset + 2 ];
  1414. return this;
  1415. },
  1416. equals: function ( v ) {
  1417. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1418. },
  1419. fromArray: function ( array, offset ) {
  1420. if ( offset === undefined ) offset = 0;
  1421. this.x = array[ offset ];
  1422. this.y = array[ offset + 1 ];
  1423. this.z = array[ offset + 2 ];
  1424. return this;
  1425. },
  1426. toArray: function ( array, offset ) {
  1427. if ( array === undefined ) array = [];
  1428. if ( offset === undefined ) offset = 0;
  1429. array[ offset ] = this.x;
  1430. array[ offset + 1 ] = this.y;
  1431. array[ offset + 2 ] = this.z;
  1432. return array;
  1433. },
  1434. fromAttribute: function ( attribute, index, offset ) {
  1435. if ( offset === undefined ) offset = 0;
  1436. index = index * attribute.itemSize + offset;
  1437. this.x = attribute.array[ index ];
  1438. this.y = attribute.array[ index + 1 ];
  1439. this.z = attribute.array[ index + 2 ];
  1440. return this;
  1441. },
  1442. clone: function () {
  1443. return new THREE.Vector3( this.x, this.y, this.z );
  1444. }
  1445. };
  1446. // File:src/math/Vector4.js
  1447. /**
  1448. * @author supereggbert / http://www.paulbrunt.co.uk/
  1449. * @author philogb / http://blog.thejit.org/
  1450. * @author mikael emtinger / http://gomo.se/
  1451. * @author egraether / http://egraether.com/
  1452. * @author WestLangley / http://github.com/WestLangley
  1453. */
  1454. THREE.Vector4 = function ( x, y, z, w ) {
  1455. this.x = x || 0;
  1456. this.y = y || 0;
  1457. this.z = z || 0;
  1458. this.w = ( w !== undefined ) ? w : 1;
  1459. };
  1460. THREE.Vector4.prototype = {
  1461. constructor: THREE.Vector4,
  1462. set: function ( x, y, z, w ) {
  1463. this.x = x;
  1464. this.y = y;
  1465. this.z = z;
  1466. this.w = w;
  1467. return this;
  1468. },
  1469. setX: function ( x ) {
  1470. this.x = x;
  1471. return this;
  1472. },
  1473. setY: function ( y ) {
  1474. this.y = y;
  1475. return this;
  1476. },
  1477. setZ: function ( z ) {
  1478. this.z = z;
  1479. return this;
  1480. },
  1481. setW: function ( w ) {
  1482. this.w = w;
  1483. return this;
  1484. },
  1485. setComponent: function ( index, value ) {
  1486. switch ( index ) {
  1487. case 0: this.x = value; break;
  1488. case 1: this.y = value; break;
  1489. case 2: this.z = value; break;
  1490. case 3: this.w = value; break;
  1491. default: throw new Error( 'index is out of range: ' + index );
  1492. }
  1493. },
  1494. getComponent: function ( index ) {
  1495. switch ( index ) {
  1496. case 0: return this.x;
  1497. case 1: return this.y;
  1498. case 2: return this.z;
  1499. case 3: return this.w;
  1500. default: throw new Error( 'index is out of range: ' + index );
  1501. }
  1502. },
  1503. copy: function ( v ) {
  1504. this.x = v.x;
  1505. this.y = v.y;
  1506. this.z = v.z;
  1507. this.w = ( v.w !== undefined ) ? v.w : 1;
  1508. return this;
  1509. },
  1510. add: function ( v, w ) {
  1511. if ( w !== undefined ) {
  1512. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1513. return this.addVectors( v, w );
  1514. }
  1515. this.x += v.x;
  1516. this.y += v.y;
  1517. this.z += v.z;
  1518. this.w += v.w;
  1519. return this;
  1520. },
  1521. addScalar: function ( s ) {
  1522. this.x += s;
  1523. this.y += s;
  1524. this.z += s;
  1525. this.w += s;
  1526. return this;
  1527. },
  1528. addVectors: function ( a, b ) {
  1529. this.x = a.x + b.x;
  1530. this.y = a.y + b.y;
  1531. this.z = a.z + b.z;
  1532. this.w = a.w + b.w;
  1533. return this;
  1534. },
  1535. sub: function ( v, w ) {
  1536. if ( w !== undefined ) {
  1537. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1538. return this.subVectors( v, w );
  1539. }
  1540. this.x -= v.x;
  1541. this.y -= v.y;
  1542. this.z -= v.z;
  1543. this.w -= v.w;
  1544. return this;
  1545. },
  1546. subScalar: function ( s ) {
  1547. this.x -= s;
  1548. this.y -= s;
  1549. this.z -= s;
  1550. this.w -= s;
  1551. return this;
  1552. },
  1553. subVectors: function ( a, b ) {
  1554. this.x = a.x - b.x;
  1555. this.y = a.y - b.y;
  1556. this.z = a.z - b.z;
  1557. this.w = a.w - b.w;
  1558. return this;
  1559. },
  1560. multiplyScalar: function ( scalar ) {
  1561. this.x *= scalar;
  1562. this.y *= scalar;
  1563. this.z *= scalar;
  1564. this.w *= scalar;
  1565. return this;
  1566. },
  1567. applyMatrix4: function ( m ) {
  1568. var x = this.x;
  1569. var y = this.y;
  1570. var z = this.z;
  1571. var w = this.w;
  1572. var e = m.elements;
  1573. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1574. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1575. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1576. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1577. return this;
  1578. },
  1579. divideScalar: function ( scalar ) {
  1580. if ( scalar !== 0 ) {
  1581. var invScalar = 1 / scalar;
  1582. this.x *= invScalar;
  1583. this.y *= invScalar;
  1584. this.z *= invScalar;
  1585. this.w *= invScalar;
  1586. } else {
  1587. this.x = 0;
  1588. this.y = 0;
  1589. this.z = 0;
  1590. this.w = 1;
  1591. }
  1592. return this;
  1593. },
  1594. setAxisAngleFromQuaternion: function ( q ) {
  1595. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1596. // q is assumed to be normalized
  1597. this.w = 2 * Math.acos( q.w );
  1598. var s = Math.sqrt( 1 - q.w * q.w );
  1599. if ( s < 0.0001 ) {
  1600. this.x = 1;
  1601. this.y = 0;
  1602. this.z = 0;
  1603. } else {
  1604. this.x = q.x / s;
  1605. this.y = q.y / s;
  1606. this.z = q.z / s;
  1607. }
  1608. return this;
  1609. },
  1610. setAxisAngleFromRotationMatrix: function ( m ) {
  1611. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1612. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1613. var angle, x, y, z, // variables for result
  1614. epsilon = 0.01, // margin to allow for rounding errors
  1615. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1616. te = m.elements,
  1617. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1618. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1619. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1620. if ( ( Math.abs( m12 - m21 ) < epsilon )
  1621. && ( Math.abs( m13 - m31 ) < epsilon )
  1622. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1623. // singularity found
  1624. // first check for identity matrix which must have +1 for all terms
  1625. // in leading diagonal and zero in other terms
  1626. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  1627. && ( Math.abs( m13 + m31 ) < epsilon2 )
  1628. && ( Math.abs( m23 + m32 ) < epsilon2 )
  1629. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1630. // this singularity is identity matrix so angle = 0
  1631. this.set( 1, 0, 0, 0 );
  1632. return this; // zero angle, arbitrary axis
  1633. }
  1634. // otherwise this singularity is angle = 180
  1635. angle = Math.PI;
  1636. var xx = ( m11 + 1 ) / 2;
  1637. var yy = ( m22 + 1 ) / 2;
  1638. var zz = ( m33 + 1 ) / 2;
  1639. var xy = ( m12 + m21 ) / 4;
  1640. var xz = ( m13 + m31 ) / 4;
  1641. var yz = ( m23 + m32 ) / 4;
  1642. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  1643. if ( xx < epsilon ) {
  1644. x = 0;
  1645. y = 0.707106781;
  1646. z = 0.707106781;
  1647. } else {
  1648. x = Math.sqrt( xx );
  1649. y = xy / x;
  1650. z = xz / x;
  1651. }
  1652. } else if ( yy > zz ) { // m22 is the largest diagonal term
  1653. if ( yy < epsilon ) {
  1654. x = 0.707106781;
  1655. y = 0;
  1656. z = 0.707106781;
  1657. } else {
  1658. y = Math.sqrt( yy );
  1659. x = xy / y;
  1660. z = yz / y;
  1661. }
  1662. } else { // m33 is the largest diagonal term so base result on this
  1663. if ( zz < epsilon ) {
  1664. x = 0.707106781;
  1665. y = 0.707106781;
  1666. z = 0;
  1667. } else {
  1668. z = Math.sqrt( zz );
  1669. x = xz / z;
  1670. y = yz / z;
  1671. }
  1672. }
  1673. this.set( x, y, z, angle );
  1674. return this; // return 180 deg rotation
  1675. }
  1676. // as we have reached here there are no singularities so we can handle normally
  1677. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  1678. + ( m13 - m31 ) * ( m13 - m31 )
  1679. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1680. if ( Math.abs( s ) < 0.001 ) s = 1;
  1681. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1682. // caught by singularity test above, but I've left it in just in case
  1683. this.x = ( m32 - m23 ) / s;
  1684. this.y = ( m13 - m31 ) / s;
  1685. this.z = ( m21 - m12 ) / s;
  1686. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1687. return this;
  1688. },
  1689. min: function ( v ) {
  1690. if ( this.x > v.x ) {
  1691. this.x = v.x;
  1692. }
  1693. if ( this.y > v.y ) {
  1694. this.y = v.y;
  1695. }
  1696. if ( this.z > v.z ) {
  1697. this.z = v.z;
  1698. }
  1699. if ( this.w > v.w ) {
  1700. this.w = v.w;
  1701. }
  1702. return this;
  1703. },
  1704. max: function ( v ) {
  1705. if ( this.x < v.x ) {
  1706. this.x = v.x;
  1707. }
  1708. if ( this.y < v.y ) {
  1709. this.y = v.y;
  1710. }
  1711. if ( this.z < v.z ) {
  1712. this.z = v.z;
  1713. }
  1714. if ( this.w < v.w ) {
  1715. this.w = v.w;
  1716. }
  1717. return this;
  1718. },
  1719. clamp: function ( min, max ) {
  1720. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1721. if ( this.x < min.x ) {
  1722. this.x = min.x;
  1723. } else if ( this.x > max.x ) {
  1724. this.x = max.x;
  1725. }
  1726. if ( this.y < min.y ) {
  1727. this.y = min.y;
  1728. } else if ( this.y > max.y ) {
  1729. this.y = max.y;
  1730. }
  1731. if ( this.z < min.z ) {
  1732. this.z = min.z;
  1733. } else if ( this.z > max.z ) {
  1734. this.z = max.z;
  1735. }
  1736. if ( this.w < min.w ) {
  1737. this.w = min.w;
  1738. } else if ( this.w > max.w ) {
  1739. this.w = max.w;
  1740. }
  1741. return this;
  1742. },
  1743. clampScalar: ( function () {
  1744. var min, max;
  1745. return function ( minVal, maxVal ) {
  1746. if ( min === undefined ) {
  1747. min = new THREE.Vector4();
  1748. max = new THREE.Vector4();
  1749. }
  1750. min.set( minVal, minVal, minVal, minVal );
  1751. max.set( maxVal, maxVal, maxVal, maxVal );
  1752. return this.clamp( min, max );
  1753. };
  1754. } )(),
  1755. floor: function () {
  1756. this.x = Math.floor( this.x );
  1757. this.y = Math.floor( this.y );
  1758. this.z = Math.floor( this.z );
  1759. this.w = Math.floor( this.w );
  1760. return this;
  1761. },
  1762. ceil: function () {
  1763. this.x = Math.ceil( this.x );
  1764. this.y = Math.ceil( this.y );
  1765. this.z = Math.ceil( this.z );
  1766. this.w = Math.ceil( this.w );
  1767. return this;
  1768. },
  1769. round: function () {
  1770. this.x = Math.round( this.x );
  1771. this.y = Math.round( this.y );
  1772. this.z = Math.round( this.z );
  1773. this.w = Math.round( this.w );
  1774. return this;
  1775. },
  1776. roundToZero: function () {
  1777. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1778. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1779. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1780. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1781. return this;
  1782. },
  1783. negate: function () {
  1784. this.x = - this.x;
  1785. this.y = - this.y;
  1786. this.z = - this.z;
  1787. this.w = - this.w;
  1788. return this;
  1789. },
  1790. dot: function ( v ) {
  1791. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1792. },
  1793. lengthSq: function () {
  1794. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1795. },
  1796. length: function () {
  1797. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1798. },
  1799. lengthManhattan: function () {
  1800. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1801. },
  1802. normalize: function () {
  1803. return this.divideScalar( this.length() );
  1804. },
  1805. setLength: function ( l ) {
  1806. var oldLength = this.length();
  1807. if ( oldLength !== 0 && l !== oldLength ) {
  1808. this.multiplyScalar( l / oldLength );
  1809. }
  1810. return this;
  1811. },
  1812. lerp: function ( v, alpha ) {
  1813. this.x += ( v.x - this.x ) * alpha;
  1814. this.y += ( v.y - this.y ) * alpha;
  1815. this.z += ( v.z - this.z ) * alpha;
  1816. this.w += ( v.w - this.w ) * alpha;
  1817. return this;
  1818. },
  1819. lerpVectors: function ( v1, v2, alpha ) {
  1820. this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1821. return this;
  1822. },
  1823. equals: function ( v ) {
  1824. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1825. },
  1826. fromArray: function ( array, offset ) {
  1827. if ( offset === undefined ) offset = 0;
  1828. this.x = array[ offset ];
  1829. this.y = array[ offset + 1 ];
  1830. this.z = array[ offset + 2 ];
  1831. this.w = array[ offset + 3 ];
  1832. return this;
  1833. },
  1834. toArray: function ( array, offset ) {
  1835. if ( array === undefined ) array = [];
  1836. if ( offset === undefined ) offset = 0;
  1837. array[ offset ] = this.x;
  1838. array[ offset + 1 ] = this.y;
  1839. array[ offset + 2 ] = this.z;
  1840. array[ offset + 3 ] = this.w;
  1841. return array;
  1842. },
  1843. fromAttribute: function ( attribute, index, offset ) {
  1844. if ( offset === undefined ) offset = 0;
  1845. index = index * attribute.itemSize + offset;
  1846. this.x = attribute.array[ index ];
  1847. this.y = attribute.array[ index + 1 ];
  1848. this.z = attribute.array[ index + 2 ];
  1849. this.w = attribute.array[ index + 3 ];
  1850. return this;
  1851. },
  1852. clone: function () {
  1853. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  1854. }
  1855. };
  1856. // File:src/math/Euler.js
  1857. /**
  1858. * @author mrdoob / http://mrdoob.com/
  1859. * @author WestLangley / http://github.com/WestLangley
  1860. * @author bhouston / http://exocortex.com
  1861. */
  1862. THREE.Euler = function ( x, y, z, order ) {
  1863. this._x = x || 0;
  1864. this._y = y || 0;
  1865. this._z = z || 0;
  1866. this._order = order || THREE.Euler.DefaultOrder;
  1867. };
  1868. THREE.Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  1869. THREE.Euler.DefaultOrder = 'XYZ';
  1870. THREE.Euler.prototype = {
  1871. constructor: THREE.Euler,
  1872. _x: 0, _y: 0, _z: 0, _order: THREE.Euler.DefaultOrder,
  1873. get x () {
  1874. return this._x;
  1875. },
  1876. set x ( value ) {
  1877. this._x = value;
  1878. this.onChangeCallback();
  1879. },
  1880. get y () {
  1881. return this._y;
  1882. },
  1883. set y ( value ) {
  1884. this._y = value;
  1885. this.onChangeCallback();
  1886. },
  1887. get z () {
  1888. return this._z;
  1889. },
  1890. set z ( value ) {
  1891. this._z = value;
  1892. this.onChangeCallback();
  1893. },
  1894. get order () {
  1895. return this._order;
  1896. },
  1897. set order ( value ) {
  1898. this._order = value;
  1899. this.onChangeCallback();
  1900. },
  1901. set: function ( x, y, z, order ) {
  1902. this._x = x;
  1903. this._y = y;
  1904. this._z = z;
  1905. this._order = order || this._order;
  1906. this.onChangeCallback();
  1907. return this;
  1908. },
  1909. copy: function ( euler ) {
  1910. this._x = euler._x;
  1911. this._y = euler._y;
  1912. this._z = euler._z;
  1913. this._order = euler._order;
  1914. this.onChangeCallback();
  1915. return this;
  1916. },
  1917. setFromRotationMatrix: function ( m, order, update ) {
  1918. var clamp = THREE.Math.clamp;
  1919. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1920. var te = m.elements;
  1921. var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  1922. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  1923. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1924. order = order || this._order;
  1925. if ( order === 'XYZ' ) {
  1926. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  1927. if ( Math.abs( m13 ) < 0.99999 ) {
  1928. this._x = Math.atan2( - m23, m33 );
  1929. this._z = Math.atan2( - m12, m11 );
  1930. } else {
  1931. this._x = Math.atan2( m32, m22 );
  1932. this._z = 0;
  1933. }
  1934. } else if ( order === 'YXZ' ) {
  1935. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  1936. if ( Math.abs( m23 ) < 0.99999 ) {
  1937. this._y = Math.atan2( m13, m33 );
  1938. this._z = Math.atan2( m21, m22 );
  1939. } else {
  1940. this._y = Math.atan2( - m31, m11 );
  1941. this._z = 0;
  1942. }
  1943. } else if ( order === 'ZXY' ) {
  1944. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  1945. if ( Math.abs( m32 ) < 0.99999 ) {
  1946. this._y = Math.atan2( - m31, m33 );
  1947. this._z = Math.atan2( - m12, m22 );
  1948. } else {
  1949. this._y = 0;
  1950. this._z = Math.atan2( m21, m11 );
  1951. }
  1952. } else if ( order === 'ZYX' ) {
  1953. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  1954. if ( Math.abs( m31 ) < 0.99999 ) {
  1955. this._x = Math.atan2( m32, m33 );
  1956. this._z = Math.atan2( m21, m11 );
  1957. } else {
  1958. this._x = 0;
  1959. this._z = Math.atan2( - m12, m22 );
  1960. }
  1961. } else if ( order === 'YZX' ) {
  1962. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  1963. if ( Math.abs( m21 ) < 0.99999 ) {
  1964. this._x = Math.atan2( - m23, m22 );
  1965. this._y = Math.atan2( - m31, m11 );
  1966. } else {
  1967. this._x = 0;
  1968. this._y = Math.atan2( m13, m33 );
  1969. }
  1970. } else if ( order === 'XZY' ) {
  1971. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  1972. if ( Math.abs( m12 ) < 0.99999 ) {
  1973. this._x = Math.atan2( m32, m22 );
  1974. this._y = Math.atan2( m13, m11 );
  1975. } else {
  1976. this._x = Math.atan2( - m23, m33 );
  1977. this._y = 0;
  1978. }
  1979. } else {
  1980. console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order )
  1981. }
  1982. this._order = order;
  1983. if ( update !== false ) this.onChangeCallback();
  1984. return this;
  1985. },
  1986. setFromQuaternion: function () {
  1987. var matrix;
  1988. return function ( q, order, update ) {
  1989. if ( matrix === undefined ) matrix = new THREE.Matrix4();
  1990. matrix.makeRotationFromQuaternion( q );
  1991. this.setFromRotationMatrix( matrix, order, update );
  1992. return this;
  1993. };
  1994. }(),
  1995. setFromVector3: function ( v, order ) {
  1996. return this.set( v.x, v.y, v.z, order || this._order );
  1997. },
  1998. reorder: function () {
  1999. // WARNING: this discards revolution information -bhouston
  2000. var q = new THREE.Quaternion();
  2001. return function ( newOrder ) {
  2002. q.setFromEuler( this );
  2003. this.setFromQuaternion( q, newOrder );
  2004. };
  2005. }(),
  2006. equals: function ( euler ) {
  2007. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  2008. },
  2009. fromArray: function ( array ) {
  2010. this._x = array[ 0 ];
  2011. this._y = array[ 1 ];
  2012. this._z = array[ 2 ];
  2013. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  2014. this.onChangeCallback();
  2015. return this;
  2016. },
  2017. toArray: function ( array, offset ) {
  2018. if ( array === undefined ) array = [];
  2019. if ( offset === undefined ) offset = 0;
  2020. array[ offset ] = this._x;
  2021. array[ offset + 1 ] = this._y;
  2022. array[ offset + 2 ] = this._z;
  2023. array[ offset + 3 ] = this._order;
  2024. return array;
  2025. },
  2026. toVector3: function ( optionalResult ) {
  2027. if ( optionalResult ) {
  2028. return optionalResult.set( this._x, this._y, this._z );
  2029. } else {
  2030. return new THREE.Vector3( this._x, this._y, this._z );
  2031. }
  2032. },
  2033. onChange: function ( callback ) {
  2034. this.onChangeCallback = callback;
  2035. return this;
  2036. },
  2037. onChangeCallback: function () {},
  2038. clone: function () {
  2039. return new THREE.Euler( this._x, this._y, this._z, this._order );
  2040. }
  2041. };
  2042. // File:src/math/Line3.js
  2043. /**
  2044. * @author bhouston / http://exocortex.com
  2045. */
  2046. THREE.Line3 = function ( start, end ) {
  2047. this.start = ( start !== undefined ) ? start : new THREE.Vector3();
  2048. this.end = ( end !== undefined ) ? end : new THREE.Vector3();
  2049. };
  2050. THREE.Line3.prototype = {
  2051. constructor: THREE.Line3,
  2052. set: function ( start, end ) {
  2053. this.start.copy( start );
  2054. this.end.copy( end );
  2055. return this;
  2056. },
  2057. copy: function ( line ) {
  2058. this.start.copy( line.start );
  2059. this.end.copy( line.end );
  2060. return this;
  2061. },
  2062. center: function ( optionalTarget ) {
  2063. var result = optionalTarget || new THREE.Vector3();
  2064. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  2065. },
  2066. delta: function ( optionalTarget ) {
  2067. var result = optionalTarget || new THREE.Vector3();
  2068. return result.subVectors( this.end, this.start );
  2069. },
  2070. distanceSq: function () {
  2071. return this.start.distanceToSquared( this.end );
  2072. },
  2073. distance: function () {
  2074. return this.start.distanceTo( this.end );
  2075. },
  2076. at: function ( t, optionalTarget ) {
  2077. var result = optionalTarget || new THREE.Vector3();
  2078. return this.delta( result ).multiplyScalar( t ).add( this.start );
  2079. },
  2080. closestPointToPointParameter: function () {
  2081. var startP = new THREE.Vector3();
  2082. var startEnd = new THREE.Vector3();
  2083. return function ( point, clampToLine ) {
  2084. startP.subVectors( point, this.start );
  2085. startEnd.subVectors( this.end, this.start );
  2086. var startEnd2 = startEnd.dot( startEnd );
  2087. var startEnd_startP = startEnd.dot( startP );
  2088. var t = startEnd_startP / startEnd2;
  2089. if ( clampToLine ) {
  2090. t = THREE.Math.clamp( t, 0, 1 );
  2091. }
  2092. return t;
  2093. };
  2094. }(),
  2095. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  2096. var t = this.closestPointToPointParameter( point, clampToLine );
  2097. var result = optionalTarget || new THREE.Vector3();
  2098. return this.delta( result ).multiplyScalar( t ).add( this.start );
  2099. },
  2100. applyMatrix4: function ( matrix ) {
  2101. this.start.applyMatrix4( matrix );
  2102. this.end.applyMatrix4( matrix );
  2103. return this;
  2104. },
  2105. equals: function ( line ) {
  2106. return line.start.equals( this.start ) && line.end.equals( this.end );
  2107. },
  2108. clone: function () {
  2109. return new THREE.Line3().copy( this );
  2110. }
  2111. };
  2112. // File:src/math/Box2.js
  2113. /**
  2114. * @author bhouston / http://exocortex.com
  2115. */
  2116. THREE.Box2 = function ( min, max ) {
  2117. this.min = ( min !== undefined ) ? min : new THREE.Vector2( Infinity, Infinity );
  2118. this.max = ( max !== undefined ) ? max : new THREE.Vector2( - Infinity, - Infinity );
  2119. };
  2120. THREE.Box2.prototype = {
  2121. constructor: THREE.Box2,
  2122. set: function ( min, max ) {
  2123. this.min.copy( min );
  2124. this.max.copy( max );
  2125. return this;
  2126. },
  2127. setFromPoints: function ( points ) {
  2128. this.makeEmpty();
  2129. for ( var i = 0, il = points.length; i < il; i ++ ) {
  2130. this.expandByPoint( points[ i ] )
  2131. }
  2132. return this;
  2133. },
  2134. setFromCenterAndSize: function () {
  2135. var v1 = new THREE.Vector2();
  2136. return function ( center, size ) {
  2137. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2138. this.min.copy( center ).sub( halfSize );
  2139. this.max.copy( center ).add( halfSize );
  2140. return this;
  2141. };
  2142. }(),
  2143. copy: function ( box ) {
  2144. this.min.copy( box.min );
  2145. this.max.copy( box.max );
  2146. return this;
  2147. },
  2148. makeEmpty: function () {
  2149. this.min.x = this.min.y = Infinity;
  2150. this.max.x = this.max.y = - Infinity;
  2151. return this;
  2152. },
  2153. empty: function () {
  2154. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2155. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  2156. },
  2157. center: function ( optionalTarget ) {
  2158. var result = optionalTarget || new THREE.Vector2();
  2159. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2160. },
  2161. size: function ( optionalTarget ) {
  2162. var result = optionalTarget || new THREE.Vector2();
  2163. return result.subVectors( this.max, this.min );
  2164. },
  2165. expandByPoint: function ( point ) {
  2166. this.min.min( point );
  2167. this.max.max( point );
  2168. return this;
  2169. },
  2170. expandByVector: function ( vector ) {
  2171. this.min.sub( vector );
  2172. this.max.add( vector );
  2173. return this;
  2174. },
  2175. expandByScalar: function ( scalar ) {
  2176. this.min.addScalar( - scalar );
  2177. this.max.addScalar( scalar );
  2178. return this;
  2179. },
  2180. containsPoint: function ( point ) {
  2181. if ( point.x < this.min.x || point.x > this.max.x ||
  2182. point.y < this.min.y || point.y > this.max.y ) {
  2183. return false;
  2184. }
  2185. return true;
  2186. },
  2187. containsBox: function ( box ) {
  2188. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2189. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  2190. return true;
  2191. }
  2192. return false;
  2193. },
  2194. getParameter: function ( point, optionalTarget ) {
  2195. // This can potentially have a divide by zero if the box
  2196. // has a size dimension of 0.
  2197. var result = optionalTarget || new THREE.Vector2();
  2198. return result.set(
  2199. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2200. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  2201. );
  2202. },
  2203. isIntersectionBox: function ( box ) {
  2204. // using 6 splitting planes to rule out intersections.
  2205. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2206. box.max.y < this.min.y || box.min.y > this.max.y ) {
  2207. return false;
  2208. }
  2209. return true;
  2210. },
  2211. clampPoint: function ( point, optionalTarget ) {
  2212. var result = optionalTarget || new THREE.Vector2();
  2213. return result.copy( point ).clamp( this.min, this.max );
  2214. },
  2215. distanceToPoint: function () {
  2216. var v1 = new THREE.Vector2();
  2217. return function ( point ) {
  2218. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2219. return clampedPoint.sub( point ).length();
  2220. };
  2221. }(),
  2222. intersect: function ( box ) {
  2223. this.min.max( box.min );
  2224. this.max.min( box.max );
  2225. return this;
  2226. },
  2227. union: function ( box ) {
  2228. this.min.min( box.min );
  2229. this.max.max( box.max );
  2230. return this;
  2231. },
  2232. translate: function ( offset ) {
  2233. this.min.add( offset );
  2234. this.max.add( offset );
  2235. return this;
  2236. },
  2237. equals: function ( box ) {
  2238. return box.min.equals( this.min ) && box.max.equals( this.max );
  2239. },
  2240. clone: function () {
  2241. return new THREE.Box2().copy( this );
  2242. }
  2243. };
  2244. // File:src/math/Box3.js
  2245. /**
  2246. * @author bhouston / http://exocortex.com
  2247. * @author WestLangley / http://github.com/WestLangley
  2248. */
  2249. THREE.Box3 = function ( min, max ) {
  2250. this.min = ( min !== undefined ) ? min : new THREE.Vector3( Infinity, Infinity, Infinity );
  2251. this.max = ( max !== undefined ) ? max : new THREE.Vector3( - Infinity, - Infinity, - Infinity );
  2252. };
  2253. THREE.Box3.prototype = {
  2254. constructor: THREE.Box3,
  2255. set: function ( min, max ) {
  2256. this.min.copy( min );
  2257. this.max.copy( max );
  2258. return this;
  2259. },
  2260. setFromPoints: function ( points ) {
  2261. this.makeEmpty();
  2262. for ( var i = 0, il = points.length; i < il; i ++ ) {
  2263. this.expandByPoint( points[ i ] );
  2264. }
  2265. return this;
  2266. },
  2267. setFromCenterAndSize: function () {
  2268. var v1 = new THREE.Vector3();
  2269. return function ( center, size ) {
  2270. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2271. this.min.copy( center ).sub( halfSize );
  2272. this.max.copy( center ).add( halfSize );
  2273. return this;
  2274. };
  2275. }(),
  2276. setFromObject: function () {
  2277. // Computes the world-axis-aligned bounding box of an object (including its children),
  2278. // accounting for both the object's, and childrens', world transforms
  2279. var v1 = new THREE.Vector3();
  2280. return function ( object ) {
  2281. var scope = this;
  2282. object.updateMatrixWorld( true );
  2283. this.makeEmpty();
  2284. object.traverse( function ( node ) {
  2285. var geometry = node.geometry;
  2286. if ( geometry !== undefined ) {
  2287. if ( geometry instanceof THREE.Geometry ) {
  2288. var vertices = geometry.vertices;
  2289. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  2290. v1.copy( vertices[ i ] );
  2291. v1.applyMatrix4( node.matrixWorld );
  2292. scope.expandByPoint( v1 );
  2293. }
  2294. } else if ( geometry instanceof THREE.BufferGeometry && geometry.attributes[ 'position' ] !== undefined ) {
  2295. var positions = geometry.attributes[ 'position' ].array;
  2296. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  2297. v1.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  2298. v1.applyMatrix4( node.matrixWorld );
  2299. scope.expandByPoint( v1 );
  2300. }
  2301. }
  2302. }
  2303. } );
  2304. return this;
  2305. };
  2306. }(),
  2307. copy: function ( box ) {
  2308. this.min.copy( box.min );
  2309. this.max.copy( box.max );
  2310. return this;
  2311. },
  2312. makeEmpty: function () {
  2313. this.min.x = this.min.y = this.min.z = Infinity;
  2314. this.max.x = this.max.y = this.max.z = - Infinity;
  2315. return this;
  2316. },
  2317. empty: function () {
  2318. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2319. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2320. },
  2321. center: function ( optionalTarget ) {
  2322. var result = optionalTarget || new THREE.Vector3();
  2323. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2324. },
  2325. size: function ( optionalTarget ) {
  2326. var result = optionalTarget || new THREE.Vector3();
  2327. return result.subVectors( this.max, this.min );
  2328. },
  2329. expandByPoint: function ( point ) {
  2330. this.min.min( point );
  2331. this.max.max( point );
  2332. return this;
  2333. },
  2334. expandByVector: function ( vector ) {
  2335. this.min.sub( vector );
  2336. this.max.add( vector );
  2337. return this;
  2338. },
  2339. expandByScalar: function ( scalar ) {
  2340. this.min.addScalar( - scalar );
  2341. this.max.addScalar( scalar );
  2342. return this;
  2343. },
  2344. containsPoint: function ( point ) {
  2345. if ( point.x < this.min.x || point.x > this.max.x ||
  2346. point.y < this.min.y || point.y > this.max.y ||
  2347. point.z < this.min.z || point.z > this.max.z ) {
  2348. return false;
  2349. }
  2350. return true;
  2351. },
  2352. containsBox: function ( box ) {
  2353. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2354. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  2355. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  2356. return true;
  2357. }
  2358. return false;
  2359. },
  2360. getParameter: function ( point, optionalTarget ) {
  2361. // This can potentially have a divide by zero if the box
  2362. // has a size dimension of 0.
  2363. var result = optionalTarget || new THREE.Vector3();
  2364. return result.set(
  2365. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2366. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2367. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2368. );
  2369. },
  2370. isIntersectionBox: function ( box ) {
  2371. // using 6 splitting planes to rule out intersections.
  2372. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2373. box.max.y < this.min.y || box.min.y > this.max.y ||
  2374. box.max.z < this.min.z || box.min.z > this.max.z ) {
  2375. return false;
  2376. }
  2377. return true;
  2378. },
  2379. clampPoint: function ( point, optionalTarget ) {
  2380. var result = optionalTarget || new THREE.Vector3();
  2381. return result.copy( point ).clamp( this.min, this.max );
  2382. },
  2383. distanceToPoint: function () {
  2384. var v1 = new THREE.Vector3();
  2385. return function ( point ) {
  2386. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2387. return clampedPoint.sub( point ).length();
  2388. };
  2389. }(),
  2390. getBoundingSphere: function () {
  2391. var v1 = new THREE.Vector3();
  2392. return function ( optionalTarget ) {
  2393. var result = optionalTarget || new THREE.Sphere();
  2394. result.center = this.center();
  2395. result.radius = this.size( v1 ).length() * 0.5;
  2396. return result;
  2397. };
  2398. }(),
  2399. intersect: function ( box ) {
  2400. this.min.max( box.min );
  2401. this.max.min( box.max );
  2402. return this;
  2403. },
  2404. union: function ( box ) {
  2405. this.min.min( box.min );
  2406. this.max.max( box.max );
  2407. return this;
  2408. },
  2409. applyMatrix4: function () {
  2410. var points = [
  2411. new THREE.Vector3(),
  2412. new THREE.Vector3(),
  2413. new THREE.Vector3(),
  2414. new THREE.Vector3(),
  2415. new THREE.Vector3(),
  2416. new THREE.Vector3(),
  2417. new THREE.Vector3(),
  2418. new THREE.Vector3()
  2419. ];
  2420. return function ( matrix ) {
  2421. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2422. points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2423. points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2424. points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2425. points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2426. points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2427. points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2428. points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2429. points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2430. this.makeEmpty();
  2431. this.setFromPoints( points );
  2432. return this;
  2433. };
  2434. }(),
  2435. translate: function ( offset ) {
  2436. this.min.add( offset );
  2437. this.max.add( offset );
  2438. return this;
  2439. },
  2440. equals: function ( box ) {
  2441. return box.min.equals( this.min ) && box.max.equals( this.max );
  2442. },
  2443. clone: function () {
  2444. return new THREE.Box3().copy( this );
  2445. }
  2446. };
  2447. // File:src/math/Matrix3.js
  2448. /**
  2449. * @author alteredq / http://alteredqualia.com/
  2450. * @author WestLangley / http://github.com/WestLangley
  2451. * @author bhouston / http://exocortex.com
  2452. */
  2453. THREE.Matrix3 = function () {
  2454. this.elements = new Float32Array( [
  2455. 1, 0, 0,
  2456. 0, 1, 0,
  2457. 0, 0, 1
  2458. ] );
  2459. if ( arguments.length > 0 ) {
  2460. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  2461. }
  2462. };
  2463. THREE.Matrix3.prototype = {
  2464. constructor: THREE.Matrix3,
  2465. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2466. var te = this.elements;
  2467. te[ 0 ] = n11; te[ 3 ] = n12; te[ 6 ] = n13;
  2468. te[ 1 ] = n21; te[ 4 ] = n22; te[ 7 ] = n23;
  2469. te[ 2 ] = n31; te[ 5 ] = n32; te[ 8 ] = n33;
  2470. return this;
  2471. },
  2472. identity: function () {
  2473. this.set(
  2474. 1, 0, 0,
  2475. 0, 1, 0,
  2476. 0, 0, 1
  2477. );
  2478. return this;
  2479. },
  2480. copy: function ( m ) {
  2481. var me = m.elements;
  2482. this.set(
  2483. me[ 0 ], me[ 3 ], me[ 6 ],
  2484. me[ 1 ], me[ 4 ], me[ 7 ],
  2485. me[ 2 ], me[ 5 ], me[ 8 ]
  2486. );
  2487. return this;
  2488. },
  2489. multiplyVector3: function ( vector ) {
  2490. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  2491. return vector.applyMatrix3( this );
  2492. },
  2493. multiplyVector3Array: function ( a ) {
  2494. console.warn( 'THREE.Matrix3: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  2495. return this.applyToVector3Array( a );
  2496. },
  2497. applyToVector3Array: function () {
  2498. var v1;
  2499. return function ( array, offset, length ) {
  2500. if ( v1 === undefined ) v1 = new THREE.Vector3();
  2501. if ( offset === undefined ) offset = 0;
  2502. if ( length === undefined ) length = array.length;
  2503. for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) {
  2504. v1.fromArray( array, j );
  2505. v1.applyMatrix3( this );
  2506. v1.toArray( array, j );
  2507. }
  2508. return array;
  2509. };
  2510. }(),
  2511. applyToBuffer: function () {
  2512. var v1;
  2513. return function applyToBuffer( buffer, offset, length ) {
  2514. if ( v1 === undefined ) v1 = new THREE.Vector3();
  2515. if ( offset === undefined ) offset = 0;
  2516. if ( length === undefined ) length = buffer.length / buffer.itemSize;
  2517. for ( var i = 0, j = offset; i < length; i ++, j ++ ) {
  2518. v1.x = buffer.getX( j );
  2519. v1.y = buffer.getY( j );
  2520. v1.z = buffer.getZ( j );
  2521. v1.applyMatrix3( this );
  2522. buffer.setXYZ( v1.x, v1.y, v1.z );
  2523. }
  2524. return buffer;
  2525. };
  2526. }(),
  2527. multiplyScalar: function ( s ) {
  2528. var te = this.elements;
  2529. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  2530. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  2531. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  2532. return this;
  2533. },
  2534. determinant: function () {
  2535. var te = this.elements;
  2536. var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  2537. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  2538. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  2539. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  2540. },
  2541. getInverse: function ( matrix, throwOnInvertible ) {
  2542. // input: THREE.Matrix4
  2543. // ( based on http://code.google.com/p/webgl-mjs/ )
  2544. var me = matrix.elements;
  2545. var te = this.elements;
  2546. te[ 0 ] = me[ 10 ] * me[ 5 ] - me[ 6 ] * me[ 9 ];
  2547. te[ 1 ] = - me[ 10 ] * me[ 1 ] + me[ 2 ] * me[ 9 ];
  2548. te[ 2 ] = me[ 6 ] * me[ 1 ] - me[ 2 ] * me[ 5 ];
  2549. te[ 3 ] = - me[ 10 ] * me[ 4 ] + me[ 6 ] * me[ 8 ];
  2550. te[ 4 ] = me[ 10 ] * me[ 0 ] - me[ 2 ] * me[ 8 ];
  2551. te[ 5 ] = - me[ 6 ] * me[ 0 ] + me[ 2 ] * me[ 4 ];
  2552. te[ 6 ] = me[ 9 ] * me[ 4 ] - me[ 5 ] * me[ 8 ];
  2553. te[ 7 ] = - me[ 9 ] * me[ 0 ] + me[ 1 ] * me[ 8 ];
  2554. te[ 8 ] = me[ 5 ] * me[ 0 ] - me[ 1 ] * me[ 4 ];
  2555. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ];
  2556. // no inverse
  2557. if ( det === 0 ) {
  2558. var msg = "Matrix3.getInverse(): can't invert matrix, determinant is 0";
  2559. if ( throwOnInvertible || false ) {
  2560. throw new Error( msg );
  2561. } else {
  2562. console.warn( msg );
  2563. }
  2564. this.identity();
  2565. return this;
  2566. }
  2567. this.multiplyScalar( 1.0 / det );
  2568. return this;
  2569. },
  2570. transpose: function () {
  2571. var tmp, m = this.elements;
  2572. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  2573. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  2574. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  2575. return this;
  2576. },
  2577. flattenToArrayOffset: function ( array, offset ) {
  2578. var te = this.elements;
  2579. array[ offset ] = te[ 0 ];
  2580. array[ offset + 1 ] = te[ 1 ];
  2581. array[ offset + 2 ] = te[ 2 ];
  2582. array[ offset + 3 ] = te[ 3 ];
  2583. array[ offset + 4 ] = te[ 4 ];
  2584. array[ offset + 5 ] = te[ 5 ];
  2585. array[ offset + 6 ] = te[ 6 ];
  2586. array[ offset + 7 ] = te[ 7 ];
  2587. array[ offset + 8 ] = te[ 8 ];
  2588. return array;
  2589. },
  2590. getNormalMatrix: function ( m ) {
  2591. // input: THREE.Matrix4
  2592. this.getInverse( m ).transpose();
  2593. return this;
  2594. },
  2595. transposeIntoArray: function ( r ) {
  2596. var m = this.elements;
  2597. r[ 0 ] = m[ 0 ];
  2598. r[ 1 ] = m[ 3 ];
  2599. r[ 2 ] = m[ 6 ];
  2600. r[ 3 ] = m[ 1 ];
  2601. r[ 4 ] = m[ 4 ];
  2602. r[ 5 ] = m[ 7 ];
  2603. r[ 6 ] = m[ 2 ];
  2604. r[ 7 ] = m[ 5 ];
  2605. r[ 8 ] = m[ 8 ];
  2606. return this;
  2607. },
  2608. fromArray: function ( array ) {
  2609. this.elements.set( array );
  2610. return this;
  2611. },
  2612. toArray: function () {
  2613. var te = this.elements;
  2614. return [
  2615. te[ 0 ], te[ 1 ], te[ 2 ],
  2616. te[ 3 ], te[ 4 ], te[ 5 ],
  2617. te[ 6 ], te[ 7 ], te[ 8 ]
  2618. ];
  2619. },
  2620. clone: function () {
  2621. return new THREE.Matrix3().fromArray( this.elements );
  2622. }
  2623. };
  2624. // File:src/math/Matrix4.js
  2625. /**
  2626. * @author mrdoob / http://mrdoob.com/
  2627. * @author supereggbert / http://www.paulbrunt.co.uk/
  2628. * @author philogb / http://blog.thejit.org/
  2629. * @author jordi_ros / http://plattsoft.com
  2630. * @author D1plo1d / http://github.com/D1plo1d
  2631. * @author alteredq / http://alteredqualia.com/
  2632. * @author mikael emtinger / http://gomo.se/
  2633. * @author timknip / http://www.floorplanner.com/
  2634. * @author bhouston / http://exocortex.com
  2635. * @author WestLangley / http://github.com/WestLangley
  2636. */
  2637. THREE.Matrix4 = function () {
  2638. this.elements = new Float32Array( [
  2639. 1, 0, 0, 0,
  2640. 0, 1, 0, 0,
  2641. 0, 0, 1, 0,
  2642. 0, 0, 0, 1
  2643. ] );
  2644. if ( arguments.length > 0 ) {
  2645. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  2646. }
  2647. };
  2648. THREE.Matrix4.prototype = {
  2649. constructor: THREE.Matrix4,
  2650. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2651. var te = this.elements;
  2652. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  2653. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  2654. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  2655. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  2656. return this;
  2657. },
  2658. identity: function () {
  2659. this.set(
  2660. 1, 0, 0, 0,
  2661. 0, 1, 0, 0,
  2662. 0, 0, 1, 0,
  2663. 0, 0, 0, 1
  2664. );
  2665. return this;
  2666. },
  2667. copy: function ( m ) {
  2668. this.elements.set( m.elements );
  2669. return this;
  2670. },
  2671. extractPosition: function ( m ) {
  2672. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  2673. return this.copyPosition( m );
  2674. },
  2675. copyPosition: function ( m ) {
  2676. var te = this.elements;
  2677. var me = m.elements;
  2678. te[ 12 ] = me[ 12 ];
  2679. te[ 13 ] = me[ 13 ];
  2680. te[ 14 ] = me[ 14 ];
  2681. return this;
  2682. },
  2683. extractBasis: function ( xAxis, yAxis, zAxis ) {
  2684. var te = this.elements;
  2685. xAxis.set( te[ 0 ], te[ 1 ], te[ 2 ] );
  2686. yAxis.set( te[ 4 ], te[ 5 ], te[ 6 ] );
  2687. zAxis.set( te[ 8 ], te[ 9 ], te[ 10 ] );
  2688. return this;
  2689. },
  2690. makeBasis: function ( xAxis, yAxis, zAxis ) {
  2691. this.set(
  2692. xAxis.x, yAxis.x, zAxis.x, 0,
  2693. xAxis.y, yAxis.y, zAxis.y, 0,
  2694. xAxis.z, yAxis.z, zAxis.z, 0,
  2695. 0, 0, 0, 1
  2696. );
  2697. return this;
  2698. },
  2699. extractRotation: function () {
  2700. var v1;
  2701. return function ( m ) {
  2702. if ( v1 === undefined ) v1 = new THREE.Vector3();
  2703. var te = this.elements;
  2704. var me = m.elements;
  2705. var scaleX = 1 / v1.set( me[ 0 ], me[ 1 ], me[ 2 ] ).length();
  2706. var scaleY = 1 / v1.set( me[ 4 ], me[ 5 ], me[ 6 ] ).length();
  2707. var scaleZ = 1 / v1.set( me[ 8 ], me[ 9 ], me[ 10 ] ).length();
  2708. te[ 0 ] = me[ 0 ] * scaleX;
  2709. te[ 1 ] = me[ 1 ] * scaleX;
  2710. te[ 2 ] = me[ 2 ] * scaleX;
  2711. te[ 4 ] = me[ 4 ] * scaleY;
  2712. te[ 5 ] = me[ 5 ] * scaleY;
  2713. te[ 6 ] = me[ 6 ] * scaleY;
  2714. te[ 8 ] = me[ 8 ] * scaleZ;
  2715. te[ 9 ] = me[ 9 ] * scaleZ;
  2716. te[ 10 ] = me[ 10 ] * scaleZ;
  2717. return this;
  2718. };
  2719. }(),
  2720. makeRotationFromEuler: function ( euler ) {
  2721. if ( euler instanceof THREE.Euler === false ) {
  2722. console.error( 'THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  2723. }
  2724. var te = this.elements;
  2725. var x = euler.x, y = euler.y, z = euler.z;
  2726. var a = Math.cos( x ), b = Math.sin( x );
  2727. var c = Math.cos( y ), d = Math.sin( y );
  2728. var e = Math.cos( z ), f = Math.sin( z );
  2729. if ( euler.order === 'XYZ' ) {
  2730. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2731. te[ 0 ] = c * e;
  2732. te[ 4 ] = - c * f;
  2733. te[ 8 ] = d;
  2734. te[ 1 ] = af + be * d;
  2735. te[ 5 ] = ae - bf * d;
  2736. te[ 9 ] = - b * c;
  2737. te[ 2 ] = bf - ae * d;
  2738. te[ 6 ] = be + af * d;
  2739. te[ 10 ] = a * c;
  2740. } else if ( euler.order === 'YXZ' ) {
  2741. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2742. te[ 0 ] = ce + df * b;
  2743. te[ 4 ] = de * b - cf;
  2744. te[ 8 ] = a * d;
  2745. te[ 1 ] = a * f;
  2746. te[ 5 ] = a * e;
  2747. te[ 9 ] = - b;
  2748. te[ 2 ] = cf * b - de;
  2749. te[ 6 ] = df + ce * b;
  2750. te[ 10 ] = a * c;
  2751. } else if ( euler.order === 'ZXY' ) {
  2752. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2753. te[ 0 ] = ce - df * b;
  2754. te[ 4 ] = - a * f;
  2755. te[ 8 ] = de + cf * b;
  2756. te[ 1 ] = cf + de * b;
  2757. te[ 5 ] = a * e;
  2758. te[ 9 ] = df - ce * b;
  2759. te[ 2 ] = - a * d;
  2760. te[ 6 ] = b;
  2761. te[ 10 ] = a * c;
  2762. } else if ( euler.order === 'ZYX' ) {
  2763. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2764. te[ 0 ] = c * e;
  2765. te[ 4 ] = be * d - af;
  2766. te[ 8 ] = ae * d + bf;
  2767. te[ 1 ] = c * f;
  2768. te[ 5 ] = bf * d + ae;
  2769. te[ 9 ] = af * d - be;
  2770. te[ 2 ] = - d;
  2771. te[ 6 ] = b * c;
  2772. te[ 10 ] = a * c;
  2773. } else if ( euler.order === 'YZX' ) {
  2774. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2775. te[ 0 ] = c * e;
  2776. te[ 4 ] = bd - ac * f;
  2777. te[ 8 ] = bc * f + ad;
  2778. te[ 1 ] = f;
  2779. te[ 5 ] = a * e;
  2780. te[ 9 ] = - b * e;
  2781. te[ 2 ] = - d * e;
  2782. te[ 6 ] = ad * f + bc;
  2783. te[ 10 ] = ac - bd * f;
  2784. } else if ( euler.order === 'XZY' ) {
  2785. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2786. te[ 0 ] = c * e;
  2787. te[ 4 ] = - f;
  2788. te[ 8 ] = d * e;
  2789. te[ 1 ] = ac * f + bd;
  2790. te[ 5 ] = a * e;
  2791. te[ 9 ] = ad * f - bc;
  2792. te[ 2 ] = bc * f - ad;
  2793. te[ 6 ] = b * e;
  2794. te[ 10 ] = bd * f + ac;
  2795. }
  2796. // last column
  2797. te[ 3 ] = 0;
  2798. te[ 7 ] = 0;
  2799. te[ 11 ] = 0;
  2800. // bottom row
  2801. te[ 12 ] = 0;
  2802. te[ 13 ] = 0;
  2803. te[ 14 ] = 0;
  2804. te[ 15 ] = 1;
  2805. return this;
  2806. },
  2807. setRotationFromQuaternion: function ( q ) {
  2808. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  2809. return this.makeRotationFromQuaternion( q );
  2810. },
  2811. makeRotationFromQuaternion: function ( q ) {
  2812. var te = this.elements;
  2813. var x = q.x, y = q.y, z = q.z, w = q.w;
  2814. var x2 = x + x, y2 = y + y, z2 = z + z;
  2815. var xx = x * x2, xy = x * y2, xz = x * z2;
  2816. var yy = y * y2, yz = y * z2, zz = z * z2;
  2817. var wx = w * x2, wy = w * y2, wz = w * z2;
  2818. te[ 0 ] = 1 - ( yy + zz );
  2819. te[ 4 ] = xy - wz;
  2820. te[ 8 ] = xz + wy;
  2821. te[ 1 ] = xy + wz;
  2822. te[ 5 ] = 1 - ( xx + zz );
  2823. te[ 9 ] = yz - wx;
  2824. te[ 2 ] = xz - wy;
  2825. te[ 6 ] = yz + wx;
  2826. te[ 10 ] = 1 - ( xx + yy );
  2827. // last column
  2828. te[ 3 ] = 0;
  2829. te[ 7 ] = 0;
  2830. te[ 11 ] = 0;
  2831. // bottom row
  2832. te[ 12 ] = 0;
  2833. te[ 13 ] = 0;
  2834. te[ 14 ] = 0;
  2835. te[ 15 ] = 1;
  2836. return this;
  2837. },
  2838. lookAt: function () {
  2839. var x, y, z;
  2840. return function ( eye, target, up ) {
  2841. if ( x === undefined ) x = new THREE.Vector3();
  2842. if ( y === undefined ) y = new THREE.Vector3();
  2843. if ( z === undefined ) z = new THREE.Vector3();
  2844. var te = this.elements;
  2845. z.subVectors( eye, target ).normalize();
  2846. if ( z.length() === 0 ) {
  2847. z.z = 1;
  2848. }
  2849. x.crossVectors( up, z ).normalize();
  2850. if ( x.length() === 0 ) {
  2851. z.x += 0.0001;
  2852. x.crossVectors( up, z ).normalize();
  2853. }
  2854. y.crossVectors( z, x );
  2855. te[ 0 ] = x.x; te[ 4 ] = y.x; te[ 8 ] = z.x;
  2856. te[ 1 ] = x.y; te[ 5 ] = y.y; te[ 9 ] = z.y;
  2857. te[ 2 ] = x.z; te[ 6 ] = y.z; te[ 10 ] = z.z;
  2858. return this;
  2859. };
  2860. }(),
  2861. multiply: function ( m, n ) {
  2862. if ( n !== undefined ) {
  2863. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2864. return this.multiplyMatrices( m, n );
  2865. }
  2866. return this.multiplyMatrices( this, m );
  2867. },
  2868. multiplyMatrices: function ( a, b ) {
  2869. var ae = a.elements;
  2870. var be = b.elements;
  2871. var te = this.elements;
  2872. var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  2873. var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  2874. var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  2875. var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  2876. var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  2877. var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  2878. var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  2879. var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  2880. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2881. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2882. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2883. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2884. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2885. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2886. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2887. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2888. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2889. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2890. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2891. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2892. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2893. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2894. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2895. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2896. return this;
  2897. },
  2898. multiplyToArray: function ( a, b, r ) {
  2899. var te = this.elements;
  2900. this.multiplyMatrices( a, b );
  2901. r[ 0 ] = te[ 0 ]; r[ 1 ] = te[ 1 ]; r[ 2 ] = te[ 2 ]; r[ 3 ] = te[ 3 ];
  2902. r[ 4 ] = te[ 4 ]; r[ 5 ] = te[ 5 ]; r[ 6 ] = te[ 6 ]; r[ 7 ] = te[ 7 ];
  2903. r[ 8 ] = te[ 8 ]; r[ 9 ] = te[ 9 ]; r[ 10 ] = te[ 10 ]; r[ 11 ] = te[ 11 ];
  2904. r[ 12 ] = te[ 12 ]; r[ 13 ] = te[ 13 ]; r[ 14 ] = te[ 14 ]; r[ 15 ] = te[ 15 ];
  2905. return this;
  2906. },
  2907. multiplyScalar: function ( s ) {
  2908. var te = this.elements;
  2909. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  2910. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  2911. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  2912. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  2913. return this;
  2914. },
  2915. multiplyVector3: function ( vector ) {
  2916. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  2917. return vector.applyProjection( this );
  2918. },
  2919. multiplyVector4: function ( vector ) {
  2920. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2921. return vector.applyMatrix4( this );
  2922. },
  2923. multiplyVector3Array: function ( a ) {
  2924. console.warn( 'THREE.Matrix4: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  2925. return this.applyToVector3Array( a );
  2926. },
  2927. applyToVector3Array: function () {
  2928. var v1;
  2929. return function ( array, offset, length ) {
  2930. if ( v1 === undefined ) v1 = new THREE.Vector3();
  2931. if ( offset === undefined ) offset = 0;
  2932. if ( length === undefined ) length = array.length;
  2933. for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) {
  2934. v1.fromArray( array, j );
  2935. v1.applyMatrix4( this );
  2936. v1.toArray( array, j );
  2937. }
  2938. return array;
  2939. };
  2940. }(),
  2941. applyToBuffer: function () {
  2942. var v1;
  2943. return function applyToBuffer( buffer, offset, length ) {
  2944. if ( v1 === undefined ) v1 = new THREE.Vector3();
  2945. if ( offset === undefined ) offset = 0;
  2946. if ( length === undefined ) length = buffer.length / buffer.itemSize;
  2947. for ( var i = 0, j = offset; i < length; i ++, j ++ ) {
  2948. v1.x = buffer.getX( j );
  2949. v1.y = buffer.getY( j );
  2950. v1.z = buffer.getZ( j );
  2951. v1.applyMatrix4( this );
  2952. buffer.setXYZ( v1.x, v1.y, v1.z );
  2953. }
  2954. return buffer;
  2955. };
  2956. }(),
  2957. rotateAxis: function ( v ) {
  2958. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  2959. v.transformDirection( this );
  2960. },
  2961. crossVector: function ( vector ) {
  2962. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2963. return vector.applyMatrix4( this );
  2964. },
  2965. determinant: function () {
  2966. var te = this.elements;
  2967. var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  2968. var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  2969. var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  2970. var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  2971. //TODO: make this more efficient
  2972. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2973. return (
  2974. n41 * (
  2975. + n14 * n23 * n32
  2976. - n13 * n24 * n32
  2977. - n14 * n22 * n33
  2978. + n12 * n24 * n33
  2979. + n13 * n22 * n34
  2980. - n12 * n23 * n34
  2981. ) +
  2982. n42 * (
  2983. + n11 * n23 * n34
  2984. - n11 * n24 * n33
  2985. + n14 * n21 * n33
  2986. - n13 * n21 * n34
  2987. + n13 * n24 * n31
  2988. - n14 * n23 * n31
  2989. ) +
  2990. n43 * (
  2991. + n11 * n24 * n32
  2992. - n11 * n22 * n34
  2993. - n14 * n21 * n32
  2994. + n12 * n21 * n34
  2995. + n14 * n22 * n31
  2996. - n12 * n24 * n31
  2997. ) +
  2998. n44 * (
  2999. - n13 * n22 * n31
  3000. - n11 * n23 * n32
  3001. + n11 * n22 * n33
  3002. + n13 * n21 * n32
  3003. - n12 * n21 * n33
  3004. + n12 * n23 * n31
  3005. )
  3006. );
  3007. },
  3008. transpose: function () {
  3009. var te = this.elements;
  3010. var tmp;
  3011. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  3012. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  3013. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  3014. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  3015. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  3016. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  3017. return this;
  3018. },
  3019. flattenToArrayOffset: function ( array, offset ) {
  3020. var te = this.elements;
  3021. array[ offset ] = te[ 0 ];
  3022. array[ offset + 1 ] = te[ 1 ];
  3023. array[ offset + 2 ] = te[ 2 ];
  3024. array[ offset + 3 ] = te[ 3 ];
  3025. array[ offset + 4 ] = te[ 4 ];
  3026. array[ offset + 5 ] = te[ 5 ];
  3027. array[ offset + 6 ] = te[ 6 ];
  3028. array[ offset + 7 ] = te[ 7 ];
  3029. array[ offset + 8 ] = te[ 8 ];
  3030. array[ offset + 9 ] = te[ 9 ];
  3031. array[ offset + 10 ] = te[ 10 ];
  3032. array[ offset + 11 ] = te[ 11 ];
  3033. array[ offset + 12 ] = te[ 12 ];
  3034. array[ offset + 13 ] = te[ 13 ];
  3035. array[ offset + 14 ] = te[ 14 ];
  3036. array[ offset + 15 ] = te[ 15 ];
  3037. return array;
  3038. },
  3039. getPosition: function () {
  3040. var v1;
  3041. return function () {
  3042. if ( v1 === undefined ) v1 = new THREE.Vector3();
  3043. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  3044. var te = this.elements;
  3045. return v1.set( te[ 12 ], te[ 13 ], te[ 14 ] );
  3046. };
  3047. }(),
  3048. setPosition: function ( v ) {
  3049. var te = this.elements;
  3050. te[ 12 ] = v.x;
  3051. te[ 13 ] = v.y;
  3052. te[ 14 ] = v.z;
  3053. return this;
  3054. },
  3055. getInverse: function ( m, throwOnInvertible ) {
  3056. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3057. var te = this.elements;
  3058. var me = m.elements;
  3059. var n11 = me[ 0 ], n12 = me[ 4 ], n13 = me[ 8 ], n14 = me[ 12 ];
  3060. var n21 = me[ 1 ], n22 = me[ 5 ], n23 = me[ 9 ], n24 = me[ 13 ];
  3061. var n31 = me[ 2 ], n32 = me[ 6 ], n33 = me[ 10 ], n34 = me[ 14 ];
  3062. var n41 = me[ 3 ], n42 = me[ 7 ], n43 = me[ 11 ], n44 = me[ 15 ];
  3063. te[ 0 ] = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44;
  3064. te[ 4 ] = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44;
  3065. te[ 8 ] = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44;
  3066. te[ 12 ] = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3067. te[ 1 ] = n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44;
  3068. te[ 5 ] = n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44;
  3069. te[ 9 ] = n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44;
  3070. te[ 13 ] = n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34;
  3071. te[ 2 ] = n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44;
  3072. te[ 6 ] = n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44;
  3073. te[ 10 ] = n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44;
  3074. te[ 14 ] = n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34;
  3075. te[ 3 ] = n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43;
  3076. te[ 7 ] = n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43;
  3077. te[ 11 ] = n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43;
  3078. te[ 15 ] = n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33;
  3079. var det = n11 * te[ 0 ] + n21 * te[ 4 ] + n31 * te[ 8 ] + n41 * te[ 12 ];
  3080. if ( det === 0 ) {
  3081. var msg = "THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0";
  3082. if ( throwOnInvertible || false ) {
  3083. throw new Error( msg );
  3084. } else {
  3085. console.warn( msg );
  3086. }
  3087. this.identity();
  3088. return this;
  3089. }
  3090. this.multiplyScalar( 1 / det );
  3091. return this;
  3092. },
  3093. translate: function ( v ) {
  3094. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  3095. },
  3096. rotateX: function ( angle ) {
  3097. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  3098. },
  3099. rotateY: function ( angle ) {
  3100. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  3101. },
  3102. rotateZ: function ( angle ) {
  3103. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  3104. },
  3105. rotateByAxis: function ( axis, angle ) {
  3106. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  3107. },
  3108. scale: function ( v ) {
  3109. var te = this.elements;
  3110. var x = v.x, y = v.y, z = v.z;
  3111. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  3112. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  3113. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  3114. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  3115. return this;
  3116. },
  3117. getMaxScaleOnAxis: function () {
  3118. var te = this.elements;
  3119. var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  3120. var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  3121. var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  3122. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  3123. },
  3124. makeTranslation: function ( x, y, z ) {
  3125. this.set(
  3126. 1, 0, 0, x,
  3127. 0, 1, 0, y,
  3128. 0, 0, 1, z,
  3129. 0, 0, 0, 1
  3130. );
  3131. return this;
  3132. },
  3133. makeRotationX: function ( theta ) {
  3134. var c = Math.cos( theta ), s = Math.sin( theta );
  3135. this.set(
  3136. 1, 0, 0, 0,
  3137. 0, c, - s, 0,
  3138. 0, s, c, 0,
  3139. 0, 0, 0, 1
  3140. );
  3141. return this;
  3142. },
  3143. makeRotationY: function ( theta ) {
  3144. var c = Math.cos( theta ), s = Math.sin( theta );
  3145. this.set(
  3146. c, 0, s, 0,
  3147. 0, 1, 0, 0,
  3148. - s, 0, c, 0,
  3149. 0, 0, 0, 1
  3150. );
  3151. return this;
  3152. },
  3153. makeRotationZ: function ( theta ) {
  3154. var c = Math.cos( theta ), s = Math.sin( theta );
  3155. this.set(
  3156. c, - s, 0, 0,
  3157. s, c, 0, 0,
  3158. 0, 0, 1, 0,
  3159. 0, 0, 0, 1
  3160. );
  3161. return this;
  3162. },
  3163. makeRotationAxis: function ( axis, angle ) {
  3164. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3165. var c = Math.cos( angle );
  3166. var s = Math.sin( angle );
  3167. var t = 1 - c;
  3168. var x = axis.x, y = axis.y, z = axis.z;
  3169. var tx = t * x, ty = t * y;
  3170. this.set(
  3171. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  3172. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3173. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3174. 0, 0, 0, 1
  3175. );
  3176. return this;
  3177. },
  3178. makeScale: function ( x, y, z ) {
  3179. this.set(
  3180. x, 0, 0, 0,
  3181. 0, y, 0, 0,
  3182. 0, 0, z, 0,
  3183. 0, 0, 0, 1
  3184. );
  3185. return this;
  3186. },
  3187. compose: function ( position, quaternion, scale ) {
  3188. this.makeRotationFromQuaternion( quaternion );
  3189. this.scale( scale );
  3190. this.setPosition( position );
  3191. return this;
  3192. },
  3193. decompose: function () {
  3194. var vector, matrix;
  3195. return function ( position, quaternion, scale ) {
  3196. if ( vector === undefined ) vector = new THREE.Vector3();
  3197. if ( matrix === undefined ) matrix = new THREE.Matrix4();
  3198. var te = this.elements;
  3199. var sx = vector.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  3200. var sy = vector.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  3201. var sz = vector.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  3202. // if determine is negative, we need to invert one scale
  3203. var det = this.determinant();
  3204. if ( det < 0 ) {
  3205. sx = - sx;
  3206. }
  3207. position.x = te[ 12 ];
  3208. position.y = te[ 13 ];
  3209. position.z = te[ 14 ];
  3210. // scale the rotation part
  3211. matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy()
  3212. var invSX = 1 / sx;
  3213. var invSY = 1 / sy;
  3214. var invSZ = 1 / sz;
  3215. matrix.elements[ 0 ] *= invSX;
  3216. matrix.elements[ 1 ] *= invSX;
  3217. matrix.elements[ 2 ] *= invSX;
  3218. matrix.elements[ 4 ] *= invSY;
  3219. matrix.elements[ 5 ] *= invSY;
  3220. matrix.elements[ 6 ] *= invSY;
  3221. matrix.elements[ 8 ] *= invSZ;
  3222. matrix.elements[ 9 ] *= invSZ;
  3223. matrix.elements[ 10 ] *= invSZ;
  3224. quaternion.setFromRotationMatrix( matrix );
  3225. scale.x = sx;
  3226. scale.y = sy;
  3227. scale.z = sz;
  3228. return this;
  3229. };
  3230. }(),
  3231. makeFrustum: function ( left, right, bottom, top, near, far ) {
  3232. var te = this.elements;
  3233. var x = 2 * near / ( right - left );
  3234. var y = 2 * near / ( top - bottom );
  3235. var a = ( right + left ) / ( right - left );
  3236. var b = ( top + bottom ) / ( top - bottom );
  3237. var c = - ( far + near ) / ( far - near );
  3238. var d = - 2 * far * near / ( far - near );
  3239. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  3240. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  3241. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  3242. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  3243. return this;
  3244. },
  3245. makePerspective: function ( fov, aspect, near, far ) {
  3246. var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) );
  3247. var ymin = - ymax;
  3248. var xmin = ymin * aspect;
  3249. var xmax = ymax * aspect;
  3250. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  3251. },
  3252. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  3253. var te = this.elements;
  3254. var w = right - left;
  3255. var h = top - bottom;
  3256. var p = far - near;
  3257. var x = ( right + left ) / w;
  3258. var y = ( top + bottom ) / h;
  3259. var z = ( far + near ) / p;
  3260. te[ 0 ] = 2 / w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  3261. te[ 1 ] = 0; te[ 5 ] = 2 / h; te[ 9 ] = 0; te[ 13 ] = - y;
  3262. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 / p; te[ 14 ] = - z;
  3263. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  3264. return this;
  3265. },
  3266. fromArray: function ( array ) {
  3267. this.elements.set( array );
  3268. return this;
  3269. },
  3270. toArray: function () {
  3271. var te = this.elements;
  3272. return [
  3273. te[ 0 ], te[ 1 ], te[ 2 ], te[ 3 ],
  3274. te[ 4 ], te[ 5 ], te[ 6 ], te[ 7 ],
  3275. te[ 8 ], te[ 9 ], te[ 10 ], te[ 11 ],
  3276. te[ 12 ], te[ 13 ], te[ 14 ], te[ 15 ]
  3277. ];
  3278. },
  3279. clone: function () {
  3280. return new THREE.Matrix4().fromArray( this.elements );
  3281. }
  3282. };
  3283. // File:src/math/Ray.js
  3284. /**
  3285. * @author bhouston / http://exocortex.com
  3286. */
  3287. THREE.Ray = function ( origin, direction ) {
  3288. this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3();
  3289. this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3();
  3290. };
  3291. THREE.Ray.prototype = {
  3292. constructor: THREE.Ray,
  3293. set: function ( origin, direction ) {
  3294. this.origin.copy( origin );
  3295. this.direction.copy( direction );
  3296. return this;
  3297. },
  3298. copy: function ( ray ) {
  3299. this.origin.copy( ray.origin );
  3300. this.direction.copy( ray.direction );
  3301. return this;
  3302. },
  3303. at: function ( t, optionalTarget ) {
  3304. var result = optionalTarget || new THREE.Vector3();
  3305. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  3306. },
  3307. recast: function () {
  3308. var v1 = new THREE.Vector3();
  3309. return function ( t ) {
  3310. this.origin.copy( this.at( t, v1 ) );
  3311. return this;
  3312. };
  3313. }(),
  3314. closestPointToPoint: function ( point, optionalTarget ) {
  3315. var result = optionalTarget || new THREE.Vector3();
  3316. result.subVectors( point, this.origin );
  3317. var directionDistance = result.dot( this.direction );
  3318. if ( directionDistance < 0 ) {
  3319. return result.copy( this.origin );
  3320. }
  3321. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3322. },
  3323. distanceToPoint: function () {
  3324. var v1 = new THREE.Vector3();
  3325. return function ( point ) {
  3326. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  3327. // point behind the ray
  3328. if ( directionDistance < 0 ) {
  3329. return this.origin.distanceTo( point );
  3330. }
  3331. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3332. return v1.distanceTo( point );
  3333. };
  3334. }(),
  3335. distanceSqToSegment: function () {
  3336. var segCenter = new THREE.Vector3();
  3337. var segDir = new THREE.Vector3();
  3338. var diff = new THREE.Vector3();
  3339. return function ( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3340. // from http://www.geometrictools.com/LibMathematics/Distance/Wm5DistRay3Segment3.cpp
  3341. // It returns the min distance between the ray and the segment
  3342. // defined by v0 and v1
  3343. // It can also set two optional targets :
  3344. // - The closest point on the ray
  3345. // - The closest point on the segment
  3346. segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3347. segDir.copy( v1 ).sub( v0 ).normalize();
  3348. diff.copy( this.origin ).sub( segCenter );
  3349. var segExtent = v0.distanceTo( v1 ) * 0.5;
  3350. var a01 = - this.direction.dot( segDir );
  3351. var b0 = diff.dot( this.direction );
  3352. var b1 = - diff.dot( segDir );
  3353. var c = diff.lengthSq();
  3354. var det = Math.abs( 1 - a01 * a01 );
  3355. var s0, s1, sqrDist, extDet;
  3356. if ( det > 0 ) {
  3357. // The ray and segment are not parallel.
  3358. s0 = a01 * b1 - b0;
  3359. s1 = a01 * b0 - b1;
  3360. extDet = segExtent * det;
  3361. if ( s0 >= 0 ) {
  3362. if ( s1 >= - extDet ) {
  3363. if ( s1 <= extDet ) {
  3364. // region 0
  3365. // Minimum at interior points of ray and segment.
  3366. var invDet = 1 / det;
  3367. s0 *= invDet;
  3368. s1 *= invDet;
  3369. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3370. } else {
  3371. // region 1
  3372. s1 = segExtent;
  3373. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3374. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3375. }
  3376. } else {
  3377. // region 5
  3378. s1 = - segExtent;
  3379. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3380. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3381. }
  3382. } else {
  3383. if ( s1 <= - extDet ) {
  3384. // region 4
  3385. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3386. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3387. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3388. } else if ( s1 <= extDet ) {
  3389. // region 3
  3390. s0 = 0;
  3391. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3392. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3393. } else {
  3394. // region 2
  3395. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3396. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3397. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3398. }
  3399. }
  3400. } else {
  3401. // Ray and segment are parallel.
  3402. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3403. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3404. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3405. }
  3406. if ( optionalPointOnRay ) {
  3407. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  3408. }
  3409. if ( optionalPointOnSegment ) {
  3410. optionalPointOnSegment.copy( segDir ).multiplyScalar( s1 ).add( segCenter );
  3411. }
  3412. return sqrDist;
  3413. };
  3414. }(),
  3415. isIntersectionSphere: function ( sphere ) {
  3416. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  3417. },
  3418. intersectSphere: function () {
  3419. // from http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-sphere-intersection/
  3420. var v1 = new THREE.Vector3();
  3421. return function ( sphere, optionalTarget ) {
  3422. v1.subVectors( sphere.center, this.origin );
  3423. var tca = v1.dot( this.direction );
  3424. var d2 = v1.dot( v1 ) - tca * tca;
  3425. var radius2 = sphere.radius * sphere.radius;
  3426. if ( d2 > radius2 ) return null;
  3427. var thc = Math.sqrt( radius2 - d2 );
  3428. // t0 = first intersect point - entrance on front of sphere
  3429. var t0 = tca - thc;
  3430. // t1 = second intersect point - exit point on back of sphere
  3431. var t1 = tca + thc;
  3432. // test to see if both t0 and t1 are behind the ray - if so, return null
  3433. if ( t0 < 0 && t1 < 0 ) return null;
  3434. // test to see if t0 is behind the ray:
  3435. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3436. // in order to always return an intersect point that is in front of the ray.
  3437. if ( t0 < 0 ) return this.at( t1, optionalTarget );
  3438. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3439. return this.at( t0, optionalTarget );
  3440. }
  3441. }(),
  3442. isIntersectionPlane: function ( plane ) {
  3443. // check if the ray lies on the plane first
  3444. var distToPoint = plane.distanceToPoint( this.origin );
  3445. if ( distToPoint === 0 ) {
  3446. return true;
  3447. }
  3448. var denominator = plane.normal.dot( this.direction );
  3449. if ( denominator * distToPoint < 0 ) {
  3450. return true;
  3451. }
  3452. // ray origin is behind the plane (and is pointing behind it)
  3453. return false;
  3454. },
  3455. distanceToPlane: function ( plane ) {
  3456. var denominator = plane.normal.dot( this.direction );
  3457. if ( denominator === 0 ) {
  3458. // line is coplanar, return origin
  3459. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3460. return 0;
  3461. }
  3462. // Null is preferable to undefined since undefined means.... it is undefined
  3463. return null;
  3464. }
  3465. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3466. // Return if the ray never intersects the plane
  3467. return t >= 0 ? t : null;
  3468. },
  3469. intersectPlane: function ( plane, optionalTarget ) {
  3470. var t = this.distanceToPlane( plane );
  3471. if ( t === null ) {
  3472. return null;
  3473. }
  3474. return this.at( t, optionalTarget );
  3475. },
  3476. isIntersectionBox: function () {
  3477. var v = new THREE.Vector3();
  3478. return function ( box ) {
  3479. return this.intersectBox( box, v ) !== null;
  3480. };
  3481. }(),
  3482. intersectBox: function ( box, optionalTarget ) {
  3483. // http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-box-intersection/
  3484. var tmin,tmax,tymin,tymax,tzmin,tzmax;
  3485. var invdirx = 1 / this.direction.x,
  3486. invdiry = 1 / this.direction.y,
  3487. invdirz = 1 / this.direction.z;
  3488. var origin = this.origin;
  3489. if ( invdirx >= 0 ) {
  3490. tmin = ( box.min.x - origin.x ) * invdirx;
  3491. tmax = ( box.max.x - origin.x ) * invdirx;
  3492. } else {
  3493. tmin = ( box.max.x - origin.x ) * invdirx;
  3494. tmax = ( box.min.x - origin.x ) * invdirx;
  3495. }
  3496. if ( invdiry >= 0 ) {
  3497. tymin = ( box.min.y - origin.y ) * invdiry;
  3498. tymax = ( box.max.y - origin.y ) * invdiry;
  3499. } else {
  3500. tymin = ( box.max.y - origin.y ) * invdiry;
  3501. tymax = ( box.min.y - origin.y ) * invdiry;
  3502. }
  3503. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3504. // These lines also handle the case where tmin or tmax is NaN
  3505. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3506. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  3507. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  3508. if ( invdirz >= 0 ) {
  3509. tzmin = ( box.min.z - origin.z ) * invdirz;
  3510. tzmax = ( box.max.z - origin.z ) * invdirz;
  3511. } else {
  3512. tzmin = ( box.max.z - origin.z ) * invdirz;
  3513. tzmax = ( box.min.z - origin.z ) * invdirz;
  3514. }
  3515. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3516. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3517. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3518. //return point closest to the ray (positive side)
  3519. if ( tmax < 0 ) return null;
  3520. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  3521. },
  3522. intersectTriangle: function () {
  3523. // Compute the offset origin, edges, and normal.
  3524. var diff = new THREE.Vector3();
  3525. var edge1 = new THREE.Vector3();
  3526. var edge2 = new THREE.Vector3();
  3527. var normal = new THREE.Vector3();
  3528. return function ( a, b, c, backfaceCulling, optionalTarget ) {
  3529. // from http://www.geometrictools.com/LibMathematics/Intersection/Wm5IntrRay3Triangle3.cpp
  3530. edge1.subVectors( b, a );
  3531. edge2.subVectors( c, a );
  3532. normal.crossVectors( edge1, edge2 );
  3533. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3534. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3535. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3536. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3537. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3538. var DdN = this.direction.dot( normal );
  3539. var sign;
  3540. if ( DdN > 0 ) {
  3541. if ( backfaceCulling ) return null;
  3542. sign = 1;
  3543. } else if ( DdN < 0 ) {
  3544. sign = - 1;
  3545. DdN = - DdN;
  3546. } else {
  3547. return null;
  3548. }
  3549. diff.subVectors( this.origin, a );
  3550. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  3551. // b1 < 0, no intersection
  3552. if ( DdQxE2 < 0 ) {
  3553. return null;
  3554. }
  3555. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  3556. // b2 < 0, no intersection
  3557. if ( DdE1xQ < 0 ) {
  3558. return null;
  3559. }
  3560. // b1+b2 > 1, no intersection
  3561. if ( DdQxE2 + DdE1xQ > DdN ) {
  3562. return null;
  3563. }
  3564. // Line intersects triangle, check if ray does.
  3565. var QdN = - sign * diff.dot( normal );
  3566. // t < 0, no intersection
  3567. if ( QdN < 0 ) {
  3568. return null;
  3569. }
  3570. // Ray intersects triangle.
  3571. return this.at( QdN / DdN, optionalTarget );
  3572. };
  3573. }(),
  3574. applyMatrix4: function ( matrix4 ) {
  3575. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  3576. this.origin.applyMatrix4( matrix4 );
  3577. this.direction.sub( this.origin );
  3578. this.direction.normalize();
  3579. return this;
  3580. },
  3581. equals: function ( ray ) {
  3582. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3583. },
  3584. clone: function () {
  3585. return new THREE.Ray().copy( this );
  3586. }
  3587. };
  3588. // File:src/math/Sphere.js
  3589. /**
  3590. * @author bhouston / http://exocortex.com
  3591. * @author mrdoob / http://mrdoob.com/
  3592. */
  3593. THREE.Sphere = function ( center, radius ) {
  3594. this.center = ( center !== undefined ) ? center : new THREE.Vector3();
  3595. this.radius = ( radius !== undefined ) ? radius : 0;
  3596. };
  3597. THREE.Sphere.prototype = {
  3598. constructor: THREE.Sphere,
  3599. set: function ( center, radius ) {
  3600. this.center.copy( center );
  3601. this.radius = radius;
  3602. return this;
  3603. },
  3604. setFromPoints: function () {
  3605. var box = new THREE.Box3();
  3606. return function ( points, optionalCenter ) {
  3607. var center = this.center;
  3608. if ( optionalCenter !== undefined ) {
  3609. center.copy( optionalCenter );
  3610. } else {
  3611. box.setFromPoints( points ).center( center );
  3612. }
  3613. var maxRadiusSq = 0;
  3614. for ( var i = 0, il = points.length; i < il; i ++ ) {
  3615. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3616. }
  3617. this.radius = Math.sqrt( maxRadiusSq );
  3618. return this;
  3619. };
  3620. }(),
  3621. copy: function ( sphere ) {
  3622. this.center.copy( sphere.center );
  3623. this.radius = sphere.radius;
  3624. return this;
  3625. },
  3626. empty: function () {
  3627. return ( this.radius <= 0 );
  3628. },
  3629. containsPoint: function ( point ) {
  3630. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3631. },
  3632. distanceToPoint: function ( point ) {
  3633. return ( point.distanceTo( this.center ) - this.radius );
  3634. },
  3635. intersectsSphere: function ( sphere ) {
  3636. var radiusSum = this.radius + sphere.radius;
  3637. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3638. },
  3639. clampPoint: function ( point, optionalTarget ) {
  3640. var deltaLengthSq = this.center.distanceToSquared( point );
  3641. var result = optionalTarget || new THREE.Vector3();
  3642. result.copy( point );
  3643. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3644. result.sub( this.center ).normalize();
  3645. result.multiplyScalar( this.radius ).add( this.center );
  3646. }
  3647. return result;
  3648. },
  3649. getBoundingBox: function ( optionalTarget ) {
  3650. var box = optionalTarget || new THREE.Box3();
  3651. box.set( this.center, this.center );
  3652. box.expandByScalar( this.radius );
  3653. return box;
  3654. },
  3655. applyMatrix4: function ( matrix ) {
  3656. this.center.applyMatrix4( matrix );
  3657. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3658. return this;
  3659. },
  3660. translate: function ( offset ) {
  3661. this.center.add( offset );
  3662. return this;
  3663. },
  3664. equals: function ( sphere ) {
  3665. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3666. },
  3667. clone: function () {
  3668. return new THREE.Sphere().copy( this );
  3669. }
  3670. };
  3671. // File:src/math/Frustum.js
  3672. /**
  3673. * @author mrdoob / http://mrdoob.com/
  3674. * @author alteredq / http://alteredqualia.com/
  3675. * @author bhouston / http://exocortex.com
  3676. */
  3677. THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) {
  3678. this.planes = [
  3679. ( p0 !== undefined ) ? p0 : new THREE.Plane(),
  3680. ( p1 !== undefined ) ? p1 : new THREE.Plane(),
  3681. ( p2 !== undefined ) ? p2 : new THREE.Plane(),
  3682. ( p3 !== undefined ) ? p3 : new THREE.Plane(),
  3683. ( p4 !== undefined ) ? p4 : new THREE.Plane(),
  3684. ( p5 !== undefined ) ? p5 : new THREE.Plane()
  3685. ];
  3686. };
  3687. THREE.Frustum.prototype = {
  3688. constructor: THREE.Frustum,
  3689. set: function ( p0, p1, p2, p3, p4, p5 ) {
  3690. var planes = this.planes;
  3691. planes[ 0 ].copy( p0 );
  3692. planes[ 1 ].copy( p1 );
  3693. planes[ 2 ].copy( p2 );
  3694. planes[ 3 ].copy( p3 );
  3695. planes[ 4 ].copy( p4 );
  3696. planes[ 5 ].copy( p5 );
  3697. return this;
  3698. },
  3699. copy: function ( frustum ) {
  3700. var planes = this.planes;
  3701. for ( var i = 0; i < 6; i ++ ) {
  3702. planes[ i ].copy( frustum.planes[ i ] );
  3703. }
  3704. return this;
  3705. },
  3706. setFromMatrix: function ( m ) {
  3707. var planes = this.planes;
  3708. var me = m.elements;
  3709. var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  3710. var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  3711. var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  3712. var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  3713. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  3714. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  3715. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  3716. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  3717. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  3718. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  3719. return this;
  3720. },
  3721. intersectsObject: function () {
  3722. var sphere = new THREE.Sphere();
  3723. return function ( object ) {
  3724. var geometry = object.geometry;
  3725. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  3726. sphere.copy( geometry.boundingSphere );
  3727. sphere.applyMatrix4( object.matrixWorld );
  3728. return this.intersectsSphere( sphere );
  3729. };
  3730. }(),
  3731. intersectsSphere: function ( sphere ) {
  3732. var planes = this.planes;
  3733. var center = sphere.center;
  3734. var negRadius = - sphere.radius;
  3735. for ( var i = 0; i < 6; i ++ ) {
  3736. var distance = planes[ i ].distanceToPoint( center );
  3737. if ( distance < negRadius ) {
  3738. return false;
  3739. }
  3740. }
  3741. return true;
  3742. },
  3743. intersectsBox: function () {
  3744. var p1 = new THREE.Vector3(),
  3745. p2 = new THREE.Vector3();
  3746. return function ( box ) {
  3747. var planes = this.planes;
  3748. for ( var i = 0; i < 6 ; i ++ ) {
  3749. var plane = planes[ i ];
  3750. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  3751. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  3752. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  3753. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  3754. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  3755. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  3756. var d1 = plane.distanceToPoint( p1 );
  3757. var d2 = plane.distanceToPoint( p2 );
  3758. // if both outside plane, no intersection
  3759. if ( d1 < 0 && d2 < 0 ) {
  3760. return false;
  3761. }
  3762. }
  3763. return true;
  3764. };
  3765. }(),
  3766. containsPoint: function ( point ) {
  3767. var planes = this.planes;
  3768. for ( var i = 0; i < 6; i ++ ) {
  3769. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  3770. return false;
  3771. }
  3772. }
  3773. return true;
  3774. },
  3775. clone: function () {
  3776. return new THREE.Frustum().copy( this );
  3777. }
  3778. };
  3779. // File:src/math/Plane.js
  3780. /**
  3781. * @author bhouston / http://exocortex.com
  3782. */
  3783. THREE.Plane = function ( normal, constant ) {
  3784. this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 );
  3785. this.constant = ( constant !== undefined ) ? constant : 0;
  3786. };
  3787. THREE.Plane.prototype = {
  3788. constructor: THREE.Plane,
  3789. set: function ( normal, constant ) {
  3790. this.normal.copy( normal );
  3791. this.constant = constant;
  3792. return this;
  3793. },
  3794. setComponents: function ( x, y, z, w ) {
  3795. this.normal.set( x, y, z );
  3796. this.constant = w;
  3797. return this;
  3798. },
  3799. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  3800. this.normal.copy( normal );
  3801. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  3802. return this;
  3803. },
  3804. setFromCoplanarPoints: function () {
  3805. var v1 = new THREE.Vector3();
  3806. var v2 = new THREE.Vector3();
  3807. return function ( a, b, c ) {
  3808. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  3809. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  3810. this.setFromNormalAndCoplanarPoint( normal, a );
  3811. return this;
  3812. };
  3813. }(),
  3814. copy: function ( plane ) {
  3815. this.normal.copy( plane.normal );
  3816. this.constant = plane.constant;
  3817. return this;
  3818. },
  3819. normalize: function () {
  3820. // Note: will lead to a divide by zero if the plane is invalid.
  3821. var inverseNormalLength = 1.0 / this.normal.length();
  3822. this.normal.multiplyScalar( inverseNormalLength );
  3823. this.constant *= inverseNormalLength;
  3824. return this;
  3825. },
  3826. negate: function () {
  3827. this.constant *= - 1;
  3828. this.normal.negate();
  3829. return this;
  3830. },
  3831. distanceToPoint: function ( point ) {
  3832. return this.normal.dot( point ) + this.constant;
  3833. },
  3834. distanceToSphere: function ( sphere ) {
  3835. return this.distanceToPoint( sphere.center ) - sphere.radius;
  3836. },
  3837. projectPoint: function ( point, optionalTarget ) {
  3838. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  3839. },
  3840. orthoPoint: function ( point, optionalTarget ) {
  3841. var perpendicularMagnitude = this.distanceToPoint( point );
  3842. var result = optionalTarget || new THREE.Vector3();
  3843. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  3844. },
  3845. isIntersectionLine: function ( line ) {
  3846. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  3847. var startSign = this.distanceToPoint( line.start );
  3848. var endSign = this.distanceToPoint( line.end );
  3849. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  3850. },
  3851. intersectLine: function () {
  3852. var v1 = new THREE.Vector3();
  3853. return function ( line, optionalTarget ) {
  3854. var result = optionalTarget || new THREE.Vector3();
  3855. var direction = line.delta( v1 );
  3856. var denominator = this.normal.dot( direction );
  3857. if ( denominator === 0 ) {
  3858. // line is coplanar, return origin
  3859. if ( this.distanceToPoint( line.start ) === 0 ) {
  3860. return result.copy( line.start );
  3861. }
  3862. // Unsure if this is the correct method to handle this case.
  3863. return undefined;
  3864. }
  3865. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  3866. if ( t < 0 || t > 1 ) {
  3867. return undefined;
  3868. }
  3869. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  3870. };
  3871. }(),
  3872. coplanarPoint: function ( optionalTarget ) {
  3873. var result = optionalTarget || new THREE.Vector3();
  3874. return result.copy( this.normal ).multiplyScalar( - this.constant );
  3875. },
  3876. applyMatrix4: function () {
  3877. var v1 = new THREE.Vector3();
  3878. var v2 = new THREE.Vector3();
  3879. var m1 = new THREE.Matrix3();
  3880. return function ( matrix, optionalNormalMatrix ) {
  3881. // compute new normal based on theory here:
  3882. // http://www.songho.ca/opengl/gl_normaltransform.html
  3883. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  3884. var newNormal = v1.copy( this.normal ).applyMatrix3( normalMatrix );
  3885. var newCoplanarPoint = this.coplanarPoint( v2 );
  3886. newCoplanarPoint.applyMatrix4( matrix );
  3887. this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint );
  3888. return this;
  3889. };
  3890. }(),
  3891. translate: function ( offset ) {
  3892. this.constant = this.constant - offset.dot( this.normal );
  3893. return this;
  3894. },
  3895. equals: function ( plane ) {
  3896. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  3897. },
  3898. clone: function () {
  3899. return new THREE.Plane().copy( this );
  3900. }
  3901. };
  3902. // File:src/math/Math.js
  3903. /**
  3904. * @author alteredq / http://alteredqualia.com/
  3905. * @author mrdoob / http://mrdoob.com/
  3906. */
  3907. THREE.Math = {
  3908. generateUUID: function () {
  3909. // http://www.broofa.com/Tools/Math.uuid.htm
  3910. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split( '' );
  3911. var uuid = new Array( 36 );
  3912. var rnd = 0, r;
  3913. return function () {
  3914. for ( var i = 0; i < 36; i ++ ) {
  3915. if ( i === 8 || i === 13 || i === 18 || i === 23 ) {
  3916. uuid[ i ] = '-';
  3917. } else if ( i === 14 ) {
  3918. uuid[ i ] = '4';
  3919. } else {
  3920. if ( rnd <= 0x02 ) rnd = 0x2000000 + ( Math.random() * 0x1000000 ) | 0;
  3921. r = rnd & 0xf;
  3922. rnd = rnd >> 4;
  3923. uuid[ i ] = chars[ ( i === 19 ) ? ( r & 0x3 ) | 0x8 : r ];
  3924. }
  3925. }
  3926. return uuid.join( '' );
  3927. };
  3928. }(),
  3929. // Clamp value to range <a, b>
  3930. clamp: function ( x, a, b ) {
  3931. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  3932. },
  3933. // Clamp value to range <a, inf)
  3934. clampBottom: function ( x, a ) {
  3935. return x < a ? a : x;
  3936. },
  3937. // Linear mapping from range <a1, a2> to range <b1, b2>
  3938. mapLinear: function ( x, a1, a2, b1, b2 ) {
  3939. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  3940. },
  3941. // http://en.wikipedia.org/wiki/Smoothstep
  3942. smoothstep: function ( x, min, max ) {
  3943. if ( x <= min ) return 0;
  3944. if ( x >= max ) return 1;
  3945. x = ( x - min ) / ( max - min );
  3946. return x * x * ( 3 - 2 * x );
  3947. },
  3948. smootherstep: function ( x, min, max ) {
  3949. if ( x <= min ) return 0;
  3950. if ( x >= max ) return 1;
  3951. x = ( x - min ) / ( max - min );
  3952. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  3953. },
  3954. // Random float from <0, 1> with 16 bits of randomness
  3955. // (standard Math.random() creates repetitive patterns when applied over larger space)
  3956. random16: function () {
  3957. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  3958. },
  3959. // Random integer from <low, high> interval
  3960. randInt: function ( low, high ) {
  3961. return Math.floor( this.randFloat( low, high ) );
  3962. },
  3963. // Random float from <low, high> interval
  3964. randFloat: function ( low, high ) {
  3965. return low + Math.random() * ( high - low );
  3966. },
  3967. // Random float from <-range/2, range/2> interval
  3968. randFloatSpread: function ( range ) {
  3969. return range * ( 0.5 - Math.random() );
  3970. },
  3971. degToRad: function () {
  3972. var degreeToRadiansFactor = Math.PI / 180;
  3973. return function ( degrees ) {
  3974. return degrees * degreeToRadiansFactor;
  3975. };
  3976. }(),
  3977. radToDeg: function () {
  3978. var radianToDegreesFactor = 180 / Math.PI;
  3979. return function ( radians ) {
  3980. return radians * radianToDegreesFactor;
  3981. };
  3982. }(),
  3983. isPowerOfTwo: function ( value ) {
  3984. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  3985. },
  3986. nextPowerOfTwo: function ( value ) {
  3987. value --;
  3988. value |= value >> 1;
  3989. value |= value >> 2;
  3990. value |= value >> 4;
  3991. value |= value >> 8;
  3992. value |= value >> 16;
  3993. value ++;
  3994. return value;
  3995. }
  3996. };
  3997. // File:src/math/Spline.js
  3998. /**
  3999. * Spline from Tween.js, slightly optimized (and trashed)
  4000. * http://sole.github.com/tween.js/examples/05_spline.html
  4001. *
  4002. * @author mrdoob / http://mrdoob.com/
  4003. * @author alteredq / http://alteredqualia.com/
  4004. */
  4005. THREE.Spline = function ( points ) {
  4006. this.points = points;
  4007. var c = [], v3 = { x: 0, y: 0, z: 0 },
  4008. point, intPoint, weight, w2, w3,
  4009. pa, pb, pc, pd;
  4010. this.initFromArray = function ( a ) {
  4011. this.points = [];
  4012. for ( var i = 0; i < a.length; i ++ ) {
  4013. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  4014. }
  4015. };
  4016. this.getPoint = function ( k ) {
  4017. point = ( this.points.length - 1 ) * k;
  4018. intPoint = Math.floor( point );
  4019. weight = point - intPoint;
  4020. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  4021. c[ 1 ] = intPoint;
  4022. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  4023. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  4024. pa = this.points[ c[ 0 ] ];
  4025. pb = this.points[ c[ 1 ] ];
  4026. pc = this.points[ c[ 2 ] ];
  4027. pd = this.points[ c[ 3 ] ];
  4028. w2 = weight * weight;
  4029. w3 = weight * w2;
  4030. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  4031. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  4032. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  4033. return v3;
  4034. };
  4035. this.getControlPointsArray = function () {
  4036. var i, p, l = this.points.length,
  4037. coords = [];
  4038. for ( i = 0; i < l; i ++ ) {
  4039. p = this.points[ i ];
  4040. coords[ i ] = [ p.x, p.y, p.z ];
  4041. }
  4042. return coords;
  4043. };
  4044. // approximate length by summing linear segments
  4045. this.getLength = function ( nSubDivisions ) {
  4046. var i, index, nSamples, position,
  4047. point = 0, intPoint = 0, oldIntPoint = 0,
  4048. oldPosition = new THREE.Vector3(),
  4049. tmpVec = new THREE.Vector3(),
  4050. chunkLengths = [],
  4051. totalLength = 0;
  4052. // first point has 0 length
  4053. chunkLengths[ 0 ] = 0;
  4054. if ( ! nSubDivisions ) nSubDivisions = 100;
  4055. nSamples = this.points.length * nSubDivisions;
  4056. oldPosition.copy( this.points[ 0 ] );
  4057. for ( i = 1; i < nSamples; i ++ ) {
  4058. index = i / nSamples;
  4059. position = this.getPoint( index );
  4060. tmpVec.copy( position );
  4061. totalLength += tmpVec.distanceTo( oldPosition );
  4062. oldPosition.copy( position );
  4063. point = ( this.points.length - 1 ) * index;
  4064. intPoint = Math.floor( point );
  4065. if ( intPoint !== oldIntPoint ) {
  4066. chunkLengths[ intPoint ] = totalLength;
  4067. oldIntPoint = intPoint;
  4068. }
  4069. }
  4070. // last point ends with total length
  4071. chunkLengths[ chunkLengths.length ] = totalLength;
  4072. return { chunks: chunkLengths, total: totalLength };
  4073. };
  4074. this.reparametrizeByArcLength = function ( samplingCoef ) {
  4075. var i, j,
  4076. index, indexCurrent, indexNext,
  4077. realDistance,
  4078. sampling, position,
  4079. newpoints = [],
  4080. tmpVec = new THREE.Vector3(),
  4081. sl = this.getLength();
  4082. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  4083. for ( i = 1; i < this.points.length; i ++ ) {
  4084. //tmpVec.copy( this.points[ i - 1 ] );
  4085. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  4086. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  4087. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  4088. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  4089. indexNext = i / ( this.points.length - 1 );
  4090. for ( j = 1; j < sampling - 1; j ++ ) {
  4091. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  4092. position = this.getPoint( index );
  4093. newpoints.push( tmpVec.copy( position ).clone() );
  4094. }
  4095. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  4096. }
  4097. this.points = newpoints;
  4098. };
  4099. // Catmull-Rom
  4100. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  4101. var v0 = ( p2 - p0 ) * 0.5,
  4102. v1 = ( p3 - p1 ) * 0.5;
  4103. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  4104. }
  4105. };
  4106. // File:src/math/Triangle.js
  4107. /**
  4108. * @author bhouston / http://exocortex.com
  4109. * @author mrdoob / http://mrdoob.com/
  4110. */
  4111. THREE.Triangle = function ( a, b, c ) {
  4112. this.a = ( a !== undefined ) ? a : new THREE.Vector3();
  4113. this.b = ( b !== undefined ) ? b : new THREE.Vector3();
  4114. this.c = ( c !== undefined ) ? c : new THREE.Vector3();
  4115. };
  4116. THREE.Triangle.normal = function () {
  4117. var v0 = new THREE.Vector3();
  4118. return function ( a, b, c, optionalTarget ) {
  4119. var result = optionalTarget || new THREE.Vector3();
  4120. result.subVectors( c, b );
  4121. v0.subVectors( a, b );
  4122. result.cross( v0 );
  4123. var resultLengthSq = result.lengthSq();
  4124. if ( resultLengthSq > 0 ) {
  4125. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  4126. }
  4127. return result.set( 0, 0, 0 );
  4128. };
  4129. }();
  4130. // static/instance method to calculate barycoordinates
  4131. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4132. THREE.Triangle.barycoordFromPoint = function () {
  4133. var v0 = new THREE.Vector3();
  4134. var v1 = new THREE.Vector3();
  4135. var v2 = new THREE.Vector3();
  4136. return function ( point, a, b, c, optionalTarget ) {
  4137. v0.subVectors( c, a );
  4138. v1.subVectors( b, a );
  4139. v2.subVectors( point, a );
  4140. var dot00 = v0.dot( v0 );
  4141. var dot01 = v0.dot( v1 );
  4142. var dot02 = v0.dot( v2 );
  4143. var dot11 = v1.dot( v1 );
  4144. var dot12 = v1.dot( v2 );
  4145. var denom = ( dot00 * dot11 - dot01 * dot01 );
  4146. var result = optionalTarget || new THREE.Vector3();
  4147. // colinear or singular triangle
  4148. if ( denom === 0 ) {
  4149. // arbitrary location outside of triangle?
  4150. // not sure if this is the best idea, maybe should be returning undefined
  4151. return result.set( - 2, - 1, - 1 );
  4152. }
  4153. var invDenom = 1 / denom;
  4154. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  4155. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  4156. // barycoordinates must always sum to 1
  4157. return result.set( 1 - u - v, v, u );
  4158. };
  4159. }();
  4160. THREE.Triangle.containsPoint = function () {
  4161. var v1 = new THREE.Vector3();
  4162. return function ( point, a, b, c ) {
  4163. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 );
  4164. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  4165. };
  4166. }();
  4167. THREE.Triangle.prototype = {
  4168. constructor: THREE.Triangle,
  4169. set: function ( a, b, c ) {
  4170. this.a.copy( a );
  4171. this.b.copy( b );
  4172. this.c.copy( c );
  4173. return this;
  4174. },
  4175. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  4176. this.a.copy( points[ i0 ] );
  4177. this.b.copy( points[ i1 ] );
  4178. this.c.copy( points[ i2 ] );
  4179. return this;
  4180. },
  4181. copy: function ( triangle ) {
  4182. this.a.copy( triangle.a );
  4183. this.b.copy( triangle.b );
  4184. this.c.copy( triangle.c );
  4185. return this;
  4186. },
  4187. area: function () {
  4188. var v0 = new THREE.Vector3();
  4189. var v1 = new THREE.Vector3();
  4190. return function () {
  4191. v0.subVectors( this.c, this.b );
  4192. v1.subVectors( this.a, this.b );
  4193. return v0.cross( v1 ).length() * 0.5;
  4194. };
  4195. }(),
  4196. midpoint: function ( optionalTarget ) {
  4197. var result = optionalTarget || new THREE.Vector3();
  4198. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  4199. },
  4200. normal: function ( optionalTarget ) {
  4201. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  4202. },
  4203. plane: function ( optionalTarget ) {
  4204. var result = optionalTarget || new THREE.Plane();
  4205. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  4206. },
  4207. barycoordFromPoint: function ( point, optionalTarget ) {
  4208. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  4209. },
  4210. containsPoint: function ( point ) {
  4211. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  4212. },
  4213. equals: function ( triangle ) {
  4214. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  4215. },
  4216. clone: function () {
  4217. return new THREE.Triangle().copy( this );
  4218. }
  4219. };
  4220. // File:src/core/Clock.js
  4221. /**
  4222. * @author alteredq / http://alteredqualia.com/
  4223. */
  4224. THREE.Clock = function ( autoStart ) {
  4225. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  4226. this.startTime = 0;
  4227. this.oldTime = 0;
  4228. this.elapsedTime = 0;
  4229. this.running = false;
  4230. };
  4231. THREE.Clock.prototype = {
  4232. constructor: THREE.Clock,
  4233. start: function () {
  4234. this.startTime = self.performance !== undefined && self.performance.now !== undefined
  4235. ? self.performance.now()
  4236. : Date.now();
  4237. this.oldTime = this.startTime;
  4238. this.running = true;
  4239. },
  4240. stop: function () {
  4241. this.getElapsedTime();
  4242. this.running = false;
  4243. },
  4244. getElapsedTime: function () {
  4245. this.getDelta();
  4246. return this.elapsedTime;
  4247. },
  4248. getDelta: function () {
  4249. var diff = 0;
  4250. if ( this.autoStart && ! this.running ) {
  4251. this.start();
  4252. }
  4253. if ( this.running ) {
  4254. var newTime = self.performance !== undefined && self.performance.now !== undefined
  4255. ? self.performance.now()
  4256. : Date.now();
  4257. diff = 0.001 * ( newTime - this.oldTime );
  4258. this.oldTime = newTime;
  4259. this.elapsedTime += diff;
  4260. }
  4261. return diff;
  4262. }
  4263. };
  4264. // File:src/core/EventDispatcher.js
  4265. /**
  4266. * https://github.com/mrdoob/eventdispatcher.js/
  4267. */
  4268. THREE.EventDispatcher = function () {};
  4269. THREE.EventDispatcher.prototype = {
  4270. constructor: THREE.EventDispatcher,
  4271. apply: function ( object ) {
  4272. object.addEventListener = THREE.EventDispatcher.prototype.addEventListener;
  4273. object.hasEventListener = THREE.EventDispatcher.prototype.hasEventListener;
  4274. object.removeEventListener = THREE.EventDispatcher.prototype.removeEventListener;
  4275. object.dispatchEvent = THREE.EventDispatcher.prototype.dispatchEvent;
  4276. },
  4277. addEventListener: function ( type, listener ) {
  4278. if ( this._listeners === undefined ) this._listeners = {};
  4279. var listeners = this._listeners;
  4280. if ( listeners[ type ] === undefined ) {
  4281. listeners[ type ] = [];
  4282. }
  4283. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  4284. listeners[ type ].push( listener );
  4285. }
  4286. },
  4287. hasEventListener: function ( type, listener ) {
  4288. if ( this._listeners === undefined ) return false;
  4289. var listeners = this._listeners;
  4290. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  4291. return true;
  4292. }
  4293. return false;
  4294. },
  4295. removeEventListener: function ( type, listener ) {
  4296. if ( this._listeners === undefined ) return;
  4297. var listeners = this._listeners;
  4298. var listenerArray = listeners[ type ];
  4299. if ( listenerArray !== undefined ) {
  4300. var index = listenerArray.indexOf( listener );
  4301. if ( index !== - 1 ) {
  4302. listenerArray.splice( index, 1 );
  4303. }
  4304. }
  4305. },
  4306. dispatchEvent: function ( event ) {
  4307. if ( this._listeners === undefined ) return;
  4308. var listeners = this._listeners;
  4309. var listenerArray = listeners[ event.type ];
  4310. if ( listenerArray !== undefined ) {
  4311. event.target = this;
  4312. var array = [];
  4313. var length = listenerArray.length;
  4314. for ( var i = 0; i < length; i ++ ) {
  4315. array[ i ] = listenerArray[ i ];
  4316. }
  4317. for ( var i = 0; i < length; i ++ ) {
  4318. array[ i ].call( this, event );
  4319. }
  4320. }
  4321. }
  4322. };
  4323. // File:src/core/Raycaster.js
  4324. /**
  4325. * @author mrdoob / http://mrdoob.com/
  4326. * @author bhouston / http://exocortex.com/
  4327. * @author stephomi / http://stephaneginier.com/
  4328. */
  4329. ( function ( THREE ) {
  4330. THREE.Raycaster = function ( origin, direction, near, far ) {
  4331. this.ray = new THREE.Ray( origin, direction );
  4332. // direction is assumed to be normalized (for accurate distance calculations)
  4333. this.near = near || 0;
  4334. this.far = far || Infinity;
  4335. this.params = {
  4336. Sprite: {},
  4337. Mesh: {},
  4338. PointCloud: { threshold: 1 },
  4339. LOD: {},
  4340. Line: {}
  4341. };
  4342. };
  4343. var descSort = function ( a, b ) {
  4344. return a.distance - b.distance;
  4345. };
  4346. var intersectObject = function ( object, raycaster, intersects, recursive ) {
  4347. object.raycast( raycaster, intersects );
  4348. if ( recursive === true ) {
  4349. var children = object.children;
  4350. for ( var i = 0, l = children.length; i < l; i ++ ) {
  4351. intersectObject( children[ i ], raycaster, intersects, true );
  4352. }
  4353. }
  4354. };
  4355. //
  4356. THREE.Raycaster.prototype = {
  4357. constructor: THREE.Raycaster,
  4358. precision: 0.0001,
  4359. linePrecision: 1,
  4360. set: function ( origin, direction ) {
  4361. // direction is assumed to be normalized (for accurate distance calculations)
  4362. this.ray.set( origin, direction );
  4363. },
  4364. setFromCamera: function ( coords, camera ) {
  4365. if ( camera instanceof THREE.PerspectiveCamera ) {
  4366. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  4367. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  4368. } else if ( camera instanceof THREE.OrthographicCamera ) {
  4369. this.ray.origin.set( coords.x, coords.y, - 1 ).unproject( camera );
  4370. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  4371. } else {
  4372. console.error( 'THREE.Raycaster: Unsupported camera type.' );
  4373. }
  4374. },
  4375. intersectObject: function ( object, recursive ) {
  4376. var intersects = [];
  4377. intersectObject( object, this, intersects, recursive );
  4378. intersects.sort( descSort );
  4379. return intersects;
  4380. },
  4381. intersectObjects: function ( objects, recursive ) {
  4382. var intersects = [];
  4383. if ( Array.isArray( objects ) === false ) {
  4384. console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
  4385. return intersects;
  4386. }
  4387. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  4388. intersectObject( objects[ i ], this, intersects, recursive );
  4389. }
  4390. intersects.sort( descSort );
  4391. return intersects;
  4392. }
  4393. };
  4394. }( THREE ) );
  4395. // File:src/core/Object3D.js
  4396. /**
  4397. * @author mrdoob / http://mrdoob.com/
  4398. * @author mikael emtinger / http://gomo.se/
  4399. * @author alteredq / http://alteredqualia.com/
  4400. * @author WestLangley / http://github.com/WestLangley
  4401. * @author elephantatwork / www.elephantatwork.ch
  4402. */
  4403. THREE.Object3D = function () {
  4404. Object.defineProperty( this, 'id', { value: THREE.Object3DIdCount ++ } );
  4405. this.uuid = THREE.Math.generateUUID();
  4406. this.name = '';
  4407. this.type = 'Object3D';
  4408. this.parent = undefined;
  4409. this.children = [];
  4410. this.up = THREE.Object3D.DefaultUp.clone();
  4411. var position = new THREE.Vector3();
  4412. var rotation = new THREE.Euler();
  4413. var quaternion = new THREE.Quaternion();
  4414. var scale = new THREE.Vector3( 1, 1, 1 );
  4415. var onRotationChange = function () {
  4416. quaternion.setFromEuler( rotation, false );
  4417. };
  4418. var onQuaternionChange = function () {
  4419. rotation.setFromQuaternion( quaternion, undefined, false );
  4420. };
  4421. rotation.onChange( onRotationChange );
  4422. quaternion.onChange( onQuaternionChange );
  4423. Object.defineProperties( this, {
  4424. position: {
  4425. enumerable: true,
  4426. value: position
  4427. },
  4428. rotation: {
  4429. enumerable: true,
  4430. value: rotation
  4431. },
  4432. quaternion: {
  4433. enumerable: true,
  4434. value: quaternion
  4435. },
  4436. scale: {
  4437. enumerable: true,
  4438. value: scale
  4439. }
  4440. } );
  4441. this.rotationAutoUpdate = true;
  4442. this.matrix = new THREE.Matrix4();
  4443. this.matrixWorld = new THREE.Matrix4();
  4444. this.matrixAutoUpdate = true;
  4445. this.matrixWorldNeedsUpdate = false;
  4446. this.visible = true;
  4447. this.castShadow = false;
  4448. this.receiveShadow = false;
  4449. this.frustumCulled = true;
  4450. this.renderOrder = 0;
  4451. this.userData = {};
  4452. };
  4453. THREE.Object3D.DefaultUp = new THREE.Vector3( 0, 1, 0 );
  4454. THREE.Object3D.prototype = {
  4455. constructor: THREE.Object3D,
  4456. get eulerOrder () {
  4457. console.warn( 'THREE.Object3D: .eulerOrder has been moved to .rotation.order.' );
  4458. return this.rotation.order;
  4459. },
  4460. set eulerOrder ( value ) {
  4461. console.warn( 'THREE.Object3D: .eulerOrder has been moved to .rotation.order.' );
  4462. this.rotation.order = value;
  4463. },
  4464. get useQuaternion () {
  4465. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  4466. },
  4467. set useQuaternion ( value ) {
  4468. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  4469. },
  4470. applyMatrix: function ( matrix ) {
  4471. this.matrix.multiplyMatrices( matrix, this.matrix );
  4472. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4473. },
  4474. setRotationFromAxisAngle: function ( axis, angle ) {
  4475. // assumes axis is normalized
  4476. this.quaternion.setFromAxisAngle( axis, angle );
  4477. },
  4478. setRotationFromEuler: function ( euler ) {
  4479. this.quaternion.setFromEuler( euler, true );
  4480. },
  4481. setRotationFromMatrix: function ( m ) {
  4482. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4483. this.quaternion.setFromRotationMatrix( m );
  4484. },
  4485. setRotationFromQuaternion: function ( q ) {
  4486. // assumes q is normalized
  4487. this.quaternion.copy( q );
  4488. },
  4489. rotateOnAxis: function () {
  4490. // rotate object on axis in object space
  4491. // axis is assumed to be normalized
  4492. var q1 = new THREE.Quaternion();
  4493. return function ( axis, angle ) {
  4494. q1.setFromAxisAngle( axis, angle );
  4495. this.quaternion.multiply( q1 );
  4496. return this;
  4497. }
  4498. }(),
  4499. rotateX: function () {
  4500. var v1 = new THREE.Vector3( 1, 0, 0 );
  4501. return function ( angle ) {
  4502. return this.rotateOnAxis( v1, angle );
  4503. };
  4504. }(),
  4505. rotateY: function () {
  4506. var v1 = new THREE.Vector3( 0, 1, 0 );
  4507. return function ( angle ) {
  4508. return this.rotateOnAxis( v1, angle );
  4509. };
  4510. }(),
  4511. rotateZ: function () {
  4512. var v1 = new THREE.Vector3( 0, 0, 1 );
  4513. return function ( angle ) {
  4514. return this.rotateOnAxis( v1, angle );
  4515. };
  4516. }(),
  4517. translateOnAxis: function () {
  4518. // translate object by distance along axis in object space
  4519. // axis is assumed to be normalized
  4520. var v1 = new THREE.Vector3();
  4521. return function ( axis, distance ) {
  4522. v1.copy( axis ).applyQuaternion( this.quaternion );
  4523. this.position.add( v1.multiplyScalar( distance ) );
  4524. return this;
  4525. }
  4526. }(),
  4527. translate: function ( distance, axis ) {
  4528. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  4529. return this.translateOnAxis( axis, distance );
  4530. },
  4531. translateX: function () {
  4532. var v1 = new THREE.Vector3( 1, 0, 0 );
  4533. return function ( distance ) {
  4534. return this.translateOnAxis( v1, distance );
  4535. };
  4536. }(),
  4537. translateY: function () {
  4538. var v1 = new THREE.Vector3( 0, 1, 0 );
  4539. return function ( distance ) {
  4540. return this.translateOnAxis( v1, distance );
  4541. };
  4542. }(),
  4543. translateZ: function () {
  4544. var v1 = new THREE.Vector3( 0, 0, 1 );
  4545. return function ( distance ) {
  4546. return this.translateOnAxis( v1, distance );
  4547. };
  4548. }(),
  4549. localToWorld: function ( vector ) {
  4550. return vector.applyMatrix4( this.matrixWorld );
  4551. },
  4552. worldToLocal: function () {
  4553. var m1 = new THREE.Matrix4();
  4554. return function ( vector ) {
  4555. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  4556. };
  4557. }(),
  4558. lookAt: function () {
  4559. // This routine does not support objects with rotated and/or translated parent(s)
  4560. var m1 = new THREE.Matrix4();
  4561. return function ( vector ) {
  4562. m1.lookAt( vector, this.position, this.up );
  4563. this.quaternion.setFromRotationMatrix( m1 );
  4564. };
  4565. }(),
  4566. add: function ( object ) {
  4567. if ( arguments.length > 1 ) {
  4568. for ( var i = 0; i < arguments.length; i ++ ) {
  4569. this.add( arguments[ i ] );
  4570. }
  4571. return this;
  4572. }
  4573. if ( object === this ) {
  4574. console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object );
  4575. return this;
  4576. }
  4577. if ( object instanceof THREE.Object3D ) {
  4578. if ( object.parent !== undefined ) {
  4579. object.parent.remove( object );
  4580. }
  4581. object.parent = this;
  4582. object.dispatchEvent( { type: 'added' } );
  4583. this.children.push( object );
  4584. } else {
  4585. console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object );
  4586. }
  4587. return this;
  4588. },
  4589. remove: function ( object ) {
  4590. if ( arguments.length > 1 ) {
  4591. for ( var i = 0; i < arguments.length; i ++ ) {
  4592. this.remove( arguments[ i ] );
  4593. }
  4594. }
  4595. var index = this.children.indexOf( object );
  4596. if ( index !== - 1 ) {
  4597. object.parent = undefined;
  4598. object.dispatchEvent( { type: 'removed' } );
  4599. this.children.splice( index, 1 );
  4600. }
  4601. },
  4602. getChildByName: function ( name ) {
  4603. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  4604. return this.getObjectByName( name );
  4605. },
  4606. getObjectById: function ( id ) {
  4607. return this.getObjectByProperty( 'id', id );
  4608. },
  4609. getObjectByName: function ( name ) {
  4610. return this.getObjectByProperty( 'name', name );
  4611. },
  4612. getObjectByProperty: function ( name, value ) {
  4613. if ( this[ name ] === value ) return this;
  4614. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4615. var child = this.children[ i ];
  4616. var object = child.getObjectByProperty( name, value );
  4617. if ( object !== undefined ) {
  4618. return object;
  4619. }
  4620. }
  4621. return undefined;
  4622. },
  4623. getWorldPosition: function ( optionalTarget ) {
  4624. var result = optionalTarget || new THREE.Vector3();
  4625. this.updateMatrixWorld( true );
  4626. return result.setFromMatrixPosition( this.matrixWorld );
  4627. },
  4628. getWorldQuaternion: function () {
  4629. var position = new THREE.Vector3();
  4630. var scale = new THREE.Vector3();
  4631. return function ( optionalTarget ) {
  4632. var result = optionalTarget || new THREE.Quaternion();
  4633. this.updateMatrixWorld( true );
  4634. this.matrixWorld.decompose( position, result, scale );
  4635. return result;
  4636. }
  4637. }(),
  4638. getWorldRotation: function () {
  4639. var quaternion = new THREE.Quaternion();
  4640. return function ( optionalTarget ) {
  4641. var result = optionalTarget || new THREE.Euler();
  4642. this.getWorldQuaternion( quaternion );
  4643. return result.setFromQuaternion( quaternion, this.rotation.order, false );
  4644. }
  4645. }(),
  4646. getWorldScale: function () {
  4647. var position = new THREE.Vector3();
  4648. var quaternion = new THREE.Quaternion();
  4649. return function ( optionalTarget ) {
  4650. var result = optionalTarget || new THREE.Vector3();
  4651. this.updateMatrixWorld( true );
  4652. this.matrixWorld.decompose( position, quaternion, result );
  4653. return result;
  4654. }
  4655. }(),
  4656. getWorldDirection: function () {
  4657. var quaternion = new THREE.Quaternion();
  4658. return function ( optionalTarget ) {
  4659. var result = optionalTarget || new THREE.Vector3();
  4660. this.getWorldQuaternion( quaternion );
  4661. return result.set( 0, 0, 1 ).applyQuaternion( quaternion );
  4662. }
  4663. }(),
  4664. raycast: function () {},
  4665. traverse: function ( callback ) {
  4666. callback( this );
  4667. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4668. this.children[ i ].traverse( callback );
  4669. }
  4670. },
  4671. traverseVisible: function ( callback ) {
  4672. if ( this.visible === false ) return;
  4673. callback( this );
  4674. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4675. this.children[ i ].traverseVisible( callback );
  4676. }
  4677. },
  4678. traverseAncestors: function ( callback ) {
  4679. if ( this.parent ) {
  4680. callback( this.parent );
  4681. this.parent.traverseAncestors( callback );
  4682. }
  4683. },
  4684. updateMatrix: function () {
  4685. this.matrix.compose( this.position, this.quaternion, this.scale );
  4686. this.matrixWorldNeedsUpdate = true;
  4687. },
  4688. updateMatrixWorld: function ( force ) {
  4689. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  4690. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  4691. if ( this.parent === undefined ) {
  4692. this.matrixWorld.copy( this.matrix );
  4693. } else {
  4694. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4695. }
  4696. this.matrixWorldNeedsUpdate = false;
  4697. force = true;
  4698. }
  4699. // update children
  4700. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4701. this.children[ i ].updateMatrixWorld( force );
  4702. }
  4703. },
  4704. toJSON: function ( meta ) {
  4705. var isRootObject = ( meta === undefined );
  4706. var data = {};
  4707. // meta is a hash used to collect geometries, materials.
  4708. // not providing it implies that this is the root object
  4709. // being serialized.
  4710. if ( isRootObject ) {
  4711. // initialize meta obj
  4712. meta = {
  4713. geometries: {},
  4714. materials: {},
  4715. textures: {},
  4716. images: {}
  4717. };
  4718. data.metadata = {
  4719. version: 4.4,
  4720. type: 'Object',
  4721. generator: 'Object3D.toJSON'
  4722. };
  4723. }
  4724. // standard Object3D serialization
  4725. data.uuid = this.uuid;
  4726. data.type = this.type;
  4727. if ( this.name !== '' ) data.name = this.name;
  4728. if ( JSON.stringify( this.userData ) !== '{}' ) data.userData = this.userData;
  4729. if ( this.visible !== true ) data.visible = this.visible;
  4730. data.matrix = this.matrix.toArray();
  4731. if ( this.children.length > 0 ) {
  4732. data.children = [];
  4733. for ( var i = 0; i < this.children.length; i ++ ) {
  4734. data.children.push( this.children[ i ].toJSON( meta ).object );
  4735. }
  4736. }
  4737. var output = {};
  4738. if ( isRootObject ) {
  4739. var geometries = extractFromCache( meta.geometries );
  4740. var materials = extractFromCache( meta.materials );
  4741. var textures = extractFromCache( meta.textures );
  4742. var images = extractFromCache( meta.images );
  4743. if ( geometries.length > 0 ) output.geometries = geometries;
  4744. if ( materials.length > 0 ) output.materials = materials;
  4745. if ( textures.length > 0 ) output.textures = textures;
  4746. if ( images.length > 0 ) output.images = images;
  4747. }
  4748. output.object = data;
  4749. return output;
  4750. // extract data from the cache hash
  4751. // remove metadata on each item
  4752. // and return as array
  4753. function extractFromCache ( cache ) {
  4754. var values = [];
  4755. for ( var key in cache ) {
  4756. var data = cache[ key ];
  4757. delete data.metadata;
  4758. values.push( data );
  4759. }
  4760. return values;
  4761. }
  4762. },
  4763. clone: function ( object, recursive ) {
  4764. if ( object === undefined ) object = new THREE.Object3D();
  4765. if ( recursive === undefined ) recursive = true;
  4766. object.name = this.name;
  4767. object.up.copy( this.up );
  4768. object.position.copy( this.position );
  4769. object.quaternion.copy( this.quaternion );
  4770. object.scale.copy( this.scale );
  4771. object.rotationAutoUpdate = this.rotationAutoUpdate;
  4772. object.matrix.copy( this.matrix );
  4773. object.matrixWorld.copy( this.matrixWorld );
  4774. object.matrixAutoUpdate = this.matrixAutoUpdate;
  4775. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  4776. object.visible = this.visible;
  4777. object.castShadow = this.castShadow;
  4778. object.receiveShadow = this.receiveShadow;
  4779. object.frustumCulled = this.frustumCulled;
  4780. object.renderOrder = this.renderOrder;
  4781. object.userData = JSON.parse( JSON.stringify( this.userData ) );
  4782. if ( recursive === true ) {
  4783. for ( var i = 0; i < this.children.length; i ++ ) {
  4784. var child = this.children[ i ];
  4785. object.add( child.clone() );
  4786. }
  4787. }
  4788. return object;
  4789. }
  4790. };
  4791. THREE.EventDispatcher.prototype.apply( THREE.Object3D.prototype );
  4792. THREE.Object3DIdCount = 0;
  4793. // File:src/core/Face3.js
  4794. /**
  4795. * @author mrdoob / http://mrdoob.com/
  4796. * @author alteredq / http://alteredqualia.com/
  4797. */
  4798. THREE.Face3 = function ( a, b, c, normal, color ) {
  4799. this.a = a;
  4800. this.b = b;
  4801. this.c = c;
  4802. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4803. this.vertexNormals = Array.isArray( normal ) ? normal : [];
  4804. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4805. this.vertexColors = Array.isArray( color ) ? color : [];
  4806. this.vertexTangents = [];
  4807. };
  4808. THREE.Face3.prototype = {
  4809. constructor: THREE.Face3,
  4810. clone: function () {
  4811. var face = new THREE.Face3( this.a, this.b, this.c );
  4812. face.normal.copy( this.normal );
  4813. face.color.copy( this.color );
  4814. for ( var i = 0, il = this.vertexNormals.length; i < il; i ++ ) {
  4815. face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  4816. }
  4817. for ( var i = 0, il = this.vertexColors.length; i < il; i ++ ) {
  4818. face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  4819. }
  4820. for ( var i = 0, il = this.vertexTangents.length; i < il; i ++ ) {
  4821. face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  4822. }
  4823. return face;
  4824. }
  4825. };
  4826. // File:src/core/Face4.js
  4827. /**
  4828. * @author mrdoob / http://mrdoob.com/
  4829. */
  4830. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  4831. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' );
  4832. return new THREE.Face3( a, b, c, normal, color, materialIndex );
  4833. };
  4834. // File:src/core/BufferAttribute.js
  4835. /**
  4836. * @author mrdoob / http://mrdoob.com/
  4837. */
  4838. THREE.BufferAttribute = function ( array, itemSize ) {
  4839. this.array = array;
  4840. this.itemSize = itemSize;
  4841. this.needsUpdate = false;
  4842. };
  4843. THREE.BufferAttribute.prototype = {
  4844. constructor: THREE.BufferAttribute,
  4845. get length () {
  4846. console.warn( 'THREE.BufferAttribute: .length has been renamed to .count.' );
  4847. return this.count;
  4848. },
  4849. get count() {
  4850. return this.array.length / this.itemSize;
  4851. },
  4852. copyAt: function ( index1, attribute, index2 ) {
  4853. index1 *= this.itemSize;
  4854. index2 *= attribute.itemSize;
  4855. for ( var i = 0, l = this.itemSize; i < l; i ++ ) {
  4856. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  4857. }
  4858. return this;
  4859. },
  4860. copyArray: function ( array ) {
  4861. this.array.set( array );
  4862. return this;
  4863. },
  4864. copyColorsArray: function ( colors ) {
  4865. var array = this.array, offset = 0;
  4866. for ( var i = 0, l = colors.length; i < l; i ++ ) {
  4867. var color = colors[ i ];
  4868. if ( color === undefined ) {
  4869. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  4870. color = new THREE.Color();
  4871. }
  4872. array[ offset ++ ] = color.r;
  4873. array[ offset ++ ] = color.g;
  4874. array[ offset ++ ] = color.b;
  4875. }
  4876. return this;
  4877. },
  4878. copyIndicesArray: function ( indices ) {
  4879. var array = this.array, offset = 0;
  4880. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  4881. var index = indices[ i ];
  4882. array[ offset ++ ] = index.a;
  4883. array[ offset ++ ] = index.b;
  4884. array[ offset ++ ] = index.c;
  4885. }
  4886. return this;
  4887. },
  4888. copyVector2sArray: function ( vectors ) {
  4889. var array = this.array, offset = 0;
  4890. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  4891. var vector = vectors[ i ];
  4892. if ( vector === undefined ) {
  4893. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  4894. vector = new THREE.Vector2();
  4895. }
  4896. array[ offset ++ ] = vector.x;
  4897. array[ offset ++ ] = vector.y;
  4898. }
  4899. return this;
  4900. },
  4901. copyVector3sArray: function ( vectors ) {
  4902. var array = this.array, offset = 0;
  4903. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  4904. var vector = vectors[ i ];
  4905. if ( vector === undefined ) {
  4906. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  4907. vector = new THREE.Vector3();
  4908. }
  4909. array[ offset ++ ] = vector.x;
  4910. array[ offset ++ ] = vector.y;
  4911. array[ offset ++ ] = vector.z;
  4912. }
  4913. return this;
  4914. },
  4915. copyVector4sArray: function ( vectors ) {
  4916. var array = this.array, offset = 0;
  4917. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  4918. var vector = vectors[ i ];
  4919. if ( vector === undefined ) {
  4920. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  4921. vector = new THREE.Vector4();
  4922. }
  4923. array[ offset ++ ] = vector.x;
  4924. array[ offset ++ ] = vector.y;
  4925. array[ offset ++ ] = vector.z;
  4926. array[ offset ++ ] = vector.w;
  4927. }
  4928. return this;
  4929. },
  4930. set: function ( value, offset ) {
  4931. if ( offset === undefined ) offset = 0;
  4932. this.array.set( value, offset );
  4933. return this;
  4934. },
  4935. getX: function ( index ) {
  4936. return this.array[ index * this.itemSize ];
  4937. },
  4938. setX: function ( index, x ) {
  4939. this.array[ index * this.itemSize ] = x;
  4940. return this;
  4941. },
  4942. getY: function ( index ) {
  4943. return this.array[ index * this.itemSize + 1 ];
  4944. },
  4945. setY: function ( index, y ) {
  4946. this.array[ index * this.itemSize + 1 ] = y;
  4947. return this;
  4948. },
  4949. getZ: function ( index ) {
  4950. return this.array[ index * this.itemSize + 2 ];
  4951. },
  4952. setZ: function ( index, z ) {
  4953. this.array[ index * this.itemSize + 2 ] = z;
  4954. return this;
  4955. },
  4956. getW: function ( index ) {
  4957. return this.array[ index * this.itemSize + 3 ];
  4958. },
  4959. setW: function ( index, w ) {
  4960. this.array[ index * this.itemSize + 3 ] = w;
  4961. return this;
  4962. },
  4963. setXY: function ( index, x, y ) {
  4964. index *= this.itemSize;
  4965. this.array[ index + 0 ] = x;
  4966. this.array[ index + 1 ] = y;
  4967. return this;
  4968. },
  4969. setXYZ: function ( index, x, y, z ) {
  4970. index *= this.itemSize;
  4971. this.array[ index + 0 ] = x;
  4972. this.array[ index + 1 ] = y;
  4973. this.array[ index + 2 ] = z;
  4974. return this;
  4975. },
  4976. setXYZW: function ( index, x, y, z, w ) {
  4977. index *= this.itemSize;
  4978. this.array[ index + 0 ] = x;
  4979. this.array[ index + 1 ] = y;
  4980. this.array[ index + 2 ] = z;
  4981. this.array[ index + 3 ] = w;
  4982. return this;
  4983. },
  4984. clone: function () {
  4985. return new THREE.BufferAttribute( new this.array.constructor( this.array ), this.itemSize );
  4986. }
  4987. };
  4988. //
  4989. THREE.Int8Attribute = function ( array, itemSize ) {
  4990. return new THREE.BufferAttribute( new Int8Array( array ), itemSize );
  4991. };
  4992. THREE.Uint8Attribute = function ( array, itemSize ) {
  4993. return new THREE.BufferAttribute( new Uint8Array( array ), itemSize );
  4994. };
  4995. THREE.Uint8ClampedAttribute = function ( array, itemSize ) {
  4996. return new THREE.BufferAttribute( new Uint8ClampedArray( array ), itemSize );
  4997. };
  4998. THREE.Int16Attribute = function ( array, itemSize ) {
  4999. return new THREE.BufferAttribute( new Int16Array( array ), itemSize );
  5000. };
  5001. THREE.Uint16Attribute = function ( array, itemSize ) {
  5002. return new THREE.BufferAttribute( new Uint16Array( array ), itemSize );
  5003. };
  5004. THREE.Int32Attribute = function ( array, itemSize ) {
  5005. return new THREE.BufferAttribute( new Int32Array( array ), itemSize );
  5006. };
  5007. THREE.Uint32Attribute = function ( array, itemSize ) {
  5008. return new THREE.BufferAttribute( new Uint32Array( array ), itemSize );
  5009. };
  5010. THREE.Float32Attribute = function ( array, itemSize ) {
  5011. return new THREE.BufferAttribute( new Float32Array( array ), itemSize );
  5012. };
  5013. THREE.Float64Attribute = function ( array, itemSize ) {
  5014. return new THREE.BufferAttribute( new Float64Array( array ), itemSize );
  5015. };
  5016. // File:src/core/DynamicBufferAttribute.js
  5017. /**
  5018. * @author benaadams / https://twitter.com/ben_a_adams
  5019. * @author mrdoob / http://mrdoob.com/
  5020. */
  5021. THREE.DynamicBufferAttribute = function ( array, itemSize ) {
  5022. THREE.BufferAttribute.call( this, array, itemSize );
  5023. this.updateRange = { offset: 0, count: -1 };
  5024. };
  5025. THREE.DynamicBufferAttribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5026. THREE.DynamicBufferAttribute.prototype.constructor = THREE.DynamicBufferAttribute;
  5027. THREE.DynamicBufferAttribute.prototype.clone = function () {
  5028. return new THREE.DynamicBufferAttribute( new this.array.constructor( this.array ), this.itemSize );
  5029. };
  5030. // File:src/core/InstancedBufferAttribute.js
  5031. /**
  5032. * @author benaadams / https://twitter.com/ben_a_adams
  5033. */
  5034. THREE.InstancedBufferAttribute = function (array, itemSize, meshPerAttribute, dynamic) {
  5035. THREE.DynamicBufferAttribute.call( this, array, itemSize );
  5036. this.dynamic = dynamic || false;
  5037. this.meshPerAttribute = meshPerAttribute || 1;
  5038. };
  5039. THREE.InstancedBufferAttribute.prototype = Object.create( THREE.DynamicBufferAttribute.prototype );
  5040. THREE.InstancedBufferAttribute.prototype.constructor = THREE.InstancedBufferAttribute;
  5041. THREE.InstancedBufferAttribute.prototype.clone = function () {
  5042. return new THREE.InstancedBufferAttribute( new this.array.constructor( this.array ), this.itemSize, this.meshPerAttribute, this.dynamic );
  5043. };
  5044. // File:src/core/InterleavedBuffer.js
  5045. /**
  5046. * @author benaadams / https://twitter.com/ben_a_adams
  5047. */
  5048. THREE.InterleavedBuffer = function ( array, stride, dynamic ) {
  5049. this.array = array;
  5050. this.stride = stride;
  5051. this.needsUpdate = false;
  5052. this.dynamic = dynamic || false;
  5053. this.updateRange = { offset: 0, count: -1 };
  5054. };
  5055. THREE.InterleavedBuffer.prototype = {
  5056. constructor: THREE.InterleavedBuffer,
  5057. get length () {
  5058. return this.array.length;
  5059. },
  5060. copyAt: function ( index1, attribute, index2 ) {
  5061. index1 *= this.stride;
  5062. index2 *= attribute.stride;
  5063. for ( var i = 0, l = this.stride; i < l; i++ ) {
  5064. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5065. }
  5066. return this;
  5067. },
  5068. set: function ( value, offset ) {
  5069. if ( offset === undefined ) offset = 0;
  5070. this.array.set( value, offset );
  5071. return this;
  5072. },
  5073. clone: function () {
  5074. return new THREE.InterleavedBuffer( new this.array.constructor( this.array ), this.stride, this.dynamic );
  5075. }
  5076. };
  5077. // File:src/core/InstancedInterleavedBuffer.js
  5078. /**
  5079. * @author benaadams / https://twitter.com/ben_a_adams
  5080. */
  5081. THREE.InstancedInterleavedBuffer = function ( array, stride, dynamic, meshPerAttribute ) {
  5082. THREE.InterleavedBuffer.call( this, array, stride, dynamic );
  5083. this.meshPerAttribute = meshPerAttribute || 1;
  5084. };
  5085. THREE.InstancedInterleavedBuffer.prototype = Object.create( THREE.InterleavedBuffer.prototype );
  5086. THREE.InstancedInterleavedBuffer.prototype.constructor = THREE.InstancedInterleavedBuffer;
  5087. THREE.InstancedInterleavedBuffer.prototype.clone = function () {
  5088. return new THREE.InstancedInterleavedBuffer( new this.array.constructor( this.array ), this.stride, this.dynamic, this.meshPerAttribute );
  5089. };
  5090. // File:src/core/InterleavedBufferAttribute.js
  5091. /**
  5092. * @author benaadams / https://twitter.com/ben_a_adams
  5093. */
  5094. THREE.InterleavedBufferAttribute = function ( interleavedBuffer, itemSize, offset ) {
  5095. this.data = interleavedBuffer;
  5096. this.itemSize = itemSize;
  5097. this.offset = offset;
  5098. };
  5099. THREE.InterleavedBufferAttribute.prototype = {
  5100. constructor: THREE.InterleavedBufferAttribute,
  5101. get length() {
  5102. console.warn( 'THREE.InterleavedBufferAttribute: .length has been renamed to .count.' );
  5103. return this.count;
  5104. },
  5105. get count() {
  5106. return this.data.array.length / this.data.stride;
  5107. },
  5108. setX: function ( index, x ) {
  5109. this.data.array[ index * this.data.stride + this.offset ] = x;
  5110. return this;
  5111. },
  5112. setY: function ( index, y ) {
  5113. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  5114. return this;
  5115. },
  5116. setZ: function ( index, z ) {
  5117. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  5118. return this;
  5119. },
  5120. setW: function ( index, w ) {
  5121. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  5122. return this;
  5123. },
  5124. getX: function ( index ) {
  5125. return this.data.array[ index * this.data.stride + this.offset ];
  5126. },
  5127. getY: function ( index ) {
  5128. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  5129. },
  5130. getZ: function ( index ) {
  5131. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  5132. },
  5133. getW: function ( index ) {
  5134. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  5135. },
  5136. setXY: function ( index, x, y ) {
  5137. index = index * this.data.stride + this.offset;
  5138. this.data.array[ index + 0 ] = x;
  5139. this.data.array[ index + 1 ] = y;
  5140. return this;
  5141. },
  5142. setXYZ: function ( index, x, y, z ) {
  5143. index = index * this.data.stride + this.offset;
  5144. this.data.array[ index + 0 ] = x;
  5145. this.data.array[ index + 1 ] = y;
  5146. this.data.array[ index + 2 ] = z;
  5147. return this;
  5148. },
  5149. setXYZW: function ( index, x, y, z, w ) {
  5150. index = index * this.data.stride + this.offset;
  5151. this.data.array[ index + 0 ] = x;
  5152. this.data.array[ index + 1 ] = y;
  5153. this.data.array[ index + 2 ] = z;
  5154. this.data.array[ index + 3 ] = w;
  5155. return this;
  5156. }
  5157. };
  5158. // File:src/core/Geometry.js
  5159. /**
  5160. * @author mrdoob / http://mrdoob.com/
  5161. * @author kile / http://kile.stravaganza.org/
  5162. * @author alteredq / http://alteredqualia.com/
  5163. * @author mikael emtinger / http://gomo.se/
  5164. * @author zz85 / http://www.lab4games.net/zz85/blog
  5165. * @author bhouston / http://exocortex.com
  5166. */
  5167. THREE.Geometry = function () {
  5168. Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } );
  5169. this.uuid = THREE.Math.generateUUID();
  5170. this.name = '';
  5171. this.type = 'Geometry';
  5172. this.vertices = [];
  5173. this.colors = [];
  5174. this.faces = [];
  5175. this.faceVertexUvs = [ [] ];
  5176. this.morphTargets = [];
  5177. this.morphColors = [];
  5178. this.morphNormals = [];
  5179. this.skinWeights = [];
  5180. this.skinIndices = [];
  5181. this.lineDistances = [];
  5182. this.boundingBox = null;
  5183. this.boundingSphere = null;
  5184. this.hasTangents = false;
  5185. // update flags
  5186. this.verticesNeedUpdate = false;
  5187. this.elementsNeedUpdate = false;
  5188. this.uvsNeedUpdate = false;
  5189. this.normalsNeedUpdate = false;
  5190. this.tangentsNeedUpdate = false;
  5191. this.colorsNeedUpdate = false;
  5192. this.lineDistancesNeedUpdate = false;
  5193. this.groupsNeedUpdate = false;
  5194. };
  5195. THREE.Geometry.prototype = {
  5196. constructor: THREE.Geometry,
  5197. applyMatrix: function ( matrix ) {
  5198. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5199. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  5200. var vertex = this.vertices[ i ];
  5201. vertex.applyMatrix4( matrix );
  5202. }
  5203. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  5204. var face = this.faces[ i ];
  5205. face.normal.applyMatrix3( normalMatrix ).normalize();
  5206. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  5207. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  5208. }
  5209. }
  5210. if ( this.boundingBox !== null ) {
  5211. this.computeBoundingBox();
  5212. }
  5213. if ( this.boundingSphere !== null ) {
  5214. this.computeBoundingSphere();
  5215. }
  5216. this.verticesNeedUpdate = true;
  5217. this.normalsNeedUpdate = true;
  5218. },
  5219. fromBufferGeometry: function ( geometry ) {
  5220. var scope = this;
  5221. var attributes = geometry.attributes;
  5222. var vertices = attributes.position.array;
  5223. var indices = attributes.index !== undefined ? attributes.index.array : undefined;
  5224. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  5225. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  5226. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  5227. var tempNormals = [];
  5228. var tempUVs = [];
  5229. for ( var i = 0, j = 0; i < vertices.length; i += 3, j += 2 ) {
  5230. scope.vertices.push( new THREE.Vector3( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] ) );
  5231. if ( normals !== undefined ) {
  5232. tempNormals.push( new THREE.Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) );
  5233. }
  5234. if ( colors !== undefined ) {
  5235. scope.colors.push( new THREE.Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) );
  5236. }
  5237. if ( uvs !== undefined ) {
  5238. tempUVs.push( new THREE.Vector2( uvs[ j ], uvs[ j + 1 ] ) );
  5239. }
  5240. }
  5241. var addFace = function ( a, b, c ) {
  5242. var vertexNormals = normals !== undefined ? [ tempNormals[ a ].clone(), tempNormals[ b ].clone(), tempNormals[ c ].clone() ] : [];
  5243. var vertexColors = colors !== undefined ? [ scope.colors[ a ].clone(), scope.colors[ b ].clone(), scope.colors[ c ].clone() ] : [];
  5244. scope.faces.push( new THREE.Face3( a, b, c, vertexNormals, vertexColors ) );
  5245. if ( uvs !== undefined ) {
  5246. scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] );
  5247. }
  5248. };
  5249. if ( indices !== undefined ) {
  5250. var drawcalls = geometry.drawcalls;
  5251. if ( drawcalls.length > 0 ) {
  5252. for ( var i = 0; i < drawcalls.length; i ++ ) {
  5253. var drawcall = drawcalls[ i ];
  5254. var start = drawcall.start;
  5255. var count = drawcall.count;
  5256. var index = drawcall.index;
  5257. for ( var j = start, jl = start + count; j < jl; j += 3 ) {
  5258. addFace( index + indices[ j ], index + indices[ j + 1 ], index + indices[ j + 2 ] );
  5259. }
  5260. }
  5261. } else {
  5262. for ( var i = 0; i < indices.length; i += 3 ) {
  5263. addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  5264. }
  5265. }
  5266. } else {
  5267. for ( var i = 0; i < vertices.length / 3; i += 3 ) {
  5268. addFace( i, i + 1, i + 2 );
  5269. }
  5270. }
  5271. this.computeFaceNormals();
  5272. if ( geometry.boundingBox !== null ) {
  5273. this.boundingBox = geometry.boundingBox.clone();
  5274. }
  5275. if ( geometry.boundingSphere !== null ) {
  5276. this.boundingSphere = geometry.boundingSphere.clone();
  5277. }
  5278. return this;
  5279. },
  5280. center: function () {
  5281. this.computeBoundingBox();
  5282. var offset = this.boundingBox.center().negate();
  5283. this.applyMatrix( new THREE.Matrix4().setPosition( offset ) );
  5284. return offset;
  5285. },
  5286. normalize: function () {
  5287. this.computeBoundingSphere();
  5288. var center = this.boundingSphere.center;
  5289. var radius = this.boundingSphere.radius;
  5290. var s = radius === 0 ? 1 : 1.0 / radius;
  5291. var matrix = new THREE.Matrix4();
  5292. matrix.set(
  5293. s, 0, 0, -s * center.x,
  5294. 0, s, 0, -s * center.y,
  5295. 0, 0, s, -s * center.z,
  5296. 0, 0, 0, 1
  5297. );
  5298. this.applyMatrix( matrix );
  5299. return this;
  5300. },
  5301. computeFaceNormals: function () {
  5302. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  5303. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5304. var face = this.faces[ f ];
  5305. var vA = this.vertices[ face.a ];
  5306. var vB = this.vertices[ face.b ];
  5307. var vC = this.vertices[ face.c ];
  5308. cb.subVectors( vC, vB );
  5309. ab.subVectors( vA, vB );
  5310. cb.cross( ab );
  5311. cb.normalize();
  5312. face.normal.copy( cb );
  5313. }
  5314. },
  5315. computeVertexNormals: function ( areaWeighted ) {
  5316. var v, vl, f, fl, face, vertices;
  5317. vertices = new Array( this.vertices.length );
  5318. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5319. vertices[ v ] = new THREE.Vector3();
  5320. }
  5321. if ( areaWeighted ) {
  5322. // vertex normals weighted by triangle areas
  5323. // http://www.iquilezles.org/www/articles/normals/normals.htm
  5324. var vA, vB, vC;
  5325. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  5326. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5327. face = this.faces[ f ];
  5328. vA = this.vertices[ face.a ];
  5329. vB = this.vertices[ face.b ];
  5330. vC = this.vertices[ face.c ];
  5331. cb.subVectors( vC, vB );
  5332. ab.subVectors( vA, vB );
  5333. cb.cross( ab );
  5334. vertices[ face.a ].add( cb );
  5335. vertices[ face.b ].add( cb );
  5336. vertices[ face.c ].add( cb );
  5337. }
  5338. } else {
  5339. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5340. face = this.faces[ f ];
  5341. vertices[ face.a ].add( face.normal );
  5342. vertices[ face.b ].add( face.normal );
  5343. vertices[ face.c ].add( face.normal );
  5344. }
  5345. }
  5346. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5347. vertices[ v ].normalize();
  5348. }
  5349. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5350. face = this.faces[ f ];
  5351. var vertexNormals = face.vertexNormals;
  5352. if ( vertexNormals.length === 3 ) {
  5353. vertexNormals[ 0 ].copy( vertices[ face.a ] );
  5354. vertexNormals[ 1 ].copy( vertices[ face.b ] );
  5355. vertexNormals[ 2 ].copy( vertices[ face.c ] );
  5356. } else {
  5357. vertexNormals[ 0 ] = vertices[ face.a ].clone();
  5358. vertexNormals[ 1 ] = vertices[ face.b ].clone();
  5359. vertexNormals[ 2 ] = vertices[ face.c ].clone();
  5360. }
  5361. }
  5362. },
  5363. computeMorphNormals: function () {
  5364. var i, il, f, fl, face;
  5365. // save original normals
  5366. // - create temp variables on first access
  5367. // otherwise just copy (for faster repeated calls)
  5368. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5369. face = this.faces[ f ];
  5370. if ( ! face.__originalFaceNormal ) {
  5371. face.__originalFaceNormal = face.normal.clone();
  5372. } else {
  5373. face.__originalFaceNormal.copy( face.normal );
  5374. }
  5375. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  5376. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  5377. if ( ! face.__originalVertexNormals[ i ] ) {
  5378. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  5379. } else {
  5380. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  5381. }
  5382. }
  5383. }
  5384. // use temp geometry to compute face and vertex normals for each morph
  5385. var tmpGeo = new THREE.Geometry();
  5386. tmpGeo.faces = this.faces;
  5387. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  5388. // create on first access
  5389. if ( ! this.morphNormals[ i ] ) {
  5390. this.morphNormals[ i ] = {};
  5391. this.morphNormals[ i ].faceNormals = [];
  5392. this.morphNormals[ i ].vertexNormals = [];
  5393. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  5394. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  5395. var faceNormal, vertexNormals;
  5396. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5397. faceNormal = new THREE.Vector3();
  5398. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  5399. dstNormalsFace.push( faceNormal );
  5400. dstNormalsVertex.push( vertexNormals );
  5401. }
  5402. }
  5403. var morphNormals = this.morphNormals[ i ];
  5404. // set vertices to morph target
  5405. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  5406. // compute morph normals
  5407. tmpGeo.computeFaceNormals();
  5408. tmpGeo.computeVertexNormals();
  5409. // store morph normals
  5410. var faceNormal, vertexNormals;
  5411. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5412. face = this.faces[ f ];
  5413. faceNormal = morphNormals.faceNormals[ f ];
  5414. vertexNormals = morphNormals.vertexNormals[ f ];
  5415. faceNormal.copy( face.normal );
  5416. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  5417. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  5418. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  5419. }
  5420. }
  5421. // restore original normals
  5422. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5423. face = this.faces[ f ];
  5424. face.normal = face.__originalFaceNormal;
  5425. face.vertexNormals = face.__originalVertexNormals;
  5426. }
  5427. },
  5428. computeTangents: function () {
  5429. // based on http://www.terathon.com/code/tangent.html
  5430. // tangents go to vertices
  5431. var f, fl, v, vl, i, vertexIndex,
  5432. face, uv, vA, vB, vC, uvA, uvB, uvC,
  5433. x1, x2, y1, y2, z1, z2,
  5434. s1, s2, t1, t2, r, t, test,
  5435. tan1 = [], tan2 = [],
  5436. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  5437. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  5438. n = new THREE.Vector3(), w;
  5439. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5440. tan1[ v ] = new THREE.Vector3();
  5441. tan2[ v ] = new THREE.Vector3();
  5442. }
  5443. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  5444. vA = context.vertices[ a ];
  5445. vB = context.vertices[ b ];
  5446. vC = context.vertices[ c ];
  5447. uvA = uv[ ua ];
  5448. uvB = uv[ ub ];
  5449. uvC = uv[ uc ];
  5450. x1 = vB.x - vA.x;
  5451. x2 = vC.x - vA.x;
  5452. y1 = vB.y - vA.y;
  5453. y2 = vC.y - vA.y;
  5454. z1 = vB.z - vA.z;
  5455. z2 = vC.z - vA.z;
  5456. s1 = uvB.x - uvA.x;
  5457. s2 = uvC.x - uvA.x;
  5458. t1 = uvB.y - uvA.y;
  5459. t2 = uvC.y - uvA.y;
  5460. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5461. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  5462. ( t2 * y1 - t1 * y2 ) * r,
  5463. ( t2 * z1 - t1 * z2 ) * r );
  5464. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  5465. ( s1 * y2 - s2 * y1 ) * r,
  5466. ( s1 * z2 - s2 * z1 ) * r );
  5467. tan1[ a ].add( sdir );
  5468. tan1[ b ].add( sdir );
  5469. tan1[ c ].add( sdir );
  5470. tan2[ a ].add( tdir );
  5471. tan2[ b ].add( tdir );
  5472. tan2[ c ].add( tdir );
  5473. }
  5474. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5475. face = this.faces[ f ];
  5476. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  5477. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  5478. }
  5479. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  5480. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5481. face = this.faces[ f ];
  5482. for ( i = 0; i < Math.min( face.vertexNormals.length, 3 ); i ++ ) {
  5483. n.copy( face.vertexNormals[ i ] );
  5484. vertexIndex = face[ faceIndex[ i ] ];
  5485. t = tan1[ vertexIndex ];
  5486. // Gram-Schmidt orthogonalize
  5487. tmp.copy( t );
  5488. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5489. // Calculate handedness
  5490. tmp2.crossVectors( face.vertexNormals[ i ], t );
  5491. test = tmp2.dot( tan2[ vertexIndex ] );
  5492. w = ( test < 0.0 ) ? - 1.0 : 1.0;
  5493. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  5494. }
  5495. }
  5496. this.hasTangents = true;
  5497. },
  5498. computeLineDistances: function () {
  5499. var d = 0;
  5500. var vertices = this.vertices;
  5501. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  5502. if ( i > 0 ) {
  5503. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  5504. }
  5505. this.lineDistances[ i ] = d;
  5506. }
  5507. },
  5508. computeBoundingBox: function () {
  5509. if ( this.boundingBox === null ) {
  5510. this.boundingBox = new THREE.Box3();
  5511. }
  5512. this.boundingBox.setFromPoints( this.vertices );
  5513. },
  5514. computeBoundingSphere: function () {
  5515. if ( this.boundingSphere === null ) {
  5516. this.boundingSphere = new THREE.Sphere();
  5517. }
  5518. this.boundingSphere.setFromPoints( this.vertices );
  5519. },
  5520. merge: function ( geometry, matrix ) {
  5521. if ( geometry instanceof THREE.Geometry === false ) {
  5522. console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  5523. return;
  5524. }
  5525. var normalMatrix,
  5526. vertexOffset = this.vertices.length,
  5527. vertices1 = this.vertices,
  5528. vertices2 = geometry.vertices,
  5529. faces1 = this.faces,
  5530. faces2 = geometry.faces,
  5531. uvs1 = this.faceVertexUvs[ 0 ],
  5532. uvs2 = geometry.faceVertexUvs[ 0 ];
  5533. if ( matrix !== undefined ) {
  5534. normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5535. }
  5536. // vertices
  5537. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  5538. var vertex = vertices2[ i ];
  5539. var vertexCopy = vertex.clone();
  5540. if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
  5541. vertices1.push( vertexCopy );
  5542. }
  5543. // faces
  5544. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  5545. var face = faces2[ i ], faceCopy, normal, color,
  5546. faceVertexNormals = face.vertexNormals,
  5547. faceVertexColors = face.vertexColors;
  5548. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  5549. faceCopy.normal.copy( face.normal );
  5550. if ( normalMatrix !== undefined ) {
  5551. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  5552. }
  5553. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  5554. normal = faceVertexNormals[ j ].clone();
  5555. if ( normalMatrix !== undefined ) {
  5556. normal.applyMatrix3( normalMatrix ).normalize();
  5557. }
  5558. faceCopy.vertexNormals.push( normal );
  5559. }
  5560. faceCopy.color.copy( face.color );
  5561. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  5562. color = faceVertexColors[ j ];
  5563. faceCopy.vertexColors.push( color.clone() );
  5564. }
  5565. faces1.push( faceCopy );
  5566. }
  5567. // uvs
  5568. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  5569. var uv = uvs2[ i ], uvCopy = [];
  5570. if ( uv === undefined ) {
  5571. continue;
  5572. }
  5573. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  5574. uvCopy.push( uv[ j ].clone() );
  5575. }
  5576. uvs1.push( uvCopy );
  5577. }
  5578. },
  5579. mergeMesh: function ( mesh ) {
  5580. if ( mesh instanceof THREE.Mesh === false ) {
  5581. console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
  5582. return;
  5583. }
  5584. mesh.matrixAutoUpdate && mesh.updateMatrix();
  5585. this.merge( mesh.geometry, mesh.matrix );
  5586. },
  5587. /*
  5588. * Checks for duplicate vertices with hashmap.
  5589. * Duplicated vertices are removed
  5590. * and faces' vertices are updated.
  5591. */
  5592. mergeVertices: function () {
  5593. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  5594. var unique = [], changes = [];
  5595. var v, key;
  5596. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  5597. var precision = Math.pow( 10, precisionPoints );
  5598. var i, il, face;
  5599. var indices, j, jl;
  5600. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  5601. v = this.vertices[ i ];
  5602. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  5603. if ( verticesMap[ key ] === undefined ) {
  5604. verticesMap[ key ] = i;
  5605. unique.push( this.vertices[ i ] );
  5606. changes[ i ] = unique.length - 1;
  5607. } else {
  5608. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  5609. changes[ i ] = changes[ verticesMap[ key ] ];
  5610. }
  5611. }
  5612. // if faces are completely degenerate after merging vertices, we
  5613. // have to remove them from the geometry.
  5614. var faceIndicesToRemove = [];
  5615. for ( i = 0, il = this.faces.length; i < il; i ++ ) {
  5616. face = this.faces[ i ];
  5617. face.a = changes[ face.a ];
  5618. face.b = changes[ face.b ];
  5619. face.c = changes[ face.c ];
  5620. indices = [ face.a, face.b, face.c ];
  5621. var dupIndex = - 1;
  5622. // if any duplicate vertices are found in a Face3
  5623. // we have to remove the face as nothing can be saved
  5624. for ( var n = 0; n < 3; n ++ ) {
  5625. if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) {
  5626. dupIndex = n;
  5627. faceIndicesToRemove.push( i );
  5628. break;
  5629. }
  5630. }
  5631. }
  5632. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  5633. var idx = faceIndicesToRemove[ i ];
  5634. this.faces.splice( idx, 1 );
  5635. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  5636. this.faceVertexUvs[ j ].splice( idx, 1 );
  5637. }
  5638. }
  5639. // Use unique set of vertices
  5640. var diff = this.vertices.length - unique.length;
  5641. this.vertices = unique;
  5642. return diff;
  5643. },
  5644. toJSON: function () {
  5645. var data = {
  5646. metadata: {
  5647. version: 4.4,
  5648. type: 'Geometry',
  5649. generator: 'Geometry.toJSON'
  5650. }
  5651. };
  5652. // standard Geometry serialization
  5653. data.uuid = this.uuid;
  5654. data.type = this.type;
  5655. if ( this.name !== '' ) data.name = this.name;
  5656. if ( this.parameters !== undefined ) {
  5657. var parameters = this.parameters;
  5658. for ( var key in parameters ) {
  5659. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  5660. }
  5661. return data;
  5662. }
  5663. var vertices = [];
  5664. for ( var i = 0; i < this.vertices.length; i ++ ) {
  5665. var vertex = this.vertices[ i ];
  5666. vertices.push( vertex.x, vertex.y, vertex.z );
  5667. }
  5668. var faces = [];
  5669. var normals = [];
  5670. var normalsHash = {};
  5671. var colors = [];
  5672. var colorsHash = {};
  5673. var uvs = [];
  5674. var uvsHash = {};
  5675. for ( var i = 0; i < this.faces.length; i ++ ) {
  5676. var face = this.faces[ i ];
  5677. var hasMaterial = false; // face.materialIndex !== undefined;
  5678. var hasFaceUv = false; // deprecated
  5679. var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined;
  5680. var hasFaceNormal = face.normal.length() > 0;
  5681. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  5682. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  5683. var hasFaceVertexColor = face.vertexColors.length > 0;
  5684. var faceType = 0;
  5685. faceType = setBit( faceType, 0, 0 );
  5686. faceType = setBit( faceType, 1, hasMaterial );
  5687. faceType = setBit( faceType, 2, hasFaceUv );
  5688. faceType = setBit( faceType, 3, hasFaceVertexUv );
  5689. faceType = setBit( faceType, 4, hasFaceNormal );
  5690. faceType = setBit( faceType, 5, hasFaceVertexNormal );
  5691. faceType = setBit( faceType, 6, hasFaceColor );
  5692. faceType = setBit( faceType, 7, hasFaceVertexColor );
  5693. faces.push( faceType );
  5694. faces.push( face.a, face.b, face.c );
  5695. if ( hasFaceVertexUv ) {
  5696. var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ];
  5697. faces.push(
  5698. getUvIndex( faceVertexUvs[ 0 ] ),
  5699. getUvIndex( faceVertexUvs[ 1 ] ),
  5700. getUvIndex( faceVertexUvs[ 2 ] )
  5701. );
  5702. }
  5703. if ( hasFaceNormal ) {
  5704. faces.push( getNormalIndex( face.normal ) );
  5705. }
  5706. if ( hasFaceVertexNormal ) {
  5707. var vertexNormals = face.vertexNormals;
  5708. faces.push(
  5709. getNormalIndex( vertexNormals[ 0 ] ),
  5710. getNormalIndex( vertexNormals[ 1 ] ),
  5711. getNormalIndex( vertexNormals[ 2 ] )
  5712. );
  5713. }
  5714. if ( hasFaceColor ) {
  5715. faces.push( getColorIndex( face.color ) );
  5716. }
  5717. if ( hasFaceVertexColor ) {
  5718. var vertexColors = face.vertexColors;
  5719. faces.push(
  5720. getColorIndex( vertexColors[ 0 ] ),
  5721. getColorIndex( vertexColors[ 1 ] ),
  5722. getColorIndex( vertexColors[ 2 ] )
  5723. );
  5724. }
  5725. }
  5726. function setBit( value, position, enabled ) {
  5727. return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position) );
  5728. }
  5729. function getNormalIndex( normal ) {
  5730. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  5731. if ( normalsHash[ hash ] !== undefined ) {
  5732. return normalsHash[ hash ];
  5733. }
  5734. normalsHash[ hash ] = normals.length / 3;
  5735. normals.push( normal.x, normal.y, normal.z );
  5736. return normalsHash[ hash ];
  5737. }
  5738. function getColorIndex( color ) {
  5739. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  5740. if ( colorsHash[ hash ] !== undefined ) {
  5741. return colorsHash[ hash ];
  5742. }
  5743. colorsHash[ hash ] = colors.length;
  5744. colors.push( color.getHex() );
  5745. return colorsHash[ hash ];
  5746. }
  5747. function getUvIndex( uv ) {
  5748. var hash = uv.x.toString() + uv.y.toString();
  5749. if ( uvsHash[ hash ] !== undefined ) {
  5750. return uvsHash[ hash ];
  5751. }
  5752. uvsHash[ hash ] = uvs.length / 2;
  5753. uvs.push( uv.x, uv.y );
  5754. return uvsHash[ hash ];
  5755. }
  5756. data.data = {};
  5757. data.data.vertices = vertices;
  5758. data.data.normals = normals;
  5759. if ( colors.length > 0 ) data.data.colors = colors;
  5760. if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility
  5761. data.data.faces = faces;
  5762. return data;
  5763. },
  5764. clone: function () {
  5765. var geometry = new THREE.Geometry();
  5766. var vertices = this.vertices;
  5767. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  5768. geometry.vertices.push( vertices[ i ].clone() );
  5769. }
  5770. var faces = this.faces;
  5771. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  5772. geometry.faces.push( faces[ i ].clone() );
  5773. }
  5774. for ( var i = 0, il = this.faceVertexUvs.length; i < il; i ++ ) {
  5775. var faceVertexUvs = this.faceVertexUvs[ i ];
  5776. if ( geometry.faceVertexUvs[ i ] === undefined ) {
  5777. geometry.faceVertexUvs[ i ] = [];
  5778. }
  5779. for ( var j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {
  5780. var uvs = faceVertexUvs[ j ], uvsCopy = [];
  5781. for ( var k = 0, kl = uvs.length; k < kl; k ++ ) {
  5782. var uv = uvs[ k ];
  5783. uvsCopy.push( uv.clone() );
  5784. }
  5785. geometry.faceVertexUvs[ i ].push( uvsCopy );
  5786. }
  5787. }
  5788. return geometry;
  5789. },
  5790. dispose: function () {
  5791. this.dispatchEvent( { type: 'dispose' } );
  5792. }
  5793. };
  5794. THREE.EventDispatcher.prototype.apply( THREE.Geometry.prototype );
  5795. THREE.GeometryIdCount = 0;
  5796. // File:src/core/DirectGeometry.js
  5797. /**
  5798. * @author mrdoob / http://mrdoob.com/
  5799. */
  5800. THREE.DirectGeometry = function () {
  5801. Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } );
  5802. this.uuid = THREE.Math.generateUUID();
  5803. this.name = '';
  5804. this.type = 'DirectGeometry';
  5805. this.indices = [];
  5806. this.vertices = [];
  5807. this.colors = [];
  5808. this.normals = [];
  5809. this.colors = [];
  5810. this.uvs = [];
  5811. this.uvs2 = [];
  5812. this.morphTargets = [];
  5813. this.morphColors = [];
  5814. this.morphNormals = [];
  5815. this.skinWeights = [];
  5816. this.skinIndices = [];
  5817. // this.lineDistances = [];
  5818. this.boundingBox = null;
  5819. this.boundingSphere = null;
  5820. // update flags
  5821. this.verticesNeedUpdate = false;
  5822. this.normalsNeedUpdate = false;
  5823. this.colorsNeedUpdate = false;
  5824. this.uvsNeedUpdate = false;
  5825. };
  5826. THREE.DirectGeometry.prototype = {
  5827. constructor: THREE.DirectGeometry,
  5828. computeBoundingBox: THREE.Geometry.prototype.computeBoundingBox,
  5829. computeBoundingSphere: THREE.Geometry.prototype.computeBoundingSphere,
  5830. computeFaceNormals: function () {
  5831. console.warn( 'THREE.DirectGeometry: computeFaceNormals() is not a method of this type of geometry.' );
  5832. return this;
  5833. },
  5834. computeVertexNormals: function () {
  5835. console.warn( 'THREE.DirectGeometry: computeVertexNormals() is not a method of this type of geometry.' );
  5836. return this;
  5837. },
  5838. fromGeometry: function ( geometry, material ) {
  5839. material = material || { 'vertexColors': THREE.NoColors };
  5840. var faces = geometry.faces;
  5841. var vertices = geometry.vertices;
  5842. var faceVertexUvs = geometry.faceVertexUvs;
  5843. var materialVertexColors = material.vertexColors;
  5844. var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0;
  5845. var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0;
  5846. // morphs
  5847. var morphTargets = geometry.morphTargets;
  5848. var morphTargetsLength = morphTargets.length;
  5849. for ( var i = 0; i < morphTargetsLength; i ++ ) {
  5850. this.morphTargets[ i ] = [];
  5851. }
  5852. var morphNormals = geometry.morphNormals;
  5853. var morphNormalsLength = morphNormals.length;
  5854. for ( var i = 0; i < morphNormalsLength; i ++ ) {
  5855. this.morphNormals[ i ] = [];
  5856. }
  5857. var morphColors = geometry.morphColors;
  5858. var morphColorsLength = morphColors.length;
  5859. for ( var i = 0; i < morphColorsLength; i ++ ) {
  5860. this.morphColors[ i ] = [];
  5861. }
  5862. // skins
  5863. var skinIndices = geometry.skinIndices;
  5864. var skinWeights = geometry.skinWeights;
  5865. var hasSkinIndices = skinIndices.length === vertices.length;
  5866. var hasSkinWeights = skinWeights.length === vertices.length;
  5867. //
  5868. for ( var i = 0; i < faces.length; i ++ ) {
  5869. var face = faces[ i ];
  5870. this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] );
  5871. var vertexNormals = face.vertexNormals;
  5872. if ( vertexNormals.length === 3 ) {
  5873. this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] );
  5874. } else {
  5875. var normal = face.normal;
  5876. this.normals.push( normal, normal, normal );
  5877. }
  5878. var vertexColors = face.vertexColors;
  5879. if ( materialVertexColors === THREE.VertexColors ) {
  5880. this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] );
  5881. } else if ( materialVertexColors === THREE.FaceColors ) {
  5882. var color = face.color;
  5883. this.colors.push( color, color, color );
  5884. }
  5885. if ( hasFaceVertexUv === true ) {
  5886. var vertexUvs = faceVertexUvs[ 0 ][ i ];
  5887. if ( vertexUvs !== undefined ) {
  5888. this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  5889. } else {
  5890. console.warn( 'THREE.BufferGeometry.fromGeometry(): Undefined vertexUv', i );
  5891. this.uvs.push( new THREE.Vector2(), new THREE.Vector2(), new THREE.Vector2() );
  5892. }
  5893. }
  5894. if ( hasFaceVertexUv2 === true ) {
  5895. var vertexUvs = faceVertexUvs[ 1 ][ i ];
  5896. if ( vertexUvs !== undefined ) {
  5897. this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  5898. } else {
  5899. console.warn( 'THREE.BufferGeometry.fromGeometry(): Undefined vertexUv2', i );
  5900. this.uvs2.push( new THREE.Vector2(), new THREE.Vector2(), new THREE.Vector2() );
  5901. }
  5902. }
  5903. // morphs
  5904. for ( var j = 0; j < morphTargetsLength; j ++ ) {
  5905. var morphTarget = morphTargets[ j ].vertices;
  5906. this.morphTargets[ j ].push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] );
  5907. }
  5908. for ( var j = 0; j < morphNormalsLength; j ++ ) {
  5909. var morphNormal = morphNormals[ j ].normals;
  5910. this.morphNormals[ j ].push( morphNormal[ face.a ], morphNormal[ face.b ], morphNormal[ face.c ] );
  5911. }
  5912. for ( var j = 0; j < morphColorsLength; j ++ ) {
  5913. var morphColor = morphColors[ j ].colors;
  5914. this.morphColors[ j ].push( morphColor[ face.a ], morphColor[ face.b ], morphColor[ face.c ] );
  5915. }
  5916. // skins
  5917. if ( hasSkinIndices ) {
  5918. this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] );
  5919. }
  5920. if ( hasSkinWeights ) {
  5921. this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] );
  5922. }
  5923. }
  5924. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  5925. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  5926. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  5927. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  5928. return this;
  5929. },
  5930. dispose: function () {
  5931. this.dispatchEvent( { type: 'dispose' } );
  5932. }
  5933. };
  5934. THREE.EventDispatcher.prototype.apply( THREE.DirectGeometry.prototype );
  5935. // File:src/core/BufferGeometry.js
  5936. /**
  5937. * @author alteredq / http://alteredqualia.com/
  5938. * @author mrdoob / http://mrdoob.com/
  5939. */
  5940. THREE.BufferGeometry = function () {
  5941. Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } );
  5942. this.uuid = THREE.Math.generateUUID();
  5943. this.name = '';
  5944. this.type = 'BufferGeometry';
  5945. this.attributes = {};
  5946. this.morphAttributes = [];
  5947. this.drawcalls = [];
  5948. this.offsets = this.drawcalls; // backwards compatibility
  5949. this.boundingBox = null;
  5950. this.boundingSphere = null;
  5951. };
  5952. THREE.BufferGeometry.prototype = {
  5953. constructor: THREE.BufferGeometry,
  5954. addAttribute: function ( name, attribute ) {
  5955. if ( attribute instanceof THREE.BufferAttribute === false && attribute instanceof THREE.InterleavedBufferAttribute === false ) {
  5956. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  5957. this.attributes[ name ] = { array: arguments[ 1 ], itemSize: arguments[ 2 ] };
  5958. return;
  5959. }
  5960. this.attributes[ name ] = attribute;
  5961. },
  5962. getAttribute: function ( name ) {
  5963. return this.attributes[ name ];
  5964. },
  5965. addDrawCall: function ( start, count, indexOffset ) {
  5966. this.drawcalls.push( {
  5967. start: start,
  5968. count: count,
  5969. index: indexOffset !== undefined ? indexOffset : 0
  5970. } );
  5971. },
  5972. applyMatrix: function ( matrix ) {
  5973. var position = this.attributes.position;
  5974. if ( position !== undefined ) {
  5975. matrix.applyToVector3Array( position.array );
  5976. position.needsUpdate = true;
  5977. }
  5978. var normal = this.attributes.normal;
  5979. if ( normal !== undefined ) {
  5980. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5981. normalMatrix.applyToVector3Array( normal.array );
  5982. normal.needsUpdate = true;
  5983. }
  5984. if ( this.boundingBox !== null ) {
  5985. this.computeBoundingBox();
  5986. }
  5987. if ( this.boundingSphere !== null ) {
  5988. this.computeBoundingSphere();
  5989. }
  5990. },
  5991. copy: function ( geometry ) {
  5992. var attributes = geometry.attributes;
  5993. var offsets = geometry.offsets;
  5994. for ( var name in attributes ) {
  5995. var attribute = attributes[ name ];
  5996. this.addAttribute( name, attribute.clone() );
  5997. }
  5998. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  5999. var offset = offsets[ i ];
  6000. this.offsets.push( {
  6001. start: offset.start,
  6002. index: offset.index,
  6003. count: offset.count
  6004. } );
  6005. }
  6006. return this;
  6007. },
  6008. center: function () {
  6009. this.computeBoundingBox();
  6010. var offset = this.boundingBox.center().negate();
  6011. this.applyMatrix( new THREE.Matrix4().setPosition( offset ) );
  6012. return offset;
  6013. },
  6014. setFromObject: function ( object ) {
  6015. console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  6016. var geometry = object.geometry;
  6017. var material = object.material;
  6018. if ( object instanceof THREE.PointCloud || object instanceof THREE.Line ) {
  6019. var positions = new THREE.Float32Attribute( geometry.vertices.length * 3, 3 );
  6020. var colors = new THREE.Float32Attribute( geometry.colors.length * 3, 3 );
  6021. this.addAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) );
  6022. this.addAttribute( 'color', colors.copyColorsArray( geometry.colors ) );
  6023. if ( geometry.boundingSphere !== null ) {
  6024. this.boundingSphere = geometry.boundingSphere.clone();
  6025. }
  6026. if ( geometry.boundingBox !== null ) {
  6027. this.boundingBox = geometry.boundingBox.clone();
  6028. }
  6029. } else if ( object instanceof THREE.Mesh ) {
  6030. if ( geometry instanceof THREE.Geometry ) {
  6031. this.fromGeometry( geometry );
  6032. var directgeometry = geometry.__directGeometry;
  6033. // morphs
  6034. if ( object.morphTargetInfluences !== undefined ) {
  6035. var morphTargets = directgeometry.morphTargets;
  6036. for ( var i = 0, l = morphTargets.length; i < l; i ++ ) {
  6037. var morphTarget = morphTargets[ i ];
  6038. var attribute = new THREE.Float32Attribute( morphTarget.length * 3, 3 );
  6039. this.morphAttributes.push( attribute.copyVector3sArray( morphTarget ) );
  6040. }
  6041. // TODO normals, colors
  6042. }
  6043. // skinning
  6044. if ( object instanceof THREE.SkinnedMesh ) {
  6045. var skinIndices = new THREE.Float32Attribute( directgeometry.skinIndices.length * 4, 4 );
  6046. var skinWeights = new THREE.Float32Attribute( directgeometry.skinWeights.length * 4, 4 );
  6047. this.addAttribute( 'skinIndex', skinIndices.copyVector4sArray( directgeometry.skinIndices ) );
  6048. this.addAttribute( 'skinWeight', skinWeights.copyVector4sArray( directgeometry.skinWeights ) );
  6049. }
  6050. }
  6051. }
  6052. return this;
  6053. },
  6054. updateFromObject: function ( object ) {
  6055. var geometry = object.geometry;
  6056. if ( object instanceof THREE.Mesh ) {
  6057. var direct = geometry.__directGeometry;
  6058. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  6059. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  6060. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  6061. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  6062. geometry.verticesNeedUpdate = false;
  6063. geometry.normalsNeedUpdate = false;
  6064. geometry.colorsNeedUpdate = false;
  6065. geometry.uvsNeedUpdate = false;
  6066. geometry = direct;
  6067. }
  6068. if ( geometry.verticesNeedUpdate === true ) {
  6069. var attribute = this.attributes.position;
  6070. if ( attribute !== undefined ) {
  6071. attribute.copyVector3sArray( geometry.vertices );
  6072. attribute.needsUpdate = true;
  6073. }
  6074. geometry.verticesNeedUpdate = false;
  6075. }
  6076. if ( geometry.normalsNeedUpdate === true ) {
  6077. var attribute = this.attributes.normal;
  6078. if ( attribute !== undefined ) {
  6079. attribute.copyVector3sArray( geometry.normals );
  6080. attribute.needsUpdate = true;
  6081. }
  6082. geometry.normalsNeedUpdate = false;
  6083. }
  6084. if ( geometry.colorsNeedUpdate === true ) {
  6085. var attribute = this.attributes.color;
  6086. if ( attribute !== undefined ) {
  6087. attribute.copyColorsArray( geometry.colors );
  6088. attribute.needsUpdate = true;
  6089. }
  6090. geometry.colorsNeedUpdate = false;
  6091. }
  6092. return this;
  6093. },
  6094. fromGeometry: function ( geometry, material ) {
  6095. geometry.__directGeometry = new THREE.DirectGeometry().fromGeometry( geometry, material );
  6096. return this.fromDirectGeometry( geometry.__directGeometry );
  6097. },
  6098. fromDirectGeometry: function ( geometry ) {
  6099. if ( geometry.indices.length > 0 ) {
  6100. var indices = new Uint16Array( geometry.indices.length * 3 );
  6101. this.addAttribute( 'index', new THREE.BufferAttribute( indices, 1 ).copyIndicesArray( geometry.indices ) );
  6102. }
  6103. if ( geometry.vertices.length > 0 ) {
  6104. var positions = new Float32Array( geometry.vertices.length * 3 );
  6105. this.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) );
  6106. }
  6107. if ( geometry.normals.length > 0 ) {
  6108. var normals = new Float32Array( geometry.normals.length * 3 );
  6109. this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) );
  6110. }
  6111. if ( geometry.colors.length > 0 ) {
  6112. var colors = new Float32Array( geometry.colors.length * 3 );
  6113. this.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) );
  6114. }
  6115. if ( geometry.uvs.length > 0 ) {
  6116. var uvs = new Float32Array( geometry.uvs.length * 2 );
  6117. this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) );
  6118. }
  6119. if ( geometry.boundingSphere !== null ) {
  6120. this.boundingSphere = geometry.boundingSphere.clone();
  6121. }
  6122. if ( geometry.boundingBox !== null ) {
  6123. this.boundingBox = geometry.boundingBox.clone();
  6124. }
  6125. return this;
  6126. },
  6127. computeBoundingBox: function () {
  6128. var vector = new THREE.Vector3();
  6129. return function () {
  6130. if ( this.boundingBox === null ) {
  6131. this.boundingBox = new THREE.Box3();
  6132. }
  6133. var positions = this.attributes.position.array;
  6134. if ( positions ) {
  6135. var bb = this.boundingBox;
  6136. bb.makeEmpty();
  6137. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  6138. vector.fromArray( positions, i );
  6139. bb.expandByPoint( vector );
  6140. }
  6141. }
  6142. if ( positions === undefined || positions.length === 0 ) {
  6143. this.boundingBox.min.set( 0, 0, 0 );
  6144. this.boundingBox.max.set( 0, 0, 0 );
  6145. }
  6146. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  6147. console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6148. }
  6149. };
  6150. }(),
  6151. computeBoundingSphere: function () {
  6152. var box = new THREE.Box3();
  6153. var vector = new THREE.Vector3();
  6154. return function () {
  6155. if ( this.boundingSphere === null ) {
  6156. this.boundingSphere = new THREE.Sphere();
  6157. }
  6158. var positions = this.attributes.position.array;
  6159. if ( positions ) {
  6160. box.makeEmpty();
  6161. var center = this.boundingSphere.center;
  6162. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  6163. vector.fromArray( positions, i );
  6164. box.expandByPoint( vector );
  6165. }
  6166. box.center( center );
  6167. // hoping to find a boundingSphere with a radius smaller than the
  6168. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6169. var maxRadiusSq = 0;
  6170. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  6171. vector.fromArray( positions, i );
  6172. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  6173. }
  6174. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6175. if ( isNaN( this.boundingSphere.radius ) ) {
  6176. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6177. }
  6178. }
  6179. };
  6180. }(),
  6181. computeFaceNormals: function () {
  6182. // backwards compatibility
  6183. },
  6184. computeVertexNormals: function () {
  6185. var attributes = this.attributes;
  6186. if ( attributes.position ) {
  6187. var positions = attributes.position.array;
  6188. if ( attributes.normal === undefined ) {
  6189. this.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( positions.length ), 3 ) );
  6190. } else {
  6191. // reset existing normals to zero
  6192. var normals = attributes.normal.array;
  6193. for ( var i = 0, il = normals.length; i < il; i ++ ) {
  6194. normals[ i ] = 0;
  6195. }
  6196. }
  6197. var normals = attributes.normal.array;
  6198. var vA, vB, vC,
  6199. pA = new THREE.Vector3(),
  6200. pB = new THREE.Vector3(),
  6201. pC = new THREE.Vector3(),
  6202. cb = new THREE.Vector3(),
  6203. ab = new THREE.Vector3();
  6204. // indexed elements
  6205. if ( attributes.index ) {
  6206. var indices = attributes.index.array;
  6207. var offsets = ( this.offsets.length > 0 ? this.offsets : [ { start: 0, count: indices.length, index: 0 } ] );
  6208. for ( var j = 0, jl = offsets.length; j < jl; ++ j ) {
  6209. var start = offsets[ j ].start;
  6210. var count = offsets[ j ].count;
  6211. var index = offsets[ j ].index;
  6212. for ( var i = start, il = start + count; i < il; i += 3 ) {
  6213. vA = ( index + indices[ i ] ) * 3;
  6214. vB = ( index + indices[ i + 1 ] ) * 3;
  6215. vC = ( index + indices[ i + 2 ] ) * 3;
  6216. pA.fromArray( positions, vA );
  6217. pB.fromArray( positions, vB );
  6218. pC.fromArray( positions, vC );
  6219. cb.subVectors( pC, pB );
  6220. ab.subVectors( pA, pB );
  6221. cb.cross( ab );
  6222. normals[ vA ] += cb.x;
  6223. normals[ vA + 1 ] += cb.y;
  6224. normals[ vA + 2 ] += cb.z;
  6225. normals[ vB ] += cb.x;
  6226. normals[ vB + 1 ] += cb.y;
  6227. normals[ vB + 2 ] += cb.z;
  6228. normals[ vC ] += cb.x;
  6229. normals[ vC + 1 ] += cb.y;
  6230. normals[ vC + 2 ] += cb.z;
  6231. }
  6232. }
  6233. } else {
  6234. // non-indexed elements (unconnected triangle soup)
  6235. for ( var i = 0, il = positions.length; i < il; i += 9 ) {
  6236. pA.fromArray( positions, i );
  6237. pB.fromArray( positions, i + 3 );
  6238. pC.fromArray( positions, i + 6 );
  6239. cb.subVectors( pC, pB );
  6240. ab.subVectors( pA, pB );
  6241. cb.cross( ab );
  6242. normals[ i ] = cb.x;
  6243. normals[ i + 1 ] = cb.y;
  6244. normals[ i + 2 ] = cb.z;
  6245. normals[ i + 3 ] = cb.x;
  6246. normals[ i + 4 ] = cb.y;
  6247. normals[ i + 5 ] = cb.z;
  6248. normals[ i + 6 ] = cb.x;
  6249. normals[ i + 7 ] = cb.y;
  6250. normals[ i + 8 ] = cb.z;
  6251. }
  6252. }
  6253. this.normalizeNormals();
  6254. attributes.normal.needsUpdate = true;
  6255. }
  6256. },
  6257. computeTangents: function () {
  6258. // based on http://www.terathon.com/code/tangent.html
  6259. // (per vertex tangents)
  6260. if ( this.attributes.index === undefined ||
  6261. this.attributes.position === undefined ||
  6262. this.attributes.normal === undefined ||
  6263. this.attributes.uv === undefined ) {
  6264. console.warn( 'THREE.BufferGeometry: Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()' );
  6265. return;
  6266. }
  6267. var indices = this.attributes.index.array;
  6268. var positions = this.attributes.position.array;
  6269. var normals = this.attributes.normal.array;
  6270. var uvs = this.attributes.uv.array;
  6271. var nVertices = positions.length / 3;
  6272. if ( this.attributes.tangent === undefined ) {
  6273. this.addAttribute( 'tangent', new THREE.BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) );
  6274. }
  6275. var tangents = this.attributes.tangent.array;
  6276. var tan1 = [], tan2 = [];
  6277. for ( var k = 0; k < nVertices; k ++ ) {
  6278. tan1[ k ] = new THREE.Vector3();
  6279. tan2[ k ] = new THREE.Vector3();
  6280. }
  6281. var vA = new THREE.Vector3(),
  6282. vB = new THREE.Vector3(),
  6283. vC = new THREE.Vector3(),
  6284. uvA = new THREE.Vector2(),
  6285. uvB = new THREE.Vector2(),
  6286. uvC = new THREE.Vector2(),
  6287. x1, x2, y1, y2, z1, z2,
  6288. s1, s2, t1, t2, r;
  6289. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  6290. function handleTriangle( a, b, c ) {
  6291. vA.fromArray( positions, a * 3 );
  6292. vB.fromArray( positions, b * 3 );
  6293. vC.fromArray( positions, c * 3 );
  6294. uvA.fromArray( uvs, a * 2 );
  6295. uvB.fromArray( uvs, b * 2 );
  6296. uvC.fromArray( uvs, c * 2 );
  6297. x1 = vB.x - vA.x;
  6298. x2 = vC.x - vA.x;
  6299. y1 = vB.y - vA.y;
  6300. y2 = vC.y - vA.y;
  6301. z1 = vB.z - vA.z;
  6302. z2 = vC.z - vA.z;
  6303. s1 = uvB.x - uvA.x;
  6304. s2 = uvC.x - uvA.x;
  6305. t1 = uvB.y - uvA.y;
  6306. t2 = uvC.y - uvA.y;
  6307. r = 1.0 / ( s1 * t2 - s2 * t1 );
  6308. sdir.set(
  6309. ( t2 * x1 - t1 * x2 ) * r,
  6310. ( t2 * y1 - t1 * y2 ) * r,
  6311. ( t2 * z1 - t1 * z2 ) * r
  6312. );
  6313. tdir.set(
  6314. ( s1 * x2 - s2 * x1 ) * r,
  6315. ( s1 * y2 - s2 * y1 ) * r,
  6316. ( s1 * z2 - s2 * z1 ) * r
  6317. );
  6318. tan1[ a ].add( sdir );
  6319. tan1[ b ].add( sdir );
  6320. tan1[ c ].add( sdir );
  6321. tan2[ a ].add( tdir );
  6322. tan2[ b ].add( tdir );
  6323. tan2[ c ].add( tdir );
  6324. }
  6325. var i, il;
  6326. var j, jl;
  6327. var iA, iB, iC;
  6328. if ( this.drawcalls.length === 0 ) {
  6329. this.addDrawCall( 0, indices.length, 0 );
  6330. }
  6331. var drawcalls = this.drawcalls;
  6332. for ( j = 0, jl = drawcalls.length; j < jl; ++ j ) {
  6333. var start = drawcalls[ j ].start;
  6334. var count = drawcalls[ j ].count;
  6335. var index = drawcalls[ j ].index;
  6336. for ( i = start, il = start + count; i < il; i += 3 ) {
  6337. iA = index + indices[ i ];
  6338. iB = index + indices[ i + 1 ];
  6339. iC = index + indices[ i + 2 ];
  6340. handleTriangle( iA, iB, iC );
  6341. }
  6342. }
  6343. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  6344. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  6345. var w, t, test;
  6346. function handleVertex( v ) {
  6347. n.fromArray( normals, v * 3 );
  6348. n2.copy( n );
  6349. t = tan1[ v ];
  6350. // Gram-Schmidt orthogonalize
  6351. tmp.copy( t );
  6352. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6353. // Calculate handedness
  6354. tmp2.crossVectors( n2, t );
  6355. test = tmp2.dot( tan2[ v ] );
  6356. w = ( test < 0.0 ) ? - 1.0 : 1.0;
  6357. tangents[ v * 4 ] = tmp.x;
  6358. tangents[ v * 4 + 1 ] = tmp.y;
  6359. tangents[ v * 4 + 2 ] = tmp.z;
  6360. tangents[ v * 4 + 3 ] = w;
  6361. }
  6362. for ( j = 0, jl = drawcalls.length; j < jl; ++ j ) {
  6363. var start = drawcalls[ j ].start;
  6364. var count = drawcalls[ j ].count;
  6365. var index = drawcalls[ j ].index;
  6366. for ( i = start, il = start + count; i < il; i += 3 ) {
  6367. iA = index + indices[ i ];
  6368. iB = index + indices[ i + 1 ];
  6369. iC = index + indices[ i + 2 ];
  6370. handleVertex( iA );
  6371. handleVertex( iB );
  6372. handleVertex( iC );
  6373. }
  6374. }
  6375. },
  6376. /*
  6377. Compute the draw offset for large models by chunking the index buffer into chunks of 65k addressable vertices.
  6378. This method will effectively rewrite the index buffer and remap all attributes to match the new indices.
  6379. WARNING: This method will also expand the vertex count to prevent sprawled triangles across draw offsets.
  6380. size - Defaults to 65535 or 4294967296 if extension OES_element_index_uint supported, but allows for larger or smaller chunks.
  6381. */
  6382. computeOffsets: function ( size ) {
  6383. if ( size === undefined ) size = THREE.BufferGeometry.MaxIndex;
  6384. var indices = this.attributes.index.array;
  6385. var vertices = this.attributes.position.array;
  6386. var facesCount = ( indices.length / 3 );
  6387. var UintArray = ( ( vertices.length / 3 ) > 65535 && THREE.BufferGeometry.MaxIndex > 65535 ) ? Uint32Array : Uint16Array;
  6388. /*
  6389. console.log("Computing buffers in offsets of "+size+" -> indices:"+indices.length+" vertices:"+vertices.length);
  6390. console.log("Faces to process: "+(indices.length/3));
  6391. console.log("Reordering "+verticesCount+" vertices.");
  6392. */
  6393. var sortedIndices = new UintArray( indices.length );
  6394. var indexPtr = 0;
  6395. var vertexPtr = 0;
  6396. var offsets = [ { start:0, count:0, index:0 } ];
  6397. var offset = offsets[ 0 ];
  6398. var duplicatedVertices = 0;
  6399. var newVerticeMaps = 0;
  6400. var faceVertices = new Int32Array( 6 );
  6401. var vertexMap = new Int32Array( vertices.length );
  6402. var revVertexMap = new Int32Array( vertices.length );
  6403. for ( var j = 0; j < vertices.length; j ++ ) { vertexMap[ j ] = - 1; revVertexMap[ j ] = - 1; }
  6404. /*
  6405. Traverse every face and reorder vertices in the proper offsets of 65k.
  6406. We can have more than 'size' entries in the index buffer per offset, but only reference 'size' values.
  6407. */
  6408. for ( var findex = 0; findex < facesCount; findex ++ ) {
  6409. newVerticeMaps = 0;
  6410. for ( var vo = 0; vo < 3; vo ++ ) {
  6411. var vid = indices[ findex * 3 + vo ];
  6412. if ( vertexMap[ vid ] === - 1 ) {
  6413. //Unmapped vertice
  6414. faceVertices[ vo * 2 ] = vid;
  6415. faceVertices[ vo * 2 + 1 ] = - 1;
  6416. newVerticeMaps ++;
  6417. } else if ( vertexMap[ vid ] < offset.index ) {
  6418. //Reused vertices from previous block (duplicate)
  6419. faceVertices[ vo * 2 ] = vid;
  6420. faceVertices[ vo * 2 + 1 ] = - 1;
  6421. duplicatedVertices ++;
  6422. } else {
  6423. //Reused vertice in the current block
  6424. faceVertices[ vo * 2 ] = vid;
  6425. faceVertices[ vo * 2 + 1 ] = vertexMap[ vid ];
  6426. }
  6427. }
  6428. var faceMax = vertexPtr + newVerticeMaps;
  6429. if ( faceMax > ( offset.index + size ) ) {
  6430. var new_offset = { start:indexPtr, count:0, index:vertexPtr };
  6431. offsets.push( new_offset );
  6432. offset = new_offset;
  6433. //Re-evaluate reused vertices in light of new offset.
  6434. for ( var v = 0; v < 6; v += 2 ) {
  6435. var new_vid = faceVertices[ v + 1 ];
  6436. if ( new_vid > - 1 && new_vid < offset.index )
  6437. faceVertices[ v + 1 ] = - 1;
  6438. }
  6439. }
  6440. //Reindex the face.
  6441. for ( var v = 0; v < 6; v += 2 ) {
  6442. var vid = faceVertices[ v ];
  6443. var new_vid = faceVertices[ v + 1 ];
  6444. if ( new_vid === - 1 )
  6445. new_vid = vertexPtr ++;
  6446. vertexMap[ vid ] = new_vid;
  6447. revVertexMap[ new_vid ] = vid;
  6448. sortedIndices[ indexPtr ++ ] = new_vid - offset.index; //XXX overflows at 16bit
  6449. offset.count ++;
  6450. }
  6451. }
  6452. /* Move all attribute values to map to the new computed indices , also expand the vertice stack to match our new vertexPtr. */
  6453. this.reorderBuffers( sortedIndices, revVertexMap, vertexPtr );
  6454. this.offsets = offsets; // TODO: Deprecate
  6455. this.drawcalls = offsets;
  6456. /*
  6457. var orderTime = Date.now();
  6458. console.log("Reorder time: "+(orderTime-s)+"ms");
  6459. console.log("Duplicated "+duplicatedVertices+" vertices.");
  6460. console.log("Compute Buffers time: "+(Date.now()-s)+"ms");
  6461. console.log("Draw offsets: "+offsets.length);
  6462. */
  6463. return offsets;
  6464. },
  6465. merge: function ( geometry, offset ) {
  6466. if ( geometry instanceof THREE.BufferGeometry === false ) {
  6467. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  6468. return;
  6469. }
  6470. if ( offset === undefined ) offset = 0;
  6471. var attributes = this.attributes;
  6472. for ( var key in attributes ) {
  6473. if ( geometry.attributes[ key ] === undefined ) continue;
  6474. var attribute1 = attributes[ key ];
  6475. var attributeArray1 = attribute1.array;
  6476. var attribute2 = geometry.attributes[ key ];
  6477. var attributeArray2 = attribute2.array;
  6478. var attributeSize = attribute2.itemSize;
  6479. for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) {
  6480. attributeArray1[ j ] = attributeArray2[ i ];
  6481. }
  6482. }
  6483. return this;
  6484. },
  6485. normalizeNormals: function () {
  6486. var normals = this.attributes.normal.array;
  6487. var x, y, z, n;
  6488. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  6489. x = normals[ i ];
  6490. y = normals[ i + 1 ];
  6491. z = normals[ i + 2 ];
  6492. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  6493. normals[ i ] *= n;
  6494. normals[ i + 1 ] *= n;
  6495. normals[ i + 2 ] *= n;
  6496. }
  6497. },
  6498. /*
  6499. reoderBuffers:
  6500. Reorder attributes based on a new indexBuffer and indexMap.
  6501. indexBuffer - Uint16Array of the new ordered indices.
  6502. indexMap - Int32Array where the position is the new vertex ID and the value the old vertex ID for each vertex.
  6503. vertexCount - Amount of total vertices considered in this reordering (in case you want to grow the vertice stack).
  6504. */
  6505. reorderBuffers: function ( indexBuffer, indexMap, vertexCount ) {
  6506. /* Create a copy of all attributes for reordering. */
  6507. var sortedAttributes = {};
  6508. for ( var attr in this.attributes ) {
  6509. if ( attr === 'index' )
  6510. continue;
  6511. var sourceArray = this.attributes[ attr ].array;
  6512. sortedAttributes[ attr ] = new sourceArray.constructor( this.attributes[ attr ].itemSize * vertexCount );
  6513. }
  6514. /* Move attribute positions based on the new index map */
  6515. for ( var new_vid = 0; new_vid < vertexCount; new_vid ++ ) {
  6516. var vid = indexMap[ new_vid ];
  6517. for ( var attr in this.attributes ) {
  6518. if ( attr === 'index' )
  6519. continue;
  6520. var attrArray = this.attributes[ attr ].array;
  6521. var attrSize = this.attributes[ attr ].itemSize;
  6522. var sortedAttr = sortedAttributes[ attr ];
  6523. for ( var k = 0; k < attrSize; k ++ )
  6524. sortedAttr[ new_vid * attrSize + k ] = attrArray[ vid * attrSize + k ];
  6525. }
  6526. }
  6527. /* Carry the new sorted buffers locally */
  6528. this.attributes[ 'index' ].array = indexBuffer;
  6529. for ( var attr in this.attributes ) {
  6530. if ( attr === 'index' )
  6531. continue;
  6532. this.attributes[ attr ].array = sortedAttributes[ attr ];
  6533. this.attributes[ attr ].numItems = this.attributes[ attr ].itemSize * vertexCount;
  6534. }
  6535. },
  6536. toJSON: function () {
  6537. var data = {
  6538. metadata: {
  6539. version: 4.4,
  6540. type: 'BufferGeometry',
  6541. generator: 'BufferGeometry.toJSON'
  6542. }
  6543. };
  6544. // standard BufferGeometry serialization
  6545. data.uuid = this.uuid;
  6546. data.type = this.type;
  6547. if ( this.name !== '' ) data.name = this.name;
  6548. if ( this.parameters !== undefined ) {
  6549. var parameters = this.parameters;
  6550. for ( var key in parameters ) {
  6551. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6552. }
  6553. return data;
  6554. }
  6555. data.data = { attributes: {} };
  6556. var attributes = this.attributes;
  6557. var offsets = this.offsets;
  6558. var boundingSphere = this.boundingSphere;
  6559. for ( var key in attributes ) {
  6560. var attribute = attributes[ key ];
  6561. var array = Array.prototype.slice.call( attribute.array );
  6562. data.data.attributes[ key ] = {
  6563. itemSize: attribute.itemSize,
  6564. type: attribute.array.constructor.name,
  6565. array: array
  6566. }
  6567. }
  6568. if ( offsets.length > 0 ) {
  6569. data.data.offsets = JSON.parse( JSON.stringify( offsets ) );
  6570. }
  6571. if ( boundingSphere !== null ) {
  6572. data.data.boundingSphere = {
  6573. center: boundingSphere.center.toArray(),
  6574. radius: boundingSphere.radius
  6575. }
  6576. }
  6577. return data;
  6578. },
  6579. clone: function () {
  6580. var geometry = new THREE.BufferGeometry();
  6581. for ( var attr in this.attributes ) {
  6582. var sourceAttr = this.attributes[ attr ];
  6583. geometry.addAttribute( attr, sourceAttr.clone() );
  6584. }
  6585. for ( var i = 0, il = this.offsets.length; i < il; i ++ ) {
  6586. var offset = this.offsets[ i ];
  6587. geometry.offsets.push( {
  6588. start: offset.start,
  6589. index: offset.index,
  6590. count: offset.count
  6591. } );
  6592. }
  6593. return geometry;
  6594. },
  6595. dispose: function () {
  6596. this.dispatchEvent( { type: 'dispose' } );
  6597. }
  6598. };
  6599. THREE.EventDispatcher.prototype.apply( THREE.BufferGeometry.prototype );
  6600. THREE.BufferGeometry.MaxIndex = 65535;
  6601. // File:src/core/InstancedBufferGeometry.js
  6602. /**
  6603. * @author benaadams / https://twitter.com/ben_a_adams
  6604. */
  6605. THREE.InstancedBufferGeometry = function () {
  6606. THREE.BufferGeometry.call( this );
  6607. this.type = 'InstancedBufferGeometry';
  6608. this.maxInstancedCount = undefined;
  6609. };
  6610. THREE.InstancedBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  6611. THREE.InstancedBufferGeometry.prototype.constructor = THREE.InstancedBufferGeometry;
  6612. THREE.InstancedBufferGeometry.prototype.addDrawCall = function ( start, count, indexOffset, instances ) {
  6613. this.drawcalls.push( {
  6614. start: start,
  6615. count: count,
  6616. index: indexOffset !== undefined ? indexOffset : 0,
  6617. instances: instances
  6618. } );
  6619. },
  6620. THREE.InstancedBufferGeometry.prototype.clone = function () {
  6621. var geometry = new THREE.InstancedBufferGeometry();
  6622. for ( var attr in this.attributes ) {
  6623. var sourceAttr = this.attributes[attr];
  6624. geometry.addAttribute( attr, sourceAttr.clone() );
  6625. }
  6626. for ( var i = 0, il = this.offsets.length; i < il; i++ ) {
  6627. var offset = this.offsets[i];
  6628. geometry.offsets.push( {
  6629. start: offset.start,
  6630. index: offset.index,
  6631. count: offset.count,
  6632. instances: offset.instances
  6633. } );
  6634. }
  6635. return geometry;
  6636. };
  6637. THREE.EventDispatcher.prototype.apply( THREE.InstancedBufferGeometry.prototype );
  6638. // File:src/cameras/Camera.js
  6639. /**
  6640. * @author mrdoob / http://mrdoob.com/
  6641. * @author mikael emtinger / http://gomo.se/
  6642. * @author WestLangley / http://github.com/WestLangley
  6643. */
  6644. THREE.Camera = function () {
  6645. THREE.Object3D.call( this );
  6646. this.type = 'Camera';
  6647. this.matrixWorldInverse = new THREE.Matrix4();
  6648. this.projectionMatrix = new THREE.Matrix4();
  6649. };
  6650. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  6651. THREE.Camera.prototype.constructor = THREE.Camera;
  6652. THREE.Camera.prototype.getWorldDirection = function () {
  6653. var quaternion = new THREE.Quaternion();
  6654. return function ( optionalTarget ) {
  6655. var result = optionalTarget || new THREE.Vector3();
  6656. this.getWorldQuaternion( quaternion );
  6657. return result.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  6658. };
  6659. }();
  6660. THREE.Camera.prototype.lookAt = function () {
  6661. // This routine does not support cameras with rotated and/or translated parent(s)
  6662. var m1 = new THREE.Matrix4();
  6663. return function ( vector ) {
  6664. m1.lookAt( this.position, vector, this.up );
  6665. this.quaternion.setFromRotationMatrix( m1 );
  6666. };
  6667. }();
  6668. THREE.Camera.prototype.clone = function ( camera ) {
  6669. if ( camera === undefined ) camera = new THREE.Camera();
  6670. THREE.Object3D.prototype.clone.call( this, camera );
  6671. camera.matrixWorldInverse.copy( this.matrixWorldInverse );
  6672. camera.projectionMatrix.copy( this.projectionMatrix );
  6673. return camera;
  6674. };
  6675. // File:src/cameras/CubeCamera.js
  6676. /**
  6677. * Camera for rendering cube maps
  6678. * - renders scene into axis-aligned cube
  6679. *
  6680. * @author alteredq / http://alteredqualia.com/
  6681. */
  6682. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  6683. THREE.Object3D.call( this );
  6684. this.type = 'CubeCamera';
  6685. var fov = 90, aspect = 1;
  6686. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  6687. cameraPX.up.set( 0, - 1, 0 );
  6688. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  6689. this.add( cameraPX );
  6690. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  6691. cameraNX.up.set( 0, - 1, 0 );
  6692. cameraNX.lookAt( new THREE.Vector3( - 1, 0, 0 ) );
  6693. this.add( cameraNX );
  6694. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  6695. cameraPY.up.set( 0, 0, 1 );
  6696. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  6697. this.add( cameraPY );
  6698. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  6699. cameraNY.up.set( 0, 0, - 1 );
  6700. cameraNY.lookAt( new THREE.Vector3( 0, - 1, 0 ) );
  6701. this.add( cameraNY );
  6702. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  6703. cameraPZ.up.set( 0, - 1, 0 );
  6704. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  6705. this.add( cameraPZ );
  6706. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  6707. cameraNZ.up.set( 0, - 1, 0 );
  6708. cameraNZ.lookAt( new THREE.Vector3( 0, 0, - 1 ) );
  6709. this.add( cameraNZ );
  6710. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  6711. this.updateCubeMap = function ( renderer, scene ) {
  6712. if ( this.parent === undefined ) this.updateMatrixWorld();
  6713. var renderTarget = this.renderTarget;
  6714. var generateMipmaps = renderTarget.generateMipmaps;
  6715. renderTarget.generateMipmaps = false;
  6716. renderTarget.activeCubeFace = 0;
  6717. renderer.render( scene, cameraPX, renderTarget );
  6718. renderTarget.activeCubeFace = 1;
  6719. renderer.render( scene, cameraNX, renderTarget );
  6720. renderTarget.activeCubeFace = 2;
  6721. renderer.render( scene, cameraPY, renderTarget );
  6722. renderTarget.activeCubeFace = 3;
  6723. renderer.render( scene, cameraNY, renderTarget );
  6724. renderTarget.activeCubeFace = 4;
  6725. renderer.render( scene, cameraPZ, renderTarget );
  6726. renderTarget.generateMipmaps = generateMipmaps;
  6727. renderTarget.activeCubeFace = 5;
  6728. renderer.render( scene, cameraNZ, renderTarget );
  6729. renderer.setRenderTarget( null );
  6730. };
  6731. };
  6732. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  6733. THREE.CubeCamera.prototype.constructor = THREE.CubeCamera;
  6734. // File:src/cameras/OrthographicCamera.js
  6735. /**
  6736. * @author alteredq / http://alteredqualia.com/
  6737. */
  6738. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  6739. THREE.Camera.call( this );
  6740. this.type = 'OrthographicCamera';
  6741. this.zoom = 1;
  6742. this.left = left;
  6743. this.right = right;
  6744. this.top = top;
  6745. this.bottom = bottom;
  6746. this.near = ( near !== undefined ) ? near : 0.1;
  6747. this.far = ( far !== undefined ) ? far : 2000;
  6748. this.updateProjectionMatrix();
  6749. };
  6750. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  6751. THREE.OrthographicCamera.prototype.constructor = THREE.OrthographicCamera;
  6752. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  6753. var dx = ( this.right - this.left ) / ( 2 * this.zoom );
  6754. var dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  6755. var cx = ( this.right + this.left ) / 2;
  6756. var cy = ( this.top + this.bottom ) / 2;
  6757. this.projectionMatrix.makeOrthographic( cx - dx, cx + dx, cy + dy, cy - dy, this.near, this.far );
  6758. };
  6759. THREE.OrthographicCamera.prototype.clone = function () {
  6760. var camera = new THREE.OrthographicCamera();
  6761. THREE.Camera.prototype.clone.call( this, camera );
  6762. camera.zoom = this.zoom;
  6763. camera.left = this.left;
  6764. camera.right = this.right;
  6765. camera.top = this.top;
  6766. camera.bottom = this.bottom;
  6767. camera.near = this.near;
  6768. camera.far = this.far;
  6769. camera.projectionMatrix.copy( this.projectionMatrix );
  6770. return camera;
  6771. };
  6772. THREE.OrthographicCamera.prototype.toJSON = function ( meta ) {
  6773. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  6774. data.object.left = this.left;
  6775. data.object.right = this.right;
  6776. data.object.top = this.top;
  6777. data.object.bottom = this.bottom;
  6778. data.object.near = this.near;
  6779. data.object.far = this.far;
  6780. return data;
  6781. };
  6782. // File:src/cameras/PerspectiveCamera.js
  6783. /**
  6784. * @author mrdoob / http://mrdoob.com/
  6785. * @author greggman / http://games.greggman.com/
  6786. * @author zz85 / http://www.lab4games.net/zz85/blog
  6787. */
  6788. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  6789. THREE.Camera.call( this );
  6790. this.type = 'PerspectiveCamera';
  6791. this.zoom = 1;
  6792. this.fov = fov !== undefined ? fov : 50;
  6793. this.aspect = aspect !== undefined ? aspect : 1;
  6794. this.near = near !== undefined ? near : 0.1;
  6795. this.far = far !== undefined ? far : 2000;
  6796. this.updateProjectionMatrix();
  6797. };
  6798. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  6799. THREE.PerspectiveCamera.prototype.constructor = THREE.PerspectiveCamera;
  6800. /**
  6801. * Uses Focal Length (in mm) to estimate and set FOV
  6802. * 35mm (fullframe) camera is used if frame size is not specified;
  6803. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  6804. */
  6805. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  6806. if ( frameHeight === undefined ) frameHeight = 24;
  6807. this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  6808. this.updateProjectionMatrix();
  6809. };
  6810. /**
  6811. * Sets an offset in a larger frustum. This is useful for multi-window or
  6812. * multi-monitor/multi-machine setups.
  6813. *
  6814. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  6815. * the monitors are in grid like this
  6816. *
  6817. * +---+---+---+
  6818. * | A | B | C |
  6819. * +---+---+---+
  6820. * | D | E | F |
  6821. * +---+---+---+
  6822. *
  6823. * then for each monitor you would call it like this
  6824. *
  6825. * var w = 1920;
  6826. * var h = 1080;
  6827. * var fullWidth = w * 3;
  6828. * var fullHeight = h * 2;
  6829. *
  6830. * --A--
  6831. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  6832. * --B--
  6833. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  6834. * --C--
  6835. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  6836. * --D--
  6837. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  6838. * --E--
  6839. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  6840. * --F--
  6841. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  6842. *
  6843. * Note there is no reason monitors have to be the same size or in a grid.
  6844. */
  6845. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  6846. this.fullWidth = fullWidth;
  6847. this.fullHeight = fullHeight;
  6848. this.x = x;
  6849. this.y = y;
  6850. this.width = width;
  6851. this.height = height;
  6852. this.updateProjectionMatrix();
  6853. };
  6854. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  6855. var fov = THREE.Math.radToDeg( 2 * Math.atan( Math.tan( THREE.Math.degToRad( this.fov ) * 0.5 ) / this.zoom ) );
  6856. if ( this.fullWidth ) {
  6857. var aspect = this.fullWidth / this.fullHeight;
  6858. var top = Math.tan( THREE.Math.degToRad( fov * 0.5 ) ) * this.near;
  6859. var bottom = - top;
  6860. var left = aspect * bottom;
  6861. var right = aspect * top;
  6862. var width = Math.abs( right - left );
  6863. var height = Math.abs( top - bottom );
  6864. this.projectionMatrix.makeFrustum(
  6865. left + this.x * width / this.fullWidth,
  6866. left + ( this.x + this.width ) * width / this.fullWidth,
  6867. top - ( this.y + this.height ) * height / this.fullHeight,
  6868. top - this.y * height / this.fullHeight,
  6869. this.near,
  6870. this.far
  6871. );
  6872. } else {
  6873. this.projectionMatrix.makePerspective( fov, this.aspect, this.near, this.far );
  6874. }
  6875. };
  6876. THREE.PerspectiveCamera.prototype.clone = function () {
  6877. var camera = new THREE.PerspectiveCamera();
  6878. THREE.Camera.prototype.clone.call( this, camera );
  6879. camera.zoom = this.zoom;
  6880. camera.fov = this.fov;
  6881. camera.aspect = this.aspect;
  6882. camera.near = this.near;
  6883. camera.far = this.far;
  6884. camera.projectionMatrix.copy( this.projectionMatrix );
  6885. return camera;
  6886. };
  6887. THREE.PerspectiveCamera.prototype.toJSON = function ( meta ) {
  6888. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  6889. data.object.fov = this.fov;
  6890. data.object.aspect = this.aspect;
  6891. data.object.near = this.near;
  6892. data.object.far = this.far;
  6893. return data;
  6894. };
  6895. // File:src/lights/Light.js
  6896. /**
  6897. * @author mrdoob / http://mrdoob.com/
  6898. * @author alteredq / http://alteredqualia.com/
  6899. */
  6900. THREE.Light = function ( color ) {
  6901. THREE.Object3D.call( this );
  6902. this.type = 'Light';
  6903. this.color = new THREE.Color( color );
  6904. };
  6905. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  6906. THREE.Light.prototype.constructor = THREE.Light;
  6907. THREE.Light.prototype.clone = function ( light ) {
  6908. if ( light === undefined ) light = new THREE.Light();
  6909. THREE.Object3D.prototype.clone.call( this, light );
  6910. light.color.copy( this.color );
  6911. return light;
  6912. };
  6913. // File:src/lights/AmbientLight.js
  6914. /**
  6915. * @author mrdoob / http://mrdoob.com/
  6916. */
  6917. THREE.AmbientLight = function ( color ) {
  6918. THREE.Light.call( this, color );
  6919. this.type = 'AmbientLight';
  6920. };
  6921. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  6922. THREE.AmbientLight.prototype.constructor = THREE.AmbientLight;
  6923. THREE.AmbientLight.prototype.clone = function () {
  6924. var light = new THREE.AmbientLight();
  6925. THREE.Light.prototype.clone.call( this, light );
  6926. return light;
  6927. };
  6928. THREE.AmbientLight.prototype.toJSON = function ( meta ) {
  6929. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  6930. data.object.color = this.color.getHex();
  6931. return data;
  6932. };
  6933. // File:src/lights/AreaLight.js
  6934. /**
  6935. * @author MPanknin / http://www.redplant.de/
  6936. * @author alteredq / http://alteredqualia.com/
  6937. */
  6938. THREE.AreaLight = function ( color, intensity ) {
  6939. THREE.Light.call( this, color );
  6940. this.type = 'AreaLight';
  6941. this.normal = new THREE.Vector3( 0, - 1, 0 );
  6942. this.right = new THREE.Vector3( 1, 0, 0 );
  6943. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6944. this.width = 1.0;
  6945. this.height = 1.0;
  6946. this.constantAttenuation = 1.5;
  6947. this.linearAttenuation = 0.5;
  6948. this.quadraticAttenuation = 0.1;
  6949. };
  6950. THREE.AreaLight.prototype = Object.create( THREE.Light.prototype );
  6951. THREE.AreaLight.prototype.constructor = THREE.AreaLight;
  6952. // File:src/lights/DirectionalLight.js
  6953. /**
  6954. * @author mrdoob / http://mrdoob.com/
  6955. * @author alteredq / http://alteredqualia.com/
  6956. */
  6957. THREE.DirectionalLight = function ( color, intensity ) {
  6958. THREE.Light.call( this, color );
  6959. this.type = 'DirectionalLight';
  6960. this.position.set( 0, 1, 0 );
  6961. this.target = new THREE.Object3D();
  6962. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6963. this.castShadow = false;
  6964. this.onlyShadow = false;
  6965. //
  6966. this.shadowCameraNear = 50;
  6967. this.shadowCameraFar = 5000;
  6968. this.shadowCameraLeft = - 500;
  6969. this.shadowCameraRight = 500;
  6970. this.shadowCameraTop = 500;
  6971. this.shadowCameraBottom = - 500;
  6972. this.shadowCameraVisible = false;
  6973. this.shadowBias = 0;
  6974. this.shadowDarkness = 0.5;
  6975. this.shadowMapWidth = 512;
  6976. this.shadowMapHeight = 512;
  6977. //
  6978. this.shadowCascade = false;
  6979. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, - 1000 );
  6980. this.shadowCascadeCount = 2;
  6981. this.shadowCascadeBias = [ 0, 0, 0 ];
  6982. this.shadowCascadeWidth = [ 512, 512, 512 ];
  6983. this.shadowCascadeHeight = [ 512, 512, 512 ];
  6984. this.shadowCascadeNearZ = [ - 1.000, 0.990, 0.998 ];
  6985. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  6986. this.shadowCascadeArray = [];
  6987. //
  6988. this.shadowMap = null;
  6989. this.shadowMapSize = null;
  6990. this.shadowCamera = null;
  6991. this.shadowMatrix = null;
  6992. };
  6993. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  6994. THREE.DirectionalLight.prototype.constructor = THREE.DirectionalLight;
  6995. THREE.DirectionalLight.prototype.clone = function () {
  6996. var light = new THREE.DirectionalLight();
  6997. THREE.Light.prototype.clone.call( this, light );
  6998. light.target = this.target.clone();
  6999. light.intensity = this.intensity;
  7000. light.castShadow = this.castShadow;
  7001. light.onlyShadow = this.onlyShadow;
  7002. //
  7003. light.shadowCameraNear = this.shadowCameraNear;
  7004. light.shadowCameraFar = this.shadowCameraFar;
  7005. light.shadowCameraLeft = this.shadowCameraLeft;
  7006. light.shadowCameraRight = this.shadowCameraRight;
  7007. light.shadowCameraTop = this.shadowCameraTop;
  7008. light.shadowCameraBottom = this.shadowCameraBottom;
  7009. light.shadowCameraVisible = this.shadowCameraVisible;
  7010. light.shadowBias = this.shadowBias;
  7011. light.shadowDarkness = this.shadowDarkness;
  7012. light.shadowMapWidth = this.shadowMapWidth;
  7013. light.shadowMapHeight = this.shadowMapHeight;
  7014. //
  7015. light.shadowCascade = this.shadowCascade;
  7016. light.shadowCascadeOffset.copy( this.shadowCascadeOffset );
  7017. light.shadowCascadeCount = this.shadowCascadeCount;
  7018. light.shadowCascadeBias = this.shadowCascadeBias.slice( 0 );
  7019. light.shadowCascadeWidth = this.shadowCascadeWidth.slice( 0 );
  7020. light.shadowCascadeHeight = this.shadowCascadeHeight.slice( 0 );
  7021. light.shadowCascadeNearZ = this.shadowCascadeNearZ.slice( 0 );
  7022. light.shadowCascadeFarZ = this.shadowCascadeFarZ.slice( 0 );
  7023. return light;
  7024. };
  7025. THREE.DirectionalLight.prototype.toJSON = function ( meta ) {
  7026. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  7027. data.object.color = this.color.getHex();
  7028. data.object.intensity = this.intensity;
  7029. return data;
  7030. };
  7031. // File:src/lights/HemisphereLight.js
  7032. /**
  7033. * @author alteredq / http://alteredqualia.com/
  7034. */
  7035. THREE.HemisphereLight = function ( skyColor, groundColor, intensity ) {
  7036. THREE.Light.call( this, skyColor );
  7037. this.type = 'HemisphereLight';
  7038. this.position.set( 0, 100, 0 );
  7039. this.groundColor = new THREE.Color( groundColor );
  7040. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  7041. };
  7042. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  7043. THREE.HemisphereLight.prototype.constructor = THREE.HemisphereLight;
  7044. THREE.HemisphereLight.prototype.clone = function () {
  7045. var light = new THREE.HemisphereLight();
  7046. THREE.Light.prototype.clone.call( this, light );
  7047. light.groundColor.copy( this.groundColor );
  7048. light.intensity = this.intensity;
  7049. return light;
  7050. };
  7051. THREE.HemisphereLight.prototype.toJSON = function ( meta ) {
  7052. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  7053. data.object.color = this.color.getHex();
  7054. data.object.groundColor = this.groundColor.getHex();
  7055. return data;
  7056. };
  7057. // File:src/lights/PointLight.js
  7058. /**
  7059. * @author mrdoob / http://mrdoob.com/
  7060. */
  7061. THREE.PointLight = function ( color, intensity, distance, decay ) {
  7062. THREE.Light.call( this, color );
  7063. this.type = 'PointLight';
  7064. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  7065. this.distance = ( distance !== undefined ) ? distance : 0;
  7066. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  7067. };
  7068. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  7069. THREE.PointLight.prototype.constructor = THREE.PointLight;
  7070. THREE.PointLight.prototype.clone = function () {
  7071. var light = new THREE.PointLight();
  7072. THREE.Light.prototype.clone.call( this, light );
  7073. light.intensity = this.intensity;
  7074. light.distance = this.distance;
  7075. light.decay = this.decay;
  7076. return light;
  7077. };
  7078. THREE.PointLight.prototype.toJSON = function ( meta ) {
  7079. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  7080. data.object.color = this.color.getHex();
  7081. data.object.intensity = this.intensity;
  7082. data.object.distance = this.distance;
  7083. data.object.decay = this.decay;
  7084. return data;
  7085. };
  7086. // File:src/lights/SpotLight.js
  7087. /**
  7088. * @author alteredq / http://alteredqualia.com/
  7089. */
  7090. THREE.SpotLight = function ( color, intensity, distance, angle, exponent, decay ) {
  7091. THREE.Light.call( this, color );
  7092. this.type = 'SpotLight';
  7093. this.position.set( 0, 1, 0 );
  7094. this.target = new THREE.Object3D();
  7095. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  7096. this.distance = ( distance !== undefined ) ? distance : 0;
  7097. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  7098. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  7099. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  7100. this.castShadow = false;
  7101. this.onlyShadow = false;
  7102. //
  7103. this.shadowCameraNear = 50;
  7104. this.shadowCameraFar = 5000;
  7105. this.shadowCameraFov = 50;
  7106. this.shadowCameraVisible = false;
  7107. this.shadowBias = 0;
  7108. this.shadowDarkness = 0.5;
  7109. this.shadowMapWidth = 512;
  7110. this.shadowMapHeight = 512;
  7111. //
  7112. this.shadowMap = null;
  7113. this.shadowMapSize = null;
  7114. this.shadowCamera = null;
  7115. this.shadowMatrix = null;
  7116. };
  7117. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  7118. THREE.SpotLight.prototype.constructor = THREE.SpotLight;
  7119. THREE.SpotLight.prototype.clone = function () {
  7120. var light = new THREE.SpotLight();
  7121. THREE.Light.prototype.clone.call( this, light );
  7122. light.target = this.target.clone();
  7123. light.intensity = this.intensity;
  7124. light.distance = this.distance;
  7125. light.angle = this.angle;
  7126. light.exponent = this.exponent;
  7127. light.decay = this.decay;
  7128. light.castShadow = this.castShadow;
  7129. light.onlyShadow = this.onlyShadow;
  7130. //
  7131. light.shadowCameraNear = this.shadowCameraNear;
  7132. light.shadowCameraFar = this.shadowCameraFar;
  7133. light.shadowCameraFov = this.shadowCameraFov;
  7134. light.shadowCameraVisible = this.shadowCameraVisible;
  7135. light.shadowBias = this.shadowBias;
  7136. light.shadowDarkness = this.shadowDarkness;
  7137. light.shadowMapWidth = this.shadowMapWidth;
  7138. light.shadowMapHeight = this.shadowMapHeight;
  7139. return light;
  7140. };
  7141. THREE.SpotLight.prototype.toJSON = function ( meta ) {
  7142. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  7143. data.object.color = this.color.getHex();
  7144. data.object.intensity = this.intensity;
  7145. data.object.distance = this.distance;
  7146. data.object.angle = this.angle;
  7147. data.object.exponent = this.exponent;
  7148. data.object.decay = this.decay;
  7149. return data;
  7150. };
  7151. // File:src/loaders/Cache.js
  7152. /**
  7153. * @author mrdoob / http://mrdoob.com/
  7154. */
  7155. THREE.Cache = {
  7156. files: {},
  7157. add: function ( key, file ) {
  7158. // console.log( 'THREE.Cache', 'Adding key:', key );
  7159. this.files[ key ] = file;
  7160. },
  7161. get: function ( key ) {
  7162. // console.log( 'THREE.Cache', 'Checking key:', key );
  7163. return this.files[ key ];
  7164. },
  7165. remove: function ( key ) {
  7166. delete this.files[ key ];
  7167. },
  7168. clear: function () {
  7169. this.files = {}
  7170. }
  7171. };
  7172. // File:src/loaders/Loader.js
  7173. /**
  7174. * @author alteredq / http://alteredqualia.com/
  7175. */
  7176. THREE.Loader = function ( showStatus ) {
  7177. this.showStatus = showStatus;
  7178. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  7179. this.imageLoader = new THREE.ImageLoader();
  7180. this.onLoadStart = function () {};
  7181. this.onLoadProgress = function () {};
  7182. this.onLoadComplete = function () {};
  7183. };
  7184. THREE.Loader.prototype = {
  7185. constructor: THREE.Loader,
  7186. crossOrigin: undefined,
  7187. addStatusElement: function () {
  7188. var e = document.createElement( 'div' );
  7189. e.style.position = 'absolute';
  7190. e.style.right = '0px';
  7191. e.style.top = '0px';
  7192. e.style.fontSize = '0.8em';
  7193. e.style.textAlign = 'left';
  7194. e.style.background = 'rgba(0,0,0,0.25)';
  7195. e.style.color = '#fff';
  7196. e.style.width = '120px';
  7197. e.style.padding = '0.5em 0.5em 0.5em 0.5em';
  7198. e.style.zIndex = 1000;
  7199. e.innerHTML = 'Loading ...';
  7200. return e;
  7201. },
  7202. updateProgress: function ( progress ) {
  7203. var message = 'Loaded ';
  7204. if ( progress.total ) {
  7205. message += ( 100 * progress.loaded / progress.total ).toFixed( 0 ) + '%';
  7206. } else {
  7207. message += ( progress.loaded / 1024 ).toFixed( 2 ) + ' KB';
  7208. }
  7209. this.statusDomElement.innerHTML = message;
  7210. },
  7211. extractUrlBase: function ( url ) {
  7212. var parts = url.split( '/' );
  7213. if ( parts.length === 1 ) return './';
  7214. parts.pop();
  7215. return parts.join( '/' ) + '/';
  7216. },
  7217. initMaterials: function ( materials, texturePath ) {
  7218. var array = [];
  7219. for ( var i = 0; i < materials.length; ++ i ) {
  7220. array[ i ] = this.createMaterial( materials[ i ], texturePath );
  7221. }
  7222. return array;
  7223. },
  7224. needsTangents: function ( materials ) {
  7225. for ( var i = 0, il = materials.length; i < il; i ++ ) {
  7226. var m = materials[ i ];
  7227. if ( m instanceof THREE.ShaderMaterial ) return true;
  7228. }
  7229. return false;
  7230. },
  7231. createMaterial: function ( m, texturePath ) {
  7232. var scope = this;
  7233. function nearest_pow2( n ) {
  7234. var l = Math.log( n ) / Math.LN2;
  7235. return Math.pow( 2, Math.round( l ) );
  7236. }
  7237. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  7238. var fullPath = texturePath + sourceFile;
  7239. var texture;
  7240. var loader = THREE.Loader.Handlers.get( fullPath );
  7241. if ( loader !== null ) {
  7242. texture = loader.load( fullPath );
  7243. } else {
  7244. texture = new THREE.Texture();
  7245. loader = scope.imageLoader;
  7246. loader.crossOrigin = scope.crossOrigin;
  7247. loader.load( fullPath, function ( image ) {
  7248. if ( THREE.Math.isPowerOfTwo( image.width ) === false ||
  7249. THREE.Math.isPowerOfTwo( image.height ) === false ) {
  7250. var width = nearest_pow2( image.width );
  7251. var height = nearest_pow2( image.height );
  7252. var canvas = document.createElement( 'canvas' );
  7253. canvas.width = width;
  7254. canvas.height = height;
  7255. var context = canvas.getContext( '2d' );
  7256. context.drawImage( image, 0, 0, width, height );
  7257. texture.image = canvas;
  7258. } else {
  7259. texture.image = image;
  7260. }
  7261. texture.needsUpdate = true;
  7262. } );
  7263. }
  7264. texture.sourceFile = sourceFile;
  7265. if ( repeat ) {
  7266. texture.repeat.set( repeat[ 0 ], repeat[ 1 ] );
  7267. if ( repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  7268. if ( repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  7269. }
  7270. if ( offset ) {
  7271. texture.offset.set( offset[ 0 ], offset[ 1 ] );
  7272. }
  7273. if ( wrap ) {
  7274. var wrapMap = {
  7275. 'repeat': THREE.RepeatWrapping,
  7276. 'mirror': THREE.MirroredRepeatWrapping
  7277. };
  7278. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ wrap[ 0 ] ];
  7279. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ wrap[ 1 ] ];
  7280. }
  7281. if ( anisotropy ) {
  7282. texture.anisotropy = anisotropy;
  7283. }
  7284. where[ name ] = texture;
  7285. }
  7286. function rgb2hex( rgb ) {
  7287. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  7288. }
  7289. // defaults
  7290. var mtype = 'MeshLambertMaterial';
  7291. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  7292. // parameters from model file
  7293. if ( m.shading ) {
  7294. var shading = m.shading.toLowerCase();
  7295. if ( shading === 'phong' ) mtype = 'MeshPhongMaterial';
  7296. else if ( shading === 'basic' ) mtype = 'MeshBasicMaterial';
  7297. }
  7298. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  7299. mpars.blending = THREE[ m.blending ];
  7300. }
  7301. if ( m.transparent !== undefined ) {
  7302. mpars.transparent = m.transparent;
  7303. }
  7304. if ( m.opacity !== undefined && m.opacity < 1.0 ) {
  7305. mpars.transparent = true;
  7306. }
  7307. if ( m.depthTest !== undefined ) {
  7308. mpars.depthTest = m.depthTest;
  7309. }
  7310. if ( m.depthWrite !== undefined ) {
  7311. mpars.depthWrite = m.depthWrite;
  7312. }
  7313. if ( m.visible !== undefined ) {
  7314. mpars.visible = m.visible;
  7315. }
  7316. if ( m.flipSided !== undefined ) {
  7317. mpars.side = THREE.BackSide;
  7318. }
  7319. if ( m.doubleSided !== undefined ) {
  7320. mpars.side = THREE.DoubleSide;
  7321. }
  7322. if ( m.wireframe !== undefined ) {
  7323. mpars.wireframe = m.wireframe;
  7324. }
  7325. if ( m.vertexColors !== undefined ) {
  7326. if ( m.vertexColors === 'face' ) {
  7327. mpars.vertexColors = THREE.FaceColors;
  7328. } else if ( m.vertexColors ) {
  7329. mpars.vertexColors = THREE.VertexColors;
  7330. }
  7331. }
  7332. // colors
  7333. if ( m.colorDiffuse ) {
  7334. mpars.color = rgb2hex( m.colorDiffuse );
  7335. } else if ( m.DbgColor ) {
  7336. mpars.color = m.DbgColor;
  7337. }
  7338. if ( m.colorSpecular ) {
  7339. mpars.specular = rgb2hex( m.colorSpecular );
  7340. }
  7341. if ( m.colorEmissive ) {
  7342. mpars.emissive = rgb2hex( m.colorEmissive );
  7343. }
  7344. // modifiers
  7345. if ( m.transparency !== undefined ) {
  7346. console.warn( 'THREE.Loader: transparency has been renamed to opacity' );
  7347. m.opacity = m.transparency;
  7348. }
  7349. if ( m.opacity !== undefined ) {
  7350. mpars.opacity = m.opacity;
  7351. }
  7352. if ( m.specularCoef ) {
  7353. mpars.shininess = m.specularCoef;
  7354. }
  7355. // textures
  7356. if ( m.mapDiffuse && texturePath ) {
  7357. create_texture( mpars, 'map', m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  7358. }
  7359. if ( m.mapLight && texturePath ) {
  7360. create_texture( mpars, 'lightMap', m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  7361. }
  7362. if ( m.mapAO && texturePath ) {
  7363. create_texture( mpars, 'aoMap', m.mapAO, m.mapAORepeat, m.mapAOOffset, m.mapAOWrap, m.mapAOAnisotropy );
  7364. }
  7365. if ( m.mapBump && texturePath ) {
  7366. create_texture( mpars, 'bumpMap', m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  7367. }
  7368. if ( m.mapNormal && texturePath ) {
  7369. create_texture( mpars, 'normalMap', m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  7370. }
  7371. if ( m.mapSpecular && texturePath ) {
  7372. create_texture( mpars, 'specularMap', m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  7373. }
  7374. if ( m.mapAlpha && texturePath ) {
  7375. create_texture( mpars, 'alphaMap', m.mapAlpha, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy );
  7376. }
  7377. //
  7378. if ( m.mapBumpScale ) {
  7379. mpars.bumpScale = m.mapBumpScale;
  7380. }
  7381. if ( m.mapNormalFactor ) {
  7382. mpars.normalScale = new THREE.Vector2( m.mapNormalFactor, m.mapNormalFactor );
  7383. }
  7384. var material = new THREE[ mtype ]( mpars );
  7385. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  7386. return material;
  7387. }
  7388. };
  7389. THREE.Loader.Handlers = {
  7390. handlers: [],
  7391. add: function ( regex, loader ) {
  7392. this.handlers.push( regex, loader );
  7393. },
  7394. get: function ( file ) {
  7395. for ( var i = 0, l = this.handlers.length; i < l; i += 2 ) {
  7396. var regex = this.handlers[ i ];
  7397. var loader = this.handlers[ i + 1 ];
  7398. if ( regex.test( file ) ) {
  7399. return loader;
  7400. }
  7401. }
  7402. return null;
  7403. }
  7404. };
  7405. // File:src/loaders/XHRLoader.js
  7406. /**
  7407. * @author mrdoob / http://mrdoob.com/
  7408. */
  7409. THREE.XHRLoader = function ( manager ) {
  7410. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7411. };
  7412. THREE.XHRLoader.prototype = {
  7413. constructor: THREE.XHRLoader,
  7414. load: function ( url, onLoad, onProgress, onError ) {
  7415. var scope = this;
  7416. var cached = THREE.Cache.get( url );
  7417. if ( cached !== undefined ) {
  7418. if ( onLoad ) onLoad( cached );
  7419. return cached;
  7420. }
  7421. var request = new XMLHttpRequest();
  7422. request.open( 'GET', url, true );
  7423. request.addEventListener( 'load', function ( event ) {
  7424. THREE.Cache.add( url, this.response );
  7425. if ( onLoad ) onLoad( this.response );
  7426. scope.manager.itemEnd( url );
  7427. }, false );
  7428. if ( onProgress !== undefined ) {
  7429. request.addEventListener( 'progress', function ( event ) {
  7430. onProgress( event );
  7431. }, false );
  7432. }
  7433. if ( onError !== undefined ) {
  7434. request.addEventListener( 'error', function ( event ) {
  7435. onError( event );
  7436. }, false );
  7437. }
  7438. if ( this.crossOrigin !== undefined ) request.crossOrigin = this.crossOrigin;
  7439. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  7440. request.send( null );
  7441. scope.manager.itemStart( url );
  7442. },
  7443. setResponseType: function ( value ) {
  7444. this.responseType = value;
  7445. },
  7446. setCrossOrigin: function ( value ) {
  7447. this.crossOrigin = value;
  7448. }
  7449. };
  7450. // File:src/loaders/ImageLoader.js
  7451. /**
  7452. * @author mrdoob / http://mrdoob.com/
  7453. */
  7454. THREE.ImageLoader = function ( manager ) {
  7455. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7456. };
  7457. THREE.ImageLoader.prototype = {
  7458. constructor: THREE.ImageLoader,
  7459. load: function ( url, onLoad, onProgress, onError ) {
  7460. var scope = this;
  7461. var cached = THREE.Cache.get( url );
  7462. if ( cached !== undefined ) {
  7463. if ( onLoad ) onLoad( cached );
  7464. return cached;
  7465. }
  7466. var image = document.createElement( 'img' );
  7467. image.addEventListener( 'load', function ( event ) {
  7468. THREE.Cache.add( url, this );
  7469. if ( onLoad ) onLoad( this );
  7470. scope.manager.itemEnd( url );
  7471. }, false );
  7472. if ( onProgress !== undefined ) {
  7473. image.addEventListener( 'progress', function ( event ) {
  7474. onProgress( event );
  7475. }, false );
  7476. }
  7477. if ( onError !== undefined ) {
  7478. image.addEventListener( 'error', function ( event ) {
  7479. onError( event );
  7480. }, false );
  7481. }
  7482. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  7483. scope.manager.itemStart( url );
  7484. image.src = url;
  7485. return image;
  7486. },
  7487. setCrossOrigin: function ( value ) {
  7488. this.crossOrigin = value;
  7489. }
  7490. };
  7491. // File:src/loaders/JSONLoader.js
  7492. /**
  7493. * @author mrdoob / http://mrdoob.com/
  7494. * @author alteredq / http://alteredqualia.com/
  7495. */
  7496. THREE.JSONLoader = function ( showStatus ) {
  7497. THREE.Loader.call( this, showStatus );
  7498. this.withCredentials = false;
  7499. };
  7500. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  7501. THREE.JSONLoader.prototype.constructor = THREE.JSONLoader;
  7502. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  7503. // todo: unify load API to for easier SceneLoader use
  7504. texturePath = texturePath && ( typeof texturePath === 'string' ) ? texturePath : this.extractUrlBase( url );
  7505. this.onLoadStart();
  7506. this.loadAjaxJSON( this, url, callback, texturePath );
  7507. };
  7508. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  7509. var xhr = new XMLHttpRequest();
  7510. var length = 0;
  7511. xhr.onreadystatechange = function () {
  7512. if ( xhr.readyState === xhr.DONE ) {
  7513. if ( xhr.status === 200 || xhr.status === 0 ) {
  7514. if ( xhr.responseText ) {
  7515. var json = JSON.parse( xhr.responseText );
  7516. var metadata = json.metadata;
  7517. if ( metadata !== undefined ) {
  7518. if ( metadata.type === 'object' ) {
  7519. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' );
  7520. return;
  7521. }
  7522. if ( metadata.type === 'scene' ) {
  7523. console.error( 'THREE.JSONLoader: ' + url + ' seems to be a Scene. Use THREE.SceneLoader instead.' );
  7524. return;
  7525. }
  7526. }
  7527. var result = context.parse( json, texturePath );
  7528. callback( result.geometry, result.materials );
  7529. } else {
  7530. console.error( 'THREE.JSONLoader: ' + url + ' seems to be unreachable or the file is empty.' );
  7531. }
  7532. // in context of more complex asset initialization
  7533. // do not block on single failed file
  7534. // maybe should go even one more level up
  7535. context.onLoadComplete();
  7536. } else {
  7537. console.error( 'THREE.JSONLoader: Couldn\'t load ' + url + ' (' + xhr.status + ')' );
  7538. }
  7539. } else if ( xhr.readyState === xhr.LOADING ) {
  7540. if ( callbackProgress ) {
  7541. if ( length === 0 ) {
  7542. length = xhr.getResponseHeader( 'Content-Length' );
  7543. }
  7544. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  7545. }
  7546. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  7547. if ( callbackProgress !== undefined ) {
  7548. length = xhr.getResponseHeader( 'Content-Length' );
  7549. }
  7550. }
  7551. };
  7552. xhr.open( 'GET', url, true );
  7553. xhr.withCredentials = this.withCredentials;
  7554. xhr.send( null );
  7555. };
  7556. THREE.JSONLoader.prototype.parse = function ( json, texturePath ) {
  7557. var geometry = new THREE.Geometry(),
  7558. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  7559. parseModel( scale );
  7560. parseSkin();
  7561. parseMorphing( scale );
  7562. geometry.computeFaceNormals();
  7563. geometry.computeBoundingSphere();
  7564. function parseModel( scale ) {
  7565. function isBitSet( value, position ) {
  7566. return value & ( 1 << position );
  7567. }
  7568. var i, j, fi,
  7569. offset, zLength,
  7570. colorIndex, normalIndex, uvIndex,
  7571. type,
  7572. isQuad,
  7573. hasMaterial,
  7574. hasFaceVertexUv,
  7575. hasFaceNormal, hasFaceVertexNormal,
  7576. hasFaceColor, hasFaceVertexColor,
  7577. vertex, face, faceA, faceB, hex, normal,
  7578. uvLayer, uv, u, v,
  7579. faces = json.faces,
  7580. vertices = json.vertices,
  7581. normals = json.normals,
  7582. colors = json.colors,
  7583. nUvLayers = 0;
  7584. if ( json.uvs !== undefined ) {
  7585. // disregard empty arrays
  7586. for ( i = 0; i < json.uvs.length; i ++ ) {
  7587. if ( json.uvs[ i ].length ) nUvLayers ++;
  7588. }
  7589. for ( i = 0; i < nUvLayers; i ++ ) {
  7590. geometry.faceVertexUvs[ i ] = [];
  7591. }
  7592. }
  7593. offset = 0;
  7594. zLength = vertices.length;
  7595. while ( offset < zLength ) {
  7596. vertex = new THREE.Vector3();
  7597. vertex.x = vertices[ offset ++ ] * scale;
  7598. vertex.y = vertices[ offset ++ ] * scale;
  7599. vertex.z = vertices[ offset ++ ] * scale;
  7600. geometry.vertices.push( vertex );
  7601. }
  7602. offset = 0;
  7603. zLength = faces.length;
  7604. while ( offset < zLength ) {
  7605. type = faces[ offset ++ ];
  7606. isQuad = isBitSet( type, 0 );
  7607. hasMaterial = isBitSet( type, 1 );
  7608. hasFaceVertexUv = isBitSet( type, 3 );
  7609. hasFaceNormal = isBitSet( type, 4 );
  7610. hasFaceVertexNormal = isBitSet( type, 5 );
  7611. hasFaceColor = isBitSet( type, 6 );
  7612. hasFaceVertexColor = isBitSet( type, 7 );
  7613. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  7614. if ( isQuad ) {
  7615. faceA = new THREE.Face3();
  7616. faceA.a = faces[ offset ];
  7617. faceA.b = faces[ offset + 1 ];
  7618. faceA.c = faces[ offset + 3 ];
  7619. faceB = new THREE.Face3();
  7620. faceB.a = faces[ offset + 1 ];
  7621. faceB.b = faces[ offset + 2 ];
  7622. faceB.c = faces[ offset + 3 ];
  7623. offset += 4;
  7624. if ( hasMaterial ) {
  7625. offset ++;
  7626. }
  7627. // to get face <=> uv index correspondence
  7628. fi = geometry.faces.length;
  7629. if ( hasFaceVertexUv ) {
  7630. for ( i = 0; i < nUvLayers; i ++ ) {
  7631. uvLayer = json.uvs[ i ];
  7632. geometry.faceVertexUvs[ i ][ fi ] = [];
  7633. geometry.faceVertexUvs[ i ][ fi + 1 ] = [];
  7634. for ( j = 0; j < 4; j ++ ) {
  7635. uvIndex = faces[ offset ++ ];
  7636. u = uvLayer[ uvIndex * 2 ];
  7637. v = uvLayer[ uvIndex * 2 + 1 ];
  7638. uv = new THREE.Vector2( u, v );
  7639. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  7640. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  7641. }
  7642. }
  7643. }
  7644. if ( hasFaceNormal ) {
  7645. normalIndex = faces[ offset ++ ] * 3;
  7646. faceA.normal.set(
  7647. normals[ normalIndex ++ ],
  7648. normals[ normalIndex ++ ],
  7649. normals[ normalIndex ]
  7650. );
  7651. faceB.normal.copy( faceA.normal );
  7652. }
  7653. if ( hasFaceVertexNormal ) {
  7654. for ( i = 0; i < 4; i ++ ) {
  7655. normalIndex = faces[ offset ++ ] * 3;
  7656. normal = new THREE.Vector3(
  7657. normals[ normalIndex ++ ],
  7658. normals[ normalIndex ++ ],
  7659. normals[ normalIndex ]
  7660. );
  7661. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  7662. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  7663. }
  7664. }
  7665. if ( hasFaceColor ) {
  7666. colorIndex = faces[ offset ++ ];
  7667. hex = colors[ colorIndex ];
  7668. faceA.color.setHex( hex );
  7669. faceB.color.setHex( hex );
  7670. }
  7671. if ( hasFaceVertexColor ) {
  7672. for ( i = 0; i < 4; i ++ ) {
  7673. colorIndex = faces[ offset ++ ];
  7674. hex = colors[ colorIndex ];
  7675. if ( i !== 2 ) faceA.vertexColors.push( new THREE.Color( hex ) );
  7676. if ( i !== 0 ) faceB.vertexColors.push( new THREE.Color( hex ) );
  7677. }
  7678. }
  7679. geometry.faces.push( faceA );
  7680. geometry.faces.push( faceB );
  7681. } else {
  7682. face = new THREE.Face3();
  7683. face.a = faces[ offset ++ ];
  7684. face.b = faces[ offset ++ ];
  7685. face.c = faces[ offset ++ ];
  7686. if ( hasMaterial ) {
  7687. offset ++;
  7688. }
  7689. // to get face <=> uv index correspondence
  7690. fi = geometry.faces.length;
  7691. if ( hasFaceVertexUv ) {
  7692. for ( i = 0; i < nUvLayers; i ++ ) {
  7693. uvLayer = json.uvs[ i ];
  7694. geometry.faceVertexUvs[ i ][ fi ] = [];
  7695. for ( j = 0; j < 3; j ++ ) {
  7696. uvIndex = faces[ offset ++ ];
  7697. u = uvLayer[ uvIndex * 2 ];
  7698. v = uvLayer[ uvIndex * 2 + 1 ];
  7699. uv = new THREE.Vector2( u, v );
  7700. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  7701. }
  7702. }
  7703. }
  7704. if ( hasFaceNormal ) {
  7705. normalIndex = faces[ offset ++ ] * 3;
  7706. face.normal.set(
  7707. normals[ normalIndex ++ ],
  7708. normals[ normalIndex ++ ],
  7709. normals[ normalIndex ]
  7710. );
  7711. }
  7712. if ( hasFaceVertexNormal ) {
  7713. for ( i = 0; i < 3; i ++ ) {
  7714. normalIndex = faces[ offset ++ ] * 3;
  7715. normal = new THREE.Vector3(
  7716. normals[ normalIndex ++ ],
  7717. normals[ normalIndex ++ ],
  7718. normals[ normalIndex ]
  7719. );
  7720. face.vertexNormals.push( normal );
  7721. }
  7722. }
  7723. if ( hasFaceColor ) {
  7724. colorIndex = faces[ offset ++ ];
  7725. face.color.setHex( colors[ colorIndex ] );
  7726. }
  7727. if ( hasFaceVertexColor ) {
  7728. for ( i = 0; i < 3; i ++ ) {
  7729. colorIndex = faces[ offset ++ ];
  7730. face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) );
  7731. }
  7732. }
  7733. geometry.faces.push( face );
  7734. }
  7735. }
  7736. }
  7737. function parseSkin() {
  7738. var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2;
  7739. if ( json.skinWeights ) {
  7740. for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {
  7741. var x = json.skinWeights[ i ];
  7742. var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
  7743. var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
  7744. var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;
  7745. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  7746. }
  7747. }
  7748. if ( json.skinIndices ) {
  7749. for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {
  7750. var a = json.skinIndices[ i ];
  7751. var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
  7752. var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
  7753. var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;
  7754. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  7755. }
  7756. }
  7757. geometry.bones = json.bones;
  7758. if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {
  7759. console.warn( 'THREE.JSONLoader: When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
  7760. geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );
  7761. }
  7762. // could change this to json.animations[0] or remove completely
  7763. geometry.animation = json.animation;
  7764. geometry.animations = json.animations;
  7765. }
  7766. function parseMorphing( scale ) {
  7767. if ( json.morphTargets !== undefined ) {
  7768. var i, l, v, vl, dstVertices, srcVertices;
  7769. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  7770. geometry.morphTargets[ i ] = {};
  7771. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  7772. geometry.morphTargets[ i ].vertices = [];
  7773. dstVertices = geometry.morphTargets[ i ].vertices;
  7774. srcVertices = json.morphTargets [ i ].vertices;
  7775. for ( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  7776. var vertex = new THREE.Vector3();
  7777. vertex.x = srcVertices[ v ] * scale;
  7778. vertex.y = srcVertices[ v + 1 ] * scale;
  7779. vertex.z = srcVertices[ v + 2 ] * scale;
  7780. dstVertices.push( vertex );
  7781. }
  7782. }
  7783. }
  7784. if ( json.morphColors !== undefined ) {
  7785. var i, l, c, cl, dstColors, srcColors, color;
  7786. for ( i = 0, l = json.morphColors.length; i < l; i ++ ) {
  7787. geometry.morphColors[ i ] = {};
  7788. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  7789. geometry.morphColors[ i ].colors = [];
  7790. dstColors = geometry.morphColors[ i ].colors;
  7791. srcColors = json.morphColors [ i ].colors;
  7792. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  7793. color = new THREE.Color( 0xffaa00 );
  7794. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  7795. dstColors.push( color );
  7796. }
  7797. }
  7798. }
  7799. }
  7800. if ( json.materials === undefined || json.materials.length === 0 ) {
  7801. return { geometry: geometry };
  7802. } else {
  7803. var materials = this.initMaterials( json.materials, texturePath );
  7804. if ( this.needsTangents( materials ) ) {
  7805. geometry.computeTangents();
  7806. }
  7807. return { geometry: geometry, materials: materials };
  7808. }
  7809. };
  7810. // File:src/loaders/LoadingManager.js
  7811. /**
  7812. * @author mrdoob / http://mrdoob.com/
  7813. */
  7814. THREE.LoadingManager = function ( onLoad, onProgress, onError ) {
  7815. var scope = this;
  7816. var loaded = 0, total = 0;
  7817. this.onLoad = onLoad;
  7818. this.onProgress = onProgress;
  7819. this.onError = onError;
  7820. this.itemStart = function ( url ) {
  7821. total ++;
  7822. };
  7823. this.itemEnd = function ( url ) {
  7824. loaded ++;
  7825. if ( scope.onProgress !== undefined ) {
  7826. scope.onProgress( url, loaded, total );
  7827. }
  7828. if ( loaded === total && scope.onLoad !== undefined ) {
  7829. scope.onLoad();
  7830. }
  7831. };
  7832. };
  7833. THREE.DefaultLoadingManager = new THREE.LoadingManager();
  7834. // File:src/loaders/BufferGeometryLoader.js
  7835. /**
  7836. * @author mrdoob / http://mrdoob.com/
  7837. */
  7838. THREE.BufferGeometryLoader = function ( manager ) {
  7839. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7840. };
  7841. THREE.BufferGeometryLoader.prototype = {
  7842. constructor: THREE.BufferGeometryLoader,
  7843. load: function ( url, onLoad, onProgress, onError ) {
  7844. var scope = this;
  7845. var loader = new THREE.XHRLoader( scope.manager );
  7846. loader.setCrossOrigin( this.crossOrigin );
  7847. loader.load( url, function ( text ) {
  7848. onLoad( scope.parse( JSON.parse( text ) ) );
  7849. }, onProgress, onError );
  7850. },
  7851. setCrossOrigin: function ( value ) {
  7852. this.crossOrigin = value;
  7853. },
  7854. parse: function ( json ) {
  7855. var geometry = new THREE.BufferGeometry();
  7856. var attributes = json.data.attributes;
  7857. for ( var key in attributes ) {
  7858. var attribute = attributes[ key ];
  7859. var typedArray = new self[ attribute.type ]( attribute.array );
  7860. geometry.addAttribute( key, new THREE.BufferAttribute( typedArray, attribute.itemSize ) );
  7861. }
  7862. var offsets = json.data.offsets;
  7863. if ( offsets !== undefined ) {
  7864. geometry.offsets = JSON.parse( JSON.stringify( offsets ) );
  7865. }
  7866. var boundingSphere = json.data.boundingSphere;
  7867. if ( boundingSphere !== undefined ) {
  7868. var center = new THREE.Vector3();
  7869. if ( boundingSphere.center !== undefined ) {
  7870. center.fromArray( boundingSphere.center );
  7871. }
  7872. geometry.boundingSphere = new THREE.Sphere( center, boundingSphere.radius );
  7873. }
  7874. return geometry;
  7875. }
  7876. };
  7877. // File:src/loaders/MaterialLoader.js
  7878. /**
  7879. * @author mrdoob / http://mrdoob.com/
  7880. */
  7881. THREE.MaterialLoader = function ( manager ) {
  7882. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7883. };
  7884. THREE.MaterialLoader.prototype = {
  7885. constructor: THREE.MaterialLoader,
  7886. load: function ( url, onLoad, onProgress, onError ) {
  7887. var scope = this;
  7888. var loader = new THREE.XHRLoader( scope.manager );
  7889. loader.setCrossOrigin( this.crossOrigin );
  7890. loader.load( url, function ( text ) {
  7891. onLoad( scope.parse( JSON.parse( text ) ) );
  7892. }, onProgress, onError );
  7893. },
  7894. setCrossOrigin: function ( value ) {
  7895. this.crossOrigin = value;
  7896. },
  7897. parse: function ( json ) {
  7898. var material = new THREE[ json.type ];
  7899. if ( json.color !== undefined ) material.color.setHex( json.color );
  7900. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  7901. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  7902. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  7903. if ( json.uniforms !== undefined ) material.uniforms = json.uniforms;
  7904. if ( json.attributes !== undefined ) material.attributes = json.attributes;
  7905. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  7906. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  7907. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  7908. if ( json.shading !== undefined ) material.shading = json.shading;
  7909. if ( json.blending !== undefined ) material.blending = json.blending;
  7910. if ( json.side !== undefined ) material.side = json.side;
  7911. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  7912. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  7913. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  7914. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  7915. // for PointCloudMaterial
  7916. if ( json.size !== undefined ) material.size = json.size;
  7917. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  7918. if ( json.materials !== undefined ) {
  7919. for ( var i = 0, l = json.materials.length; i < l; i ++ ) {
  7920. material.materials.push( this.parse( json.materials[ i ] ) );
  7921. }
  7922. }
  7923. return material;
  7924. }
  7925. };
  7926. // File:src/loaders/ObjectLoader.js
  7927. /**
  7928. * @author mrdoob / http://mrdoob.com/
  7929. */
  7930. THREE.ObjectLoader = function ( manager ) {
  7931. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7932. this.texturePath = '';
  7933. };
  7934. THREE.ObjectLoader.prototype = {
  7935. constructor: THREE.ObjectLoader,
  7936. load: function ( url, onLoad, onProgress, onError ) {
  7937. if ( this.texturePath === '' ) {
  7938. this.texturePath = url.substring( 0, url.lastIndexOf( '/' ) + 1 );
  7939. }
  7940. var scope = this;
  7941. var loader = new THREE.XHRLoader( scope.manager );
  7942. loader.setCrossOrigin( this.crossOrigin );
  7943. loader.load( url, function ( text ) {
  7944. scope.parse( JSON.parse( text ), onLoad );
  7945. }, onProgress, onError );
  7946. },
  7947. setTexturePath: function ( value ) {
  7948. this.texturePath = value;
  7949. },
  7950. setCrossOrigin: function ( value ) {
  7951. this.crossOrigin = value;
  7952. },
  7953. parse: function ( json, onLoad ) {
  7954. var geometries = this.parseGeometries( json.geometries );
  7955. var images = this.parseImages( json.images, function () {
  7956. if ( onLoad !== undefined ) onLoad( object );
  7957. } );
  7958. var textures = this.parseTextures( json.textures, images );
  7959. var materials = this.parseMaterials( json.materials, textures );
  7960. var object = this.parseObject( json.object, geometries, materials );
  7961. if ( json.images === undefined || json.images.length === 0 ) {
  7962. if ( onLoad !== undefined ) onLoad( object );
  7963. }
  7964. return object;
  7965. },
  7966. parseGeometries: function ( json ) {
  7967. var geometries = {};
  7968. if ( json !== undefined ) {
  7969. var geometryLoader = new THREE.JSONLoader();
  7970. var bufferGeometryLoader = new THREE.BufferGeometryLoader();
  7971. for ( var i = 0, l = json.length; i < l; i ++ ) {
  7972. var geometry;
  7973. var data = json[ i ];
  7974. switch ( data.type ) {
  7975. case 'PlaneGeometry':
  7976. case 'PlaneBufferGeometry':
  7977. geometry = new THREE[ data.type ](
  7978. data.width,
  7979. data.height,
  7980. data.widthSegments,
  7981. data.heightSegments
  7982. );
  7983. break;
  7984. case 'BoxGeometry':
  7985. case 'CubeGeometry': // backwards compatible
  7986. geometry = new THREE.BoxGeometry(
  7987. data.width,
  7988. data.height,
  7989. data.depth,
  7990. data.widthSegments,
  7991. data.heightSegments,
  7992. data.depthSegments
  7993. );
  7994. break;
  7995. case 'CircleGeometry':
  7996. geometry = new THREE.CircleGeometry(
  7997. data.radius,
  7998. data.segments
  7999. );
  8000. break;
  8001. case 'CylinderGeometry':
  8002. geometry = new THREE.CylinderGeometry(
  8003. data.radiusTop,
  8004. data.radiusBottom,
  8005. data.height,
  8006. data.radialSegments,
  8007. data.heightSegments,
  8008. data.openEnded
  8009. );
  8010. break;
  8011. case 'SphereGeometry':
  8012. geometry = new THREE.SphereGeometry(
  8013. data.radius,
  8014. data.widthSegments,
  8015. data.heightSegments,
  8016. data.phiStart,
  8017. data.phiLength,
  8018. data.thetaStart,
  8019. data.thetaLength
  8020. );
  8021. break;
  8022. case 'IcosahedronGeometry':
  8023. geometry = new THREE.IcosahedronGeometry(
  8024. data.radius,
  8025. data.detail
  8026. );
  8027. break;
  8028. case 'TorusGeometry':
  8029. geometry = new THREE.TorusGeometry(
  8030. data.radius,
  8031. data.tube,
  8032. data.radialSegments,
  8033. data.tubularSegments,
  8034. data.arc
  8035. );
  8036. break;
  8037. case 'TorusKnotGeometry':
  8038. geometry = new THREE.TorusKnotGeometry(
  8039. data.radius,
  8040. data.tube,
  8041. data.radialSegments,
  8042. data.tubularSegments,
  8043. data.p,
  8044. data.q,
  8045. data.heightScale
  8046. );
  8047. break;
  8048. case 'BufferGeometry':
  8049. geometry = bufferGeometryLoader.parse( data );
  8050. break;
  8051. case 'Geometry':
  8052. geometry = geometryLoader.parse( data.data ).geometry;
  8053. break;
  8054. case 'TextGeometry':
  8055. geometry = new THREE.TextGeometry(
  8056. data.text,
  8057. data.data
  8058. );
  8059. break;
  8060. }
  8061. geometry.uuid = data.uuid;
  8062. if ( data.name !== undefined ) geometry.name = data.name;
  8063. geometries[ data.uuid ] = geometry;
  8064. }
  8065. }
  8066. return geometries;
  8067. },
  8068. parseMaterials: function ( json, textures ) {
  8069. var materials = {};
  8070. if ( json !== undefined ) {
  8071. var getTexture = function ( name ) {
  8072. if ( textures[ name ] === undefined ) {
  8073. console.warn( 'THREE.ObjectLoader: Undefined texture', name );
  8074. }
  8075. return textures[ name ];
  8076. };
  8077. var loader = new THREE.MaterialLoader();
  8078. for ( var i = 0, l = json.length; i < l; i ++ ) {
  8079. var data = json[ i ];
  8080. var material = loader.parse( data );
  8081. material.uuid = data.uuid;
  8082. if ( data.depthTest !== undefined ) material.depthTest = data.depthTest;
  8083. if ( data.depthWrite !== undefined ) material.depthWrite = data.depthWrite;
  8084. if ( data.name !== undefined ) material.name = data.name;
  8085. if ( data.map !== undefined ) material.map = getTexture( data.map );
  8086. if ( data.alphaMap !== undefined ) {
  8087. material.alphaMap = getTexture( data.alphaMap );
  8088. material.transparent = true;
  8089. }
  8090. if ( data.bumpMap !== undefined ) material.bumpMap = getTexture( data.bumpMap );
  8091. if ( data.bumpScale !== undefined ) material.bumpScale = data.bumpScale;
  8092. if ( data.normalMap !== undefined ) material.normalMap = getTexture( data.normalMap );
  8093. if ( data.normalScale ) material.normalScale = new THREE.Vector2( data.normalScale, data.normalScale );
  8094. if ( data.specularMap !== undefined ) material.specularMap = getTexture( data.specularMap );
  8095. if ( data.envMap !== undefined ) {
  8096. material.envMap = getTexture( data.envMap );
  8097. material.combine = THREE.MultiplyOperation;
  8098. }
  8099. if ( data.reflectivity ) material.reflectivity = data.reflectivity;
  8100. if ( data.lightMap !== undefined ) material.lightMap = getTexture( data.lightMap );
  8101. if ( data.lightMapIntensity !== undefined ) material.lightMapIntensity = data.lightMapIntensity;
  8102. if ( data.aoMap !== undefined ) material.aoMap = getTexture( data.aoMap );
  8103. if ( data.aoMapIntensity !== undefined ) material.aoMapIntensity = data.aoMapIntensity;
  8104. materials[ data.uuid ] = material;
  8105. }
  8106. }
  8107. return materials;
  8108. },
  8109. parseImages: function ( json, onLoad ) {
  8110. var scope = this;
  8111. var images = {};
  8112. if ( json !== undefined && json.length > 0 ) {
  8113. var manager = new THREE.LoadingManager( onLoad );
  8114. var loader = new THREE.ImageLoader( manager );
  8115. loader.setCrossOrigin( this.crossOrigin );
  8116. var loadImage = function ( url ) {
  8117. scope.manager.itemStart( url );
  8118. return loader.load( url, function () {
  8119. scope.manager.itemEnd( url );
  8120. } );
  8121. };
  8122. for ( var i = 0, l = json.length; i < l; i ++ ) {
  8123. var image = json[ i ];
  8124. images[ image.uuid ] = loadImage( image.url );
  8125. }
  8126. }
  8127. return images;
  8128. },
  8129. parseTextures: function ( json, images ) {
  8130. function parseConstant( value ) {
  8131. if ( typeof( value ) === 'number' ) return value;
  8132. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  8133. return THREE[ value ];
  8134. }
  8135. var textures = {};
  8136. if ( json !== undefined ) {
  8137. for ( var i = 0, l = json.length; i < l; i ++ ) {
  8138. var data = json[ i ];
  8139. if ( data.image === undefined ) {
  8140. console.warn( 'THREE.ObjectLoader: No "image" speficied for', data.uuid );
  8141. }
  8142. if ( images[ data.image ] === undefined ) {
  8143. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  8144. }
  8145. var texture = new THREE.Texture( images[ data.image ] );
  8146. texture.needsUpdate = true;
  8147. texture.uuid = data.uuid;
  8148. if ( data.name !== undefined ) texture.name = data.name;
  8149. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping );
  8150. if ( data.repeat !== undefined ) texture.repeat = new THREE.Vector2( data.repeat[ 0 ], data.repeat[ 1 ] );
  8151. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter );
  8152. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter );
  8153. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  8154. if ( Array.isArray( data.wrap ) ) {
  8155. texture.wrapS = parseConstant( data.wrap[ 0 ] );
  8156. texture.wrapT = parseConstant( data.wrap[ 1 ] );
  8157. }
  8158. textures[ data.uuid ] = texture;
  8159. }
  8160. }
  8161. return textures;
  8162. },
  8163. parseObject: function () {
  8164. var matrix = new THREE.Matrix4();
  8165. return function ( data, geometries, materials ) {
  8166. var object;
  8167. var getGeometry = function ( name ) {
  8168. if ( geometries[ name ] === undefined ) {
  8169. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  8170. }
  8171. return geometries[ name ];
  8172. };
  8173. var getMaterial = function ( name ) {
  8174. if ( materials[ name ] === undefined ) {
  8175. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  8176. }
  8177. return materials[ name ];
  8178. };
  8179. switch ( data.type ) {
  8180. case 'Scene':
  8181. object = new THREE.Scene();
  8182. break;
  8183. case 'PerspectiveCamera':
  8184. object = new THREE.PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  8185. break;
  8186. case 'OrthographicCamera':
  8187. object = new THREE.OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  8188. break;
  8189. case 'AmbientLight':
  8190. object = new THREE.AmbientLight( data.color );
  8191. break;
  8192. case 'DirectionalLight':
  8193. object = new THREE.DirectionalLight( data.color, data.intensity );
  8194. break;
  8195. case 'PointLight':
  8196. object = new THREE.PointLight( data.color, data.intensity, data.distance, data.decay );
  8197. break;
  8198. case 'SpotLight':
  8199. object = new THREE.SpotLight( data.color, data.intensity, data.distance, data.angle, data.exponent, data.decay );
  8200. break;
  8201. case 'HemisphereLight':
  8202. object = new THREE.HemisphereLight( data.color, data.groundColor, data.intensity );
  8203. break;
  8204. case 'Mesh':
  8205. object = new THREE.Mesh( getGeometry( data.geometry ), getMaterial( data.material ) );
  8206. break;
  8207. case 'Line':
  8208. object = new THREE.Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode );
  8209. break;
  8210. case 'PointCloud':
  8211. object = new THREE.PointCloud( getGeometry( data.geometry ), getMaterial( data.material ) );
  8212. break;
  8213. case 'Sprite':
  8214. object = new THREE.Sprite( getMaterial( data.material ) );
  8215. break;
  8216. case 'Group':
  8217. object = new THREE.Group();
  8218. break;
  8219. default:
  8220. object = new THREE.Object3D();
  8221. }
  8222. object.uuid = data.uuid;
  8223. if ( data.name !== undefined ) object.name = data.name;
  8224. if ( data.matrix !== undefined ) {
  8225. matrix.fromArray( data.matrix );
  8226. matrix.decompose( object.position, object.quaternion, object.scale );
  8227. } else {
  8228. if ( data.position !== undefined ) object.position.fromArray( data.position );
  8229. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  8230. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  8231. }
  8232. if ( data.visible !== undefined ) object.visible = data.visible;
  8233. if ( data.userData !== undefined ) object.userData = data.userData;
  8234. if ( data.children !== undefined ) {
  8235. for ( var child in data.children ) {
  8236. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  8237. }
  8238. }
  8239. return object;
  8240. }
  8241. }()
  8242. };
  8243. // File:src/loaders/TextureLoader.js
  8244. /**
  8245. * @author mrdoob / http://mrdoob.com/
  8246. */
  8247. THREE.TextureLoader = function ( manager ) {
  8248. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  8249. };
  8250. THREE.TextureLoader.prototype = {
  8251. constructor: THREE.TextureLoader,
  8252. load: function ( url, onLoad, onProgress, onError ) {
  8253. var scope = this;
  8254. var loader = new THREE.ImageLoader( scope.manager );
  8255. loader.setCrossOrigin( this.crossOrigin );
  8256. loader.load( url, function ( image ) {
  8257. var texture = new THREE.Texture( image );
  8258. texture.needsUpdate = true;
  8259. if ( onLoad !== undefined ) {
  8260. onLoad( texture );
  8261. }
  8262. }, onProgress, onError );
  8263. },
  8264. setCrossOrigin: function ( value ) {
  8265. this.crossOrigin = value;
  8266. }
  8267. };
  8268. // File:src/loaders/BinaryTextureLoader.js
  8269. /**
  8270. * @author Nikos M. / https://github.com/foo123/
  8271. *
  8272. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  8273. */
  8274. THREE.DataTextureLoader = THREE.BinaryTextureLoader = function () {
  8275. // override in sub classes
  8276. this._parser = null;
  8277. };
  8278. THREE.BinaryTextureLoader.prototype = {
  8279. constructor: THREE.BinaryTextureLoader,
  8280. load: function ( url, onLoad, onProgress, onError ) {
  8281. var scope = this;
  8282. var texture = new THREE.DataTexture( );
  8283. var loader = new THREE.XHRLoader();
  8284. loader.setResponseType( 'arraybuffer' );
  8285. loader.load( url, function ( buffer ) {
  8286. var texData = scope._parser( buffer );
  8287. if ( !texData ) return;
  8288. if ( undefined !== texData.image ) {
  8289. texture.image = texData.image;
  8290. } else if ( undefined !== texData.data ) {
  8291. texture.image.width = texData.width;
  8292. texture.image.height = texData.height;
  8293. texture.image.data = texData.data;
  8294. }
  8295. texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : THREE.ClampToEdgeWrapping;
  8296. texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : THREE.ClampToEdgeWrapping;
  8297. texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : THREE.LinearFilter;
  8298. texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : THREE.LinearMipMapLinearFilter;
  8299. texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1;
  8300. if ( undefined !== texData.format ) {
  8301. texture.format = texData.format;
  8302. }
  8303. if ( undefined !== texData.type ) {
  8304. texture.type = texData.type;
  8305. }
  8306. if ( undefined !== texData.mipmaps ) {
  8307. texture.mipmaps = texData.mipmaps;
  8308. }
  8309. if ( 1 === texData.mipmapCount ) {
  8310. texture.minFilter = THREE.LinearFilter;
  8311. }
  8312. texture.needsUpdate = true;
  8313. if ( onLoad ) onLoad( texture, texData );
  8314. }, onProgress, onError );
  8315. return texture;
  8316. }
  8317. };
  8318. // File:src/loaders/CompressedTextureLoader.js
  8319. /**
  8320. * @author mrdoob / http://mrdoob.com/
  8321. *
  8322. * Abstract Base class to block based textures loader (dds, pvr, ...)
  8323. */
  8324. THREE.CompressedTextureLoader = function () {
  8325. // override in sub classes
  8326. this._parser = null;
  8327. };
  8328. THREE.CompressedTextureLoader.prototype = {
  8329. constructor: THREE.CompressedTextureLoader,
  8330. load: function ( url, onLoad, onError ) {
  8331. var scope = this;
  8332. var images = [];
  8333. var texture = new THREE.CompressedTexture();
  8334. texture.image = images;
  8335. var loader = new THREE.XHRLoader();
  8336. loader.setResponseType( 'arraybuffer' );
  8337. if ( Array.isArray( url ) ) {
  8338. var loaded = 0;
  8339. var loadTexture = function ( i ) {
  8340. loader.load( url[ i ], function ( buffer ) {
  8341. var texDatas = scope._parser( buffer, true );
  8342. images[ i ] = {
  8343. width: texDatas.width,
  8344. height: texDatas.height,
  8345. format: texDatas.format,
  8346. mipmaps: texDatas.mipmaps
  8347. };
  8348. loaded += 1;
  8349. if ( loaded === 6 ) {
  8350. if (texDatas.mipmapCount === 1)
  8351. texture.minFilter = THREE.LinearFilter;
  8352. texture.format = texDatas.format;
  8353. texture.needsUpdate = true;
  8354. if ( onLoad ) onLoad( texture );
  8355. }
  8356. } );
  8357. };
  8358. for ( var i = 0, il = url.length; i < il; ++ i ) {
  8359. loadTexture( i );
  8360. }
  8361. } else {
  8362. // compressed cubemap texture stored in a single DDS file
  8363. loader.load( url, function ( buffer ) {
  8364. var texDatas = scope._parser( buffer, true );
  8365. if ( texDatas.isCubemap ) {
  8366. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  8367. for ( var f = 0; f < faces; f ++ ) {
  8368. images[ f ] = { mipmaps : [] };
  8369. for ( var i = 0; i < texDatas.mipmapCount; i ++ ) {
  8370. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  8371. images[ f ].format = texDatas.format;
  8372. images[ f ].width = texDatas.width;
  8373. images[ f ].height = texDatas.height;
  8374. }
  8375. }
  8376. } else {
  8377. texture.image.width = texDatas.width;
  8378. texture.image.height = texDatas.height;
  8379. texture.mipmaps = texDatas.mipmaps;
  8380. }
  8381. if ( texDatas.mipmapCount === 1 ) {
  8382. texture.minFilter = THREE.LinearFilter;
  8383. }
  8384. texture.format = texDatas.format;
  8385. texture.needsUpdate = true;
  8386. if ( onLoad ) onLoad( texture );
  8387. } );
  8388. }
  8389. return texture;
  8390. }
  8391. };
  8392. // File:src/materials/Material.js
  8393. /**
  8394. * @author mrdoob / http://mrdoob.com/
  8395. * @author alteredq / http://alteredqualia.com/
  8396. */
  8397. THREE.Material = function () {
  8398. Object.defineProperty( this, 'id', { value: THREE.MaterialIdCount ++ } );
  8399. this.uuid = THREE.Math.generateUUID();
  8400. this.name = '';
  8401. this.type = 'Material';
  8402. this.side = THREE.FrontSide;
  8403. this.opacity = 1;
  8404. this.transparent = false;
  8405. this.blending = THREE.NormalBlending;
  8406. this.blendSrc = THREE.SrcAlphaFactor;
  8407. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  8408. this.blendEquation = THREE.AddEquation;
  8409. this.blendSrcAlpha = null;
  8410. this.blendDstAlpha = null;
  8411. this.blendEquationAlpha = null;
  8412. this.depthFunc = THREE.LessEqualDepth;
  8413. this.depthTest = true;
  8414. this.depthWrite = true;
  8415. this.colorWrite = true;
  8416. this.polygonOffset = false;
  8417. this.polygonOffsetFactor = 0;
  8418. this.polygonOffsetUnits = 0;
  8419. this.alphaTest = 0;
  8420. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  8421. this.visible = true;
  8422. this._needsUpdate = true;
  8423. };
  8424. THREE.Material.prototype = {
  8425. constructor: THREE.Material,
  8426. get needsUpdate () {
  8427. return this._needsUpdate;
  8428. },
  8429. set needsUpdate ( value ) {
  8430. if ( value === true ) this.update();
  8431. this._needsUpdate = value;
  8432. },
  8433. setValues: function ( values ) {
  8434. if ( values === undefined ) return;
  8435. for ( var key in values ) {
  8436. var newValue = values[ key ];
  8437. if ( newValue === undefined ) {
  8438. console.warn( "THREE.Material: '" + key + "' parameter is undefined." );
  8439. continue;
  8440. }
  8441. if ( key in this ) {
  8442. var currentValue = this[ key ];
  8443. if ( currentValue instanceof THREE.Color ) {
  8444. currentValue.set( newValue );
  8445. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  8446. currentValue.copy( newValue );
  8447. } else if ( key === 'overdraw' ) {
  8448. // ensure overdraw is backwards-compatable with legacy boolean type
  8449. this[ key ] = Number( newValue );
  8450. } else {
  8451. this[ key ] = newValue;
  8452. }
  8453. }
  8454. }
  8455. },
  8456. toJSON: function ( meta ) {
  8457. var data = {
  8458. metadata: {
  8459. version: 4.4,
  8460. type: 'Material',
  8461. generator: 'Material.toJSON'
  8462. }
  8463. };
  8464. // standard Material serialization
  8465. data.uuid = this.uuid;
  8466. data.type = this.type;
  8467. if ( this.name !== '' ) data.name = this.name;
  8468. if ( this.color instanceof THREE.Color ) data.color = this.color.getHex();
  8469. if ( this.emissive instanceof THREE.Color ) data.emissive = this.emissive.getHex();
  8470. if ( this.specular instanceof THREE.Color ) data.specular = this.specular.getHex();
  8471. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  8472. if ( this.map instanceof THREE.Texture ) data.map = this.map.toJSON( meta ).uuid;
  8473. if ( this.alphaMap instanceof THREE.Texture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  8474. if ( this.lightMap instanceof THREE.Texture ) data.lightMap = this.lightMap.toJSON( meta ).uuid;
  8475. if ( this.bumpMap instanceof THREE.Texture ) {
  8476. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  8477. data.bumpScale = this.bumpScale;
  8478. }
  8479. if ( this.normalMap instanceof THREE.Texture ) {
  8480. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  8481. data.normalScale = this.normalScale; // Removed for now, causes issue in editor ui.js
  8482. }
  8483. if ( this.specularMap instanceof THREE.Texture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  8484. if ( this.envMap instanceof THREE.Texture ) {
  8485. data.envMap = this.envMap.toJSON( meta ).uuid;
  8486. data.reflectivity = this.reflectivity; // Scale behind envMap
  8487. }
  8488. if ( this.size !== undefined ) data.size = this.size;
  8489. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  8490. if ( this.vertexColors !== undefined && this.vertexColors !== THREE.NoColors ) data.vertexColors = this.vertexColors;
  8491. if ( this.shading !== undefined && this.shading !== THREE.SmoothShading ) data.shading = this.shading;
  8492. if ( this.blending !== undefined && this.blending !== THREE.NormalBlending ) data.blending = this.blending;
  8493. if ( this.side !== undefined && this.side !== THREE.FrontSide ) data.side = this.side;
  8494. if ( this.opacity < 1 ) data.opacity = this.opacity;
  8495. if ( this.transparent === true ) data.transparent = this.transparent;
  8496. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  8497. return data;
  8498. },
  8499. clone: function ( material ) {
  8500. if ( material === undefined ) material = new THREE.Material();
  8501. material.name = this.name;
  8502. material.side = this.side;
  8503. material.opacity = this.opacity;
  8504. material.transparent = this.transparent;
  8505. material.blending = this.blending;
  8506. material.blendSrc = this.blendSrc;
  8507. material.blendDst = this.blendDst;
  8508. material.blendEquation = this.blendEquation;
  8509. material.blendSrcAlpha = this.blendSrcAlpha;
  8510. material.blendDstAlpha = this.blendDstAlpha;
  8511. material.blendEquationAlpha = this.blendEquationAlpha;
  8512. material.depthFunc = this.depthFunc;
  8513. material.depthTest = this.depthTest;
  8514. material.depthWrite = this.depthWrite;
  8515. material.polygonOffset = this.polygonOffset;
  8516. material.polygonOffsetFactor = this.polygonOffsetFactor;
  8517. material.polygonOffsetUnits = this.polygonOffsetUnits;
  8518. material.alphaTest = this.alphaTest;
  8519. material.overdraw = this.overdraw;
  8520. material.visible = this.visible;
  8521. return material;
  8522. },
  8523. update: function () {
  8524. this.dispatchEvent( { type: 'update' } );
  8525. },
  8526. dispose: function () {
  8527. this.dispatchEvent( { type: 'dispose' } );
  8528. }
  8529. };
  8530. THREE.EventDispatcher.prototype.apply( THREE.Material.prototype );
  8531. THREE.MaterialIdCount = 0;
  8532. // File:src/materials/LineBasicMaterial.js
  8533. /**
  8534. * @author mrdoob / http://mrdoob.com/
  8535. * @author alteredq / http://alteredqualia.com/
  8536. *
  8537. * parameters = {
  8538. * color: <hex>,
  8539. * opacity: <float>,
  8540. *
  8541. * blending: THREE.NormalBlending,
  8542. * depthTest: <bool>,
  8543. * depthWrite: <bool>,
  8544. *
  8545. * linewidth: <float>,
  8546. * linecap: "round",
  8547. * linejoin: "round",
  8548. *
  8549. * vertexColors: <bool>
  8550. *
  8551. * fog: <bool>
  8552. * }
  8553. */
  8554. THREE.LineBasicMaterial = function ( parameters ) {
  8555. THREE.Material.call( this );
  8556. this.type = 'LineBasicMaterial';
  8557. this.color = new THREE.Color( 0xffffff );
  8558. this.linewidth = 1;
  8559. this.linecap = 'round';
  8560. this.linejoin = 'round';
  8561. this.vertexColors = THREE.NoColors;
  8562. this.fog = true;
  8563. this.setValues( parameters );
  8564. };
  8565. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  8566. THREE.LineBasicMaterial.prototype.constructor = THREE.LineBasicMaterial;
  8567. THREE.LineBasicMaterial.prototype.clone = function () {
  8568. var material = new THREE.LineBasicMaterial();
  8569. THREE.Material.prototype.clone.call( this, material );
  8570. material.color.copy( this.color );
  8571. material.linewidth = this.linewidth;
  8572. material.linecap = this.linecap;
  8573. material.linejoin = this.linejoin;
  8574. material.vertexColors = this.vertexColors;
  8575. material.fog = this.fog;
  8576. return material;
  8577. };
  8578. // File:src/materials/LineDashedMaterial.js
  8579. /**
  8580. * @author alteredq / http://alteredqualia.com/
  8581. *
  8582. * parameters = {
  8583. * color: <hex>,
  8584. * opacity: <float>,
  8585. *
  8586. * blending: THREE.NormalBlending,
  8587. * depthTest: <bool>,
  8588. * depthWrite: <bool>,
  8589. *
  8590. * linewidth: <float>,
  8591. *
  8592. * scale: <float>,
  8593. * dashSize: <float>,
  8594. * gapSize: <float>,
  8595. *
  8596. * vertexColors: <bool>
  8597. *
  8598. * fog: <bool>
  8599. * }
  8600. */
  8601. THREE.LineDashedMaterial = function ( parameters ) {
  8602. THREE.Material.call( this );
  8603. this.type = 'LineDashedMaterial';
  8604. this.color = new THREE.Color( 0xffffff );
  8605. this.linewidth = 1;
  8606. this.scale = 1;
  8607. this.dashSize = 3;
  8608. this.gapSize = 1;
  8609. this.vertexColors = false;
  8610. this.fog = true;
  8611. this.setValues( parameters );
  8612. };
  8613. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  8614. THREE.LineDashedMaterial.prototype.constructor = THREE.LineDashedMaterial;
  8615. THREE.LineDashedMaterial.prototype.clone = function () {
  8616. var material = new THREE.LineDashedMaterial();
  8617. THREE.Material.prototype.clone.call( this, material );
  8618. material.color.copy( this.color );
  8619. material.linewidth = this.linewidth;
  8620. material.scale = this.scale;
  8621. material.dashSize = this.dashSize;
  8622. material.gapSize = this.gapSize;
  8623. material.vertexColors = this.vertexColors;
  8624. material.fog = this.fog;
  8625. return material;
  8626. };
  8627. // File:src/materials/MeshBasicMaterial.js
  8628. /**
  8629. * @author mrdoob / http://mrdoob.com/
  8630. * @author alteredq / http://alteredqualia.com/
  8631. *
  8632. * parameters = {
  8633. * color: <hex>,
  8634. * opacity: <float>,
  8635. * map: new THREE.Texture( <Image> ),
  8636. *
  8637. * aoMap: new THREE.Texture( <Image> ),
  8638. * aoMapIntensity: <float>
  8639. *
  8640. * specularMap: new THREE.Texture( <Image> ),
  8641. *
  8642. * alphaMap: new THREE.Texture( <Image> ),
  8643. *
  8644. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8645. * combine: THREE.Multiply,
  8646. * reflectivity: <float>,
  8647. * refractionRatio: <float>,
  8648. *
  8649. * shading: THREE.SmoothShading,
  8650. * blending: THREE.NormalBlending,
  8651. * depthTest: <bool>,
  8652. * depthWrite: <bool>,
  8653. *
  8654. * wireframe: <boolean>,
  8655. * wireframeLinewidth: <float>,
  8656. *
  8657. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8658. *
  8659. * skinning: <bool>,
  8660. * morphTargets: <bool>,
  8661. *
  8662. * fog: <bool>
  8663. * }
  8664. */
  8665. THREE.MeshBasicMaterial = function ( parameters ) {
  8666. THREE.Material.call( this );
  8667. this.type = 'MeshBasicMaterial';
  8668. this.color = new THREE.Color( 0xffffff ); // emissive
  8669. this.map = null;
  8670. this.aoMap = null;
  8671. this.aoMapIntensity = 1.0;
  8672. this.specularMap = null;
  8673. this.alphaMap = null;
  8674. this.envMap = null;
  8675. this.combine = THREE.MultiplyOperation;
  8676. this.reflectivity = 1;
  8677. this.refractionRatio = 0.98;
  8678. this.fog = true;
  8679. this.shading = THREE.SmoothShading;
  8680. this.wireframe = false;
  8681. this.wireframeLinewidth = 1;
  8682. this.wireframeLinecap = 'round';
  8683. this.wireframeLinejoin = 'round';
  8684. this.vertexColors = THREE.NoColors;
  8685. this.skinning = false;
  8686. this.morphTargets = false;
  8687. this.setValues( parameters );
  8688. };
  8689. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  8690. THREE.MeshBasicMaterial.prototype.constructor = THREE.MeshBasicMaterial;
  8691. THREE.MeshBasicMaterial.prototype.clone = function () {
  8692. var material = new THREE.MeshBasicMaterial();
  8693. THREE.Material.prototype.clone.call( this, material );
  8694. material.color.copy( this.color );
  8695. material.map = this.map;
  8696. material.aoMap = this.aoMap;
  8697. material.aoMapIntensity = this.aoMapIntensity;
  8698. material.specularMap = this.specularMap;
  8699. material.alphaMap = this.alphaMap;
  8700. material.envMap = this.envMap;
  8701. material.combine = this.combine;
  8702. material.reflectivity = this.reflectivity;
  8703. material.refractionRatio = this.refractionRatio;
  8704. material.fog = this.fog;
  8705. material.shading = this.shading;
  8706. material.wireframe = this.wireframe;
  8707. material.wireframeLinewidth = this.wireframeLinewidth;
  8708. material.wireframeLinecap = this.wireframeLinecap;
  8709. material.wireframeLinejoin = this.wireframeLinejoin;
  8710. material.vertexColors = this.vertexColors;
  8711. material.skinning = this.skinning;
  8712. material.morphTargets = this.morphTargets;
  8713. return material;
  8714. };
  8715. // File:src/materials/MeshLambertMaterial.js
  8716. /**
  8717. * @author mrdoob / http://mrdoob.com/
  8718. * @author alteredq / http://alteredqualia.com/
  8719. *
  8720. * parameters = {
  8721. * color: <hex>,
  8722. * emissive: <hex>,
  8723. * opacity: <float>,
  8724. *
  8725. * map: new THREE.Texture( <Image> ),
  8726. *
  8727. * specularMap: new THREE.Texture( <Image> ),
  8728. *
  8729. * alphaMap: new THREE.Texture( <Image> ),
  8730. *
  8731. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8732. * combine: THREE.Multiply,
  8733. * reflectivity: <float>,
  8734. * refractionRatio: <float>,
  8735. *
  8736. * shading: THREE.SmoothShading,
  8737. * blending: THREE.NormalBlending,
  8738. * depthTest: <bool>,
  8739. * depthWrite: <bool>,
  8740. *
  8741. * wireframe: <boolean>,
  8742. * wireframeLinewidth: <float>,
  8743. *
  8744. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8745. *
  8746. * skinning: <bool>,
  8747. * morphTargets: <bool>,
  8748. * morphNormals: <bool>,
  8749. *
  8750. * fog: <bool>
  8751. * }
  8752. */
  8753. THREE.MeshLambertMaterial = function ( parameters ) {
  8754. THREE.Material.call( this );
  8755. this.type = 'MeshLambertMaterial';
  8756. this.color = new THREE.Color( 0xffffff ); // diffuse
  8757. this.emissive = new THREE.Color( 0x000000 );
  8758. this.map = null;
  8759. this.specularMap = null;
  8760. this.alphaMap = null;
  8761. this.envMap = null;
  8762. this.combine = THREE.MultiplyOperation;
  8763. this.reflectivity = 1;
  8764. this.refractionRatio = 0.98;
  8765. this.fog = true;
  8766. this.shading = THREE.SmoothShading;
  8767. this.wireframe = false;
  8768. this.wireframeLinewidth = 1;
  8769. this.wireframeLinecap = 'round';
  8770. this.wireframeLinejoin = 'round';
  8771. this.vertexColors = THREE.NoColors;
  8772. this.skinning = false;
  8773. this.morphTargets = false;
  8774. this.morphNormals = false;
  8775. this.setValues( parameters );
  8776. };
  8777. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  8778. THREE.MeshLambertMaterial.prototype.constructor = THREE.MeshLambertMaterial;
  8779. THREE.MeshLambertMaterial.prototype.clone = function () {
  8780. var material = new THREE.MeshLambertMaterial();
  8781. THREE.Material.prototype.clone.call( this, material );
  8782. material.color.copy( this.color );
  8783. material.emissive.copy( this.emissive );
  8784. material.map = this.map;
  8785. material.specularMap = this.specularMap;
  8786. material.alphaMap = this.alphaMap;
  8787. material.envMap = this.envMap;
  8788. material.combine = this.combine;
  8789. material.reflectivity = this.reflectivity;
  8790. material.refractionRatio = this.refractionRatio;
  8791. material.fog = this.fog;
  8792. material.shading = this.shading;
  8793. material.wireframe = this.wireframe;
  8794. material.wireframeLinewidth = this.wireframeLinewidth;
  8795. material.wireframeLinecap = this.wireframeLinecap;
  8796. material.wireframeLinejoin = this.wireframeLinejoin;
  8797. material.vertexColors = this.vertexColors;
  8798. material.skinning = this.skinning;
  8799. material.morphTargets = this.morphTargets;
  8800. material.morphNormals = this.morphNormals;
  8801. return material;
  8802. };
  8803. // File:src/materials/MeshPhongMaterial.js
  8804. /**
  8805. * @author mrdoob / http://mrdoob.com/
  8806. * @author alteredq / http://alteredqualia.com/
  8807. *
  8808. * parameters = {
  8809. * color: <hex>,
  8810. * emissive: <hex>,
  8811. * specular: <hex>,
  8812. * shininess: <float>,
  8813. * opacity: <float>,
  8814. *
  8815. * map: new THREE.Texture( <Image> ),
  8816. *
  8817. * lightMap: new THREE.Texture( <Image> ),
  8818. * lightMapIntensity: <float>
  8819. *
  8820. * aoMap: new THREE.Texture( <Image> ),
  8821. * aoMapIntensity: <float>
  8822. *
  8823. * bumpMap: new THREE.Texture( <Image> ),
  8824. * bumpScale: <float>,
  8825. *
  8826. * normalMap: new THREE.Texture( <Image> ),
  8827. * normalScale: <Vector2>,
  8828. *
  8829. * specularMap: new THREE.Texture( <Image> ),
  8830. *
  8831. * alphaMap: new THREE.Texture( <Image> ),
  8832. *
  8833. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8834. * combine: THREE.Multiply,
  8835. * reflectivity: <float>,
  8836. * refractionRatio: <float>,
  8837. *
  8838. * shading: THREE.SmoothShading,
  8839. * blending: THREE.NormalBlending,
  8840. * depthTest: <bool>,
  8841. * depthWrite: <bool>,
  8842. *
  8843. * wireframe: <boolean>,
  8844. * wireframeLinewidth: <float>,
  8845. *
  8846. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8847. *
  8848. * skinning: <bool>,
  8849. * morphTargets: <bool>,
  8850. * morphNormals: <bool>,
  8851. *
  8852. * fog: <bool>
  8853. * }
  8854. */
  8855. THREE.MeshPhongMaterial = function ( parameters ) {
  8856. THREE.Material.call( this );
  8857. this.type = 'MeshPhongMaterial';
  8858. this.color = new THREE.Color( 0xffffff ); // diffuse
  8859. this.emissive = new THREE.Color( 0x000000 );
  8860. this.specular = new THREE.Color( 0x111111 );
  8861. this.shininess = 30;
  8862. this.metal = false;
  8863. this.map = null;
  8864. this.lightMap = null;
  8865. this.lightMapIntensity = 1.0;
  8866. this.aoMap = null;
  8867. this.aoMapIntensity = 1.0;
  8868. this.bumpMap = null;
  8869. this.bumpScale = 1;
  8870. this.normalMap = null;
  8871. this.normalScale = new THREE.Vector2( 1, 1 );
  8872. this.specularMap = null;
  8873. this.alphaMap = null;
  8874. this.envMap = null;
  8875. this.combine = THREE.MultiplyOperation;
  8876. this.reflectivity = 1;
  8877. this.refractionRatio = 0.98;
  8878. this.fog = true;
  8879. this.shading = THREE.SmoothShading;
  8880. this.wireframe = false;
  8881. this.wireframeLinewidth = 1;
  8882. this.wireframeLinecap = 'round';
  8883. this.wireframeLinejoin = 'round';
  8884. this.vertexColors = THREE.NoColors;
  8885. this.skinning = false;
  8886. this.morphTargets = false;
  8887. this.morphNormals = false;
  8888. this.setValues( parameters );
  8889. };
  8890. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  8891. THREE.MeshPhongMaterial.prototype.constructor = THREE.MeshPhongMaterial;
  8892. THREE.MeshPhongMaterial.prototype.clone = function () {
  8893. var material = new THREE.MeshPhongMaterial();
  8894. THREE.Material.prototype.clone.call( this, material );
  8895. material.color.copy( this.color );
  8896. material.emissive.copy( this.emissive );
  8897. material.specular.copy( this.specular );
  8898. material.shininess = this.shininess;
  8899. material.metal = this.metal;
  8900. material.map = this.map;
  8901. material.lightMap = this.lightMap;
  8902. material.lightMapIntensity = this.lightMapIntensity;
  8903. material.aoMap = this.aoMap;
  8904. material.aoMapIntensity = this.aoMapIntensity;
  8905. material.bumpMap = this.bumpMap;
  8906. material.bumpScale = this.bumpScale;
  8907. material.normalMap = this.normalMap;
  8908. material.normalScale.copy( this.normalScale );
  8909. material.specularMap = this.specularMap;
  8910. material.alphaMap = this.alphaMap;
  8911. material.envMap = this.envMap;
  8912. material.combine = this.combine;
  8913. material.reflectivity = this.reflectivity;
  8914. material.refractionRatio = this.refractionRatio;
  8915. material.fog = this.fog;
  8916. material.shading = this.shading;
  8917. material.wireframe = this.wireframe;
  8918. material.wireframeLinewidth = this.wireframeLinewidth;
  8919. material.wireframeLinecap = this.wireframeLinecap;
  8920. material.wireframeLinejoin = this.wireframeLinejoin;
  8921. material.vertexColors = this.vertexColors;
  8922. material.skinning = this.skinning;
  8923. material.morphTargets = this.morphTargets;
  8924. material.morphNormals = this.morphNormals;
  8925. return material;
  8926. };
  8927. // File:src/materials/MeshDepthMaterial.js
  8928. /**
  8929. * @author mrdoob / http://mrdoob.com/
  8930. * @author alteredq / http://alteredqualia.com/
  8931. *
  8932. * parameters = {
  8933. * opacity: <float>,
  8934. *
  8935. * blending: THREE.NormalBlending,
  8936. * depthTest: <bool>,
  8937. * depthWrite: <bool>,
  8938. *
  8939. * wireframe: <boolean>,
  8940. * wireframeLinewidth: <float>
  8941. * }
  8942. */
  8943. THREE.MeshDepthMaterial = function ( parameters ) {
  8944. THREE.Material.call( this );
  8945. this.type = 'MeshDepthMaterial';
  8946. this.morphTargets = false;
  8947. this.wireframe = false;
  8948. this.wireframeLinewidth = 1;
  8949. this.setValues( parameters );
  8950. };
  8951. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  8952. THREE.MeshDepthMaterial.prototype.constructor = THREE.MeshDepthMaterial;
  8953. THREE.MeshDepthMaterial.prototype.clone = function () {
  8954. var material = new THREE.MeshDepthMaterial();
  8955. THREE.Material.prototype.clone.call( this, material );
  8956. material.wireframe = this.wireframe;
  8957. material.wireframeLinewidth = this.wireframeLinewidth;
  8958. return material;
  8959. };
  8960. // File:src/materials/MeshNormalMaterial.js
  8961. /**
  8962. * @author mrdoob / http://mrdoob.com/
  8963. *
  8964. * parameters = {
  8965. * opacity: <float>,
  8966. *
  8967. * shading: THREE.FlatShading,
  8968. * blending: THREE.NormalBlending,
  8969. * depthTest: <bool>,
  8970. * depthWrite: <bool>,
  8971. *
  8972. * wireframe: <boolean>,
  8973. * wireframeLinewidth: <float>
  8974. * }
  8975. */
  8976. THREE.MeshNormalMaterial = function ( parameters ) {
  8977. THREE.Material.call( this, parameters );
  8978. this.type = 'MeshNormalMaterial';
  8979. this.wireframe = false;
  8980. this.wireframeLinewidth = 1;
  8981. this.morphTargets = false;
  8982. this.setValues( parameters );
  8983. };
  8984. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  8985. THREE.MeshNormalMaterial.prototype.constructor = THREE.MeshNormalMaterial;
  8986. THREE.MeshNormalMaterial.prototype.clone = function () {
  8987. var material = new THREE.MeshNormalMaterial();
  8988. THREE.Material.prototype.clone.call( this, material );
  8989. material.wireframe = this.wireframe;
  8990. material.wireframeLinewidth = this.wireframeLinewidth;
  8991. return material;
  8992. };
  8993. // File:src/materials/MeshFaceMaterial.js
  8994. /**
  8995. * @author mrdoob / http://mrdoob.com/
  8996. */
  8997. THREE.MeshFaceMaterial = function ( materials ) {
  8998. console.error( 'THREE.MeshFaceMaterial has been removed.' );
  8999. var material = Array.isArray( materials ) ? materials[ 0 ] : new THREE.MeshBasicMaterial();
  9000. material.materials = []; // temporal workaround
  9001. return material;
  9002. };
  9003. // File:src/materials/PointCloudMaterial.js
  9004. /**
  9005. * @author mrdoob / http://mrdoob.com/
  9006. * @author alteredq / http://alteredqualia.com/
  9007. *
  9008. * parameters = {
  9009. * color: <hex>,
  9010. * opacity: <float>,
  9011. * map: new THREE.Texture( <Image> ),
  9012. *
  9013. * size: <float>,
  9014. * sizeAttenuation: <bool>,
  9015. *
  9016. * blending: THREE.NormalBlending,
  9017. * depthTest: <bool>,
  9018. * depthWrite: <bool>,
  9019. *
  9020. * vertexColors: <bool>,
  9021. *
  9022. * fog: <bool>
  9023. * }
  9024. */
  9025. THREE.PointCloudMaterial = function ( parameters ) {
  9026. THREE.Material.call( this );
  9027. this.type = 'PointCloudMaterial';
  9028. this.color = new THREE.Color( 0xffffff );
  9029. this.map = null;
  9030. this.size = 1;
  9031. this.sizeAttenuation = true;
  9032. this.vertexColors = THREE.NoColors;
  9033. this.fog = true;
  9034. this.setValues( parameters );
  9035. };
  9036. THREE.PointCloudMaterial.prototype = Object.create( THREE.Material.prototype );
  9037. THREE.PointCloudMaterial.prototype.constructor = THREE.PointCloudMaterial;
  9038. THREE.PointCloudMaterial.prototype.clone = function () {
  9039. var material = new THREE.PointCloudMaterial();
  9040. THREE.Material.prototype.clone.call( this, material );
  9041. material.color.copy( this.color );
  9042. material.map = this.map;
  9043. material.size = this.size;
  9044. material.sizeAttenuation = this.sizeAttenuation;
  9045. material.vertexColors = this.vertexColors;
  9046. material.fog = this.fog;
  9047. return material;
  9048. };
  9049. // backwards compatibility
  9050. THREE.ParticleBasicMaterial = function ( parameters ) {
  9051. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointCloudMaterial.' );
  9052. return new THREE.PointCloudMaterial( parameters );
  9053. };
  9054. THREE.ParticleSystemMaterial = function ( parameters ) {
  9055. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointCloudMaterial.' );
  9056. return new THREE.PointCloudMaterial( parameters );
  9057. };
  9058. // File:src/materials/ShaderMaterial.js
  9059. /**
  9060. * @author alteredq / http://alteredqualia.com/
  9061. *
  9062. * parameters = {
  9063. * defines: { "label" : "value" },
  9064. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  9065. *
  9066. * fragmentShader: <string>,
  9067. * vertexShader: <string>,
  9068. *
  9069. * shading: THREE.SmoothShading,
  9070. * blending: THREE.NormalBlending,
  9071. * depthTest: <bool>,
  9072. * depthWrite: <bool>,
  9073. *
  9074. * wireframe: <boolean>,
  9075. * wireframeLinewidth: <float>,
  9076. *
  9077. * lights: <bool>,
  9078. *
  9079. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  9080. *
  9081. * skinning: <bool>,
  9082. * morphTargets: <bool>,
  9083. * morphNormals: <bool>,
  9084. *
  9085. * fog: <bool>
  9086. * }
  9087. */
  9088. THREE.ShaderMaterial = function ( parameters ) {
  9089. THREE.Material.call( this );
  9090. this.type = 'ShaderMaterial';
  9091. this.defines = {};
  9092. this.uniforms = {};
  9093. this.attributes = [];
  9094. this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}';
  9095. this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}';
  9096. this.shading = THREE.SmoothShading;
  9097. this.linewidth = 1;
  9098. this.wireframe = false;
  9099. this.wireframeLinewidth = 1;
  9100. this.fog = false; // set to use scene fog
  9101. this.lights = false; // set to use scene lights
  9102. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  9103. this.skinning = false; // set to use skinning attribute streams
  9104. this.morphTargets = false; // set to use morph targets
  9105. this.morphNormals = false; // set to use morph normals
  9106. this.derivatives = false; // set to use derivatives
  9107. // When rendered geometry doesn't include these attributes but the material does,
  9108. // use these default values in WebGL. This avoids errors when buffer data is missing.
  9109. this.defaultAttributeValues = {
  9110. 'color': [ 1, 1, 1 ],
  9111. 'uv': [ 0, 0 ],
  9112. 'uv2': [ 0, 0 ]
  9113. };
  9114. this.index0AttributeName = undefined;
  9115. if ( parameters !== undefined ) {
  9116. if ( parameters.attributes !== undefined && Array.isArray( parameters.attributes ) === false ) {
  9117. console.warn( 'THREE.ShaderMaterial: attributes should now be an array of attribute names.' );
  9118. parameters.attributes = Object.keys( parameters.attributes );
  9119. }
  9120. this.setValues( parameters );
  9121. }
  9122. };
  9123. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  9124. THREE.ShaderMaterial.prototype.constructor = THREE.ShaderMaterial;
  9125. THREE.ShaderMaterial.prototype.clone = function ( material ) {
  9126. if ( material === undefined ) material = new THREE.ShaderMaterial();
  9127. THREE.Material.prototype.clone.call( this, material );
  9128. material.fragmentShader = this.fragmentShader;
  9129. material.vertexShader = this.vertexShader;
  9130. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  9131. material.attributes = this.attributes;
  9132. material.defines = this.defines;
  9133. material.shading = this.shading;
  9134. material.wireframe = this.wireframe;
  9135. material.wireframeLinewidth = this.wireframeLinewidth;
  9136. material.fog = this.fog;
  9137. material.lights = this.lights;
  9138. material.vertexColors = this.vertexColors;
  9139. material.skinning = this.skinning;
  9140. material.morphTargets = this.morphTargets;
  9141. material.morphNormals = this.morphNormals;
  9142. return material;
  9143. };
  9144. THREE.ShaderMaterial.prototype.toJSON = function ( meta ) {
  9145. var data = THREE.Material.prototype.toJSON.call( this, meta );
  9146. data.uniforms = this.uniforms;
  9147. data.attributes = this.attributes;
  9148. data.vertexShader = this.vertexShader;
  9149. data.fragmentShader = this.fragmentShader;
  9150. return data;
  9151. };
  9152. // File:src/materials/RawShaderMaterial.js
  9153. /**
  9154. * @author mrdoob / http://mrdoob.com/
  9155. */
  9156. THREE.RawShaderMaterial = function ( parameters ) {
  9157. THREE.ShaderMaterial.call( this, parameters );
  9158. this.type = 'RawShaderMaterial';
  9159. };
  9160. THREE.RawShaderMaterial.prototype = Object.create( THREE.ShaderMaterial.prototype );
  9161. THREE.RawShaderMaterial.prototype.constructor = THREE.RawShaderMaterial;
  9162. THREE.RawShaderMaterial.prototype.clone = function () {
  9163. var material = new THREE.RawShaderMaterial();
  9164. THREE.ShaderMaterial.prototype.clone.call( this, material );
  9165. return material;
  9166. };
  9167. // File:src/materials/SpriteMaterial.js
  9168. /**
  9169. * @author alteredq / http://alteredqualia.com/
  9170. *
  9171. * parameters = {
  9172. * color: <hex>,
  9173. * opacity: <float>,
  9174. * map: new THREE.Texture( <Image> ),
  9175. *
  9176. * blending: THREE.NormalBlending,
  9177. * depthTest: <bool>,
  9178. * depthWrite: <bool>,
  9179. *
  9180. * uvOffset: new THREE.Vector2(),
  9181. * uvScale: new THREE.Vector2(),
  9182. *
  9183. * fog: <bool>
  9184. * }
  9185. */
  9186. THREE.SpriteMaterial = function ( parameters ) {
  9187. THREE.Material.call( this );
  9188. this.type = 'SpriteMaterial';
  9189. this.color = new THREE.Color( 0xffffff );
  9190. this.map = null;
  9191. this.rotation = 0;
  9192. this.fog = false;
  9193. // set parameters
  9194. this.setValues( parameters );
  9195. };
  9196. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  9197. THREE.SpriteMaterial.prototype.constructor = THREE.SpriteMaterial;
  9198. THREE.SpriteMaterial.prototype.clone = function () {
  9199. var material = new THREE.SpriteMaterial();
  9200. THREE.Material.prototype.clone.call( this, material );
  9201. material.color.copy( this.color );
  9202. material.map = this.map;
  9203. material.rotation = this.rotation;
  9204. material.fog = this.fog;
  9205. return material;
  9206. };
  9207. // File:src/textures/Texture.js
  9208. /**
  9209. * @author mrdoob / http://mrdoob.com/
  9210. * @author alteredq / http://alteredqualia.com/
  9211. * @author szimek / https://github.com/szimek/
  9212. */
  9213. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  9214. Object.defineProperty( this, 'id', { value: THREE.TextureIdCount ++ } );
  9215. this.uuid = THREE.Math.generateUUID();
  9216. this.name = '';
  9217. this.sourceFile = '';
  9218. this.image = image !== undefined ? image : THREE.Texture.DEFAULT_IMAGE;
  9219. this.mipmaps = [];
  9220. this.mapping = mapping !== undefined ? mapping : THREE.Texture.DEFAULT_MAPPING;
  9221. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  9222. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  9223. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  9224. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  9225. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  9226. this.format = format !== undefined ? format : THREE.RGBAFormat;
  9227. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  9228. this.offset = new THREE.Vector2( 0, 0 );
  9229. this.repeat = new THREE.Vector2( 1, 1 );
  9230. this.generateMipmaps = true;
  9231. this.premultiplyAlpha = false;
  9232. this.flipY = true;
  9233. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  9234. this._needsUpdate = false;
  9235. this.onUpdate = null;
  9236. };
  9237. THREE.Texture.DEFAULT_IMAGE = undefined;
  9238. THREE.Texture.DEFAULT_MAPPING = THREE.UVMapping;
  9239. THREE.Texture.prototype = {
  9240. constructor: THREE.Texture,
  9241. get needsUpdate () {
  9242. return this._needsUpdate;
  9243. },
  9244. set needsUpdate ( value ) {
  9245. if ( value === true ) this.update();
  9246. this._needsUpdate = value;
  9247. },
  9248. clone: function ( texture ) {
  9249. if ( texture === undefined ) texture = new THREE.Texture();
  9250. texture.image = this.image;
  9251. texture.mipmaps = this.mipmaps.slice( 0 );
  9252. texture.mapping = this.mapping;
  9253. texture.wrapS = this.wrapS;
  9254. texture.wrapT = this.wrapT;
  9255. texture.magFilter = this.magFilter;
  9256. texture.minFilter = this.minFilter;
  9257. texture.anisotropy = this.anisotropy;
  9258. texture.format = this.format;
  9259. texture.type = this.type;
  9260. texture.offset.copy( this.offset );
  9261. texture.repeat.copy( this.repeat );
  9262. texture.generateMipmaps = this.generateMipmaps;
  9263. texture.premultiplyAlpha = this.premultiplyAlpha;
  9264. texture.flipY = this.flipY;
  9265. texture.unpackAlignment = this.unpackAlignment;
  9266. return texture;
  9267. },
  9268. toJSON: function ( meta ) {
  9269. if ( meta.textures[ this.uuid ] !== undefined ) {
  9270. return meta.textures[ this.uuid ];
  9271. }
  9272. var output = {
  9273. metadata: {
  9274. version: 4.4,
  9275. type: 'Texture',
  9276. generator: 'Texture.toJSON'
  9277. },
  9278. uuid: this.uuid,
  9279. name: this.name,
  9280. mapping: this.mapping,
  9281. repeat: [ this.repeat.x, this.repeat.y ],
  9282. offset: [ this.offset.x, this.offset.y ],
  9283. wrap: [ this.wrapS, this.wrapT ],
  9284. minFilter: this.minFilter,
  9285. magFilter: this.magFilter,
  9286. anisotropy: this.anisotropy
  9287. };
  9288. if ( this.image !== undefined ) {
  9289. // TODO: Move to THREE.Image
  9290. var image = this.image;
  9291. if ( image.uuid === undefined ) {
  9292. image.uuid = THREE.Math.generateUUID(); // UGH
  9293. }
  9294. if ( meta.images[ this.image.uuid ] === undefined ) {
  9295. var canvas = document.createElement( 'canvas' );
  9296. canvas.width = image.width;
  9297. canvas.height = image.height;
  9298. var context = canvas.getContext( '2d' );
  9299. context.drawImage( image, 0, 0, image.width, image.height );
  9300. var src;
  9301. if ( image.width > 2048 || image.height > 2048 ) {
  9302. src = canvas.toDataURL( 'image/jpeg', 0.6 );
  9303. } else {
  9304. src = canvas.toDataURL( 'image/png' );
  9305. }
  9306. meta.images[ this.image.uuid ] = { uuid: this.image.uuid, url: src };
  9307. }
  9308. output.image = image.uuid;
  9309. }
  9310. meta.textures[ this.uuid ] = output;
  9311. return output;
  9312. },
  9313. update: function () {
  9314. this.dispatchEvent( { type: 'update' } );
  9315. },
  9316. dispose: function () {
  9317. this.dispatchEvent( { type: 'dispose' } );
  9318. }
  9319. };
  9320. THREE.EventDispatcher.prototype.apply( THREE.Texture.prototype );
  9321. THREE.TextureIdCount = 0;
  9322. // File:src/textures/CubeTexture.js
  9323. /**
  9324. * @author mrdoob / http://mrdoob.com/
  9325. */
  9326. THREE.CubeTexture = function ( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  9327. mapping = mapping !== undefined ? mapping : THREE.CubeReflectionMapping;
  9328. THREE.Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  9329. this.images = images;
  9330. };
  9331. THREE.CubeTexture.prototype = Object.create( THREE.Texture.prototype );
  9332. THREE.CubeTexture.prototype.constructor = THREE.CubeTexture;
  9333. THREE.CubeTexture.clone = function ( texture ) {
  9334. if ( texture === undefined ) texture = new THREE.CubeTexture();
  9335. THREE.Texture.prototype.clone.call( this, texture );
  9336. texture.images = this.images;
  9337. return texture;
  9338. };
  9339. // File:src/textures/CompressedTexture.js
  9340. /**
  9341. * @author alteredq / http://alteredqualia.com/
  9342. */
  9343. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  9344. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  9345. this.image = { width: width, height: height };
  9346. this.mipmaps = mipmaps;
  9347. // no flipping for cube textures
  9348. // (also flipping doesn't work for compressed textures )
  9349. this.flipY = false;
  9350. // can't generate mipmaps for compressed textures
  9351. // mips must be embedded in DDS files
  9352. this.generateMipmaps = false;
  9353. };
  9354. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  9355. THREE.CompressedTexture.prototype.constructor = THREE.CompressedTexture;
  9356. THREE.CompressedTexture.prototype.clone = function () {
  9357. var texture = new THREE.CompressedTexture();
  9358. THREE.Texture.prototype.clone.call( this, texture );
  9359. return texture;
  9360. };
  9361. // File:src/textures/DataTexture.js
  9362. /**
  9363. * @author alteredq / http://alteredqualia.com/
  9364. */
  9365. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  9366. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  9367. this.image = { data: data, width: width, height: height };
  9368. };
  9369. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  9370. THREE.DataTexture.prototype.constructor = THREE.DataTexture;
  9371. THREE.DataTexture.prototype.clone = function () {
  9372. var texture = new THREE.DataTexture();
  9373. THREE.Texture.prototype.clone.call( this, texture );
  9374. return texture;
  9375. };
  9376. // File:src/textures/VideoTexture.js
  9377. /**
  9378. * @author mrdoob / http://mrdoob.com/
  9379. */
  9380. THREE.VideoTexture = function ( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  9381. THREE.Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  9382. this.generateMipmaps = false;
  9383. var scope = this;
  9384. var update = function () {
  9385. requestAnimationFrame( update );
  9386. if ( video.readyState === video.HAVE_ENOUGH_DATA ) {
  9387. scope.needsUpdate = true;
  9388. }
  9389. };
  9390. update();
  9391. };
  9392. THREE.VideoTexture.prototype = Object.create( THREE.Texture.prototype );
  9393. THREE.VideoTexture.prototype.constructor = THREE.VideoTexture;
  9394. // File:src/objects/Group.js
  9395. /**
  9396. * @author mrdoob / http://mrdoob.com/
  9397. */
  9398. THREE.Group = function () {
  9399. THREE.Object3D.call( this );
  9400. this.type = 'Group';
  9401. };
  9402. THREE.Group.prototype = Object.create( THREE.Object3D.prototype );
  9403. THREE.Group.prototype.constructor = THREE.Group;
  9404. // File:src/objects/PointCloud.js
  9405. /**
  9406. * @author alteredq / http://alteredqualia.com/
  9407. */
  9408. THREE.PointCloud = function ( geometry, material ) {
  9409. THREE.Object3D.call( this );
  9410. this.type = 'PointCloud';
  9411. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  9412. this.material = material !== undefined ? material : new THREE.PointCloudMaterial( { color: Math.random() * 0xffffff } );
  9413. };
  9414. THREE.PointCloud.prototype = Object.create( THREE.Object3D.prototype );
  9415. THREE.PointCloud.prototype.constructor = THREE.PointCloud;
  9416. THREE.PointCloud.prototype.raycast = ( function () {
  9417. var inverseMatrix = new THREE.Matrix4();
  9418. var ray = new THREE.Ray();
  9419. return function ( raycaster, intersects ) {
  9420. var object = this;
  9421. var geometry = object.geometry;
  9422. var threshold = raycaster.params.PointCloud.threshold;
  9423. inverseMatrix.getInverse( this.matrixWorld );
  9424. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  9425. if ( geometry.boundingBox !== null ) {
  9426. if ( ray.isIntersectionBox( geometry.boundingBox ) === false ) {
  9427. return;
  9428. }
  9429. }
  9430. var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  9431. var position = new THREE.Vector3();
  9432. var testPoint = function ( point, index ) {
  9433. var rayPointDistance = ray.distanceToPoint( point );
  9434. if ( rayPointDistance < localThreshold ) {
  9435. var intersectPoint = ray.closestPointToPoint( point );
  9436. intersectPoint.applyMatrix4( object.matrixWorld );
  9437. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  9438. intersects.push( {
  9439. distance: distance,
  9440. distanceToRay: rayPointDistance,
  9441. point: intersectPoint.clone(),
  9442. index: index,
  9443. face: null,
  9444. object: object
  9445. } );
  9446. }
  9447. };
  9448. if ( geometry instanceof THREE.BufferGeometry ) {
  9449. var attributes = geometry.attributes;
  9450. var positions = attributes.position.array;
  9451. if ( attributes.index !== undefined ) {
  9452. var indices = attributes.index.array;
  9453. var offsets = geometry.offsets;
  9454. if ( offsets.length === 0 ) {
  9455. var offset = {
  9456. start: 0,
  9457. count: indices.length,
  9458. index: 0
  9459. };
  9460. offsets = [ offset ];
  9461. }
  9462. for ( var oi = 0, ol = offsets.length; oi < ol; ++ oi ) {
  9463. var start = offsets[ oi ].start;
  9464. var count = offsets[ oi ].count;
  9465. var index = offsets[ oi ].index;
  9466. for ( var i = start, il = start + count; i < il; i ++ ) {
  9467. var a = index + indices[ i ];
  9468. position.fromArray( positions, a * 3 );
  9469. testPoint( position, a );
  9470. }
  9471. }
  9472. } else {
  9473. var pointCount = positions.length / 3;
  9474. for ( var i = 0; i < pointCount; i ++ ) {
  9475. position.set(
  9476. positions[ 3 * i ],
  9477. positions[ 3 * i + 1 ],
  9478. positions[ 3 * i + 2 ]
  9479. );
  9480. testPoint( position, i );
  9481. }
  9482. }
  9483. } else {
  9484. var vertices = this.geometry.vertices;
  9485. for ( var i = 0; i < vertices.length; i ++ ) {
  9486. testPoint( vertices[ i ], i );
  9487. }
  9488. }
  9489. };
  9490. }() );
  9491. THREE.PointCloud.prototype.clone = function ( object ) {
  9492. if ( object === undefined ) object = new THREE.PointCloud( this.geometry, this.material );
  9493. THREE.Object3D.prototype.clone.call( this, object );
  9494. return object;
  9495. };
  9496. THREE.PointCloud.prototype.toJSON = function ( meta ) {
  9497. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  9498. // only serialize if not in meta geometries cache
  9499. if ( meta.geometries[ this.geometry.uuid ] === undefined ) {
  9500. meta.geometries[ this.geometry.uuid ] = this.geometry.toJSON();
  9501. }
  9502. // only serialize if not in meta materials cache
  9503. if ( meta.materials[ this.material.uuid ] === undefined ) {
  9504. meta.materials[ this.material.uuid ] = this.material.toJSON();
  9505. }
  9506. data.object.geometry = this.geometry.uuid;
  9507. data.object.material = this.material.uuid;
  9508. return data;
  9509. };
  9510. // Backwards compatibility
  9511. THREE.ParticleSystem = function ( geometry, material ) {
  9512. console.warn( 'THREE.ParticleSystem has been renamed to THREE.PointCloud.' );
  9513. return new THREE.PointCloud( geometry, material );
  9514. };
  9515. // File:src/objects/Line.js
  9516. /**
  9517. * @author mrdoob / http://mrdoob.com/
  9518. */
  9519. THREE.Line = function ( geometry, material, mode ) {
  9520. if ( mode === 1 ) {
  9521. console.error( 'THREE.Line: THREE.LinePieces mode has been removed. Use THREE.LineSegments instead.' );
  9522. }
  9523. THREE.Object3D.call( this );
  9524. this.type = 'Line';
  9525. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  9526. this.material = material !== undefined ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  9527. };
  9528. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  9529. THREE.Line.prototype.constructor = THREE.Line;
  9530. THREE.Line.prototype.raycast = ( function () {
  9531. var inverseMatrix = new THREE.Matrix4();
  9532. var ray = new THREE.Ray();
  9533. var sphere = new THREE.Sphere();
  9534. return function ( raycaster, intersects ) {
  9535. var precision = raycaster.linePrecision;
  9536. var precisionSq = precision * precision;
  9537. var geometry = this.geometry;
  9538. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9539. // Checking boundingSphere distance to ray
  9540. sphere.copy( geometry.boundingSphere );
  9541. sphere.applyMatrix4( this.matrixWorld );
  9542. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  9543. return;
  9544. }
  9545. inverseMatrix.getInverse( this.matrixWorld );
  9546. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  9547. var vStart = new THREE.Vector3();
  9548. var vEnd = new THREE.Vector3();
  9549. var interSegment = new THREE.Vector3();
  9550. var interRay = new THREE.Vector3();
  9551. var step = this instanceof THREE.LineSegments ? 2 : 1;
  9552. if ( geometry instanceof THREE.BufferGeometry ) {
  9553. var attributes = geometry.attributes;
  9554. if ( attributes.index !== undefined ) {
  9555. var indices = attributes.index.array;
  9556. var positions = attributes.position.array;
  9557. var offsets = geometry.offsets;
  9558. if ( offsets.length === 0 ) {
  9559. offsets = [ { start: 0, count: indices.length, index: 0 } ];
  9560. }
  9561. for ( var oi = 0; oi < offsets.length; oi ++) {
  9562. var start = offsets[ oi ].start;
  9563. var count = offsets[ oi ].count;
  9564. var index = offsets[ oi ].index;
  9565. for ( var i = start; i < start + count - 1; i += step ) {
  9566. var a = index + indices[ i ];
  9567. var b = index + indices[ i + 1 ];
  9568. vStart.fromArray( positions, a * 3 );
  9569. vEnd.fromArray( positions, b * 3 );
  9570. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  9571. if ( distSq > precisionSq ) continue;
  9572. var distance = ray.origin.distanceTo( interRay );
  9573. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  9574. intersects.push( {
  9575. distance: distance,
  9576. // What do we want? intersection point on the ray or on the segment??
  9577. // point: raycaster.ray.at( distance ),
  9578. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  9579. index: i,
  9580. offsetIndex: oi,
  9581. face: null,
  9582. faceIndex: null,
  9583. object: this
  9584. } );
  9585. }
  9586. }
  9587. } else {
  9588. var positions = attributes.position.array;
  9589. for ( var i = 0; i < positions.length / 3 - 1; i += step ) {
  9590. vStart.fromArray( positions, 3 * i );
  9591. vEnd.fromArray( positions, 3 * i + 3 );
  9592. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  9593. if ( distSq > precisionSq ) continue;
  9594. var distance = ray.origin.distanceTo( interRay );
  9595. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  9596. intersects.push( {
  9597. distance: distance,
  9598. // What do we want? intersection point on the ray or on the segment??
  9599. // point: raycaster.ray.at( distance ),
  9600. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  9601. index: i,
  9602. face: null,
  9603. faceIndex: null,
  9604. object: this
  9605. } );
  9606. }
  9607. }
  9608. } else if ( geometry instanceof THREE.Geometry ) {
  9609. var vertices = geometry.vertices;
  9610. var nbVertices = vertices.length;
  9611. for ( var i = 0; i < nbVertices - 1; i += step ) {
  9612. var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  9613. if ( distSq > precisionSq ) continue;
  9614. var distance = ray.origin.distanceTo( interRay );
  9615. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  9616. intersects.push( {
  9617. distance: distance,
  9618. // What do we want? intersection point on the ray or on the segment??
  9619. // point: raycaster.ray.at( distance ),
  9620. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  9621. index: i,
  9622. face: null,
  9623. faceIndex: null,
  9624. object: this
  9625. } );
  9626. }
  9627. }
  9628. };
  9629. }() );
  9630. THREE.Line.prototype.clone = function ( object ) {
  9631. if ( object === undefined ) object = new THREE[ this.type ]( this.geometry, this.material );
  9632. THREE.Object3D.prototype.clone.call( this, object );
  9633. return object;
  9634. };
  9635. THREE.Line.prototype.toJSON = function ( meta ) {
  9636. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  9637. // only serialize if not in meta geometries cache
  9638. if ( meta.geometries[ this.geometry.uuid ] === undefined ) {
  9639. meta.geometries[ this.geometry.uuid ] = this.geometry.toJSON();
  9640. }
  9641. // only serialize if not in meta materials cache
  9642. if ( meta.materials[ this.material.uuid ] === undefined ) {
  9643. meta.materials[ this.material.uuid ] = this.material.toJSON();
  9644. }
  9645. data.object.geometry = this.geometry.uuid;
  9646. data.object.material = this.material.uuid;
  9647. return data;
  9648. };
  9649. // DEPRECATED
  9650. THREE.LineStrip = 0;
  9651. THREE.LinePieces = 1;
  9652. // File:src/objects/LineSegments.js
  9653. /**
  9654. * @author mrdoob / http://mrdoob.com/
  9655. */
  9656. THREE.LineSegments = function ( geometry, material ) {
  9657. THREE.Line.call( this, geometry, material );
  9658. this.type = 'LineSegments';
  9659. };
  9660. THREE.LineSegments.prototype = Object.create( THREE.Line.prototype );
  9661. THREE.LineSegments.prototype.constructor = THREE.LineSegments;
  9662. // File:src/objects/Mesh.js
  9663. /**
  9664. * @author mrdoob / http://mrdoob.com/
  9665. * @author alteredq / http://alteredqualia.com/
  9666. * @author mikael emtinger / http://gomo.se/
  9667. * @author jonobr1 / http://jonobr1.com/
  9668. */
  9669. THREE.Mesh = function ( geometry, material ) {
  9670. THREE.Object3D.call( this );
  9671. this.type = 'Mesh';
  9672. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  9673. this.material = material !== undefined ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  9674. this.updateMorphTargets();
  9675. };
  9676. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  9677. THREE.Mesh.prototype.constructor = THREE.Mesh;
  9678. THREE.Mesh.prototype.updateMorphTargets = function () {
  9679. if ( this.geometry.morphTargets !== undefined && this.geometry.morphTargets.length > 0 ) {
  9680. this.morphTargetBase = - 1;
  9681. this.morphTargetForcedOrder = [];
  9682. this.morphTargetInfluences = [];
  9683. this.morphTargetDictionary = {};
  9684. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  9685. this.morphTargetInfluences.push( 0 );
  9686. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  9687. }
  9688. }
  9689. };
  9690. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  9691. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  9692. return this.morphTargetDictionary[ name ];
  9693. }
  9694. console.warn( 'THREE.Mesh.getMorphTargetIndexByName: morph target ' + name + ' does not exist. Returning 0.' );
  9695. return 0;
  9696. };
  9697. THREE.Mesh.prototype.raycast = ( function () {
  9698. var inverseMatrix = new THREE.Matrix4();
  9699. var ray = new THREE.Ray();
  9700. var sphere = new THREE.Sphere();
  9701. var vA = new THREE.Vector3();
  9702. var vB = new THREE.Vector3();
  9703. var vC = new THREE.Vector3();
  9704. return function ( raycaster, intersects ) {
  9705. var geometry = this.geometry;
  9706. // Checking boundingSphere distance to ray
  9707. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9708. sphere.copy( geometry.boundingSphere );
  9709. sphere.applyMatrix4( this.matrixWorld );
  9710. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  9711. return;
  9712. }
  9713. // Check boundingBox before continuing
  9714. inverseMatrix.getInverse( this.matrixWorld );
  9715. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  9716. if ( geometry.boundingBox !== null ) {
  9717. if ( ray.isIntersectionBox( geometry.boundingBox ) === false ) {
  9718. return;
  9719. }
  9720. }
  9721. if ( geometry instanceof THREE.BufferGeometry ) {
  9722. var material = this.material;
  9723. if ( material === undefined ) return;
  9724. var attributes = geometry.attributes;
  9725. var a, b, c;
  9726. var precision = raycaster.precision;
  9727. if ( attributes.index !== undefined ) {
  9728. var indices = attributes.index.array;
  9729. var positions = attributes.position.array;
  9730. var offsets = geometry.offsets;
  9731. if ( offsets.length === 0 ) {
  9732. offsets = [ { start: 0, count: indices.length, index: 0 } ];
  9733. }
  9734. for ( var oi = 0, ol = offsets.length; oi < ol; ++ oi ) {
  9735. var start = offsets[ oi ].start;
  9736. var count = offsets[ oi ].count;
  9737. var index = offsets[ oi ].index;
  9738. for ( var i = start, il = start + count; i < il; i += 3 ) {
  9739. a = index + indices[ i ];
  9740. b = index + indices[ i + 1 ];
  9741. c = index + indices[ i + 2 ];
  9742. vA.fromArray( positions, a * 3 );
  9743. vB.fromArray( positions, b * 3 );
  9744. vC.fromArray( positions, c * 3 );
  9745. if ( material.side === THREE.BackSide ) {
  9746. var intersectionPoint = ray.intersectTriangle( vC, vB, vA, true );
  9747. } else {
  9748. var intersectionPoint = ray.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );
  9749. }
  9750. if ( intersectionPoint === null ) continue;
  9751. intersectionPoint.applyMatrix4( this.matrixWorld );
  9752. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  9753. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  9754. intersects.push( {
  9755. distance: distance,
  9756. point: intersectionPoint,
  9757. face: new THREE.Face3( a, b, c, THREE.Triangle.normal( vA, vB, vC ) ),
  9758. faceIndex: null,
  9759. object: this
  9760. } );
  9761. }
  9762. }
  9763. } else {
  9764. var positions = attributes.position.array;
  9765. for ( var i = 0, j = 0, il = positions.length; i < il; i += 3, j += 9 ) {
  9766. a = i;
  9767. b = i + 1;
  9768. c = i + 2;
  9769. vA.fromArray( positions, j );
  9770. vB.fromArray( positions, j + 3 );
  9771. vC.fromArray( positions, j + 6 );
  9772. if ( material.side === THREE.BackSide ) {
  9773. var intersectionPoint = ray.intersectTriangle( vC, vB, vA, true );
  9774. } else {
  9775. var intersectionPoint = ray.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );
  9776. }
  9777. if ( intersectionPoint === null ) continue;
  9778. intersectionPoint.applyMatrix4( this.matrixWorld );
  9779. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  9780. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  9781. intersects.push( {
  9782. distance: distance,
  9783. point: intersectionPoint,
  9784. face: new THREE.Face3( a, b, c, THREE.Triangle.normal( vA, vB, vC ) ),
  9785. faceIndex: null,
  9786. object: this
  9787. } );
  9788. }
  9789. }
  9790. } else if ( geometry instanceof THREE.Geometry ) {
  9791. var isFaceMaterial = this.material instanceof THREE.MeshFaceMaterial;
  9792. var objectMaterials = isFaceMaterial === true ? this.material.materials : null;
  9793. var a, b, c;
  9794. var precision = raycaster.precision;
  9795. var vertices = geometry.vertices;
  9796. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  9797. var face = geometry.faces[ f ];
  9798. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : this.material;
  9799. if ( material === undefined ) continue;
  9800. a = vertices[ face.a ];
  9801. b = vertices[ face.b ];
  9802. c = vertices[ face.c ];
  9803. if ( material.morphTargets === true ) {
  9804. var morphTargets = geometry.morphTargets;
  9805. var morphInfluences = this.morphTargetInfluences;
  9806. vA.set( 0, 0, 0 );
  9807. vB.set( 0, 0, 0 );
  9808. vC.set( 0, 0, 0 );
  9809. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  9810. var influence = morphInfluences[ t ];
  9811. if ( influence === 0 ) continue;
  9812. var targets = morphTargets[ t ].vertices;
  9813. vA.x += ( targets[ face.a ].x - a.x ) * influence;
  9814. vA.y += ( targets[ face.a ].y - a.y ) * influence;
  9815. vA.z += ( targets[ face.a ].z - a.z ) * influence;
  9816. vB.x += ( targets[ face.b ].x - b.x ) * influence;
  9817. vB.y += ( targets[ face.b ].y - b.y ) * influence;
  9818. vB.z += ( targets[ face.b ].z - b.z ) * influence;
  9819. vC.x += ( targets[ face.c ].x - c.x ) * influence;
  9820. vC.y += ( targets[ face.c ].y - c.y ) * influence;
  9821. vC.z += ( targets[ face.c ].z - c.z ) * influence;
  9822. }
  9823. vA.add( a );
  9824. vB.add( b );
  9825. vC.add( c );
  9826. a = vA;
  9827. b = vB;
  9828. c = vC;
  9829. }
  9830. if ( material.side === THREE.BackSide ) {
  9831. var intersectionPoint = ray.intersectTriangle( c, b, a, true );
  9832. } else {
  9833. var intersectionPoint = ray.intersectTriangle( a, b, c, material.side !== THREE.DoubleSide );
  9834. }
  9835. if ( intersectionPoint === null ) continue;
  9836. intersectionPoint.applyMatrix4( this.matrixWorld );
  9837. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  9838. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  9839. intersects.push( {
  9840. distance: distance,
  9841. point: intersectionPoint,
  9842. face: face,
  9843. faceIndex: f,
  9844. object: this
  9845. } );
  9846. }
  9847. }
  9848. };
  9849. }() );
  9850. THREE.Mesh.prototype.clone = function ( object, recursive ) {
  9851. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  9852. THREE.Object3D.prototype.clone.call( this, object, recursive );
  9853. return object;
  9854. };
  9855. THREE.Mesh.prototype.toJSON = function ( meta ) {
  9856. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  9857. // only serialize if not in meta geometries cache
  9858. if ( meta.geometries[ this.geometry.uuid ] === undefined ) {
  9859. meta.geometries[ this.geometry.uuid ] = this.geometry.toJSON( meta );
  9860. }
  9861. // only serialize if not in meta materials cache
  9862. if ( meta.materials[ this.material.uuid ] === undefined ) {
  9863. meta.materials[ this.material.uuid ] = this.material.toJSON( meta );
  9864. }
  9865. data.object.geometry = this.geometry.uuid;
  9866. data.object.material = this.material.uuid;
  9867. return data;
  9868. };
  9869. // File:src/objects/Bone.js
  9870. /**
  9871. * @author mikael emtinger / http://gomo.se/
  9872. * @author alteredq / http://alteredqualia.com/
  9873. * @author ikerr / http://verold.com
  9874. */
  9875. THREE.Bone = function ( skin ) {
  9876. THREE.Object3D.call( this );
  9877. this.type = 'Bone';
  9878. this.skin = skin;
  9879. };
  9880. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  9881. THREE.Bone.prototype.constructor = THREE.Bone;
  9882. // File:src/objects/Skeleton.js
  9883. /**
  9884. * @author mikael emtinger / http://gomo.se/
  9885. * @author alteredq / http://alteredqualia.com/
  9886. * @author michael guerrero / http://realitymeltdown.com
  9887. * @author ikerr / http://verold.com
  9888. */
  9889. THREE.Skeleton = function ( bones, boneInverses, useVertexTexture ) {
  9890. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  9891. this.identityMatrix = new THREE.Matrix4();
  9892. // copy the bone array
  9893. bones = bones || [];
  9894. this.bones = bones.slice( 0 );
  9895. // create a bone texture or an array of floats
  9896. if ( this.useVertexTexture ) {
  9897. // layout (1 matrix = 4 pixels)
  9898. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  9899. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  9900. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  9901. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  9902. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  9903. var size;
  9904. if ( this.bones.length > 256 )
  9905. size = 64;
  9906. else if ( this.bones.length > 64 )
  9907. size = 32;
  9908. else if ( this.bones.length > 16 )
  9909. size = 16;
  9910. else
  9911. size = 8;
  9912. this.boneTextureWidth = size;
  9913. this.boneTextureHeight = size;
  9914. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  9915. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  9916. this.boneTexture.minFilter = THREE.NearestFilter;
  9917. this.boneTexture.magFilter = THREE.NearestFilter;
  9918. this.boneTexture.generateMipmaps = false;
  9919. this.boneTexture.flipY = false;
  9920. } else {
  9921. this.boneMatrices = new Float32Array( 16 * this.bones.length );
  9922. }
  9923. // use the supplied bone inverses or calculate the inverses
  9924. if ( boneInverses === undefined ) {
  9925. this.calculateInverses();
  9926. } else {
  9927. if ( this.bones.length === boneInverses.length ) {
  9928. this.boneInverses = boneInverses.slice( 0 );
  9929. } else {
  9930. console.warn( 'THREE.Skeleton bonInverses is the wrong length.' );
  9931. this.boneInverses = [];
  9932. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  9933. this.boneInverses.push( new THREE.Matrix4() );
  9934. }
  9935. }
  9936. }
  9937. };
  9938. THREE.Skeleton.prototype.calculateInverses = function () {
  9939. this.boneInverses = [];
  9940. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  9941. var inverse = new THREE.Matrix4();
  9942. if ( this.bones[ b ] ) {
  9943. inverse.getInverse( this.bones[ b ].matrixWorld );
  9944. }
  9945. this.boneInverses.push( inverse );
  9946. }
  9947. };
  9948. THREE.Skeleton.prototype.pose = function () {
  9949. var bone;
  9950. // recover the bind-time world matrices
  9951. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  9952. bone = this.bones[ b ];
  9953. if ( bone ) {
  9954. bone.matrixWorld.getInverse( this.boneInverses[ b ] );
  9955. }
  9956. }
  9957. // compute the local matrices, positions, rotations and scales
  9958. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  9959. bone = this.bones[ b ];
  9960. if ( bone ) {
  9961. if ( bone.parent ) {
  9962. bone.matrix.getInverse( bone.parent.matrixWorld );
  9963. bone.matrix.multiply( bone.matrixWorld );
  9964. } else {
  9965. bone.matrix.copy( bone.matrixWorld );
  9966. }
  9967. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  9968. }
  9969. }
  9970. };
  9971. THREE.Skeleton.prototype.update = ( function () {
  9972. var offsetMatrix = new THREE.Matrix4();
  9973. return function () {
  9974. // flatten bone matrices to array
  9975. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  9976. // compute the offset between the current and the original transform
  9977. var matrix = this.bones[ b ] ? this.bones[ b ].matrixWorld : this.identityMatrix;
  9978. offsetMatrix.multiplyMatrices( matrix, this.boneInverses[ b ] );
  9979. offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  9980. }
  9981. if ( this.useVertexTexture ) {
  9982. this.boneTexture.needsUpdate = true;
  9983. }
  9984. };
  9985. } )();
  9986. // File:src/objects/SkinnedMesh.js
  9987. /**
  9988. * @author mikael emtinger / http://gomo.se/
  9989. * @author alteredq / http://alteredqualia.com/
  9990. * @author ikerr / http://verold.com
  9991. */
  9992. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  9993. THREE.Mesh.call( this, geometry, material );
  9994. this.type = 'SkinnedMesh';
  9995. this.bindMode = "attached";
  9996. this.bindMatrix = new THREE.Matrix4();
  9997. this.bindMatrixInverse = new THREE.Matrix4();
  9998. // init bones
  9999. // TODO: remove bone creation as there is no reason (other than
  10000. // convenience) for THREE.SkinnedMesh to do this.
  10001. var bones = [];
  10002. if ( this.geometry && this.geometry.bones !== undefined ) {
  10003. var bone, gbone, p, q, s;
  10004. for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {
  10005. gbone = this.geometry.bones[ b ];
  10006. p = gbone.pos;
  10007. q = gbone.rotq;
  10008. s = gbone.scl;
  10009. bone = new THREE.Bone( this );
  10010. bones.push( bone );
  10011. bone.name = gbone.name;
  10012. bone.position.set( p[ 0 ], p[ 1 ], p[ 2 ] );
  10013. bone.quaternion.set( q[ 0 ], q[ 1 ], q[ 2 ], q[ 3 ] );
  10014. if ( s !== undefined ) {
  10015. bone.scale.set( s[ 0 ], s[ 1 ], s[ 2 ] );
  10016. } else {
  10017. bone.scale.set( 1, 1, 1 );
  10018. }
  10019. }
  10020. for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {
  10021. gbone = this.geometry.bones[ b ];
  10022. if ( gbone.parent !== - 1 ) {
  10023. bones[ gbone.parent ].add( bones[ b ] );
  10024. } else {
  10025. this.add( bones[ b ] );
  10026. }
  10027. }
  10028. }
  10029. this.normalizeSkinWeights();
  10030. this.updateMatrixWorld( true );
  10031. this.bind( new THREE.Skeleton( bones, undefined, useVertexTexture ) );
  10032. };
  10033. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  10034. THREE.SkinnedMesh.prototype.constructor = THREE.SkinnedMesh;
  10035. THREE.SkinnedMesh.prototype.bind = function( skeleton, bindMatrix ) {
  10036. this.skeleton = skeleton;
  10037. if ( bindMatrix === undefined ) {
  10038. this.updateMatrixWorld( true );
  10039. bindMatrix = this.matrixWorld;
  10040. }
  10041. this.bindMatrix.copy( bindMatrix );
  10042. this.bindMatrixInverse.getInverse( bindMatrix );
  10043. };
  10044. THREE.SkinnedMesh.prototype.pose = function () {
  10045. this.skeleton.pose();
  10046. };
  10047. THREE.SkinnedMesh.prototype.normalizeSkinWeights = function () {
  10048. if ( this.geometry instanceof THREE.Geometry ) {
  10049. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  10050. var sw = this.geometry.skinWeights[ i ];
  10051. var scale = 1.0 / sw.lengthManhattan();
  10052. if ( scale !== Infinity ) {
  10053. sw.multiplyScalar( scale );
  10054. } else {
  10055. sw.set( 1 ); // this will be normalized by the shader anyway
  10056. }
  10057. }
  10058. } else {
  10059. // skinning weights assumed to be normalized for THREE.BufferGeometry
  10060. }
  10061. };
  10062. THREE.SkinnedMesh.prototype.updateMatrixWorld = function( force ) {
  10063. THREE.Mesh.prototype.updateMatrixWorld.call( this, true );
  10064. if ( this.bindMode === "attached" ) {
  10065. this.bindMatrixInverse.getInverse( this.matrixWorld );
  10066. } else if ( this.bindMode === "detached" ) {
  10067. this.bindMatrixInverse.getInverse( this.bindMatrix );
  10068. } else {
  10069. console.warn( 'THREE.SkinnedMesh unreckognized bindMode: ' + this.bindMode );
  10070. }
  10071. };
  10072. THREE.SkinnedMesh.prototype.clone = function( object ) {
  10073. if ( object === undefined ) {
  10074. object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  10075. }
  10076. THREE.Mesh.prototype.clone.call( this, object );
  10077. return object;
  10078. };
  10079. // File:src/objects/MorphAnimMesh.js
  10080. /**
  10081. * @author alteredq / http://alteredqualia.com/
  10082. */
  10083. THREE.MorphAnimMesh = function ( geometry, material ) {
  10084. THREE.Mesh.call( this, geometry, material );
  10085. this.type = 'MorphAnimMesh';
  10086. // API
  10087. this.duration = 1000; // milliseconds
  10088. this.mirroredLoop = false;
  10089. this.time = 0;
  10090. // internals
  10091. this.lastKeyframe = 0;
  10092. this.currentKeyframe = 0;
  10093. this.direction = 1;
  10094. this.directionBackwards = false;
  10095. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  10096. };
  10097. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  10098. THREE.MorphAnimMesh.prototype.constructor = THREE.MorphAnimMesh;
  10099. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  10100. this.startKeyframe = start;
  10101. this.endKeyframe = end;
  10102. this.length = this.endKeyframe - this.startKeyframe + 1;
  10103. };
  10104. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  10105. this.direction = 1;
  10106. this.directionBackwards = false;
  10107. };
  10108. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  10109. this.direction = - 1;
  10110. this.directionBackwards = true;
  10111. };
  10112. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  10113. var geometry = this.geometry;
  10114. if ( ! geometry.animations ) geometry.animations = {};
  10115. var firstAnimation, animations = geometry.animations;
  10116. var pattern = /([a-z]+)_?(\d+)/;
  10117. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  10118. var morph = geometry.morphTargets[ i ];
  10119. var parts = morph.name.match( pattern );
  10120. if ( parts && parts.length > 1 ) {
  10121. var label = parts[ 1 ];
  10122. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: - Infinity };
  10123. var animation = animations[ label ];
  10124. if ( i < animation.start ) animation.start = i;
  10125. if ( i > animation.end ) animation.end = i;
  10126. if ( ! firstAnimation ) firstAnimation = label;
  10127. }
  10128. }
  10129. geometry.firstAnimation = firstAnimation;
  10130. };
  10131. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  10132. if ( ! this.geometry.animations ) this.geometry.animations = {};
  10133. this.geometry.animations[ label ] = { start: start, end: end };
  10134. };
  10135. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  10136. var animation = this.geometry.animations[ label ];
  10137. if ( animation ) {
  10138. this.setFrameRange( animation.start, animation.end );
  10139. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  10140. this.time = 0;
  10141. } else {
  10142. console.warn( 'THREE.MorphAnimMesh: animation[' + label + '] undefined in .playAnimation()' );
  10143. }
  10144. };
  10145. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  10146. var frameTime = this.duration / this.length;
  10147. this.time += this.direction * delta;
  10148. if ( this.mirroredLoop ) {
  10149. if ( this.time > this.duration || this.time < 0 ) {
  10150. this.direction *= - 1;
  10151. if ( this.time > this.duration ) {
  10152. this.time = this.duration;
  10153. this.directionBackwards = true;
  10154. }
  10155. if ( this.time < 0 ) {
  10156. this.time = 0;
  10157. this.directionBackwards = false;
  10158. }
  10159. }
  10160. } else {
  10161. this.time = this.time % this.duration;
  10162. if ( this.time < 0 ) this.time += this.duration;
  10163. }
  10164. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  10165. if ( keyframe !== this.currentKeyframe ) {
  10166. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  10167. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  10168. this.morphTargetInfluences[ keyframe ] = 0;
  10169. this.lastKeyframe = this.currentKeyframe;
  10170. this.currentKeyframe = keyframe;
  10171. }
  10172. var mix = ( this.time % frameTime ) / frameTime;
  10173. if ( this.directionBackwards ) {
  10174. mix = 1 - mix;
  10175. }
  10176. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  10177. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  10178. };
  10179. THREE.MorphAnimMesh.prototype.interpolateTargets = function ( a, b, t ) {
  10180. var influences = this.morphTargetInfluences;
  10181. for ( var i = 0, l = influences.length; i < l; i ++ ) {
  10182. influences[ i ] = 0;
  10183. }
  10184. if ( a > -1 ) influences[ a ] = 1 - t;
  10185. if ( b > -1 ) influences[ b ] = t;
  10186. };
  10187. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  10188. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  10189. object.duration = this.duration;
  10190. object.mirroredLoop = this.mirroredLoop;
  10191. object.time = this.time;
  10192. object.lastKeyframe = this.lastKeyframe;
  10193. object.currentKeyframe = this.currentKeyframe;
  10194. object.direction = this.direction;
  10195. object.directionBackwards = this.directionBackwards;
  10196. THREE.Mesh.prototype.clone.call( this, object );
  10197. return object;
  10198. };
  10199. // File:src/objects/LOD.js
  10200. /**
  10201. * @author mikael emtinger / http://gomo.se/
  10202. * @author alteredq / http://alteredqualia.com/
  10203. * @author mrdoob / http://mrdoob.com/
  10204. */
  10205. THREE.LOD = function () {
  10206. THREE.Object3D.call( this );
  10207. this.objects = [];
  10208. };
  10209. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  10210. THREE.LOD.prototype.constructor = THREE.LOD;
  10211. THREE.LOD.prototype.addLevel = function ( object, distance ) {
  10212. if ( distance === undefined ) distance = 0;
  10213. distance = Math.abs( distance );
  10214. for ( var l = 0; l < this.objects.length; l ++ ) {
  10215. if ( distance < this.objects[ l ].distance ) {
  10216. break;
  10217. }
  10218. }
  10219. this.objects.splice( l, 0, { distance: distance, object: object } );
  10220. this.add( object );
  10221. };
  10222. THREE.LOD.prototype.getObjectForDistance = function ( distance ) {
  10223. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  10224. if ( distance < this.objects[ i ].distance ) {
  10225. break;
  10226. }
  10227. }
  10228. return this.objects[ i - 1 ].object;
  10229. };
  10230. THREE.LOD.prototype.raycast = ( function () {
  10231. var matrixPosition = new THREE.Vector3();
  10232. return function ( raycaster, intersects ) {
  10233. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  10234. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  10235. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  10236. };
  10237. }() );
  10238. THREE.LOD.prototype.update = function () {
  10239. var v1 = new THREE.Vector3();
  10240. var v2 = new THREE.Vector3();
  10241. return function ( camera ) {
  10242. if ( this.objects.length > 1 ) {
  10243. v1.setFromMatrixPosition( camera.matrixWorld );
  10244. v2.setFromMatrixPosition( this.matrixWorld );
  10245. var distance = v1.distanceTo( v2 );
  10246. this.objects[ 0 ].object.visible = true;
  10247. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  10248. if ( distance >= this.objects[ i ].distance ) {
  10249. this.objects[ i - 1 ].object.visible = false;
  10250. this.objects[ i ].object.visible = true;
  10251. } else {
  10252. break;
  10253. }
  10254. }
  10255. for ( ; i < l; i ++ ) {
  10256. this.objects[ i ].object.visible = false;
  10257. }
  10258. }
  10259. };
  10260. }();
  10261. THREE.LOD.prototype.clone = function ( object ) {
  10262. if ( object === undefined ) object = new THREE.LOD();
  10263. THREE.Object3D.prototype.clone.call( this, object );
  10264. for ( var i = 0, l = this.objects.length; i < l; i ++ ) {
  10265. var x = this.objects[ i ].object.clone();
  10266. x.visible = i === 0;
  10267. object.addLevel( x, this.objects[ i ].distance );
  10268. }
  10269. return object;
  10270. };
  10271. // File:src/objects/Sprite.js
  10272. /**
  10273. * @author mikael emtinger / http://gomo.se/
  10274. * @author alteredq / http://alteredqualia.com/
  10275. */
  10276. THREE.Sprite = ( function () {
  10277. var indices = new Uint16Array( [ 0, 1, 2, 0, 2, 3 ] );
  10278. var vertices = new Float32Array( [ - 0.5, - 0.5, 0, 0.5, - 0.5, 0, 0.5, 0.5, 0, - 0.5, 0.5, 0 ] );
  10279. var uvs = new Float32Array( [ 0, 0, 1, 0, 1, 1, 0, 1 ] );
  10280. var geometry = new THREE.BufferGeometry();
  10281. geometry.addAttribute( 'index', new THREE.BufferAttribute( indices, 1 ) );
  10282. geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  10283. geometry.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) );
  10284. return function ( material ) {
  10285. THREE.Object3D.call( this );
  10286. this.type = 'Sprite';
  10287. this.geometry = geometry;
  10288. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  10289. };
  10290. } )();
  10291. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  10292. THREE.Sprite.prototype.constructor = THREE.Sprite;
  10293. THREE.Sprite.prototype.raycast = ( function () {
  10294. var matrixPosition = new THREE.Vector3();
  10295. return function ( raycaster, intersects ) {
  10296. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  10297. var distance = raycaster.ray.distanceToPoint( matrixPosition );
  10298. if ( distance > this.scale.x ) {
  10299. return;
  10300. }
  10301. intersects.push( {
  10302. distance: distance,
  10303. point: this.position,
  10304. face: null,
  10305. object: this
  10306. } );
  10307. };
  10308. }() );
  10309. THREE.Sprite.prototype.clone = function ( object ) {
  10310. if ( object === undefined ) object = new THREE.Sprite( this.material );
  10311. THREE.Object3D.prototype.clone.call( this, object );
  10312. return object;
  10313. };
  10314. THREE.Sprite.prototype.toJSON = function ( meta ) {
  10315. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  10316. // only serialize if not in meta materials cache
  10317. if ( meta.materials[ this.material.uuid ] === undefined ) {
  10318. meta.materials[ this.material.uuid ] = this.material.toJSON();
  10319. }
  10320. data.object.material = this.material.uuid;
  10321. return data;
  10322. };
  10323. // Backwards compatibility
  10324. THREE.Particle = THREE.Sprite;
  10325. // File:src/objects/LensFlare.js
  10326. /**
  10327. * @author mikael emtinger / http://gomo.se/
  10328. * @author alteredq / http://alteredqualia.com/
  10329. */
  10330. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  10331. THREE.Object3D.call( this );
  10332. this.lensFlares = [];
  10333. this.positionScreen = new THREE.Vector3();
  10334. this.customUpdateCallback = undefined;
  10335. if ( texture !== undefined ) {
  10336. this.add( texture, size, distance, blending, color );
  10337. }
  10338. };
  10339. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  10340. THREE.LensFlare.prototype.constructor = THREE.LensFlare;
  10341. /*
  10342. * Add: adds another flare
  10343. */
  10344. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  10345. if ( size === undefined ) size = - 1;
  10346. if ( distance === undefined ) distance = 0;
  10347. if ( opacity === undefined ) opacity = 1;
  10348. if ( color === undefined ) color = new THREE.Color( 0xffffff );
  10349. if ( blending === undefined ) blending = THREE.NormalBlending;
  10350. distance = Math.min( distance, Math.max( 0, distance ) );
  10351. this.lensFlares.push( {
  10352. texture: texture, // THREE.Texture
  10353. size: size, // size in pixels (-1 = use texture.width)
  10354. distance: distance, // distance (0-1) from light source (0=at light source)
  10355. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  10356. scale: 1, // scale
  10357. rotation: 1, // rotation
  10358. opacity: opacity, // opacity
  10359. color: color, // color
  10360. blending: blending // blending
  10361. } );
  10362. };
  10363. /*
  10364. * Update lens flares update positions on all flares based on the screen position
  10365. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  10366. */
  10367. THREE.LensFlare.prototype.updateLensFlares = function () {
  10368. var f, fl = this.lensFlares.length;
  10369. var flare;
  10370. var vecX = - this.positionScreen.x * 2;
  10371. var vecY = - this.positionScreen.y * 2;
  10372. for ( f = 0; f < fl; f ++ ) {
  10373. flare = this.lensFlares[ f ];
  10374. flare.x = this.positionScreen.x + vecX * flare.distance;
  10375. flare.y = this.positionScreen.y + vecY * flare.distance;
  10376. flare.wantedRotation = flare.x * Math.PI * 0.25;
  10377. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  10378. }
  10379. };
  10380. // File:src/scenes/Scene.js
  10381. /**
  10382. * @author mrdoob / http://mrdoob.com/
  10383. */
  10384. THREE.Scene = function () {
  10385. THREE.Object3D.call( this );
  10386. this.type = 'Scene';
  10387. this.fog = null;
  10388. this.overrideMaterial = null;
  10389. this.autoUpdate = true; // checked by the renderer
  10390. };
  10391. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  10392. THREE.Scene.prototype.constructor = THREE.Scene;
  10393. THREE.Scene.prototype.clone = function ( object ) {
  10394. if ( object === undefined ) object = new THREE.Scene();
  10395. THREE.Object3D.prototype.clone.call( this, object );
  10396. if ( this.fog !== null ) object.fog = this.fog.clone();
  10397. if ( this.overrideMaterial !== null ) object.overrideMaterial = this.overrideMaterial.clone();
  10398. object.autoUpdate = this.autoUpdate;
  10399. object.matrixAutoUpdate = this.matrixAutoUpdate;
  10400. return object;
  10401. };
  10402. // File:src/scenes/Fog.js
  10403. /**
  10404. * @author mrdoob / http://mrdoob.com/
  10405. * @author alteredq / http://alteredqualia.com/
  10406. */
  10407. THREE.Fog = function ( color, near, far ) {
  10408. this.name = '';
  10409. this.color = new THREE.Color( color );
  10410. this.near = ( near !== undefined ) ? near : 1;
  10411. this.far = ( far !== undefined ) ? far : 1000;
  10412. };
  10413. THREE.Fog.prototype.clone = function () {
  10414. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  10415. };
  10416. // File:src/scenes/FogExp2.js
  10417. /**
  10418. * @author mrdoob / http://mrdoob.com/
  10419. * @author alteredq / http://alteredqualia.com/
  10420. */
  10421. THREE.FogExp2 = function ( color, density ) {
  10422. this.name = '';
  10423. this.color = new THREE.Color( color );
  10424. this.density = ( density !== undefined ) ? density : 0.00025;
  10425. };
  10426. THREE.FogExp2.prototype.clone = function () {
  10427. return new THREE.FogExp2( this.color.getHex(), this.density );
  10428. };
  10429. // File:src/renderers/shaders/ShaderChunk.js
  10430. THREE.ShaderChunk = {};
  10431. // File:src/renderers/shaders/ShaderChunk/alphamap_fragment.glsl
  10432. THREE.ShaderChunk[ 'alphamap_fragment'] = "#ifdef USE_ALPHAMAP\n\n diffuseColor.a *= texture2D( alphaMap, vUv ).g;\n\n#endif\n";
  10433. // File:src/renderers/shaders/ShaderChunk/alphamap_pars_fragment.glsl
  10434. THREE.ShaderChunk[ 'alphamap_pars_fragment'] = "#ifdef USE_ALPHAMAP\n\n uniform sampler2D alphaMap;\n\n#endif\n";
  10435. // File:src/renderers/shaders/ShaderChunk/alphatest_fragment.glsl
  10436. THREE.ShaderChunk[ 'alphatest_fragment'] = "#ifdef ALPHATEST\n\n if ( diffuseColor.a < ALPHATEST ) discard;\n\n#endif\n";
  10437. // File:src/renderers/shaders/ShaderChunk/aomap_fragment.glsl
  10438. THREE.ShaderChunk[ 'aomap_fragment'] = "#ifdef USE_AOMAP\n\n totalAmbientLight *= ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\n#endif\n";
  10439. // File:src/renderers/shaders/ShaderChunk/aomap_pars_fragment.glsl
  10440. THREE.ShaderChunk[ 'aomap_pars_fragment'] = "#ifdef USE_AOMAP\n\n uniform sampler2D aoMap;\n uniform float aoMapIntensity;\n\n#endif";
  10441. // File:src/renderers/shaders/ShaderChunk/bumpmap_pars_fragment.glsl
  10442. THREE.ShaderChunk[ 'bumpmap_pars_fragment'] = "#ifdef USE_BUMPMAP\n\n uniform sampler2D bumpMap;\n uniform float bumpScale;\n\n // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen\n // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html\n\n // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)\n\n vec2 dHdxy_fwd() {\n\n vec2 dSTdx = dFdx( vUv );\n vec2 dSTdy = dFdy( vUv );\n\n float Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\n return vec2( dBx, dBy );\n\n }\n\n vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n\n vec3 vSigmaX = dFdx( surf_pos );\n vec3 vSigmaY = dFdy( surf_pos );\n vec3 vN = surf_norm; // normalized\n\n vec3 R1 = cross( vSigmaY, vN );\n vec3 R2 = cross( vN, vSigmaX );\n\n float fDet = dot( vSigmaX, R1 );\n\n vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n return normalize( abs( fDet ) * surf_norm - vGrad );\n\n }\n\n#endif\n";
  10443. // File:src/renderers/shaders/ShaderChunk/color_fragment.glsl
  10444. THREE.ShaderChunk[ 'color_fragment'] = "#ifdef USE_COLOR\n\n diffuseColor.rgb *= vColor;\n\n#endif";
  10445. // File:src/renderers/shaders/ShaderChunk/color_pars_fragment.glsl
  10446. THREE.ShaderChunk[ 'color_pars_fragment'] = "#ifdef USE_COLOR\n\n varying vec3 vColor;\n\n#endif\n";
  10447. // File:src/renderers/shaders/ShaderChunk/color_pars_vertex.glsl
  10448. THREE.ShaderChunk[ 'color_pars_vertex'] = "#ifdef USE_COLOR\n\n varying vec3 vColor;\n\n#endif";
  10449. // File:src/renderers/shaders/ShaderChunk/color_vertex.glsl
  10450. THREE.ShaderChunk[ 'color_vertex'] = "#ifdef USE_COLOR\n\n vColor.xyz = inputToLinear( color.xyz );\n\n#endif";
  10451. // File:src/renderers/shaders/ShaderChunk/common.glsl
  10452. THREE.ShaderChunk[ 'common'] = "#define PI 3.14159\n#define PI2 6.28318\n#define RECIPROCAL_PI2 0.15915494\n#define LOG2 1.442695\n#define EPSILON 1e-6\n\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define whiteCompliment(a) ( 1.0 - saturate( a ) )\n\nvec3 transformDirection( in vec3 normal, in mat4 matrix ) {\n\n return normalize( ( matrix * vec4( normal, 0.0 ) ).xyz );\n\n}\n\n// http://en.wikibooks.org/wiki/GLSL_Programming/Applying_Matrix_Transformations\nvec3 inverseTransformDirection( in vec3 normal, in mat4 matrix ) {\n\n return normalize( ( vec4( normal, 0.0 ) * matrix ).xyz );\n\n}\n\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\n float distance = dot( planeNormal, point - pointOnPlane );\n\n return - distance * planeNormal + point;\n\n}\n\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\n return sign( dot( point - pointOnPlane, planeNormal ) );\n\n}\n\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\n return lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n\n}\n\nfloat calcLightAttenuation( float lightDistance, float cutoffDistance, float decayExponent ) {\n\n if ( decayExponent > 0.0 ) {\n\n return pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\n }\n\n return 1.0;\n\n}\n\nvec3 F_Schlick( in vec3 specularColor, in float dotLH ) {\n\n return ( 1.0 - specularColor ) * pow( 1.0 - dotLH, 5.0 ) + specularColor;\n\n}\n\nfloat G_BlinnPhong_Implicit( /* in float dotNL, in float dotNV */ ) {\n\n // geometry term is (n⋅l)(n⋅v) / 4(n⋅l)(n⋅v)\n\n return 0.25;\n\n}\n\nfloat D_BlinnPhong( in float shininess, in float dotNH ) {\n\n // factor of 1/PI in distribution term omitted\n\n return ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n\n}\n\nvec3 BRDF_BlinnPhong( in vec3 specularColor, in float shininess, in vec3 normal, in vec3 lightDir, in vec3 viewDir ) {\n\n vec3 halfDir = normalize( lightDir + viewDir );\n\n //float dotNL = saturate( dot( normal, lightDir ) );\n //float dotNV = saturate( dot( normal, viewDir ) );\n float dotNH = saturate( dot( normal, halfDir ) );\n float dotLH = saturate( dot( lightDir, halfDir ) );\n\n vec3 F = F_Schlick( specularColor, dotLH );\n\n float G = G_BlinnPhong_Implicit( /* dotNL, dotNV */ );\n\n float D = D_BlinnPhong( shininess, dotNH );\n\n return F * G * D;\n\n}\n\nvec3 inputToLinear( in vec3 a ) {\n\n #ifdef GAMMA_INPUT\n\n return pow( a, vec3( float( GAMMA_FACTOR ) ) );\n\n #else\n\n return a;\n\n #endif\n\n}\n\nvec3 linearToOutput( in vec3 a ) {\n\n #ifdef GAMMA_OUTPUT\n\n return pow( a, vec3( 1.0 / float( GAMMA_FACTOR ) ) );\n\n #else\n\n return a;\n\n #endif\n\n}\n";
  10453. // File:src/renderers/shaders/ShaderChunk/default_vertex.glsl
  10454. THREE.ShaderChunk[ 'default_vertex'] = "#ifdef USE_SKINNING\n\n vec4 mvPosition = modelViewMatrix * skinned;\n\n#elif defined( USE_MORPHTARGETS )\n\n vec4 mvPosition = modelViewMatrix * vec4( morphed, 1.0 );\n\n#else\n\n vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n\n#endif\n\ngl_Position = projectionMatrix * mvPosition;\n";
  10455. // File:src/renderers/shaders/ShaderChunk/defaultnormal_vertex.glsl
  10456. THREE.ShaderChunk[ 'defaultnormal_vertex'] = "#ifdef USE_SKINNING\n\n vec3 objectNormal = skinnedNormal.xyz;\n\n#elif defined( USE_MORPHNORMALS )\n\n vec3 objectNormal = morphedNormal;\n\n#else\n\n vec3 objectNormal = normal;\n\n#endif\n\n#ifdef FLIP_SIDED\n\n objectNormal = -objectNormal;\n\n#endif\n\nvec3 transformedNormal = normalMatrix * objectNormal;\n";
  10457. // File:src/renderers/shaders/ShaderChunk/envmap_fragment.glsl
  10458. THREE.ShaderChunk[ 'envmap_fragment'] = "#ifdef USE_ENVMAP\n\n #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\n vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n\n // Transforming Normal Vectors with the Inverse Transformation\n vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\n #ifdef ENVMAP_MODE_REFLECTION\n\n vec3 reflectVec = reflect( cameraToVertex, worldNormal );\n\n #else\n\n vec3 reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );\n\n #endif\n\n #else\n\n vec3 reflectVec = vReflect;\n\n #endif\n\n #ifdef DOUBLE_SIDED\n float flipNormal = ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n #else\n float flipNormal = 1.0;\n #endif\n\n #ifdef ENVMAP_TYPE_CUBE\n vec4 envColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\n #elif defined( ENVMAP_TYPE_EQUIREC )\n vec2 sampleUV;\n sampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 );\n sampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n vec4 envColor = texture2D( envMap, sampleUV );\n\n #elif defined( ENVMAP_TYPE_SPHERE )\n vec3 reflectView = flipNormal * normalize((viewMatrix * vec4( reflectVec, 0.0 )).xyz + vec3(0.0,0.0,1.0));\n vec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n #endif\n\n envColor.xyz = inputToLinear( envColor.xyz );\n\n #ifdef ENVMAP_BLENDING_MULTIPLY\n\n outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\n #elif defined( ENVMAP_BLENDING_MIX )\n\n outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\n #elif defined( ENVMAP_BLENDING_ADD )\n\n outgoingLight += envColor.xyz * specularStrength * reflectivity;\n\n #endif\n\n#endif\n";
  10459. // File:src/renderers/shaders/ShaderChunk/envmap_pars_fragment.glsl
  10460. THREE.ShaderChunk[ 'envmap_pars_fragment'] = "#ifdef USE_ENVMAP\n\n uniform float reflectivity;\n #ifdef ENVMAP_TYPE_CUBE\n uniform samplerCube envMap;\n #else\n uniform sampler2D envMap;\n #endif\n uniform float flipEnvMap;\n\n #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\n uniform float refractionRatio;\n\n #else\n\n varying vec3 vReflect;\n\n #endif\n\n#endif\n";
  10461. // File:src/renderers/shaders/ShaderChunk/envmap_pars_vertex.glsl
  10462. THREE.ShaderChunk[ 'envmap_pars_vertex'] = "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP ) && ! defined( PHONG )\n\n varying vec3 vReflect;\n\n uniform float refractionRatio;\n\n#endif\n";
  10463. // File:src/renderers/shaders/ShaderChunk/envmap_vertex.glsl
  10464. THREE.ShaderChunk[ 'envmap_vertex'] = "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP ) && ! defined( PHONG )\n\n vec3 worldNormal = transformDirection( objectNormal, modelMatrix );\n\n vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\n #ifdef ENVMAP_MODE_REFLECTION\n\n vReflect = reflect( cameraToVertex, worldNormal );\n\n #else\n\n vReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\n #endif\n\n#endif\n";
  10465. // File:src/renderers/shaders/ShaderChunk/fog_fragment.glsl
  10466. THREE.ShaderChunk[ 'fog_fragment'] = "#ifdef USE_FOG\n\n #ifdef USE_LOGDEPTHBUF_EXT\n\n float depth = gl_FragDepthEXT / gl_FragCoord.w;\n\n #else\n\n float depth = gl_FragCoord.z / gl_FragCoord.w;\n\n #endif\n\n #ifdef FOG_EXP2\n\n float fogFactor = whiteCompliment( exp2( - fogDensity * fogDensity * depth * depth * LOG2 ) );\n\n #else\n\n float fogFactor = smoothstep( fogNear, fogFar, depth );\n\n #endif\n \n outgoingLight = mix( outgoingLight, fogColor, fogFactor );\n\n#endif";
  10467. // File:src/renderers/shaders/ShaderChunk/fog_pars_fragment.glsl
  10468. THREE.ShaderChunk[ 'fog_pars_fragment'] = "#ifdef USE_FOG\n\n uniform vec3 fogColor;\n\n #ifdef FOG_EXP2\n\n uniform float fogDensity;\n\n #else\n\n uniform float fogNear;\n uniform float fogFar;\n #endif\n\n#endif";
  10469. // File:src/renderers/shaders/ShaderChunk/lightmap_fragment.glsl
  10470. THREE.ShaderChunk[ 'lightmap_fragment'] = "#ifdef USE_LIGHTMAP\n\n totalAmbientLight += texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\n#endif\n";
  10471. // File:src/renderers/shaders/ShaderChunk/lightmap_pars_fragment.glsl
  10472. THREE.ShaderChunk[ 'lightmap_pars_fragment'] = "#ifdef USE_LIGHTMAP\n\n uniform sampler2D lightMap;\n uniform float lightMapIntensity;\n\n#endif";
  10473. // File:src/renderers/shaders/ShaderChunk/lights_lambert_pars_vertex.glsl
  10474. THREE.ShaderChunk[ 'lights_lambert_pars_vertex'] = "uniform vec3 ambientLightColor;\n\n#if MAX_DIR_LIGHTS > 0\n\n uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];\n uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];\n\n#endif\n\n#if MAX_HEMI_LIGHTS > 0\n\n uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];\n uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];\n uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];\n\n#endif\n\n#if MAX_POINT_LIGHTS > 0\n\n uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];\n uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];\n uniform float pointLightDistance[ MAX_POINT_LIGHTS ];\n uniform float pointLightDecay[ MAX_POINT_LIGHTS ];\n\n#endif\n\n#if MAX_SPOT_LIGHTS > 0\n\n uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];\n uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];\n uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];\n uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];\n uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];\n uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];\n uniform float spotLightDecay[ MAX_SPOT_LIGHTS ];\n\n#endif\n";
  10475. // File:src/renderers/shaders/ShaderChunk/lights_lambert_vertex.glsl
  10476. THREE.ShaderChunk[ 'lights_lambert_vertex'] = "vLightFront = vec3( 0.0 );\n\n#ifdef DOUBLE_SIDED\n\n vLightBack = vec3( 0.0 );\n\n#endif\n\nvec3 normal = normalize( transformedNormal );\n\n#if MAX_POINT_LIGHTS > 0\n\n for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {\n\n vec3 lightColor = pointLightColor[ i ];\n\n vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );\n vec3 lVector = lPosition.xyz - mvPosition.xyz;\n vec3 lightDir = normalize( lVector );\n\n // attenuation\n\n float attenuation = calcLightAttenuation( length( lVector ), pointLightDistance[ i ], pointLightDecay[ i ] );\n\n // diffuse\n\n float dotProduct = dot( normal, lightDir );\n\n vLightFront += lightColor * attenuation * saturate( dotProduct );\n\n #ifdef DOUBLE_SIDED\n\n vLightBack += lightColor * attenuation * saturate( - dotProduct );\n\n #endif\n\n }\n\n#endif\n\n#if MAX_SPOT_LIGHTS > 0\n\n for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {\n\n vec3 lightColor = spotLightColor[ i ];\n\n vec3 lightPosition = spotLightPosition[ i ];\n vec4 lPosition = viewMatrix * vec4( lightPosition, 1.0 );\n vec3 lVector = lPosition.xyz - mvPosition.xyz;\n vec3 lightDir = normalize( lVector );\n\n float spotEffect = dot( spotLightDirection[ i ], normalize( lightPosition - worldPosition.xyz ) );\n\n if ( spotEffect > spotLightAngleCos[ i ] ) {\n\n spotEffect = saturate( pow( saturate( spotEffect ), spotLightExponent[ i ] ) );\n\n // attenuation\n\n float attenuation = calcLightAttenuation( length( lVector ), spotLightDistance[ i ], spotLightDecay[ i ] );\n\n attenuation *= spotEffect;\n\n // diffuse\n\n float dotProduct = dot( normal, lightDir );\n\n vLightFront += lightColor * attenuation * saturate( dotProduct );\n\n #ifdef DOUBLE_SIDED\n\n vLightBack += lightColor * attenuation * saturate( - dotProduct );\n\n #endif\n\n }\n\n }\n\n#endif\n\n#if MAX_DIR_LIGHTS > 0\n\n for ( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {\n\n vec3 lightColor = directionalLightColor[ i ];\n\n vec3 lightDir = transformDirection( directionalLightDirection[ i ], viewMatrix );\n\n // diffuse\n\n float dotProduct = dot( normal, lightDir );\n\n vLightFront += lightColor * saturate( dotProduct );\n\n #ifdef DOUBLE_SIDED\n\n vLightBack += lightColor * saturate( - dotProduct );\n\n #endif\n\n }\n\n#endif\n\n#if MAX_HEMI_LIGHTS > 0\n\n for ( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {\n\n vec3 lightDir = transformDirection( hemisphereLightDirection[ i ], viewMatrix );\n\n // diffuse\n\n float dotProduct = dot( normal, lightDir );\n\n float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;\n\n vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );\n\n #ifdef DOUBLE_SIDED\n\n float hemiDiffuseWeightBack = - 0.5 * dotProduct + 0.5;\n\n vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );\n\n #endif\n\n }\n\n#endif\n\nvLightFront += ambientLightColor;\n\n#ifdef DOUBLE_SIDED\n\n vLightBack += ambientLightColor;\n\n#endif\n";
  10477. // File:src/renderers/shaders/ShaderChunk/lights_phong_fragment.glsl
  10478. THREE.ShaderChunk[ 'lights_phong_fragment'] = "#ifndef FLAT_SHADED\n\n vec3 normal = normalize( vNormal );\n\n #ifdef DOUBLE_SIDED\n\n normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );\n\n #endif\n\n#else\n\n vec3 fdx = dFdx( vViewPosition );\n vec3 fdy = dFdy( vViewPosition );\n vec3 normal = normalize( cross( fdx, fdy ) );\n\n#endif\n\n#ifdef USE_NORMALMAP\n\n normal = perturbNormal2Arb( -vViewPosition, normal );\n\n#elif defined( USE_BUMPMAP )\n\n normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n\n#endif\n\nvec3 viewDir = normalize( vViewPosition );\n\nvec3 totalDiffuseLight = vec3( 0.0 );\nvec3 totalSpecularLight = vec3( 0.0 );\n\n#if MAX_POINT_LIGHTS > 0\n\n for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {\n\n vec3 lightColor = pointLightColor[ i ];\n\n vec3 lightPosition = pointLightPosition[ i ];\n vec4 lPosition = viewMatrix * vec4( lightPosition, 1.0 );\n vec3 lVector = lPosition.xyz + vViewPosition.xyz;\n vec3 lightDir = normalize( lVector );\n\n // attenuation\n\n float attenuation = calcLightAttenuation( length( lVector ), pointLightDistance[ i ], pointLightDecay[ i ] );\n\n // diffuse\n\n float cosineTerm = saturate( dot( normal, lightDir ) );\n\n totalDiffuseLight += lightColor * attenuation * cosineTerm;\n\n // specular\n\n vec3 brdf = BRDF_BlinnPhong( specular, shininess, normal, lightDir, viewDir );\n\n totalSpecularLight += brdf * specularStrength * lightColor * attenuation * cosineTerm;\n\n\n }\n\n#endif\n\n#if MAX_SPOT_LIGHTS > 0\n\n for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {\n\n vec3 lightColor = spotLightColor[ i ];\n\n vec3 lightPosition = spotLightPosition[ i ];\n vec4 lPosition = viewMatrix * vec4( lightPosition, 1.0 );\n vec3 lVector = lPosition.xyz + vViewPosition.xyz;\n vec3 lightDir = normalize( lVector );\n\n float spotEffect = dot( spotLightDirection[ i ], normalize( lightPosition - vWorldPosition ) );\n\n if ( spotEffect > spotLightAngleCos[ i ] ) {\n\n spotEffect = saturate( pow( saturate( spotEffect ), spotLightExponent[ i ] ) );\n\n // attenuation\n\n float attenuation = calcLightAttenuation( length( lVector ), spotLightDistance[ i ], spotLightDecay[ i ] );\n\n attenuation *= spotEffect;\n\n // diffuse\n\n float cosineTerm = saturate( dot( normal, lightDir ) );\n\n totalDiffuseLight += lightColor * attenuation * cosineTerm;\n\n // specular\n\n vec3 brdf = BRDF_BlinnPhong( specular, shininess, normal, lightDir, viewDir );\n\n totalSpecularLight += brdf * specularStrength * lightColor * attenuation * cosineTerm;\n\n }\n\n }\n\n#endif\n\n#if MAX_DIR_LIGHTS > 0\n\n for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {\n\n vec3 lightColor = directionalLightColor[ i ];\n\n vec3 lightDir = transformDirection( directionalLightDirection[ i ], viewMatrix );\n\n // diffuse\n\n float cosineTerm = saturate( dot( normal, lightDir ) );\n\n totalDiffuseLight += lightColor * cosineTerm;\n\n // specular\n\n vec3 brdf = BRDF_BlinnPhong( specular, shininess, normal, lightDir, viewDir );\n\n totalSpecularLight += brdf * specularStrength * lightColor * cosineTerm;\n\n }\n\n#endif\n\n#if MAX_HEMI_LIGHTS > 0\n\n for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {\n\n vec3 lightDir = transformDirection( hemisphereLightDirection[ i ], viewMatrix );\n\n // diffuse\n\n float dotProduct = dot( normal, lightDir );\n\n float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;\n\n vec3 lightColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );\n\n totalDiffuseLight += lightColor;\n\n // specular (sky term only)\n\n vec3 brdf = BRDF_BlinnPhong( specular, shininess, normal, lightDir, viewDir );\n\n totalSpecularLight += brdf * specularStrength * lightColor * max( dotProduct, 0.0 );\n\n }\n\n#endif\n\n#ifdef METAL\n\n outgoingLight += diffuseColor.rgb * ( totalDiffuseLight + totalAmbientLight ) * specular + totalSpecularLight + emissive;\n\n#else\n\n outgoingLight += diffuseColor.rgb * ( totalDiffuseLight + totalAmbientLight ) + totalSpecularLight + emissive;\n\n#endif\n";
  10479. // File:src/renderers/shaders/ShaderChunk/lights_phong_pars_fragment.glsl
  10480. THREE.ShaderChunk[ 'lights_phong_pars_fragment'] = "uniform vec3 ambientLightColor;\n\n#if MAX_DIR_LIGHTS > 0\n\n uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];\n uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];\n\n#endif\n\n#if MAX_HEMI_LIGHTS > 0\n\n uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];\n uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];\n uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];\n\n#endif\n\n#if MAX_POINT_LIGHTS > 0\n\n uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];\n\n uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];\n uniform float pointLightDistance[ MAX_POINT_LIGHTS ];\n uniform float pointLightDecay[ MAX_POINT_LIGHTS ];\n\n#endif\n\n#if MAX_SPOT_LIGHTS > 0\n\n uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];\n uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];\n uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];\n uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];\n uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];\n uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];\n uniform float spotLightDecay[ MAX_SPOT_LIGHTS ];\n\n#endif\n\n#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP ) || defined( USE_ENVMAP )\n\n varying vec3 vWorldPosition;\n\n#endif\n\nvarying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n\n varying vec3 vNormal;\n\n#endif\n";
  10481. // File:src/renderers/shaders/ShaderChunk/lights_phong_pars_vertex.glsl
  10482. THREE.ShaderChunk[ 'lights_phong_pars_vertex'] = "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP ) || defined( USE_ENVMAP )\n\n varying vec3 vWorldPosition;\n\n#endif\n";
  10483. // File:src/renderers/shaders/ShaderChunk/lights_phong_vertex.glsl
  10484. THREE.ShaderChunk[ 'lights_phong_vertex'] = "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP ) || defined( USE_ENVMAP )\n\n vWorldPosition = worldPosition.xyz;\n\n#endif";
  10485. // File:src/renderers/shaders/ShaderChunk/linear_to_gamma_fragment.glsl
  10486. THREE.ShaderChunk[ 'linear_to_gamma_fragment'] = "\n outgoingLight = linearToOutput( outgoingLight );\n";
  10487. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_fragment.glsl
  10488. THREE.ShaderChunk[ 'logdepthbuf_fragment'] = "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n\n gl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n\n#endif";
  10489. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_pars_fragment.glsl
  10490. THREE.ShaderChunk[ 'logdepthbuf_pars_fragment'] = "#ifdef USE_LOGDEPTHBUF\n\n uniform float logDepthBufFC;\n\n #ifdef USE_LOGDEPTHBUF_EXT\n\n #extension GL_EXT_frag_depth : enable\n varying float vFragDepth;\n\n #endif\n\n#endif";
  10491. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_pars_vertex.glsl
  10492. THREE.ShaderChunk[ 'logdepthbuf_pars_vertex'] = "#ifdef USE_LOGDEPTHBUF\n\n #ifdef USE_LOGDEPTHBUF_EXT\n\n varying float vFragDepth;\n\n #endif\n\n uniform float logDepthBufFC;\n\n#endif";
  10493. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_vertex.glsl
  10494. THREE.ShaderChunk[ 'logdepthbuf_vertex'] = "#ifdef USE_LOGDEPTHBUF\n\n gl_Position.z = log2(max( EPSILON, gl_Position.w + 1.0 )) * logDepthBufFC;\n\n #ifdef USE_LOGDEPTHBUF_EXT\n\n vFragDepth = 1.0 + gl_Position.w;\n\n#else\n\n gl_Position.z = (gl_Position.z - 1.0) * gl_Position.w;\n\n #endif\n\n#endif";
  10495. // File:src/renderers/shaders/ShaderChunk/map_fragment.glsl
  10496. THREE.ShaderChunk[ 'map_fragment'] = "#ifdef USE_MAP\n\n vec4 texelColor = texture2D( map, vUv );\n\n texelColor.xyz = inputToLinear( texelColor.xyz );\n\n diffuseColor *= texelColor;\n\n#endif";
  10497. // File:src/renderers/shaders/ShaderChunk/map_pars_fragment.glsl
  10498. THREE.ShaderChunk[ 'map_pars_fragment'] = "#ifdef USE_MAP\n\n uniform sampler2D map;\n\n#endif";
  10499. // File:src/renderers/shaders/ShaderChunk/map_particle_fragment.glsl
  10500. THREE.ShaderChunk[ 'map_particle_fragment'] = "#ifdef USE_MAP\n\n diffuseColor *= texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) * offsetRepeat.zw + offsetRepeat.xy );\n\n#endif\n";
  10501. // File:src/renderers/shaders/ShaderChunk/map_particle_pars_fragment.glsl
  10502. THREE.ShaderChunk[ 'map_particle_pars_fragment'] = "#ifdef USE_MAP\n\n uniform vec4 offsetRepeat;\n uniform sampler2D map;\n\n#endif\n";
  10503. // File:src/renderers/shaders/ShaderChunk/morphnormal_vertex.glsl
  10504. THREE.ShaderChunk[ 'morphnormal_vertex'] = "#ifdef USE_MORPHNORMALS\n\n vec3 morphedNormal = vec3( 0.0 );\n\n morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];\n morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];\n morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];\n morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];\n\n morphedNormal += normal;\n\n#endif";
  10505. // File:src/renderers/shaders/ShaderChunk/morphtarget_pars_vertex.glsl
  10506. THREE.ShaderChunk[ 'morphtarget_pars_vertex'] = "#ifdef USE_MORPHTARGETS\n\n #ifndef USE_MORPHNORMALS\n\n uniform float morphTargetInfluences[ 8 ];\n\n #else\n\n uniform float morphTargetInfluences[ 4 ];\n\n #endif\n\n#endif";
  10507. // File:src/renderers/shaders/ShaderChunk/morphtarget_vertex.glsl
  10508. THREE.ShaderChunk[ 'morphtarget_vertex'] = "#ifdef USE_MORPHTARGETS\n\n vec3 morphed = vec3( 0.0 );\n morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];\n morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];\n morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];\n morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];\n\n #ifndef USE_MORPHNORMALS\n\n morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];\n morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];\n morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];\n morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];\n\n #endif\n\n morphed += position;\n\n#endif";
  10509. // File:src/renderers/shaders/ShaderChunk/normalmap_pars_fragment.glsl
  10510. THREE.ShaderChunk[ 'normalmap_pars_fragment'] = "#ifdef USE_NORMALMAP\n\n uniform sampler2D normalMap;\n uniform vec2 normalScale;\n\n // Per-Pixel Tangent Space Normal Mapping\n // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html\n\n vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {\n\n vec3 q0 = dFdx( eye_pos.xyz );\n vec3 q1 = dFdy( eye_pos.xyz );\n vec2 st0 = dFdx( vUv.st );\n vec2 st1 = dFdy( vUv.st );\n\n vec3 S = normalize( q0 * st1.t - q1 * st0.t );\n vec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n vec3 N = normalize( surf_norm );\n\n vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n mapN.xy = normalScale * mapN.xy;\n mat3 tsn = mat3( S, T, N );\n return normalize( tsn * mapN );\n\n }\n\n#endif\n";
  10511. // File:src/renderers/shaders/ShaderChunk/shadowmap_fragment.glsl
  10512. THREE.ShaderChunk[ 'shadowmap_fragment'] = "#ifdef USE_SHADOWMAP\n\n #ifdef SHADOWMAP_DEBUG\n\n vec3 frustumColors[3];\n frustumColors[0] = vec3( 1.0, 0.5, 0.0 );\n frustumColors[1] = vec3( 0.0, 1.0, 0.8 );\n frustumColors[2] = vec3( 0.0, 0.5, 1.0 );\n\n #endif\n\n #ifdef SHADOWMAP_CASCADE\n\n int inFrustumCount = 0;\n\n #endif\n\n float fDepth;\n vec3 shadowColor = vec3( 1.0 );\n\n for( int i = 0; i < MAX_SHADOWS; i ++ ) {\n\n vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;\n\n // if ( something && something ) breaks ATI OpenGL shader compiler\n // if ( all( something, something ) ) using this instead\n\n bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n bool inFrustum = all( inFrustumVec );\n\n // don't shadow pixels outside of light frustum\n // use just first frustum (for cascades)\n // don't shadow pixels behind far plane of light frustum\n\n #ifdef SHADOWMAP_CASCADE\n\n inFrustumCount += int( inFrustum );\n bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );\n\n #else\n\n bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\n #endif\n\n bool frustumTest = all( frustumTestVec );\n\n if ( frustumTest ) {\n\n shadowCoord.z += shadowBias[ i ];\n\n #if defined( SHADOWMAP_TYPE_PCF )\n\n // Percentage-close filtering\n // (9 pixel kernel)\n // http://fabiensanglard.net/shadowmappingPCF/\n\n float shadow = 0.0;\n\n /*\n // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL\n // must enroll loop manually\n\n for ( float y = -1.25; y <= 1.25; y += 1.25 )\n for ( float x = -1.25; x <= 1.25; x += 1.25 ) {\n\n vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );\n\n // doesn't seem to produce any noticeable visual difference compared to simple texture2D lookup\n //vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );\n\n float fDepth = unpackDepth( rgbaDepth );\n\n if ( fDepth < shadowCoord.z )\n shadow += 1.0;\n\n }\n\n shadow /= 9.0;\n\n */\n\n const float shadowDelta = 1.0 / 9.0;\n\n float xPixelOffset = 1.0 / shadowMapSize[ i ].x;\n float yPixelOffset = 1.0 / shadowMapSize[ i ].y;\n\n float dx0 = -1.25 * xPixelOffset;\n float dy0 = -1.25 * yPixelOffset;\n float dx1 = 1.25 * xPixelOffset;\n float dy1 = 1.25 * yPixelOffset;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );\n\n #elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\n // Percentage-close filtering\n // (9 pixel kernel)\n // http://fabiensanglard.net/shadowmappingPCF/\n\n float shadow = 0.0;\n\n float xPixelOffset = 1.0 / shadowMapSize[ i ].x;\n float yPixelOffset = 1.0 / shadowMapSize[ i ].y;\n\n float dx0 = -1.0 * xPixelOffset;\n float dy0 = -1.0 * yPixelOffset;\n float dx1 = 1.0 * xPixelOffset;\n float dy1 = 1.0 * yPixelOffset;\n\n mat3 shadowKernel;\n mat3 depthKernel;\n\n depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );\n depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );\n depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );\n depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );\n depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );\n depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );\n depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );\n depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );\n depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );\n\n vec3 shadowZ = vec3( shadowCoord.z );\n shadowKernel[0] = vec3(lessThan(depthKernel[0], shadowZ ));\n shadowKernel[0] *= vec3(0.25);\n\n shadowKernel[1] = vec3(lessThan(depthKernel[1], shadowZ ));\n shadowKernel[1] *= vec3(0.25);\n\n shadowKernel[2] = vec3(lessThan(depthKernel[2], shadowZ ));\n shadowKernel[2] *= vec3(0.25);\n\n vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );\n\n shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );\n shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );\n\n vec4 shadowValues;\n shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );\n shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );\n shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );\n shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );\n\n shadow = dot( shadowValues, vec4( 1.0 ) );\n\n shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );\n\n #else\n\n vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );\n float fDepth = unpackDepth( rgbaDepth );\n\n if ( fDepth < shadowCoord.z )\n\n // spot with multiple shadows is darker\n\n shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );\n\n // spot with multiple shadows has the same color as single shadow spot\n\n // shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );\n\n #endif\n\n }\n\n\n #ifdef SHADOWMAP_DEBUG\n\n #ifdef SHADOWMAP_CASCADE\n\n if ( inFrustum && inFrustumCount == 1 ) outgoingLight *= frustumColors[ i ];\n\n #else\n\n if ( inFrustum ) outgoingLight *= frustumColors[ i ];\n\n #endif\n\n #endif\n\n }\n\n // NOTE: I am unsure if this is correct in linear space. -bhouston, Dec 29, 2014\n shadowColor = inputToLinear( shadowColor );\n\n outgoingLight = outgoingLight * shadowColor;\n\n#endif\n";
  10513. // File:src/renderers/shaders/ShaderChunk/shadowmap_pars_fragment.glsl
  10514. THREE.ShaderChunk[ 'shadowmap_pars_fragment'] = "#ifdef USE_SHADOWMAP\n\n uniform sampler2D shadowMap[ MAX_SHADOWS ];\n uniform vec2 shadowMapSize[ MAX_SHADOWS ];\n\n uniform float shadowDarkness[ MAX_SHADOWS ];\n uniform float shadowBias[ MAX_SHADOWS ];\n\n varying vec4 vShadowCoord[ MAX_SHADOWS ];\n\n float unpackDepth( const in vec4 rgba_depth ) {\n\n const vec4 bit_shift = vec4( 1.0 / ( 256.0 * 256.0 * 256.0 ), 1.0 / ( 256.0 * 256.0 ), 1.0 / 256.0, 1.0 );\n float depth = dot( rgba_depth, bit_shift );\n return depth;\n\n }\n\n#endif";
  10515. // File:src/renderers/shaders/ShaderChunk/shadowmap_pars_vertex.glsl
  10516. THREE.ShaderChunk[ 'shadowmap_pars_vertex'] = "#ifdef USE_SHADOWMAP\n\n varying vec4 vShadowCoord[ MAX_SHADOWS ];\n uniform mat4 shadowMatrix[ MAX_SHADOWS ];\n\n#endif";
  10517. // File:src/renderers/shaders/ShaderChunk/shadowmap_vertex.glsl
  10518. THREE.ShaderChunk[ 'shadowmap_vertex'] = "#ifdef USE_SHADOWMAP\n\n for( int i = 0; i < MAX_SHADOWS; i ++ ) {\n\n vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;\n\n }\n\n#endif";
  10519. // File:src/renderers/shaders/ShaderChunk/skinbase_vertex.glsl
  10520. THREE.ShaderChunk[ 'skinbase_vertex'] = "#ifdef USE_SKINNING\n\n mat4 boneMatX = getBoneMatrix( skinIndex.x );\n mat4 boneMatY = getBoneMatrix( skinIndex.y );\n mat4 boneMatZ = getBoneMatrix( skinIndex.z );\n mat4 boneMatW = getBoneMatrix( skinIndex.w );\n\n#endif";
  10521. // File:src/renderers/shaders/ShaderChunk/skinning_pars_vertex.glsl
  10522. THREE.ShaderChunk[ 'skinning_pars_vertex'] = "#ifdef USE_SKINNING\n\n uniform mat4 bindMatrix;\n uniform mat4 bindMatrixInverse;\n\n #ifdef BONE_TEXTURE\n\n uniform sampler2D boneTexture;\n uniform int boneTextureWidth;\n uniform int boneTextureHeight;\n\n mat4 getBoneMatrix( const in float i ) {\n\n float j = i * 4.0;\n float x = mod( j, float( boneTextureWidth ) );\n float y = floor( j / float( boneTextureWidth ) );\n\n float dx = 1.0 / float( boneTextureWidth );\n float dy = 1.0 / float( boneTextureHeight );\n\n y = dy * ( y + 0.5 );\n\n vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\n mat4 bone = mat4( v1, v2, v3, v4 );\n\n return bone;\n\n }\n\n #else\n\n uniform mat4 boneGlobalMatrices[ MAX_BONES ];\n\n mat4 getBoneMatrix( const in float i ) {\n\n mat4 bone = boneGlobalMatrices[ int(i) ];\n return bone;\n\n }\n\n #endif\n\n#endif\n";
  10523. // File:src/renderers/shaders/ShaderChunk/skinning_vertex.glsl
  10524. THREE.ShaderChunk[ 'skinning_vertex'] = "#ifdef USE_SKINNING\n\n #ifdef USE_MORPHTARGETS\n\n vec4 skinVertex = bindMatrix * vec4( morphed, 1.0 );\n\n #else\n\n vec4 skinVertex = bindMatrix * vec4( position, 1.0 );\n\n #endif\n\n vec4 skinned = vec4( 0.0 );\n skinned += boneMatX * skinVertex * skinWeight.x;\n skinned += boneMatY * skinVertex * skinWeight.y;\n skinned += boneMatZ * skinVertex * skinWeight.z;\n skinned += boneMatW * skinVertex * skinWeight.w;\n skinned = bindMatrixInverse * skinned;\n\n#endif\n";
  10525. // File:src/renderers/shaders/ShaderChunk/skinnormal_vertex.glsl
  10526. THREE.ShaderChunk[ 'skinnormal_vertex'] = "#ifdef USE_SKINNING\n\n mat4 skinMatrix = mat4( 0.0 );\n skinMatrix += skinWeight.x * boneMatX;\n skinMatrix += skinWeight.y * boneMatY;\n skinMatrix += skinWeight.z * boneMatZ;\n skinMatrix += skinWeight.w * boneMatW;\n skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\n #ifdef USE_MORPHNORMALS\n\n vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );\n\n #else\n\n vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );\n\n #endif\n\n#endif\n";
  10527. // File:src/renderers/shaders/ShaderChunk/specularmap_fragment.glsl
  10528. THREE.ShaderChunk[ 'specularmap_fragment'] = "float specularStrength;\n\n#ifdef USE_SPECULARMAP\n\n vec4 texelSpecular = texture2D( specularMap, vUv );\n specularStrength = texelSpecular.r;\n\n#else\n\n specularStrength = 1.0;\n\n#endif";
  10529. // File:src/renderers/shaders/ShaderChunk/specularmap_pars_fragment.glsl
  10530. THREE.ShaderChunk[ 'specularmap_pars_fragment'] = "#ifdef USE_SPECULARMAP\n\n uniform sampler2D specularMap;\n\n#endif";
  10531. // File:src/renderers/shaders/ShaderChunk/uv2_pars_fragment.glsl
  10532. THREE.ShaderChunk[ 'uv2_pars_fragment'] = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\n varying vec2 vUv2;\n\n#endif";
  10533. // File:src/renderers/shaders/ShaderChunk/uv2_pars_vertex.glsl
  10534. THREE.ShaderChunk[ 'uv2_pars_vertex'] = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\n attribute vec2 uv2;\n varying vec2 vUv2;\n\n#endif";
  10535. // File:src/renderers/shaders/ShaderChunk/uv2_vertex.glsl
  10536. THREE.ShaderChunk[ 'uv2_vertex'] = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\n vUv2 = uv2;\n\n#endif";
  10537. // File:src/renderers/shaders/ShaderChunk/uv_pars_fragment.glsl
  10538. THREE.ShaderChunk[ 'uv_pars_fragment'] = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP )\n\n varying vec2 vUv;\n\n#endif";
  10539. // File:src/renderers/shaders/ShaderChunk/uv_pars_vertex.glsl
  10540. THREE.ShaderChunk[ 'uv_pars_vertex'] = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP )\n\n varying vec2 vUv;\n uniform vec4 offsetRepeat;\n\n#endif\n";
  10541. // File:src/renderers/shaders/ShaderChunk/uv_vertex.glsl
  10542. THREE.ShaderChunk[ 'uv_vertex'] = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP )\n\n vUv = uv * offsetRepeat.zw + offsetRepeat.xy;\n\n#endif";
  10543. // File:src/renderers/shaders/ShaderChunk/worldpos_vertex.glsl
  10544. THREE.ShaderChunk[ 'worldpos_vertex'] = "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )\n\n #ifdef USE_SKINNING\n\n vec4 worldPosition = modelMatrix * skinned;\n\n #elif defined( USE_MORPHTARGETS )\n\n vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );\n\n #else\n\n vec4 worldPosition = modelMatrix * vec4( position, 1.0 );\n\n #endif\n\n#endif\n";
  10545. // File:src/renderers/shaders/UniformsUtils.js
  10546. /**
  10547. * Uniform Utilities
  10548. */
  10549. THREE.UniformsUtils = {
  10550. merge: function ( uniforms ) {
  10551. var merged = {};
  10552. for ( var u = 0; u < uniforms.length; u ++ ) {
  10553. var tmp = this.clone( uniforms[ u ] );
  10554. for ( var p in tmp ) {
  10555. merged[ p ] = tmp[ p ];
  10556. }
  10557. }
  10558. return merged;
  10559. },
  10560. clone: function ( uniforms_src ) {
  10561. var uniforms_dst = {};
  10562. for ( var u in uniforms_src ) {
  10563. uniforms_dst[ u ] = {};
  10564. for ( var p in uniforms_src[ u ] ) {
  10565. var parameter_src = uniforms_src[ u ][ p ];
  10566. if ( parameter_src instanceof THREE.Color ||
  10567. parameter_src instanceof THREE.Vector2 ||
  10568. parameter_src instanceof THREE.Vector3 ||
  10569. parameter_src instanceof THREE.Vector4 ||
  10570. parameter_src instanceof THREE.Matrix3 ||
  10571. parameter_src instanceof THREE.Matrix4 ||
  10572. parameter_src instanceof THREE.Texture ) {
  10573. uniforms_dst[ u ][ p ] = parameter_src.clone();
  10574. } else if ( Array.isArray( parameter_src ) ) {
  10575. uniforms_dst[ u ][ p ] = parameter_src.slice();
  10576. } else {
  10577. uniforms_dst[ u ][ p ] = parameter_src;
  10578. }
  10579. }
  10580. }
  10581. return uniforms_dst;
  10582. }
  10583. };
  10584. // File:src/renderers/shaders/UniformsLib.js
  10585. /**
  10586. * Uniforms library for shared webgl shaders
  10587. */
  10588. THREE.UniformsLib = {
  10589. common: {
  10590. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10591. "opacity" : { type: "f", value: 1.0 },
  10592. "map" : { type: "t", value: null },
  10593. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  10594. "specularMap" : { type: "t", value: null },
  10595. "alphaMap" : { type: "t", value: null },
  10596. "envMap" : { type: "t", value: null },
  10597. "flipEnvMap" : { type: "f", value: - 1 },
  10598. "reflectivity" : { type: "f", value: 1.0 },
  10599. "refractionRatio" : { type: "f", value: 0.98 }
  10600. },
  10601. aomap: {
  10602. "aoMap" : { type: "t", value: null },
  10603. "aoMapIntensity" : { type: "f", value: 1 },
  10604. },
  10605. lightmap: {
  10606. "lightMap" : { type: "t", value: null },
  10607. "lightMapIntensity" : { type: "f", value: 1 },
  10608. },
  10609. bump: {
  10610. "bumpMap" : { type: "t", value: null },
  10611. "bumpScale" : { type: "f", value: 1 }
  10612. },
  10613. normalmap: {
  10614. "normalMap" : { type: "t", value: null },
  10615. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  10616. },
  10617. fog : {
  10618. "fogDensity" : { type: "f", value: 0.00025 },
  10619. "fogNear" : { type: "f", value: 1 },
  10620. "fogFar" : { type: "f", value: 2000 },
  10621. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10622. },
  10623. lights: {
  10624. "ambientLightColor" : { type: "fv", value: [] },
  10625. "directionalLightDirection" : { type: "fv", value: [] },
  10626. "directionalLightColor" : { type: "fv", value: [] },
  10627. "hemisphereLightDirection" : { type: "fv", value: [] },
  10628. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  10629. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  10630. "pointLightColor" : { type: "fv", value: [] },
  10631. "pointLightPosition" : { type: "fv", value: [] },
  10632. "pointLightDistance" : { type: "fv1", value: [] },
  10633. "pointLightDecay" : { type: "fv1", value: [] },
  10634. "spotLightColor" : { type: "fv", value: [] },
  10635. "spotLightPosition" : { type: "fv", value: [] },
  10636. "spotLightDirection" : { type: "fv", value: [] },
  10637. "spotLightDistance" : { type: "fv1", value: [] },
  10638. "spotLightAngleCos" : { type: "fv1", value: [] },
  10639. "spotLightExponent" : { type: "fv1", value: [] },
  10640. "spotLightDecay" : { type: "fv1", value: [] }
  10641. },
  10642. particle: {
  10643. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10644. "opacity" : { type: "f", value: 1.0 },
  10645. "size" : { type: "f", value: 1.0 },
  10646. "scale" : { type: "f", value: 1.0 },
  10647. "map" : { type: "t", value: null },
  10648. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  10649. "fogDensity" : { type: "f", value: 0.00025 },
  10650. "fogNear" : { type: "f", value: 1 },
  10651. "fogFar" : { type: "f", value: 2000 },
  10652. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10653. },
  10654. shadowmap: {
  10655. "shadowMap": { type: "tv", value: [] },
  10656. "shadowMapSize": { type: "v2v", value: [] },
  10657. "shadowBias" : { type: "fv1", value: [] },
  10658. "shadowDarkness": { type: "fv1", value: [] },
  10659. "shadowMatrix" : { type: "m4v", value: [] }
  10660. }
  10661. };
  10662. // File:src/renderers/shaders/ShaderLib.js
  10663. /**
  10664. * Webgl Shader Library for three.js
  10665. *
  10666. * @author alteredq / http://alteredqualia.com/
  10667. * @author mrdoob / http://mrdoob.com/
  10668. * @author mikael emtinger / http://gomo.se/
  10669. */
  10670. THREE.ShaderLib = {
  10671. 'basic': {
  10672. uniforms: THREE.UniformsUtils.merge( [
  10673. THREE.UniformsLib[ "common" ],
  10674. THREE.UniformsLib[ "aomap" ],
  10675. THREE.UniformsLib[ "fog" ],
  10676. THREE.UniformsLib[ "shadowmap" ]
  10677. ] ),
  10678. vertexShader: [
  10679. THREE.ShaderChunk[ "common" ],
  10680. THREE.ShaderChunk[ "uv_pars_vertex" ],
  10681. THREE.ShaderChunk[ "uv2_pars_vertex" ],
  10682. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10683. THREE.ShaderChunk[ "color_pars_vertex" ],
  10684. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10685. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10686. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10687. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  10688. "void main() {",
  10689. THREE.ShaderChunk[ "uv_vertex" ],
  10690. THREE.ShaderChunk[ "uv2_vertex" ],
  10691. THREE.ShaderChunk[ "color_vertex" ],
  10692. THREE.ShaderChunk[ "skinbase_vertex" ],
  10693. " #ifdef USE_ENVMAP",
  10694. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10695. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10696. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10697. " #endif",
  10698. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10699. THREE.ShaderChunk[ "skinning_vertex" ],
  10700. THREE.ShaderChunk[ "default_vertex" ],
  10701. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  10702. THREE.ShaderChunk[ "worldpos_vertex" ],
  10703. THREE.ShaderChunk[ "envmap_vertex" ],
  10704. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10705. "}"
  10706. ].join("\n"),
  10707. fragmentShader: [
  10708. "uniform vec3 diffuse;",
  10709. "uniform float opacity;",
  10710. THREE.ShaderChunk[ "common" ],
  10711. THREE.ShaderChunk[ "color_pars_fragment" ],
  10712. THREE.ShaderChunk[ "uv_pars_fragment" ],
  10713. THREE.ShaderChunk[ "uv2_pars_fragment" ],
  10714. THREE.ShaderChunk[ "map_pars_fragment" ],
  10715. THREE.ShaderChunk[ "alphamap_pars_fragment" ],
  10716. THREE.ShaderChunk[ "aomap_pars_fragment" ],
  10717. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10718. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10719. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10720. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10721. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  10722. "void main() {",
  10723. " vec3 outgoingLight = vec3( 0.0 );",
  10724. " vec4 diffuseColor = vec4( diffuse, opacity );",
  10725. " vec3 totalAmbientLight = vec3( 1.0 );", // hardwired
  10726. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  10727. THREE.ShaderChunk[ "map_fragment" ],
  10728. THREE.ShaderChunk[ "color_fragment" ],
  10729. THREE.ShaderChunk[ "alphamap_fragment" ],
  10730. THREE.ShaderChunk[ "alphatest_fragment" ],
  10731. THREE.ShaderChunk[ "specularmap_fragment" ],
  10732. THREE.ShaderChunk[ "aomap_fragment" ],
  10733. " outgoingLight = diffuseColor.rgb * totalAmbientLight;", // simple shader
  10734. THREE.ShaderChunk[ "envmap_fragment" ],
  10735. THREE.ShaderChunk[ "shadowmap_fragment" ], // TODO: Shadows on an otherwise unlit surface doesn't make sense.
  10736. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10737. THREE.ShaderChunk[ "fog_fragment" ],
  10738. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );", // TODO, this should be pre-multiplied to allow for bright highlights on very transparent objects
  10739. "}"
  10740. ].join("\n")
  10741. },
  10742. 'lambert': {
  10743. uniforms: THREE.UniformsUtils.merge( [
  10744. THREE.UniformsLib[ "common" ],
  10745. THREE.UniformsLib[ "fog" ],
  10746. THREE.UniformsLib[ "lights" ],
  10747. THREE.UniformsLib[ "shadowmap" ],
  10748. {
  10749. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) }
  10750. }
  10751. ] ),
  10752. vertexShader: [
  10753. "#define LAMBERT",
  10754. "varying vec3 vLightFront;",
  10755. "#ifdef DOUBLE_SIDED",
  10756. " varying vec3 vLightBack;",
  10757. "#endif",
  10758. THREE.ShaderChunk[ "common" ],
  10759. THREE.ShaderChunk[ "uv_pars_vertex" ],
  10760. THREE.ShaderChunk[ "uv2_pars_vertex" ],
  10761. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10762. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  10763. THREE.ShaderChunk[ "color_pars_vertex" ],
  10764. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10765. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10766. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10767. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  10768. "void main() {",
  10769. THREE.ShaderChunk[ "uv_vertex" ],
  10770. THREE.ShaderChunk[ "uv2_vertex" ],
  10771. THREE.ShaderChunk[ "color_vertex" ],
  10772. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10773. THREE.ShaderChunk[ "skinbase_vertex" ],
  10774. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10775. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10776. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10777. THREE.ShaderChunk[ "skinning_vertex" ],
  10778. THREE.ShaderChunk[ "default_vertex" ],
  10779. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  10780. THREE.ShaderChunk[ "worldpos_vertex" ],
  10781. THREE.ShaderChunk[ "envmap_vertex" ],
  10782. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  10783. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10784. "}"
  10785. ].join("\n"),
  10786. fragmentShader: [
  10787. "uniform vec3 diffuse;",
  10788. "uniform vec3 emissive;",
  10789. "uniform float opacity;",
  10790. "varying vec3 vLightFront;",
  10791. "#ifdef DOUBLE_SIDED",
  10792. " varying vec3 vLightBack;",
  10793. "#endif",
  10794. THREE.ShaderChunk[ "common" ],
  10795. THREE.ShaderChunk[ "color_pars_fragment" ],
  10796. THREE.ShaderChunk[ "uv_pars_fragment" ],
  10797. THREE.ShaderChunk[ "uv2_pars_fragment" ],
  10798. THREE.ShaderChunk[ "map_pars_fragment" ],
  10799. THREE.ShaderChunk[ "alphamap_pars_fragment" ],
  10800. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10801. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10802. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10803. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10804. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  10805. "void main() {",
  10806. " vec3 outgoingLight = vec3( 0.0 );", // outgoing light does not have an alpha, the surface does
  10807. " vec4 diffuseColor = vec4( diffuse, opacity );",
  10808. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  10809. THREE.ShaderChunk[ "map_fragment" ],
  10810. THREE.ShaderChunk[ "color_fragment" ],
  10811. THREE.ShaderChunk[ "alphamap_fragment" ],
  10812. THREE.ShaderChunk[ "alphatest_fragment" ],
  10813. THREE.ShaderChunk[ "specularmap_fragment" ],
  10814. " #ifdef DOUBLE_SIDED",
  10815. //"float isFront = float( gl_FrontFacing );",
  10816. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  10817. " if ( gl_FrontFacing )",
  10818. " outgoingLight += diffuseColor.rgb * vLightFront + emissive;",
  10819. " else",
  10820. " outgoingLight += diffuseColor.rgb * vLightBack + emissive;",
  10821. " #else",
  10822. " outgoingLight += diffuseColor.rgb * vLightFront + emissive;",
  10823. " #endif",
  10824. THREE.ShaderChunk[ "envmap_fragment" ],
  10825. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10826. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10827. THREE.ShaderChunk[ "fog_fragment" ],
  10828. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );", // TODO, this should be pre-multiplied to allow for bright highlights on very transparent objects
  10829. "}"
  10830. ].join("\n")
  10831. },
  10832. 'phong': {
  10833. uniforms: THREE.UniformsUtils.merge( [
  10834. THREE.UniformsLib[ "common" ],
  10835. THREE.UniformsLib[ "aomap" ],
  10836. THREE.UniformsLib[ "lightmap" ],
  10837. THREE.UniformsLib[ "bump" ],
  10838. THREE.UniformsLib[ "normalmap" ],
  10839. THREE.UniformsLib[ "fog" ],
  10840. THREE.UniformsLib[ "lights" ],
  10841. THREE.UniformsLib[ "shadowmap" ],
  10842. {
  10843. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10844. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  10845. "shininess": { type: "f", value: 30 }
  10846. }
  10847. ] ),
  10848. vertexShader: [
  10849. "#define PHONG",
  10850. "varying vec3 vViewPosition;",
  10851. "#ifndef FLAT_SHADED",
  10852. " varying vec3 vNormal;",
  10853. "#endif",
  10854. THREE.ShaderChunk[ "common" ],
  10855. THREE.ShaderChunk[ "uv_pars_vertex" ],
  10856. THREE.ShaderChunk[ "uv2_pars_vertex" ],
  10857. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10858. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  10859. THREE.ShaderChunk[ "color_pars_vertex" ],
  10860. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10861. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10862. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10863. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  10864. "void main() {",
  10865. THREE.ShaderChunk[ "uv_vertex" ],
  10866. THREE.ShaderChunk[ "uv2_vertex" ],
  10867. THREE.ShaderChunk[ "color_vertex" ],
  10868. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10869. THREE.ShaderChunk[ "skinbase_vertex" ],
  10870. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10871. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10872. "#ifndef FLAT_SHADED", // Normal computed with derivatives when FLAT_SHADED
  10873. " vNormal = normalize( transformedNormal );",
  10874. "#endif",
  10875. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10876. THREE.ShaderChunk[ "skinning_vertex" ],
  10877. THREE.ShaderChunk[ "default_vertex" ],
  10878. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  10879. " vViewPosition = -mvPosition.xyz;",
  10880. THREE.ShaderChunk[ "worldpos_vertex" ],
  10881. THREE.ShaderChunk[ "envmap_vertex" ],
  10882. THREE.ShaderChunk[ "lights_phong_vertex" ],
  10883. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10884. "}"
  10885. ].join("\n"),
  10886. fragmentShader: [
  10887. "#define PHONG",
  10888. "uniform vec3 diffuse;",
  10889. "uniform vec3 emissive;",
  10890. "uniform vec3 specular;",
  10891. "uniform float shininess;",
  10892. "uniform float opacity;",
  10893. THREE.ShaderChunk[ "common" ],
  10894. THREE.ShaderChunk[ "color_pars_fragment" ],
  10895. THREE.ShaderChunk[ "uv_pars_fragment" ],
  10896. THREE.ShaderChunk[ "uv2_pars_fragment" ],
  10897. THREE.ShaderChunk[ "map_pars_fragment" ],
  10898. THREE.ShaderChunk[ "alphamap_pars_fragment" ],
  10899. THREE.ShaderChunk[ "aomap_pars_fragment" ],
  10900. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10901. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10902. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10903. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  10904. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10905. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  10906. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  10907. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10908. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  10909. "void main() {",
  10910. " vec3 outgoingLight = vec3( 0.0 );", // outgoing light does not have an alpha, the surface does
  10911. " vec4 diffuseColor = vec4( diffuse, opacity );",
  10912. " vec3 totalAmbientLight = ambientLightColor;",
  10913. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  10914. THREE.ShaderChunk[ "map_fragment" ],
  10915. THREE.ShaderChunk[ "color_fragment" ],
  10916. THREE.ShaderChunk[ "alphamap_fragment" ],
  10917. THREE.ShaderChunk[ "alphatest_fragment" ],
  10918. THREE.ShaderChunk[ "specularmap_fragment" ],
  10919. THREE.ShaderChunk[ "lightmap_fragment" ],
  10920. THREE.ShaderChunk[ "aomap_fragment" ],
  10921. THREE.ShaderChunk[ "lights_phong_fragment" ],
  10922. THREE.ShaderChunk[ "envmap_fragment" ],
  10923. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10924. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10925. THREE.ShaderChunk[ "fog_fragment" ],
  10926. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );", // TODO, this should be pre-multiplied to allow for bright highlights on very transparent objects
  10927. "}"
  10928. ].join("\n")
  10929. },
  10930. 'particle_basic': {
  10931. uniforms: THREE.UniformsUtils.merge( [
  10932. THREE.UniformsLib[ "particle" ],
  10933. THREE.UniformsLib[ "shadowmap" ]
  10934. ] ),
  10935. vertexShader: [
  10936. "uniform float size;",
  10937. "uniform float scale;",
  10938. THREE.ShaderChunk[ "common" ],
  10939. THREE.ShaderChunk[ "color_pars_vertex" ],
  10940. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10941. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  10942. "void main() {",
  10943. THREE.ShaderChunk[ "color_vertex" ],
  10944. " vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10945. " #ifdef USE_SIZEATTENUATION",
  10946. " gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  10947. " #else",
  10948. " gl_PointSize = size;",
  10949. " #endif",
  10950. " gl_Position = projectionMatrix * mvPosition;",
  10951. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  10952. THREE.ShaderChunk[ "worldpos_vertex" ],
  10953. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10954. "}"
  10955. ].join("\n"),
  10956. fragmentShader: [
  10957. "uniform vec3 psColor;",
  10958. "uniform float opacity;",
  10959. THREE.ShaderChunk[ "common" ],
  10960. THREE.ShaderChunk[ "color_pars_fragment" ],
  10961. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  10962. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10963. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10964. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  10965. "void main() {",
  10966. " vec3 outgoingLight = vec3( 0.0 );", // outgoing light does not have an alpha, the surface does
  10967. " vec4 diffuseColor = vec4( psColor, opacity );",
  10968. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  10969. THREE.ShaderChunk[ "map_particle_fragment" ],
  10970. THREE.ShaderChunk[ "color_fragment" ],
  10971. THREE.ShaderChunk[ "alphatest_fragment" ],
  10972. " outgoingLight = diffuseColor.rgb;", // simple shader
  10973. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10974. THREE.ShaderChunk[ "fog_fragment" ],
  10975. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );", // TODO, this should be pre-multiplied to allow for bright highlights on very transparent objects
  10976. "}"
  10977. ].join("\n")
  10978. },
  10979. 'dashed': {
  10980. uniforms: THREE.UniformsUtils.merge( [
  10981. THREE.UniformsLib[ "common" ],
  10982. THREE.UniformsLib[ "fog" ],
  10983. {
  10984. "scale" : { type: "f", value: 1 },
  10985. "dashSize" : { type: "f", value: 1 },
  10986. "totalSize": { type: "f", value: 2 }
  10987. }
  10988. ] ),
  10989. vertexShader: [
  10990. "uniform float scale;",
  10991. "attribute float lineDistance;",
  10992. "varying float vLineDistance;",
  10993. THREE.ShaderChunk[ "common" ],
  10994. THREE.ShaderChunk[ "color_pars_vertex" ],
  10995. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  10996. "void main() {",
  10997. THREE.ShaderChunk[ "color_vertex" ],
  10998. " vLineDistance = scale * lineDistance;",
  10999. " vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  11000. " gl_Position = projectionMatrix * mvPosition;",
  11001. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11002. "}"
  11003. ].join("\n"),
  11004. fragmentShader: [
  11005. "uniform vec3 diffuse;",
  11006. "uniform float opacity;",
  11007. "uniform float dashSize;",
  11008. "uniform float totalSize;",
  11009. "varying float vLineDistance;",
  11010. THREE.ShaderChunk[ "common" ],
  11011. THREE.ShaderChunk[ "color_pars_fragment" ],
  11012. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11013. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11014. "void main() {",
  11015. " if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  11016. " discard;",
  11017. " }",
  11018. " vec3 outgoingLight = vec3( 0.0 );", // outgoing light does not have an alpha, the surface does
  11019. " vec4 diffuseColor = vec4( diffuse, opacity );",
  11020. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11021. THREE.ShaderChunk[ "color_fragment" ],
  11022. " outgoingLight = diffuseColor.rgb;", // simple shader
  11023. THREE.ShaderChunk[ "fog_fragment" ],
  11024. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );", // TODO, this should be pre-multiplied to allow for bright highlights on very transparent objects
  11025. "}"
  11026. ].join("\n")
  11027. },
  11028. 'depth': {
  11029. uniforms: {
  11030. "mNear": { type: "f", value: 1.0 },
  11031. "mFar" : { type: "f", value: 2000.0 },
  11032. "opacity" : { type: "f", value: 1.0 }
  11033. },
  11034. vertexShader: [
  11035. THREE.ShaderChunk[ "common" ],
  11036. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11037. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11038. "void main() {",
  11039. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11040. THREE.ShaderChunk[ "default_vertex" ],
  11041. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11042. "}"
  11043. ].join("\n"),
  11044. fragmentShader: [
  11045. "uniform float mNear;",
  11046. "uniform float mFar;",
  11047. "uniform float opacity;",
  11048. THREE.ShaderChunk[ "common" ],
  11049. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11050. "void main() {",
  11051. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11052. " #ifdef USE_LOGDEPTHBUF_EXT",
  11053. " float depth = gl_FragDepthEXT / gl_FragCoord.w;",
  11054. " #else",
  11055. " float depth = gl_FragCoord.z / gl_FragCoord.w;",
  11056. " #endif",
  11057. " float color = 1.0 - smoothstep( mNear, mFar, depth );",
  11058. " gl_FragColor = vec4( vec3( color ), opacity );", // TODO, this should be pre-multiplied to allow for bright highlights on very transparent objects
  11059. "}"
  11060. ].join("\n")
  11061. },
  11062. 'normal': {
  11063. uniforms: {
  11064. "opacity" : { type: "f", value: 1.0 }
  11065. },
  11066. vertexShader: [
  11067. "varying vec3 vNormal;",
  11068. THREE.ShaderChunk[ "common" ],
  11069. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11070. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11071. "void main() {",
  11072. " vNormal = normalize( normalMatrix * normal );",
  11073. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11074. THREE.ShaderChunk[ "default_vertex" ],
  11075. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11076. "}"
  11077. ].join("\n"),
  11078. fragmentShader: [
  11079. "uniform float opacity;",
  11080. "varying vec3 vNormal;",
  11081. THREE.ShaderChunk[ "common" ],
  11082. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11083. "void main() {",
  11084. " gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  11085. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11086. "}"
  11087. ].join("\n")
  11088. },
  11089. /* -------------------------------------------------------------------------
  11090. // Cube map shader
  11091. ------------------------------------------------------------------------- */
  11092. 'cube': {
  11093. uniforms: { "tCube": { type: "t", value: null },
  11094. "tFlip": { type: "f", value: - 1 } },
  11095. vertexShader: [
  11096. "varying vec3 vWorldPosition;",
  11097. THREE.ShaderChunk[ "common" ],
  11098. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11099. "void main() {",
  11100. " vWorldPosition = transformDirection( position, modelMatrix );",
  11101. " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  11102. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11103. "}"
  11104. ].join("\n"),
  11105. fragmentShader: [
  11106. "uniform samplerCube tCube;",
  11107. "uniform float tFlip;",
  11108. "varying vec3 vWorldPosition;",
  11109. THREE.ShaderChunk[ "common" ],
  11110. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11111. "void main() {",
  11112. " gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  11113. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11114. "}"
  11115. ].join("\n")
  11116. },
  11117. /* -------------------------------------------------------------------------
  11118. // Cube map shader
  11119. ------------------------------------------------------------------------- */
  11120. 'equirect': {
  11121. uniforms: { "tEquirect": { type: "t", value: null },
  11122. "tFlip": { type: "f", value: - 1 } },
  11123. vertexShader: [
  11124. "varying vec3 vWorldPosition;",
  11125. THREE.ShaderChunk[ "common" ],
  11126. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11127. "void main() {",
  11128. " vWorldPosition = transformDirection( position, modelMatrix );",
  11129. " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  11130. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11131. "}"
  11132. ].join("\n"),
  11133. fragmentShader: [
  11134. "uniform sampler2D tEquirect;",
  11135. "uniform float tFlip;",
  11136. "varying vec3 vWorldPosition;",
  11137. THREE.ShaderChunk[ "common" ],
  11138. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11139. "void main() {",
  11140. // " gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  11141. "vec3 direction = normalize( vWorldPosition );",
  11142. "vec2 sampleUV;",
  11143. "sampleUV.y = saturate( tFlip * direction.y * -0.5 + 0.5 );",
  11144. "sampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;",
  11145. "gl_FragColor = texture2D( tEquirect, sampleUV );",
  11146. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11147. "}"
  11148. ].join("\n")
  11149. },
  11150. /* Depth encoding into RGBA texture
  11151. *
  11152. * based on SpiderGL shadow map example
  11153. * http://spidergl.org/example.php?id=6
  11154. *
  11155. * originally from
  11156. * http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  11157. *
  11158. * see also
  11159. * http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  11160. */
  11161. 'depthRGBA': {
  11162. uniforms: {},
  11163. vertexShader: [
  11164. THREE.ShaderChunk[ "common" ],
  11165. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11166. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11167. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11168. "void main() {",
  11169. THREE.ShaderChunk[ "skinbase_vertex" ],
  11170. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11171. THREE.ShaderChunk[ "skinning_vertex" ],
  11172. THREE.ShaderChunk[ "default_vertex" ],
  11173. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11174. "}"
  11175. ].join("\n"),
  11176. fragmentShader: [
  11177. THREE.ShaderChunk[ "common" ],
  11178. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11179. "vec4 pack_depth( const in float depth ) {",
  11180. " const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  11181. " const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  11182. " vec4 res = mod( depth * bit_shift * vec4( 255 ), vec4( 256 ) ) / vec4( 255 );", // " vec4 res = fract( depth * bit_shift );",
  11183. " res -= res.xxyz * bit_mask;",
  11184. " return res;",
  11185. "}",
  11186. "void main() {",
  11187. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11188. " #ifdef USE_LOGDEPTHBUF_EXT",
  11189. " gl_FragData[ 0 ] = pack_depth( gl_FragDepthEXT );",
  11190. " #else",
  11191. " gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  11192. " #endif",
  11193. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  11194. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  11195. //"gl_FragData[ 0 ] = pack_depth( z );",
  11196. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  11197. "}"
  11198. ].join("\n")
  11199. }
  11200. };
  11201. // File:src/renderers/WebGLRenderer.js
  11202. /**
  11203. * @author supereggbert / http://www.paulbrunt.co.uk/
  11204. * @author mrdoob / http://mrdoob.com/
  11205. * @author alteredq / http://alteredqualia.com/
  11206. * @author szimek / https://github.com/szimek/
  11207. */
  11208. THREE.WebGLRenderer = function ( parameters ) {
  11209. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  11210. parameters = parameters || {};
  11211. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  11212. _context = parameters.context !== undefined ? parameters.context : null,
  11213. _width = _canvas.width,
  11214. _height = _canvas.height,
  11215. pixelRatio = 1,
  11216. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  11217. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  11218. _depth = parameters.depth !== undefined ? parameters.depth : true,
  11219. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  11220. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  11221. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  11222. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  11223. _logarithmicDepthBuffer = parameters.logarithmicDepthBuffer !== undefined ? parameters.logarithmicDepthBuffer : false,
  11224. _clearColor = new THREE.Color( 0x000000 ),
  11225. _clearAlpha = 0;
  11226. var lights = [];
  11227. var opaqueObjects = [];
  11228. var transparentObjects = [];
  11229. var sprites = [];
  11230. var lensFlares = [];
  11231. // public properties
  11232. this.domElement = _canvas;
  11233. this.context = null;
  11234. // clearing
  11235. this.autoClear = true;
  11236. this.autoClearColor = true;
  11237. this.autoClearDepth = true;
  11238. this.autoClearStencil = true;
  11239. // scene graph
  11240. this.sortObjects = true;
  11241. // physically based shading
  11242. this.gammaFactor = 2.0; // for backwards compatibility
  11243. this.gammaInput = false;
  11244. this.gammaOutput = false;
  11245. // morphs
  11246. this.maxMorphTargets = 8;
  11247. this.maxMorphNormals = 4;
  11248. // flags
  11249. this.autoScaleCubemaps = true;
  11250. // info
  11251. this.info = {
  11252. memory: {
  11253. programs: 0,
  11254. geometries: 0,
  11255. textures: 0
  11256. },
  11257. render: {
  11258. calls: 0,
  11259. vertices: 0,
  11260. faces: 0,
  11261. points: 0
  11262. }
  11263. };
  11264. // internal properties
  11265. var _this = this,
  11266. _programs = [],
  11267. // internal state cache
  11268. _currentProgram = null,
  11269. _currentFramebuffer = null,
  11270. _currentMaterialId = - 1,
  11271. _currentGeometryProgram = '',
  11272. _currentCamera = null,
  11273. _usedTextureUnits = 0,
  11274. _viewportX = 0,
  11275. _viewportY = 0,
  11276. _viewportWidth = _canvas.width,
  11277. _viewportHeight = _canvas.height,
  11278. _currentWidth = 0,
  11279. _currentHeight = 0,
  11280. // frustum
  11281. _frustum = new THREE.Frustum(),
  11282. // camera matrices cache
  11283. _projScreenMatrix = new THREE.Matrix4(),
  11284. _vector3 = new THREE.Vector3(),
  11285. // light arrays cache
  11286. _direction = new THREE.Vector3(),
  11287. _lightsNeedUpdate = true,
  11288. _lights = {
  11289. ambient: [ 0, 0, 0 ],
  11290. directional: { length: 0, colors:[], positions: [] },
  11291. point: { length: 0, colors: [], positions: [], distances: [], decays: [] },
  11292. spot: { length: 0, colors: [], positions: [], distances: [], directions: [], anglesCos: [], exponents: [], decays: [] },
  11293. hemi: { length: 0, skyColors: [], groundColors: [], positions: [] }
  11294. };
  11295. // initialize
  11296. var _gl;
  11297. try {
  11298. var attributes = {
  11299. alpha: _alpha,
  11300. depth: _depth,
  11301. stencil: _stencil,
  11302. antialias: _antialias,
  11303. premultipliedAlpha: _premultipliedAlpha,
  11304. preserveDrawingBuffer: _preserveDrawingBuffer
  11305. };
  11306. _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  11307. if ( _gl === null ) {
  11308. if ( _canvas.getContext( 'webgl') !== null ) {
  11309. throw 'Error creating WebGL context with your selected attributes.';
  11310. } else {
  11311. throw 'Error creating WebGL context.';
  11312. }
  11313. }
  11314. _canvas.addEventListener( 'webglcontextlost', function ( event ) {
  11315. event.preventDefault();
  11316. resetGLState();
  11317. setDefaultGLState();
  11318. objects.objects = {};
  11319. }, false);
  11320. } catch ( error ) {
  11321. console.error( 'THREE.WebGLRenderer: ' + error );
  11322. }
  11323. var state = new THREE.WebGLState( _gl, paramThreeToGL );
  11324. if ( _gl.getShaderPrecisionFormat === undefined ) {
  11325. _gl.getShaderPrecisionFormat = function () {
  11326. return {
  11327. 'rangeMin': 1,
  11328. 'rangeMax': 1,
  11329. 'precision': 1
  11330. };
  11331. }
  11332. }
  11333. var extensions = new THREE.WebGLExtensions( _gl );
  11334. var objects = new THREE.WebGLObjects( _gl, this.info );
  11335. extensions.get( 'OES_texture_float' );
  11336. extensions.get( 'OES_texture_float_linear' );
  11337. extensions.get( 'OES_texture_half_float' );
  11338. extensions.get( 'OES_texture_half_float_linear' );
  11339. extensions.get( 'OES_standard_derivatives' );
  11340. extensions.get( 'ANGLE_instanced_arrays' );
  11341. if ( extensions.get( 'OES_element_index_uint' ) ) {
  11342. THREE.BufferGeometry.MaxIndex = 4294967296;
  11343. }
  11344. if ( _logarithmicDepthBuffer ) {
  11345. extensions.get( 'EXT_frag_depth' );
  11346. }
  11347. //
  11348. var glClearColor = function ( r, g, b, a ) {
  11349. if ( _premultipliedAlpha === true ) {
  11350. r *= a; g *= a; b *= a;
  11351. }
  11352. _gl.clearColor( r, g, b, a );
  11353. };
  11354. var setDefaultGLState = function () {
  11355. _gl.clearColor( 0, 0, 0, 1 );
  11356. _gl.clearDepth( 1 );
  11357. _gl.clearStencil( 0 );
  11358. _gl.enable( _gl.DEPTH_TEST );
  11359. _gl.depthFunc( _gl.LEQUAL );
  11360. _gl.frontFace( _gl.CCW );
  11361. _gl.cullFace( _gl.BACK );
  11362. _gl.enable( _gl.CULL_FACE );
  11363. _gl.enable( _gl.BLEND );
  11364. _gl.blendEquation( _gl.FUNC_ADD );
  11365. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  11366. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  11367. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  11368. };
  11369. var resetGLState = function () {
  11370. _currentProgram = null;
  11371. _currentCamera = null;
  11372. _currentGeometryProgram = '';
  11373. _currentMaterialId = - 1;
  11374. _lightsNeedUpdate = true;
  11375. state.reset();
  11376. };
  11377. setDefaultGLState();
  11378. this.context = _gl;
  11379. this.extensions = extensions;
  11380. this.state = state;
  11381. // shadow map
  11382. var shadowMap = new THREE.WebGLShadowMap( this, lights, objects );
  11383. this.shadowMap = shadowMap;
  11384. // GPU capabilities
  11385. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  11386. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  11387. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  11388. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  11389. var _supportsVertexTextures = _maxVertexTextures > 0;
  11390. var _supportsBoneTextures = _supportsVertexTextures && extensions.get( 'OES_texture_float' );
  11391. var _supportsInstancedArrays = extensions.get( 'ANGLE_instanced_arrays' );
  11392. //
  11393. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  11394. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  11395. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  11396. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  11397. var getCompressedTextureFormats = ( function () {
  11398. var array;
  11399. return function () {
  11400. if ( array !== undefined ) {
  11401. return array;
  11402. }
  11403. array = [];
  11404. if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) || extensions.get( 'WEBGL_compressed_texture_s3tc' ) ) {
  11405. var formats = _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS );
  11406. for ( var i = 0; i < formats.length; i ++ ) {
  11407. array.push( formats[ i ] );
  11408. }
  11409. }
  11410. return array;
  11411. };
  11412. } )();
  11413. // clamp precision to maximum available
  11414. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  11415. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  11416. if ( _precision === 'highp' && ! highpAvailable ) {
  11417. if ( mediumpAvailable ) {
  11418. _precision = 'mediump';
  11419. console.warn( 'THREE.WebGLRenderer: highp not supported, using mediump.' );
  11420. } else {
  11421. _precision = 'lowp';
  11422. console.warn( 'THREE.WebGLRenderer: highp and mediump not supported, using lowp.' );
  11423. }
  11424. }
  11425. if ( _precision === 'mediump' && ! mediumpAvailable ) {
  11426. _precision = 'lowp';
  11427. console.warn( 'THREE.WebGLRenderer: mediump not supported, using lowp.' );
  11428. }
  11429. // Plugins
  11430. var spritePlugin = new THREE.SpritePlugin( this, sprites );
  11431. var lensFlarePlugin = new THREE.LensFlarePlugin( this, lensFlares );
  11432. // API
  11433. this.getContext = function () {
  11434. return _gl;
  11435. };
  11436. this.forceContextLoss = function () {
  11437. extensions.get( 'WEBGL_lose_context' ).loseContext();
  11438. };
  11439. this.supportsVertexTextures = function () {
  11440. return _supportsVertexTextures;
  11441. };
  11442. this.supportsInstancedArrays = function () {
  11443. return _supportsInstancedArrays;
  11444. };
  11445. this.supportsFloatTextures = function () {
  11446. return extensions.get( 'OES_texture_float' );
  11447. };
  11448. this.supportsHalfFloatTextures = function () {
  11449. return extensions.get( 'OES_texture_half_float' );
  11450. };
  11451. this.supportsStandardDerivatives = function () {
  11452. return extensions.get( 'OES_standard_derivatives' );
  11453. };
  11454. this.supportsCompressedTextureS3TC = function () {
  11455. return extensions.get( 'WEBGL_compressed_texture_s3tc' );
  11456. };
  11457. this.supportsCompressedTexturePVRTC = function () {
  11458. return extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  11459. };
  11460. this.supportsBlendMinMax = function () {
  11461. return extensions.get( 'EXT_blend_minmax' );
  11462. };
  11463. this.getMaxAnisotropy = ( function () {
  11464. var value;
  11465. return function () {
  11466. if ( value !== undefined ) return value;
  11467. var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  11468. if ( extension !== null ) {
  11469. value = _gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  11470. } else {
  11471. value = 0;
  11472. }
  11473. return value;
  11474. }
  11475. } )();
  11476. this.getPrecision = function () {
  11477. return _precision;
  11478. };
  11479. this.getPixelRatio = function () {
  11480. return pixelRatio;
  11481. };
  11482. this.setPixelRatio = function ( value ) {
  11483. pixelRatio = value;
  11484. };
  11485. this.getSize = function () {
  11486. return {
  11487. width: _width,
  11488. height: _height
  11489. };
  11490. };
  11491. this.setSize = function ( width, height, updateStyle ) {
  11492. _width = width;
  11493. _height = height;
  11494. _canvas.width = width * pixelRatio;
  11495. _canvas.height = height * pixelRatio;
  11496. if ( updateStyle !== false ) {
  11497. _canvas.style.width = width + 'px';
  11498. _canvas.style.height = height + 'px';
  11499. }
  11500. this.setViewport( 0, 0, width, height );
  11501. };
  11502. this.setViewport = function ( x, y, width, height ) {
  11503. _viewportX = x * pixelRatio;
  11504. _viewportY = y * pixelRatio;
  11505. _viewportWidth = width * pixelRatio;
  11506. _viewportHeight = height * pixelRatio;
  11507. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  11508. };
  11509. this.setScissor = function ( x, y, width, height ) {
  11510. _gl.scissor(
  11511. x * pixelRatio,
  11512. y * pixelRatio,
  11513. width * pixelRatio,
  11514. height * pixelRatio
  11515. );
  11516. };
  11517. this.enableScissorTest = function ( enable ) {
  11518. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  11519. };
  11520. // Clearing
  11521. this.getClearColor = function () {
  11522. return _clearColor;
  11523. };
  11524. this.setClearColor = function ( color, alpha ) {
  11525. _clearColor.set( color );
  11526. _clearAlpha = alpha !== undefined ? alpha : 1;
  11527. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  11528. };
  11529. this.getClearAlpha = function () {
  11530. return _clearAlpha;
  11531. };
  11532. this.setClearAlpha = function ( alpha ) {
  11533. _clearAlpha = alpha;
  11534. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  11535. };
  11536. this.clear = function ( color, depth, stencil ) {
  11537. var bits = 0;
  11538. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  11539. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  11540. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  11541. _gl.clear( bits );
  11542. };
  11543. this.clearColor = function () {
  11544. _gl.clear( _gl.COLOR_BUFFER_BIT );
  11545. };
  11546. this.clearDepth = function () {
  11547. _gl.clear( _gl.DEPTH_BUFFER_BIT );
  11548. };
  11549. this.clearStencil = function () {
  11550. _gl.clear( _gl.STENCIL_BUFFER_BIT );
  11551. };
  11552. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  11553. this.setRenderTarget( renderTarget );
  11554. this.clear( color, depth, stencil );
  11555. };
  11556. // Reset
  11557. this.resetGLState = resetGLState;
  11558. // Events
  11559. var onTextureDispose = function ( event ) {
  11560. var texture = event.target;
  11561. texture.removeEventListener( 'dispose', onTextureDispose );
  11562. deallocateTexture( texture );
  11563. _this.info.memory.textures --;
  11564. };
  11565. var onRenderTargetDispose = function ( event ) {
  11566. var renderTarget = event.target;
  11567. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  11568. deallocateRenderTarget( renderTarget );
  11569. _this.info.memory.textures --;
  11570. };
  11571. var onMaterialDispose = function ( event ) {
  11572. var material = event.target;
  11573. material.removeEventListener( 'dispose', onMaterialDispose );
  11574. deallocateMaterial( material );
  11575. };
  11576. // Buffer deallocation
  11577. var deallocateTexture = function ( texture ) {
  11578. if ( texture.image && texture.image.__webglTextureCube ) {
  11579. // cube texture
  11580. _gl.deleteTexture( texture.image.__webglTextureCube );
  11581. delete texture.image.__webglTextureCube;
  11582. } else {
  11583. // 2D texture
  11584. if ( texture.__webglInit === undefined ) return;
  11585. _gl.deleteTexture( texture.__webglTexture );
  11586. delete texture.__webglTexture;
  11587. delete texture.__webglInit;
  11588. }
  11589. };
  11590. var deallocateRenderTarget = function ( renderTarget ) {
  11591. if ( ! renderTarget || renderTarget.__webglTexture === undefined ) return;
  11592. _gl.deleteTexture( renderTarget.__webglTexture );
  11593. delete renderTarget.__webglTexture;
  11594. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  11595. for ( var i = 0; i < 6; i ++ ) {
  11596. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  11597. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  11598. }
  11599. } else {
  11600. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  11601. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  11602. }
  11603. delete renderTarget.__webglFramebuffer;
  11604. delete renderTarget.__webglRenderbuffer;
  11605. };
  11606. var deallocateMaterial = function ( material ) {
  11607. var program = material.program.program;
  11608. if ( program === undefined ) return;
  11609. material.program = undefined;
  11610. // only deallocate GL program if this was the last use of shared program
  11611. // assumed there is only single copy of any program in the _programs list
  11612. // (that's how it's constructed)
  11613. var i, il, programInfo;
  11614. var deleteProgram = false;
  11615. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  11616. programInfo = _programs[ i ];
  11617. if ( programInfo.program === program ) {
  11618. programInfo.usedTimes --;
  11619. if ( programInfo.usedTimes === 0 ) {
  11620. deleteProgram = true;
  11621. }
  11622. break;
  11623. }
  11624. }
  11625. if ( deleteProgram === true ) {
  11626. // avoid using array.splice, this is costlier than creating new array from scratch
  11627. var newPrograms = [];
  11628. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  11629. programInfo = _programs[ i ];
  11630. if ( programInfo.program !== program ) {
  11631. newPrograms.push( programInfo );
  11632. }
  11633. }
  11634. _programs = newPrograms;
  11635. _gl.deleteProgram( program );
  11636. _this.info.memory.programs --;
  11637. }
  11638. };
  11639. // Buffer rendering
  11640. this.renderBufferImmediate = function ( object, program, material ) {
  11641. state.initAttributes();
  11642. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  11643. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  11644. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  11645. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  11646. if ( object.hasPositions ) {
  11647. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  11648. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  11649. state.enableAttribute( program.attributes.position );
  11650. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11651. }
  11652. if ( object.hasNormals ) {
  11653. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  11654. if ( material instanceof THREE.MeshPhongMaterial === false && material.shading === THREE.FlatShading ) {
  11655. var nx, ny, nz,
  11656. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  11657. normalArray,
  11658. i, il = object.count * 3;
  11659. for ( i = 0; i < il; i += 9 ) {
  11660. normalArray = object.normalArray;
  11661. nax = normalArray[ i ];
  11662. nay = normalArray[ i + 1 ];
  11663. naz = normalArray[ i + 2 ];
  11664. nbx = normalArray[ i + 3 ];
  11665. nby = normalArray[ i + 4 ];
  11666. nbz = normalArray[ i + 5 ];
  11667. ncx = normalArray[ i + 6 ];
  11668. ncy = normalArray[ i + 7 ];
  11669. ncz = normalArray[ i + 8 ];
  11670. nx = ( nax + nbx + ncx ) / 3;
  11671. ny = ( nay + nby + ncy ) / 3;
  11672. nz = ( naz + nbz + ncz ) / 3;
  11673. normalArray[ i ] = nx;
  11674. normalArray[ i + 1 ] = ny;
  11675. normalArray[ i + 2 ] = nz;
  11676. normalArray[ i + 3 ] = nx;
  11677. normalArray[ i + 4 ] = ny;
  11678. normalArray[ i + 5 ] = nz;
  11679. normalArray[ i + 6 ] = nx;
  11680. normalArray[ i + 7 ] = ny;
  11681. normalArray[ i + 8 ] = nz;
  11682. }
  11683. }
  11684. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  11685. state.enableAttribute( program.attributes.normal );
  11686. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  11687. }
  11688. if ( object.hasUvs && material.map ) {
  11689. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  11690. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  11691. state.enableAttribute( program.attributes.uv );
  11692. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  11693. }
  11694. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  11695. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  11696. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  11697. state.enableAttribute( program.attributes.color );
  11698. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  11699. }
  11700. state.disableUnusedAttributes();
  11701. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  11702. object.count = 0;
  11703. };
  11704. function setupVertexAttributes( material, program, geometry, startIndex ) {
  11705. var extension;
  11706. if ( geometry instanceof THREE.InstancedBufferGeometry ) {
  11707. extension = extensions.get( 'ANGLE_instanced_arrays' );
  11708. if ( extension === null ) {
  11709. console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  11710. return;
  11711. }
  11712. }
  11713. var geometryAttributes = geometry.attributes;
  11714. var programAttributes = program.attributes;
  11715. for ( var name in programAttributes ) {
  11716. var programAttribute = programAttributes[ name ];
  11717. if ( programAttribute >= 0 ) {
  11718. var geometryAttribute = geometryAttributes[ name ];
  11719. if ( geometryAttribute !== undefined ) {
  11720. var size = geometryAttribute.itemSize;
  11721. state.enableAttribute( programAttribute );
  11722. if ( geometryAttribute instanceof THREE.InterleavedBufferAttribute ) {
  11723. var data = geometryAttribute.data;
  11724. var stride = data.stride;
  11725. var offset = geometryAttribute.offset;
  11726. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryAttribute.data.buffer );
  11727. _gl.vertexAttribPointer( programAttribute, size, _gl.FLOAT, false, stride * data.array.BYTES_PER_ELEMENT, ( startIndex * stride + offset ) * data.array.BYTES_PER_ELEMENT );
  11728. if ( data instanceof THREE.InstancedInterleavedBuffer ) {
  11729. if ( extension === null ) {
  11730. console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferAttribute but hardware does not support extension ANGLE_instanced_arrays.' );
  11731. return;
  11732. }
  11733. extension.vertexAttribDivisorANGLE( programAttribute, data.meshPerAttribute );
  11734. if ( geometry.maxInstancedCount === undefined ) {
  11735. geometry.maxInstancedCount = data.meshPerAttribute * ( data.array.length / data.stride );
  11736. }
  11737. }
  11738. } else {
  11739. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryAttribute.buffer );
  11740. _gl.vertexAttribPointer( programAttribute, size, _gl.FLOAT, false, 0, startIndex * size * 4 ); // 4 bytes per Float32
  11741. if ( geometryAttribute instanceof THREE.InstancedBufferAttribute ) {
  11742. if ( extension === null ) {
  11743. console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferAttribute but hardware does not support extension ANGLE_instanced_arrays.' );
  11744. return;
  11745. }
  11746. extension.vertexAttribDivisorANGLE( programAttribute, geometryAttribute.meshPerAttribute );
  11747. if ( geometry.maxInstancedCount === undefined ) {
  11748. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * ( geometryAttribute.array.length / geometryAttribute.itemSize );
  11749. }
  11750. }
  11751. }
  11752. } else if ( material.defaultAttributeValues !== undefined ) {
  11753. if ( material.defaultAttributeValues[ name ] !== undefined ) {
  11754. if ( material.defaultAttributeValues[ name ].length === 2 ) {
  11755. _gl.vertexAttrib2fv( programAttribute, material.defaultAttributeValues[ name ] );
  11756. } else if ( material.defaultAttributeValues[ name ].length === 3 ) {
  11757. _gl.vertexAttrib3fv( programAttribute, material.defaultAttributeValues[ name ] );
  11758. }
  11759. }
  11760. }
  11761. }
  11762. }
  11763. state.disableUnusedAttributes();
  11764. }
  11765. this.renderBufferDirect = function ( camera, lights, fog, material, object ) {
  11766. if ( material.visible === false ) return;
  11767. var geometry = objects.geometries.get( object );
  11768. var program = setProgram( camera, lights, fog, material, object );
  11769. var updateBuffers = false,
  11770. wireframeBit = material.wireframe ? 1 : 0,
  11771. geometryProgram = geometry.id + '_' + program.id + '_' + wireframeBit;
  11772. if ( geometryProgram !== _currentGeometryProgram ) {
  11773. _currentGeometryProgram = geometryProgram;
  11774. updateBuffers = true;
  11775. }
  11776. if ( updateBuffers ) {
  11777. state.initAttributes();
  11778. }
  11779. if ( object instanceof THREE.Mesh ) {
  11780. renderMesh( material, geometry, object, program, updateBuffers );
  11781. } else if ( object instanceof THREE.Line ) {
  11782. renderLine( material, geometry, object, program, updateBuffers );
  11783. } else if ( object instanceof THREE.PointCloud ) {
  11784. renderPointCloud( material, geometry, object, program, updateBuffers );
  11785. }
  11786. };
  11787. function renderMesh( material, geometry, object, program, updateBuffers ) {
  11788. var mode = material.wireframe === true ? _gl.LINES : _gl.TRIANGLES;
  11789. var index = geometry.attributes.index;
  11790. if ( index ) {
  11791. // indexed triangles
  11792. var type, size;
  11793. if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) {
  11794. type = _gl.UNSIGNED_INT;
  11795. size = 4;
  11796. } else {
  11797. type = _gl.UNSIGNED_SHORT;
  11798. size = 2;
  11799. }
  11800. var offsets = geometry.offsets;
  11801. if ( offsets.length === 0 ) {
  11802. if ( updateBuffers ) {
  11803. setupVertexAttributes( material, program, geometry, 0 );
  11804. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  11805. }
  11806. if ( geometry instanceof THREE.InstancedBufferGeometry && geometry.maxInstancedCount > 0 ) {
  11807. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  11808. if ( extension === null ) {
  11809. console.error( 'THREE.WebGLRenderer.renderMesh: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  11810. return;
  11811. }
  11812. extension.drawElementsInstancedANGLE( mode, index.array.length, type, 0, geometry.maxInstancedCount ); // Draw the instanced meshes
  11813. } else {
  11814. _gl.drawElements( mode, index.array.length, type, 0 );
  11815. }
  11816. _this.info.render.calls ++;
  11817. _this.info.render.vertices += index.array.length; // not really true, here vertices can be shared
  11818. _this.info.render.faces += index.array.length / 3;
  11819. } else {
  11820. // if there is more than 1 chunk
  11821. // must set attribute pointers to use new offsets for each chunk
  11822. // even if geometry and materials didn't change
  11823. updateBuffers = true;
  11824. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  11825. var startIndex = offsets[ i ].index;
  11826. if ( updateBuffers ) {
  11827. setupVertexAttributes( material, program, geometry, startIndex );
  11828. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  11829. }
  11830. // render indexed triangles
  11831. if ( geometry instanceof THREE.InstancedBufferGeometry && offsets[i].instances > 0 ) {
  11832. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  11833. if ( extension === null ) {
  11834. console.error( 'THREE.WebGLRenderer.renderMesh: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  11835. return;
  11836. }
  11837. extension.drawElementsInstancedANGLE( mode, offsets[i].count, type, offsets[i].start * size, offsets[i].count, type, offsets[i].instances ); // Draw the instanced meshes
  11838. } else {
  11839. _gl.drawElements( mode, offsets[ i ].count, type, offsets[ i ].start * size );
  11840. }
  11841. _this.info.render.calls ++;
  11842. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  11843. _this.info.render.faces += offsets[ i ].count / 3;
  11844. }
  11845. }
  11846. } else {
  11847. // non-indexed triangles
  11848. var offsets = geometry.offsets;
  11849. if ( offsets.length === 0 ) {
  11850. if ( updateBuffers ) {
  11851. setupVertexAttributes( material, program, geometry, 0 );
  11852. }
  11853. var position = geometry.attributes.position;
  11854. // render non-indexed triangles
  11855. if ( geometry instanceof THREE.InstancedBufferGeometry && geometry.maxInstancedCount > 0 ) {
  11856. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  11857. if ( extension === null ) {
  11858. console.error( 'THREE.WebGLRenderer.renderMesh: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  11859. return;
  11860. }
  11861. if ( position instanceof THREE.InterleavedBufferAttribute ) {
  11862. extension.drawArraysInstancedANGLE( mode, 0, position.data.array.length / position.data.stride, geometry.maxInstancedCount ); // Draw the instanced meshes
  11863. } else {
  11864. extension.drawArraysInstancedANGLE( mode, 0, position.array.length / position.itemSize, geometry.maxInstancedCount ); // Draw the instanced meshes
  11865. }
  11866. } else {
  11867. if ( position instanceof THREE.InterleavedBufferAttribute ) {
  11868. _gl.drawArrays( mode, 0, position.data.array.length / position.data.stride );
  11869. } else {
  11870. _gl.drawArrays( mode, 0, position.array.length / position.itemSize );
  11871. }
  11872. }
  11873. _this.info.render.calls++;
  11874. _this.info.render.vertices += position.array.length / position.itemSize;
  11875. _this.info.render.faces += position.array.length / ( 3 * position.itemSize );
  11876. } else {
  11877. // if there is more than 1 chunk
  11878. // must set attribute pointers to use new offsets for each chunk
  11879. // even if geometry and materials didn't change
  11880. if ( updateBuffers ) {
  11881. setupVertexAttributes( material, program, geometry, 0 );
  11882. }
  11883. for ( var i = 0, il = offsets.length; i < il; i++ ) {
  11884. // render non-indexed triangles
  11885. if ( geometry instanceof THREE.InstancedBufferGeometry ) {
  11886. console.error( 'THREE.WebGLRenderer.renderMesh: cannot use drawCalls with THREE.InstancedBufferGeometry.' );
  11887. return;
  11888. } else {
  11889. _gl.drawArrays( mode, offsets[ i ].start, offsets[ i ].count );
  11890. }
  11891. _this.info.render.calls++;
  11892. _this.info.render.vertices += offsets[ i ].count;
  11893. _this.info.render.faces += ( offsets[ i ].count ) / 3;
  11894. }
  11895. }
  11896. }
  11897. }
  11898. function renderLine( material, geometry, object, program, updateBuffers ) {
  11899. var mode = object instanceof THREE.LineSegments ? _gl.LINES : _gl.LINE_STRIP;
  11900. // In case user is not using Line*Material by mistake
  11901. var lineWidth = material.linewidth !== undefined ? material.linewidth : 1;
  11902. state.setLineWidth( lineWidth * pixelRatio );
  11903. var index = geometry.attributes.index;
  11904. if ( index ) {
  11905. // indexed lines
  11906. var type, size;
  11907. if ( index.array instanceof Uint32Array ) {
  11908. type = _gl.UNSIGNED_INT;
  11909. size = 4;
  11910. } else {
  11911. type = _gl.UNSIGNED_SHORT;
  11912. size = 2;
  11913. }
  11914. var offsets = geometry.offsets;
  11915. if ( offsets.length === 0 ) {
  11916. if ( updateBuffers ) {
  11917. setupVertexAttributes( material, program, geometry, 0 );
  11918. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  11919. }
  11920. _gl.drawElements( mode, index.array.length, type, 0 ); // 2 bytes per Uint16Array
  11921. _this.info.render.calls ++;
  11922. _this.info.render.vertices += index.array.length; // not really true, here vertices can be shared
  11923. } else {
  11924. // if there is more than 1 chunk
  11925. // must set attribute pointers to use new offsets for each chunk
  11926. // even if geometry and materials didn't change
  11927. if ( offsets.length > 1 ) updateBuffers = true;
  11928. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  11929. var startIndex = offsets[ i ].index;
  11930. if ( updateBuffers ) {
  11931. setupVertexAttributes( material, program, geometry, startIndex );
  11932. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  11933. }
  11934. // render indexed lines
  11935. _gl.drawElements( mode, offsets[ i ].count, type, offsets[ i ].start * size ); // 2 bytes per Uint16Array
  11936. _this.info.render.calls ++;
  11937. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  11938. }
  11939. }
  11940. } else {
  11941. // non-indexed lines
  11942. if ( updateBuffers ) {
  11943. setupVertexAttributes( material, program, geometry, 0 );
  11944. }
  11945. var position = geometry.attributes.position;
  11946. var offsets = geometry.offsets;
  11947. if ( offsets.length === 0 ) {
  11948. _gl.drawArrays( mode, 0, position.array.length / 3 );
  11949. _this.info.render.calls ++;
  11950. _this.info.render.vertices += position.array.length / 3;
  11951. } else {
  11952. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  11953. _gl.drawArrays( mode, offsets[ i ].index, offsets[ i ].count );
  11954. _this.info.render.calls ++;
  11955. _this.info.render.vertices += offsets[ i ].count;
  11956. }
  11957. }
  11958. }
  11959. }
  11960. function renderPointCloud( material, geometry, object, program, updateBuffers ) {
  11961. var mode = _gl.POINTS;
  11962. var index = geometry.attributes.index;
  11963. if ( index ) {
  11964. // indexed points
  11965. var type, size;
  11966. if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) {
  11967. type = _gl.UNSIGNED_INT;
  11968. size = 4;
  11969. } else {
  11970. type = _gl.UNSIGNED_SHORT;
  11971. size = 2;
  11972. }
  11973. var offsets = geometry.offsets;
  11974. if ( offsets.length === 0 ) {
  11975. if ( updateBuffers ) {
  11976. setupVertexAttributes( material, program, geometry, 0 );
  11977. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  11978. }
  11979. _gl.drawElements( mode, index.array.length, type, 0);
  11980. _this.info.render.calls ++;
  11981. _this.info.render.points += index.array.length;
  11982. } else {
  11983. // if there is more than 1 chunk
  11984. // must set attribute pointers to use new offsets for each chunk
  11985. // even if geometry and materials didn't change
  11986. if ( offsets.length > 1 ) updateBuffers = true;
  11987. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  11988. var startIndex = offsets[ i ].index;
  11989. if ( updateBuffers ) {
  11990. setupVertexAttributes( material, program, geometry, startIndex );
  11991. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  11992. }
  11993. // render indexed points
  11994. _gl.drawElements( mode, offsets[ i ].count, type, offsets[ i ].start * size );
  11995. _this.info.render.calls ++;
  11996. _this.info.render.points += offsets[ i ].count;
  11997. }
  11998. }
  11999. } else {
  12000. // non-indexed points
  12001. if ( updateBuffers ) {
  12002. setupVertexAttributes( material, program, geometry, 0 );
  12003. }
  12004. var position = geometry.attributes.position;
  12005. var offsets = geometry.offsets;
  12006. if ( offsets.length === 0 ) {
  12007. _gl.drawArrays( mode, 0, position.array.length / 3 );
  12008. _this.info.render.calls ++;
  12009. _this.info.render.points += position.array.length / 3;
  12010. } else {
  12011. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  12012. _gl.drawArrays( mode, offsets[ i ].index, offsets[ i ].count );
  12013. _this.info.render.calls ++;
  12014. _this.info.render.points += offsets[ i ].count;
  12015. }
  12016. }
  12017. }
  12018. }
  12019. // Sorting
  12020. function painterSortStable ( a, b ) {
  12021. if ( a.object.renderOrder !== b.object.renderOrder ) {
  12022. return a.object.renderOrder - b.object.renderOrder;
  12023. } else if ( a.object.material.id !== b.object.material.id ) {
  12024. return a.object.material.id - b.object.material.id;
  12025. } else if ( a.z !== b.z ) {
  12026. return a.z - b.z;
  12027. } else {
  12028. return a.id - b.id;
  12029. }
  12030. }
  12031. function reversePainterSortStable ( a, b ) {
  12032. if ( a.object.renderOrder !== b.object.renderOrder ) {
  12033. return a.object.renderOrder - b.object.renderOrder;
  12034. } if ( a.z !== b.z ) {
  12035. return b.z - a.z;
  12036. } else {
  12037. return a.id - b.id;
  12038. }
  12039. }
  12040. function numericalSort ( a, b ) {
  12041. return b[ 0 ] - a[ 0 ];
  12042. }
  12043. // Rendering
  12044. this.render = function ( scene, camera, renderTarget, forceClear ) {
  12045. if ( camera instanceof THREE.Camera === false ) {
  12046. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  12047. return;
  12048. }
  12049. var fog = scene.fog;
  12050. // reset caching for this frame
  12051. _currentGeometryProgram = '';
  12052. _currentMaterialId = - 1;
  12053. _currentCamera = null;
  12054. _lightsNeedUpdate = true;
  12055. // update scene graph
  12056. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  12057. // update camera matrices and frustum
  12058. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  12059. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  12060. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  12061. _frustum.setFromMatrix( _projScreenMatrix );
  12062. lights.length = 0;
  12063. opaqueObjects.length = 0;
  12064. transparentObjects.length = 0;
  12065. sprites.length = 0;
  12066. lensFlares.length = 0;
  12067. projectObject( scene );
  12068. if ( _this.sortObjects === true ) {
  12069. opaqueObjects.sort( painterSortStable );
  12070. transparentObjects.sort( reversePainterSortStable );
  12071. }
  12072. objects.update( opaqueObjects );
  12073. objects.update( transparentObjects );
  12074. //
  12075. shadowMap.render( scene, camera );
  12076. //
  12077. _this.info.render.calls = 0;
  12078. _this.info.render.vertices = 0;
  12079. _this.info.render.faces = 0;
  12080. _this.info.render.points = 0;
  12081. this.setRenderTarget( renderTarget );
  12082. if ( this.autoClear || forceClear ) {
  12083. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  12084. }
  12085. // set matrices for immediate objects
  12086. for ( var i = 0, il = objects.objectsImmediate.length; i < il; i ++ ) {
  12087. var webglObject = objects.objectsImmediate[ i ];
  12088. var object = webglObject.object;
  12089. if ( object.visible === true ) {
  12090. setupMatrices( object, camera );
  12091. var material = object.material;
  12092. if ( material.transparent ) {
  12093. webglObject.transparent = material;
  12094. webglObject.opaque = null;
  12095. } else {
  12096. webglObject.opaque = material;
  12097. webglObject.transparent = null;
  12098. }
  12099. }
  12100. }
  12101. if ( scene.overrideMaterial ) {
  12102. var overrideMaterial = scene.overrideMaterial;
  12103. setMaterial( overrideMaterial );
  12104. renderObjects( opaqueObjects, camera, lights, fog, overrideMaterial );
  12105. renderObjects( transparentObjects, camera, lights, fog, overrideMaterial );
  12106. renderObjectsImmediate( objects.objectsImmediate, '', camera, lights, fog, overrideMaterial );
  12107. } else {
  12108. // opaque pass (front-to-back order)
  12109. state.setBlending( THREE.NoBlending );
  12110. renderObjects( opaqueObjects, camera, lights, fog, null );
  12111. renderObjectsImmediate( objects.objectsImmediate, 'opaque', camera, lights, fog, null );
  12112. // transparent pass (back-to-front order)
  12113. renderObjects( transparentObjects, camera, lights, fog, null );
  12114. renderObjectsImmediate( objects.objectsImmediate, 'transparent', camera, lights, fog, null );
  12115. }
  12116. // custom render plugins (post pass)
  12117. spritePlugin.render( scene, camera );
  12118. lensFlarePlugin.render( scene, camera, _currentWidth, _currentHeight );
  12119. // Generate mipmap if we're using any kind of mipmap filtering
  12120. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  12121. updateRenderTargetMipmap( renderTarget );
  12122. }
  12123. // Ensure depth buffer writing is enabled so it can be cleared on next render
  12124. state.setDepthTest( true );
  12125. state.setDepthWrite( true );
  12126. state.setColorWrite( true );
  12127. // _gl.finish();
  12128. };
  12129. function projectObject( object ) {
  12130. if ( object.visible === true ) {
  12131. if ( object instanceof THREE.Scene || object instanceof THREE.Group ) {
  12132. // skip
  12133. } else {
  12134. // update Skeleton objects
  12135. if ( object instanceof THREE.SkinnedMesh ) {
  12136. object.skeleton.update();
  12137. }
  12138. objects.init( object );
  12139. if ( object instanceof THREE.Light ) {
  12140. lights.push( object );
  12141. } else if ( object instanceof THREE.Sprite ) {
  12142. sprites.push( object );
  12143. } else if ( object instanceof THREE.LensFlare ) {
  12144. lensFlares.push( object );
  12145. } else {
  12146. var webglObject = objects.objects[ object.id ];
  12147. if ( webglObject && ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) ) {
  12148. var material = object.material;
  12149. if ( material.transparent ) {
  12150. transparentObjects.push( webglObject );
  12151. } else {
  12152. opaqueObjects.push( webglObject );
  12153. }
  12154. if ( _this.sortObjects === true ) {
  12155. _vector3.setFromMatrixPosition( object.matrixWorld );
  12156. _vector3.applyProjection( _projScreenMatrix );
  12157. webglObject.z = _vector3.z;
  12158. }
  12159. }
  12160. }
  12161. }
  12162. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  12163. projectObject( object.children[ i ] );
  12164. }
  12165. }
  12166. }
  12167. function renderObjects( renderList, camera, lights, fog, overrideMaterial ) {
  12168. var material;
  12169. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  12170. var webglObject = renderList[ i ];
  12171. var object = webglObject.object;
  12172. setupMatrices( object, camera );
  12173. if ( overrideMaterial ) {
  12174. material = overrideMaterial;
  12175. } else {
  12176. material = object.material;
  12177. if ( ! material ) continue;
  12178. setMaterial( material );
  12179. }
  12180. _this.setMaterialFaces( material );
  12181. _this.renderBufferDirect( camera, lights, fog, material, object );
  12182. }
  12183. }
  12184. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, overrideMaterial ) {
  12185. var material;
  12186. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  12187. var webglObject = renderList[ i ];
  12188. var object = webglObject.object;
  12189. if ( object.visible === true ) {
  12190. if ( overrideMaterial ) {
  12191. material = overrideMaterial;
  12192. } else {
  12193. material = webglObject[ materialType ];
  12194. if ( ! material ) continue;
  12195. setMaterial( material );
  12196. }
  12197. _this.renderImmediateObject( camera, lights, fog, material, object );
  12198. }
  12199. }
  12200. }
  12201. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  12202. var program = setProgram( camera, lights, fog, material, object );
  12203. _currentGeometryProgram = '';
  12204. _this.setMaterialFaces( material );
  12205. if ( object.immediateRenderCallback ) {
  12206. object.immediateRenderCallback( program, _gl, _frustum );
  12207. } else {
  12208. object.render( function ( object ) { _this.renderBufferImmediate( object, program, material ); } );
  12209. }
  12210. };
  12211. // Materials
  12212. var shaderIDs = {
  12213. MeshDepthMaterial: 'depth',
  12214. MeshNormalMaterial: 'normal',
  12215. MeshBasicMaterial: 'basic',
  12216. MeshLambertMaterial: 'lambert',
  12217. MeshPhongMaterial: 'phong',
  12218. LineBasicMaterial: 'basic',
  12219. LineDashedMaterial: 'dashed',
  12220. PointCloudMaterial: 'particle_basic'
  12221. };
  12222. function initMaterial( material, lights, fog, object ) {
  12223. var shaderID = shaderIDs[ material.type ];
  12224. // heuristics to create shader parameters according to lights in the scene
  12225. // (not to blow over maxLights budget)
  12226. var maxLightCount = allocateLights( lights );
  12227. var maxShadows = allocateShadows( lights );
  12228. var maxBones = allocateBones( object );
  12229. var parameters = {
  12230. precision: _precision,
  12231. supportsVertexTextures: _supportsVertexTextures,
  12232. map: !! material.map,
  12233. envMap: !! material.envMap,
  12234. envMapMode: material.envMap && material.envMap.mapping,
  12235. lightMap: !! material.lightMap,
  12236. aoMap: !! material.aoMap,
  12237. bumpMap: !! material.bumpMap,
  12238. normalMap: !! material.normalMap,
  12239. specularMap: !! material.specularMap,
  12240. alphaMap: !! material.alphaMap,
  12241. combine: material.combine,
  12242. vertexColors: material.vertexColors,
  12243. fog: fog,
  12244. useFog: material.fog,
  12245. fogExp: fog instanceof THREE.FogExp2,
  12246. flatShading: material.shading === THREE.FlatShading,
  12247. sizeAttenuation: material.sizeAttenuation,
  12248. logarithmicDepthBuffer: _logarithmicDepthBuffer,
  12249. skinning: material.skinning,
  12250. maxBones: maxBones,
  12251. useVertexTexture: _supportsBoneTextures && object && object.skeleton && object.skeleton.useVertexTexture,
  12252. morphTargets: material.morphTargets,
  12253. morphNormals: material.morphNormals,
  12254. maxMorphTargets: _this.maxMorphTargets,
  12255. maxMorphNormals: _this.maxMorphNormals,
  12256. maxDirLights: maxLightCount.directional,
  12257. maxPointLights: maxLightCount.point,
  12258. maxSpotLights: maxLightCount.spot,
  12259. maxHemiLights: maxLightCount.hemi,
  12260. maxShadows: maxShadows,
  12261. shadowMapEnabled: shadowMap.enabled && object.receiveShadow && maxShadows > 0,
  12262. shadowMapType: shadowMap.type,
  12263. shadowMapDebug: shadowMap.debug,
  12264. shadowMapCascade: shadowMap.cascade,
  12265. alphaTest: material.alphaTest,
  12266. metal: material.metal,
  12267. doubleSided: material.side === THREE.DoubleSide,
  12268. flipSided: material.side === THREE.BackSide
  12269. };
  12270. // Generate code
  12271. var chunks = [];
  12272. if ( shaderID ) {
  12273. chunks.push( shaderID );
  12274. } else {
  12275. chunks.push( material.fragmentShader );
  12276. chunks.push( material.vertexShader );
  12277. }
  12278. if ( material.defines !== undefined ) {
  12279. for ( var name in material.defines ) {
  12280. chunks.push( name );
  12281. chunks.push( material.defines[ name ] );
  12282. }
  12283. }
  12284. for ( var name in parameters ) {
  12285. chunks.push( name );
  12286. chunks.push( parameters[ name ] );
  12287. }
  12288. var code = chunks.join();
  12289. if ( !material.program ) {
  12290. // new material
  12291. material.addEventListener( 'dispose', onMaterialDispose );
  12292. } else if ( material.program.code !== code ) {
  12293. // changed glsl or parameters
  12294. deallocateMaterial( material );
  12295. } else if ( shaderID !== undefined ) {
  12296. // same glsl
  12297. return;
  12298. } else if ( material.__webglShader.uniforms === material.uniforms ) {
  12299. // same uniforms (container object)
  12300. return;
  12301. }
  12302. if ( shaderID ) {
  12303. var shader = THREE.ShaderLib[ shaderID ];
  12304. material.__webglShader = {
  12305. uniforms: THREE.UniformsUtils.clone( shader.uniforms ),
  12306. vertexShader: shader.vertexShader,
  12307. fragmentShader: shader.fragmentShader
  12308. }
  12309. } else {
  12310. material.__webglShader = {
  12311. uniforms: material.uniforms,
  12312. vertexShader: material.vertexShader,
  12313. fragmentShader: material.fragmentShader
  12314. }
  12315. }
  12316. var program;
  12317. // Check if code has been already compiled
  12318. for ( var p = 0, pl = _programs.length; p < pl; p ++ ) {
  12319. var programInfo = _programs[ p ];
  12320. if ( programInfo.code === code ) {
  12321. program = programInfo;
  12322. program.usedTimes ++;
  12323. break;
  12324. }
  12325. }
  12326. if ( program === undefined ) {
  12327. program = new THREE.WebGLProgram( _this, code, material, parameters );
  12328. _programs.push( program );
  12329. _this.info.memory.programs = _programs.length;
  12330. }
  12331. material.program = program;
  12332. var attributes = program.attributes;
  12333. if ( material.morphTargets ) {
  12334. material.numSupportedMorphTargets = 0;
  12335. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  12336. if ( attributes[ 'morphTarget' + i ] >= 0 ) {
  12337. material.numSupportedMorphTargets ++;
  12338. }
  12339. }
  12340. }
  12341. if ( material.morphNormals ) {
  12342. material.numSupportedMorphNormals = 0;
  12343. for ( i = 0; i < _this.maxMorphNormals; i ++ ) {
  12344. if ( attributes[ 'morphNormal' + i ] >= 0 ) {
  12345. material.numSupportedMorphNormals ++;
  12346. }
  12347. }
  12348. }
  12349. material.uniformsList = [];
  12350. for ( var u in material.__webglShader.uniforms ) {
  12351. var location = material.program.uniforms[ u ];
  12352. if ( location ) {
  12353. material.uniformsList.push( [ material.__webglShader.uniforms[ u ], location ] );
  12354. }
  12355. }
  12356. }
  12357. function setMaterial( material ) {
  12358. if ( material.transparent === true ) {
  12359. state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha );
  12360. } else {
  12361. state.setBlending( THREE.NoBlending );
  12362. }
  12363. state.setDepthFunc( material.depthFunc );
  12364. state.setDepthTest( material.depthTest );
  12365. state.setDepthWrite( material.depthWrite );
  12366. state.setColorWrite( material.colorWrite );
  12367. state.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  12368. }
  12369. function setProgram( camera, lights, fog, material, object ) {
  12370. _usedTextureUnits = 0;
  12371. if ( material.needsUpdate ) {
  12372. initMaterial( material, lights, fog, object );
  12373. material.needsUpdate = false;
  12374. }
  12375. var refreshProgram = false;
  12376. var refreshMaterial = false;
  12377. var refreshLights = false;
  12378. var program = material.program,
  12379. p_uniforms = program.uniforms,
  12380. m_uniforms = material.__webglShader.uniforms;
  12381. if ( program.id !== _currentProgram ) {
  12382. _gl.useProgram( program.program );
  12383. _currentProgram = program.id;
  12384. refreshProgram = true;
  12385. refreshMaterial = true;
  12386. refreshLights = true;
  12387. }
  12388. if ( material.id !== _currentMaterialId ) {
  12389. if ( _currentMaterialId === -1 ) refreshLights = true;
  12390. _currentMaterialId = material.id;
  12391. refreshMaterial = true;
  12392. }
  12393. if ( refreshProgram || camera !== _currentCamera ) {
  12394. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  12395. if ( _logarithmicDepthBuffer ) {
  12396. _gl.uniform1f( p_uniforms.logDepthBufFC, 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  12397. }
  12398. if ( camera !== _currentCamera ) _currentCamera = camera;
  12399. // load material specific uniforms
  12400. // (shader material also gets them for the sake of genericity)
  12401. if ( material instanceof THREE.ShaderMaterial ||
  12402. material instanceof THREE.MeshPhongMaterial ||
  12403. material.envMap ) {
  12404. if ( p_uniforms.cameraPosition !== null ) {
  12405. _vector3.setFromMatrixPosition( camera.matrixWorld );
  12406. _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  12407. }
  12408. }
  12409. if ( material instanceof THREE.MeshPhongMaterial ||
  12410. material instanceof THREE.MeshLambertMaterial ||
  12411. material instanceof THREE.MeshBasicMaterial ||
  12412. material instanceof THREE.ShaderMaterial ||
  12413. material.skinning ) {
  12414. if ( p_uniforms.viewMatrix !== null ) {
  12415. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  12416. }
  12417. }
  12418. }
  12419. // skinning uniforms must be set even if material didn't change
  12420. // auto-setting of texture unit for bone texture must go before other textures
  12421. // not sure why, but otherwise weird things happen
  12422. if ( material.skinning ) {
  12423. if ( object.bindMatrix && p_uniforms.bindMatrix !== null ) {
  12424. _gl.uniformMatrix4fv( p_uniforms.bindMatrix, false, object.bindMatrix.elements );
  12425. }
  12426. if ( object.bindMatrixInverse && p_uniforms.bindMatrixInverse !== null ) {
  12427. _gl.uniformMatrix4fv( p_uniforms.bindMatrixInverse, false, object.bindMatrixInverse.elements );
  12428. }
  12429. if ( _supportsBoneTextures && object.skeleton && object.skeleton.useVertexTexture ) {
  12430. if ( p_uniforms.boneTexture !== null ) {
  12431. var textureUnit = getTextureUnit();
  12432. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  12433. _this.setTexture( object.skeleton.boneTexture, textureUnit );
  12434. }
  12435. if ( p_uniforms.boneTextureWidth !== null ) {
  12436. _gl.uniform1i( p_uniforms.boneTextureWidth, object.skeleton.boneTextureWidth );
  12437. }
  12438. if ( p_uniforms.boneTextureHeight !== null ) {
  12439. _gl.uniform1i( p_uniforms.boneTextureHeight, object.skeleton.boneTextureHeight );
  12440. }
  12441. } else if ( object.skeleton && object.skeleton.boneMatrices ) {
  12442. if ( p_uniforms.boneGlobalMatrices !== null ) {
  12443. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.skeleton.boneMatrices );
  12444. }
  12445. }
  12446. }
  12447. if ( refreshMaterial ) {
  12448. // refresh uniforms common to several materials
  12449. if ( fog && material.fog ) {
  12450. refreshUniformsFog( m_uniforms, fog );
  12451. }
  12452. if ( material instanceof THREE.MeshPhongMaterial ||
  12453. material instanceof THREE.MeshLambertMaterial ||
  12454. material.lights ) {
  12455. if ( _lightsNeedUpdate ) {
  12456. refreshLights = true;
  12457. setupLights( lights );
  12458. _lightsNeedUpdate = false;
  12459. }
  12460. if ( refreshLights ) {
  12461. refreshUniformsLights( m_uniforms, _lights );
  12462. markUniformsLightsNeedsUpdate( m_uniforms, true );
  12463. } else {
  12464. markUniformsLightsNeedsUpdate( m_uniforms, false );
  12465. }
  12466. }
  12467. if ( material instanceof THREE.MeshBasicMaterial ||
  12468. material instanceof THREE.MeshLambertMaterial ||
  12469. material instanceof THREE.MeshPhongMaterial ) {
  12470. refreshUniformsCommon( m_uniforms, material );
  12471. }
  12472. // refresh single material specific uniforms
  12473. if ( material instanceof THREE.LineBasicMaterial ) {
  12474. refreshUniformsLine( m_uniforms, material );
  12475. } else if ( material instanceof THREE.LineDashedMaterial ) {
  12476. refreshUniformsLine( m_uniforms, material );
  12477. refreshUniformsDash( m_uniforms, material );
  12478. } else if ( material instanceof THREE.PointCloudMaterial ) {
  12479. refreshUniformsParticle( m_uniforms, material );
  12480. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  12481. refreshUniformsPhong( m_uniforms, material );
  12482. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  12483. refreshUniformsLambert( m_uniforms, material );
  12484. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  12485. refreshUniformsBasic( m_uniforms, material );
  12486. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  12487. m_uniforms.mNear.value = camera.near;
  12488. m_uniforms.mFar.value = camera.far;
  12489. m_uniforms.opacity.value = material.opacity;
  12490. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  12491. m_uniforms.opacity.value = material.opacity;
  12492. }
  12493. if ( object.receiveShadow && ! material._shadowPass ) {
  12494. refreshUniformsShadow( m_uniforms, lights );
  12495. }
  12496. // load common uniforms
  12497. loadUniformsGeneric( material.uniformsList );
  12498. }
  12499. loadUniformsMatrices( p_uniforms, object );
  12500. if ( p_uniforms.modelMatrix !== null ) {
  12501. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  12502. }
  12503. return program;
  12504. }
  12505. // Uniforms (refresh uniforms objects)
  12506. function refreshUniformsCommon ( uniforms, material ) {
  12507. uniforms.opacity.value = material.opacity;
  12508. uniforms.diffuse.value = material.color;
  12509. uniforms.map.value = material.map;
  12510. uniforms.specularMap.value = material.specularMap;
  12511. uniforms.alphaMap.value = material.alphaMap;
  12512. if ( material.bumpMap ) {
  12513. uniforms.bumpMap.value = material.bumpMap;
  12514. uniforms.bumpScale.value = material.bumpScale;
  12515. }
  12516. if ( material.normalMap ) {
  12517. uniforms.normalMap.value = material.normalMap;
  12518. uniforms.normalScale.value.copy( material.normalScale );
  12519. }
  12520. // uv repeat and offset setting priorities
  12521. // 1. color map
  12522. // 2. specular map
  12523. // 3. normal map
  12524. // 4. bump map
  12525. // 5. alpha map
  12526. var uvScaleMap;
  12527. if ( material.map ) {
  12528. uvScaleMap = material.map;
  12529. } else if ( material.specularMap ) {
  12530. uvScaleMap = material.specularMap;
  12531. } else if ( material.normalMap ) {
  12532. uvScaleMap = material.normalMap;
  12533. } else if ( material.bumpMap ) {
  12534. uvScaleMap = material.bumpMap;
  12535. } else if ( material.alphaMap ) {
  12536. uvScaleMap = material.alphaMap;
  12537. }
  12538. if ( uvScaleMap !== undefined ) {
  12539. var offset = uvScaleMap.offset;
  12540. var repeat = uvScaleMap.repeat;
  12541. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  12542. }
  12543. uniforms.envMap.value = material.envMap;
  12544. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : - 1;
  12545. uniforms.reflectivity.value = material.reflectivity;
  12546. uniforms.refractionRatio.value = material.refractionRatio;
  12547. }
  12548. function refreshUniformsLine ( uniforms, material ) {
  12549. uniforms.diffuse.value = material.color;
  12550. uniforms.opacity.value = material.opacity;
  12551. }
  12552. function refreshUniformsDash ( uniforms, material ) {
  12553. uniforms.dashSize.value = material.dashSize;
  12554. uniforms.totalSize.value = material.dashSize + material.gapSize;
  12555. uniforms.scale.value = material.scale;
  12556. }
  12557. function refreshUniformsParticle ( uniforms, material ) {
  12558. uniforms.psColor.value = material.color;
  12559. uniforms.opacity.value = material.opacity;
  12560. uniforms.size.value = material.size;
  12561. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  12562. uniforms.map.value = material.map;
  12563. if ( material.map !== null ) {
  12564. var offset = material.map.offset;
  12565. var repeat = material.map.repeat;
  12566. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  12567. }
  12568. }
  12569. function refreshUniformsFog ( uniforms, fog ) {
  12570. uniforms.fogColor.value = fog.color;
  12571. if ( fog instanceof THREE.Fog ) {
  12572. uniforms.fogNear.value = fog.near;
  12573. uniforms.fogFar.value = fog.far;
  12574. } else if ( fog instanceof THREE.FogExp2 ) {
  12575. uniforms.fogDensity.value = fog.density;
  12576. }
  12577. }
  12578. function refreshUniformsPhong ( uniforms, material ) {
  12579. uniforms.shininess.value = material.shininess;
  12580. uniforms.emissive.value = material.emissive;
  12581. uniforms.specular.value = material.specular;
  12582. uniforms.lightMap.value = material.lightMap;
  12583. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  12584. uniforms.aoMap.value = material.aoMap;
  12585. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  12586. }
  12587. function refreshUniformsLambert ( uniforms, material ) {
  12588. uniforms.emissive.value = material.emissive;
  12589. }
  12590. function refreshUniformsBasic ( uniforms, material ) {
  12591. uniforms.aoMap.value = material.aoMap;
  12592. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  12593. }
  12594. function refreshUniformsLights ( uniforms, lights ) {
  12595. uniforms.ambientLightColor.value = lights.ambient;
  12596. uniforms.directionalLightColor.value = lights.directional.colors;
  12597. uniforms.directionalLightDirection.value = lights.directional.positions;
  12598. uniforms.pointLightColor.value = lights.point.colors;
  12599. uniforms.pointLightPosition.value = lights.point.positions;
  12600. uniforms.pointLightDistance.value = lights.point.distances;
  12601. uniforms.pointLightDecay.value = lights.point.decays;
  12602. uniforms.spotLightColor.value = lights.spot.colors;
  12603. uniforms.spotLightPosition.value = lights.spot.positions;
  12604. uniforms.spotLightDistance.value = lights.spot.distances;
  12605. uniforms.spotLightDirection.value = lights.spot.directions;
  12606. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  12607. uniforms.spotLightExponent.value = lights.spot.exponents;
  12608. uniforms.spotLightDecay.value = lights.spot.decays;
  12609. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  12610. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  12611. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  12612. }
  12613. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  12614. function markUniformsLightsNeedsUpdate ( uniforms, value ) {
  12615. uniforms.ambientLightColor.needsUpdate = value;
  12616. uniforms.directionalLightColor.needsUpdate = value;
  12617. uniforms.directionalLightDirection.needsUpdate = value;
  12618. uniforms.pointLightColor.needsUpdate = value;
  12619. uniforms.pointLightPosition.needsUpdate = value;
  12620. uniforms.pointLightDistance.needsUpdate = value;
  12621. uniforms.pointLightDecay.needsUpdate = value;
  12622. uniforms.spotLightColor.needsUpdate = value;
  12623. uniforms.spotLightPosition.needsUpdate = value;
  12624. uniforms.spotLightDistance.needsUpdate = value;
  12625. uniforms.spotLightDirection.needsUpdate = value;
  12626. uniforms.spotLightAngleCos.needsUpdate = value;
  12627. uniforms.spotLightExponent.needsUpdate = value;
  12628. uniforms.spotLightDecay.needsUpdate = value;
  12629. uniforms.hemisphereLightSkyColor.needsUpdate = value;
  12630. uniforms.hemisphereLightGroundColor.needsUpdate = value;
  12631. uniforms.hemisphereLightDirection.needsUpdate = value;
  12632. }
  12633. function refreshUniformsShadow ( uniforms, lights ) {
  12634. if ( uniforms.shadowMatrix ) {
  12635. var j = 0;
  12636. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  12637. var light = lights[ i ];
  12638. if ( ! light.castShadow ) continue;
  12639. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  12640. uniforms.shadowMap.value[ j ] = light.shadowMap;
  12641. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  12642. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  12643. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  12644. uniforms.shadowBias.value[ j ] = light.shadowBias;
  12645. j ++;
  12646. }
  12647. }
  12648. }
  12649. }
  12650. // Uniforms (load to GPU)
  12651. function loadUniformsMatrices ( uniforms, object ) {
  12652. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  12653. if ( uniforms.normalMatrix ) {
  12654. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  12655. }
  12656. }
  12657. function getTextureUnit() {
  12658. var textureUnit = _usedTextureUnits;
  12659. if ( textureUnit >= _maxTextures ) {
  12660. console.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + _maxTextures );
  12661. }
  12662. _usedTextureUnits += 1;
  12663. return textureUnit;
  12664. }
  12665. function loadUniformsGeneric ( uniforms ) {
  12666. var texture, textureUnit, offset;
  12667. for ( var j = 0, jl = uniforms.length; j < jl; j ++ ) {
  12668. var uniform = uniforms[ j ][ 0 ];
  12669. // needsUpdate property is not added to all uniforms.
  12670. if ( uniform.needsUpdate === false ) continue;
  12671. var type = uniform.type;
  12672. var value = uniform.value;
  12673. var location = uniforms[ j ][ 1 ];
  12674. switch ( type ) {
  12675. case '1i':
  12676. _gl.uniform1i( location, value );
  12677. break;
  12678. case '1f':
  12679. _gl.uniform1f( location, value );
  12680. break;
  12681. case '2f':
  12682. _gl.uniform2f( location, value[ 0 ], value[ 1 ] );
  12683. break;
  12684. case '3f':
  12685. _gl.uniform3f( location, value[ 0 ], value[ 1 ], value[ 2 ] );
  12686. break;
  12687. case '4f':
  12688. _gl.uniform4f( location, value[ 0 ], value[ 1 ], value[ 2 ], value[ 3 ] );
  12689. break;
  12690. case '1iv':
  12691. _gl.uniform1iv( location, value );
  12692. break;
  12693. case '3iv':
  12694. _gl.uniform3iv( location, value );
  12695. break;
  12696. case '1fv':
  12697. _gl.uniform1fv( location, value );
  12698. break;
  12699. case '2fv':
  12700. _gl.uniform2fv( location, value );
  12701. break;
  12702. case '3fv':
  12703. _gl.uniform3fv( location, value );
  12704. break;
  12705. case '4fv':
  12706. _gl.uniform4fv( location, value );
  12707. break;
  12708. case 'Matrix3fv':
  12709. _gl.uniformMatrix3fv( location, false, value );
  12710. break;
  12711. case 'Matrix4fv':
  12712. _gl.uniformMatrix4fv( location, false, value );
  12713. break;
  12714. //
  12715. case 'i':
  12716. // single integer
  12717. _gl.uniform1i( location, value );
  12718. break;
  12719. case 'f':
  12720. // single float
  12721. _gl.uniform1f( location, value );
  12722. break;
  12723. case 'v2':
  12724. // single THREE.Vector2
  12725. _gl.uniform2f( location, value.x, value.y );
  12726. break;
  12727. case 'v3':
  12728. // single THREE.Vector3
  12729. _gl.uniform3f( location, value.x, value.y, value.z );
  12730. break;
  12731. case 'v4':
  12732. // single THREE.Vector4
  12733. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  12734. break;
  12735. case 'c':
  12736. // single THREE.Color
  12737. _gl.uniform3f( location, value.r, value.g, value.b );
  12738. break;
  12739. case 'iv1':
  12740. // flat array of integers (JS or typed array)
  12741. _gl.uniform1iv( location, value );
  12742. break;
  12743. case 'iv':
  12744. // flat array of integers with 3 x N size (JS or typed array)
  12745. _gl.uniform3iv( location, value );
  12746. break;
  12747. case 'fv1':
  12748. // flat array of floats (JS or typed array)
  12749. _gl.uniform1fv( location, value );
  12750. break;
  12751. case 'fv':
  12752. // flat array of floats with 3 x N size (JS or typed array)
  12753. _gl.uniform3fv( location, value );
  12754. break;
  12755. case 'v2v':
  12756. // array of THREE.Vector2
  12757. if ( uniform._array === undefined ) {
  12758. uniform._array = new Float32Array( 2 * value.length );
  12759. }
  12760. for ( var i = 0, il = value.length; i < il; i ++ ) {
  12761. offset = i * 2;
  12762. uniform._array[ offset + 0 ] = value[ i ].x;
  12763. uniform._array[ offset + 1 ] = value[ i ].y;
  12764. }
  12765. _gl.uniform2fv( location, uniform._array );
  12766. break;
  12767. case 'v3v':
  12768. // array of THREE.Vector3
  12769. if ( uniform._array === undefined ) {
  12770. uniform._array = new Float32Array( 3 * value.length );
  12771. }
  12772. for ( var i = 0, il = value.length; i < il; i ++ ) {
  12773. offset = i * 3;
  12774. uniform._array[ offset + 0 ] = value[ i ].x;
  12775. uniform._array[ offset + 1 ] = value[ i ].y;
  12776. uniform._array[ offset + 2 ] = value[ i ].z;
  12777. }
  12778. _gl.uniform3fv( location, uniform._array );
  12779. break;
  12780. case 'v4v':
  12781. // array of THREE.Vector4
  12782. if ( uniform._array === undefined ) {
  12783. uniform._array = new Float32Array( 4 * value.length );
  12784. }
  12785. for ( var i = 0, il = value.length; i < il; i ++ ) {
  12786. offset = i * 4;
  12787. uniform._array[ offset + 0 ] = value[ i ].x;
  12788. uniform._array[ offset + 1 ] = value[ i ].y;
  12789. uniform._array[ offset + 2 ] = value[ i ].z;
  12790. uniform._array[ offset + 3 ] = value[ i ].w;
  12791. }
  12792. _gl.uniform4fv( location, uniform._array );
  12793. break;
  12794. case 'm3':
  12795. // single THREE.Matrix3
  12796. _gl.uniformMatrix3fv( location, false, value.elements );
  12797. break;
  12798. case 'm3v':
  12799. // array of THREE.Matrix3
  12800. if ( uniform._array === undefined ) {
  12801. uniform._array = new Float32Array( 9 * value.length );
  12802. }
  12803. for ( var i = 0, il = value.length; i < il; i ++ ) {
  12804. value[ i ].flattenToArrayOffset( uniform._array, i * 9 );
  12805. }
  12806. _gl.uniformMatrix3fv( location, false, uniform._array );
  12807. break;
  12808. case 'm4':
  12809. // single THREE.Matrix4
  12810. _gl.uniformMatrix4fv( location, false, value.elements );
  12811. break;
  12812. case 'm4v':
  12813. // array of THREE.Matrix4
  12814. if ( uniform._array === undefined ) {
  12815. uniform._array = new Float32Array( 16 * value.length );
  12816. }
  12817. for ( var i = 0, il = value.length; i < il; i ++ ) {
  12818. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  12819. }
  12820. _gl.uniformMatrix4fv( location, false, uniform._array );
  12821. break;
  12822. case 't':
  12823. // single THREE.Texture (2d or cube)
  12824. texture = value;
  12825. textureUnit = getTextureUnit();
  12826. _gl.uniform1i( location, textureUnit );
  12827. if ( ! texture ) continue;
  12828. if ( texture instanceof THREE.CubeTexture ||
  12829. ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) { // CompressedTexture can have Array in image :/
  12830. setCubeTexture( texture, textureUnit );
  12831. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  12832. setCubeTextureDynamic( texture, textureUnit );
  12833. } else {
  12834. _this.setTexture( texture, textureUnit );
  12835. }
  12836. break;
  12837. case 'tv':
  12838. // array of THREE.Texture (2d)
  12839. if ( uniform._array === undefined ) {
  12840. uniform._array = [];
  12841. }
  12842. for ( var i = 0, il = uniform.value.length; i < il; i ++ ) {
  12843. uniform._array[ i ] = getTextureUnit();
  12844. }
  12845. _gl.uniform1iv( location, uniform._array );
  12846. for ( var i = 0, il = uniform.value.length; i < il; i ++ ) {
  12847. texture = uniform.value[ i ];
  12848. textureUnit = uniform._array[ i ];
  12849. if ( ! texture ) continue;
  12850. _this.setTexture( texture, textureUnit );
  12851. }
  12852. break;
  12853. default:
  12854. console.warn( 'THREE.WebGLRenderer: Unknown uniform type: ' + type );
  12855. }
  12856. }
  12857. }
  12858. function setupMatrices ( object, camera ) {
  12859. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  12860. object._normalMatrix.getNormalMatrix( object._modelViewMatrix );
  12861. }
  12862. function setColorLinear( array, offset, color, intensity ) {
  12863. array[ offset + 0 ] = color.r * intensity;
  12864. array[ offset + 1 ] = color.g * intensity;
  12865. array[ offset + 2 ] = color.b * intensity;
  12866. }
  12867. function setupLights ( lights ) {
  12868. var l, ll, light,
  12869. r = 0, g = 0, b = 0,
  12870. color, skyColor, groundColor,
  12871. intensity,
  12872. distance,
  12873. zlights = _lights,
  12874. dirColors = zlights.directional.colors,
  12875. dirPositions = zlights.directional.positions,
  12876. pointColors = zlights.point.colors,
  12877. pointPositions = zlights.point.positions,
  12878. pointDistances = zlights.point.distances,
  12879. pointDecays = zlights.point.decays,
  12880. spotColors = zlights.spot.colors,
  12881. spotPositions = zlights.spot.positions,
  12882. spotDistances = zlights.spot.distances,
  12883. spotDirections = zlights.spot.directions,
  12884. spotAnglesCos = zlights.spot.anglesCos,
  12885. spotExponents = zlights.spot.exponents,
  12886. spotDecays = zlights.spot.decays,
  12887. hemiSkyColors = zlights.hemi.skyColors,
  12888. hemiGroundColors = zlights.hemi.groundColors,
  12889. hemiPositions = zlights.hemi.positions,
  12890. dirLength = 0,
  12891. pointLength = 0,
  12892. spotLength = 0,
  12893. hemiLength = 0,
  12894. dirCount = 0,
  12895. pointCount = 0,
  12896. spotCount = 0,
  12897. hemiCount = 0,
  12898. dirOffset = 0,
  12899. pointOffset = 0,
  12900. spotOffset = 0,
  12901. hemiOffset = 0;
  12902. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  12903. light = lights[ l ];
  12904. if ( light.onlyShadow ) continue;
  12905. color = light.color;
  12906. intensity = light.intensity;
  12907. distance = light.distance;
  12908. if ( light instanceof THREE.AmbientLight ) {
  12909. if ( ! light.visible ) continue;
  12910. r += color.r;
  12911. g += color.g;
  12912. b += color.b;
  12913. } else if ( light instanceof THREE.DirectionalLight ) {
  12914. dirCount += 1;
  12915. if ( ! light.visible ) continue;
  12916. _direction.setFromMatrixPosition( light.matrixWorld );
  12917. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  12918. _direction.sub( _vector3 );
  12919. _direction.normalize();
  12920. dirOffset = dirLength * 3;
  12921. dirPositions[ dirOffset + 0 ] = _direction.x;
  12922. dirPositions[ dirOffset + 1 ] = _direction.y;
  12923. dirPositions[ dirOffset + 2 ] = _direction.z;
  12924. setColorLinear( dirColors, dirOffset, color, intensity );
  12925. dirLength += 1;
  12926. } else if ( light instanceof THREE.PointLight ) {
  12927. pointCount += 1;
  12928. if ( ! light.visible ) continue;
  12929. pointOffset = pointLength * 3;
  12930. setColorLinear( pointColors, pointOffset, color, intensity );
  12931. _vector3.setFromMatrixPosition( light.matrixWorld );
  12932. pointPositions[ pointOffset + 0 ] = _vector3.x;
  12933. pointPositions[ pointOffset + 1 ] = _vector3.y;
  12934. pointPositions[ pointOffset + 2 ] = _vector3.z;
  12935. // distance is 0 if decay is 0, because there is no attenuation at all.
  12936. pointDistances[ pointLength ] = distance;
  12937. pointDecays[ pointLength ] = ( light.distance === 0 ) ? 0.0 : light.decay;
  12938. pointLength += 1;
  12939. } else if ( light instanceof THREE.SpotLight ) {
  12940. spotCount += 1;
  12941. if ( ! light.visible ) continue;
  12942. spotOffset = spotLength * 3;
  12943. setColorLinear( spotColors, spotOffset, color, intensity );
  12944. _direction.setFromMatrixPosition( light.matrixWorld );
  12945. spotPositions[ spotOffset + 0 ] = _direction.x;
  12946. spotPositions[ spotOffset + 1 ] = _direction.y;
  12947. spotPositions[ spotOffset + 2 ] = _direction.z;
  12948. spotDistances[ spotLength ] = distance;
  12949. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  12950. _direction.sub( _vector3 );
  12951. _direction.normalize();
  12952. spotDirections[ spotOffset + 0 ] = _direction.x;
  12953. spotDirections[ spotOffset + 1 ] = _direction.y;
  12954. spotDirections[ spotOffset + 2 ] = _direction.z;
  12955. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  12956. spotExponents[ spotLength ] = light.exponent;
  12957. spotDecays[ spotLength ] = ( light.distance === 0 ) ? 0.0 : light.decay;
  12958. spotLength += 1;
  12959. } else if ( light instanceof THREE.HemisphereLight ) {
  12960. hemiCount += 1;
  12961. if ( ! light.visible ) continue;
  12962. _direction.setFromMatrixPosition( light.matrixWorld );
  12963. _direction.normalize();
  12964. hemiOffset = hemiLength * 3;
  12965. hemiPositions[ hemiOffset + 0 ] = _direction.x;
  12966. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  12967. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  12968. skyColor = light.color;
  12969. groundColor = light.groundColor;
  12970. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  12971. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  12972. hemiLength += 1;
  12973. }
  12974. }
  12975. // null eventual remains from removed lights
  12976. // (this is to avoid if in shader)
  12977. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  12978. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  12979. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  12980. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  12981. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  12982. zlights.directional.length = dirLength;
  12983. zlights.point.length = pointLength;
  12984. zlights.spot.length = spotLength;
  12985. zlights.hemi.length = hemiLength;
  12986. zlights.ambient[ 0 ] = r;
  12987. zlights.ambient[ 1 ] = g;
  12988. zlights.ambient[ 2 ] = b;
  12989. }
  12990. // GL state setting
  12991. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  12992. if ( cullFace === THREE.CullFaceNone ) {
  12993. _gl.disable( _gl.CULL_FACE );
  12994. } else {
  12995. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  12996. _gl.frontFace( _gl.CW );
  12997. } else {
  12998. _gl.frontFace( _gl.CCW );
  12999. }
  13000. if ( cullFace === THREE.CullFaceBack ) {
  13001. _gl.cullFace( _gl.BACK );
  13002. } else if ( cullFace === THREE.CullFaceFront ) {
  13003. _gl.cullFace( _gl.FRONT );
  13004. } else {
  13005. _gl.cullFace( _gl.FRONT_AND_BACK );
  13006. }
  13007. _gl.enable( _gl.CULL_FACE );
  13008. }
  13009. };
  13010. this.setMaterialFaces = function ( material ) {
  13011. state.setDoubleSided( material.side === THREE.DoubleSide );
  13012. state.setFlipSided( material.side === THREE.BackSide );
  13013. };
  13014. // Textures
  13015. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  13016. var extension;
  13017. if ( isImagePowerOfTwo ) {
  13018. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  13019. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  13020. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  13021. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  13022. } else {
  13023. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  13024. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  13025. if ( texture.wrapS !== THREE.ClampToEdgeWrapping || texture.wrapT !== THREE.ClampToEdgeWrapping ) {
  13026. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping. ( ' + texture.sourceFile + ' )' );
  13027. }
  13028. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  13029. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  13030. if ( texture.minFilter !== THREE.NearestFilter && texture.minFilter !== THREE.LinearFilter ) {
  13031. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter. ( ' + texture.sourceFile + ' )' );
  13032. }
  13033. }
  13034. extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  13035. if ( extension && texture.type !== THREE.FloatType && texture.type !== THREE.HalfFloatType ) {
  13036. if ( texture.anisotropy > 1 || texture.__currentAnisotropy ) {
  13037. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _this.getMaxAnisotropy() ) );
  13038. texture.__currentAnisotropy = texture.anisotropy;
  13039. }
  13040. }
  13041. }
  13042. this.uploadTexture = function ( texture, slot ) {
  13043. if ( texture.__webglInit === undefined ) {
  13044. texture.__webglInit = true;
  13045. texture.addEventListener( 'dispose', onTextureDispose );
  13046. texture.__webglTexture = _gl.createTexture();
  13047. _this.info.memory.textures ++;
  13048. }
  13049. state.activeTexture( _gl.TEXTURE0 + slot );
  13050. state.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  13051. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  13052. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  13053. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  13054. texture.image = clampToMaxSize( texture.image, _maxTextureSize );
  13055. var image = texture.image,
  13056. isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ),
  13057. glFormat = paramThreeToGL( texture.format ),
  13058. glType = paramThreeToGL( texture.type );
  13059. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  13060. var mipmap, mipmaps = texture.mipmaps;
  13061. if ( texture instanceof THREE.DataTexture ) {
  13062. // use manually created mipmaps if available
  13063. // if there are no manual mipmaps
  13064. // set 0 level mipmap and then use GL to generate other mipmap levels
  13065. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  13066. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  13067. mipmap = mipmaps[ i ];
  13068. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13069. }
  13070. texture.generateMipmaps = false;
  13071. } else {
  13072. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  13073. }
  13074. } else if ( texture instanceof THREE.CompressedTexture ) {
  13075. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  13076. mipmap = mipmaps[ i ];
  13077. if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) {
  13078. if ( getCompressedTextureFormats().indexOf( glFormat ) > -1 ) {
  13079. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13080. } else {
  13081. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()" );
  13082. }
  13083. } else {
  13084. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13085. }
  13086. }
  13087. } else { // regular Texture (image, video, canvas)
  13088. // use manually created mipmaps if available
  13089. // if there are no manual mipmaps
  13090. // set 0 level mipmap and then use GL to generate other mipmap levels
  13091. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  13092. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  13093. mipmap = mipmaps[ i ];
  13094. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  13095. }
  13096. texture.generateMipmaps = false;
  13097. } else {
  13098. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  13099. }
  13100. }
  13101. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  13102. texture.needsUpdate = false;
  13103. if ( texture.onUpdate ) texture.onUpdate( texture );
  13104. };
  13105. this.setTexture = function ( texture, slot ) {
  13106. if ( texture.needsUpdate === true ) {
  13107. var image = texture.image;
  13108. if ( image === undefined ) {
  13109. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined', texture );
  13110. return;
  13111. }
  13112. if ( image.complete === false ) {
  13113. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture );
  13114. return;
  13115. }
  13116. _this.uploadTexture( texture, slot );
  13117. return;
  13118. }
  13119. state.activeTexture( _gl.TEXTURE0 + slot );
  13120. state.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  13121. };
  13122. function clampToMaxSize ( image, maxSize ) {
  13123. if ( image.width > maxSize || image.height > maxSize ) {
  13124. // Warning: Scaling through the canvas will only work with images that use
  13125. // premultiplied alpha.
  13126. var scale = maxSize / Math.max( image.width, image.height );
  13127. var canvas = document.createElement( 'canvas' );
  13128. canvas.width = Math.floor( image.width * scale );
  13129. canvas.height = Math.floor( image.height * scale );
  13130. var context = canvas.getContext( '2d' );
  13131. context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
  13132. console.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  13133. return canvas;
  13134. }
  13135. return image;
  13136. }
  13137. function setCubeTexture ( texture, slot ) {
  13138. if ( texture.image.length === 6 ) {
  13139. if ( texture.needsUpdate ) {
  13140. if ( ! texture.image.__webglTextureCube ) {
  13141. texture.addEventListener( 'dispose', onTextureDispose );
  13142. texture.image.__webglTextureCube = _gl.createTexture();
  13143. _this.info.memory.textures ++;
  13144. }
  13145. state.activeTexture( _gl.TEXTURE0 + slot );
  13146. state.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  13147. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  13148. var isCompressed = texture instanceof THREE.CompressedTexture;
  13149. var isDataTexture = texture.image[ 0 ] instanceof THREE.DataTexture;
  13150. var cubeImage = [];
  13151. for ( var i = 0; i < 6; i ++ ) {
  13152. if ( _this.autoScaleCubemaps && ! isCompressed && ! isDataTexture ) {
  13153. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  13154. } else {
  13155. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  13156. }
  13157. }
  13158. var image = cubeImage[ 0 ],
  13159. isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ),
  13160. glFormat = paramThreeToGL( texture.format ),
  13161. glType = paramThreeToGL( texture.type );
  13162. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  13163. for ( var i = 0; i < 6; i ++ ) {
  13164. if ( ! isCompressed ) {
  13165. if ( isDataTexture ) {
  13166. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  13167. } else {
  13168. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  13169. }
  13170. } else {
  13171. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  13172. for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  13173. mipmap = mipmaps[ j ];
  13174. if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) {
  13175. if ( getCompressedTextureFormats().indexOf( glFormat ) > -1 ) {
  13176. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13177. } else {
  13178. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setCubeTexture()" );
  13179. }
  13180. } else {
  13181. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13182. }
  13183. }
  13184. }
  13185. }
  13186. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  13187. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  13188. }
  13189. texture.needsUpdate = false;
  13190. if ( texture.onUpdate ) texture.onUpdate( texture );
  13191. } else {
  13192. state.activeTexture( _gl.TEXTURE0 + slot );
  13193. state.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  13194. }
  13195. }
  13196. }
  13197. function setCubeTextureDynamic ( texture, slot ) {
  13198. state.activeTexture( _gl.TEXTURE0 + slot );
  13199. state.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  13200. }
  13201. // Render targets
  13202. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  13203. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13204. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  13205. }
  13206. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  13207. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  13208. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  13209. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  13210. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  13211. /* For some reason this is not working. Defaulting to RGBA4.
  13212. } else if ( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  13213. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  13214. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  13215. */
  13216. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  13217. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  13218. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  13219. } else {
  13220. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  13221. }
  13222. }
  13223. this.setRenderTarget = function ( renderTarget ) {
  13224. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  13225. if ( renderTarget && renderTarget.__webglFramebuffer === undefined ) {
  13226. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  13227. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  13228. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  13229. renderTarget.__webglTexture = _gl.createTexture();
  13230. _this.info.memory.textures ++;
  13231. // Setup texture, create render and frame buffers
  13232. var isTargetPowerOfTwo = THREE.Math.isPowerOfTwo( renderTarget.width ) && THREE.Math.isPowerOfTwo( renderTarget.height ),
  13233. glFormat = paramThreeToGL( renderTarget.format ),
  13234. glType = paramThreeToGL( renderTarget.type );
  13235. if ( isCube ) {
  13236. renderTarget.__webglFramebuffer = [];
  13237. renderTarget.__webglRenderbuffer = [];
  13238. state.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  13239. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  13240. for ( var i = 0; i < 6; i ++ ) {
  13241. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  13242. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  13243. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  13244. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  13245. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  13246. }
  13247. if ( renderTarget.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  13248. } else {
  13249. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  13250. if ( renderTarget.shareDepthFrom ) {
  13251. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  13252. } else {
  13253. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  13254. }
  13255. state.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  13256. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  13257. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  13258. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  13259. if ( renderTarget.shareDepthFrom ) {
  13260. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  13261. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  13262. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  13263. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  13264. }
  13265. } else {
  13266. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  13267. }
  13268. if ( renderTarget.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  13269. }
  13270. // Release everything
  13271. if ( isCube ) {
  13272. state.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  13273. } else {
  13274. state.bindTexture( _gl.TEXTURE_2D, null );
  13275. }
  13276. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  13277. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  13278. }
  13279. var framebuffer, width, height, vx, vy;
  13280. if ( renderTarget ) {
  13281. if ( isCube ) {
  13282. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  13283. } else {
  13284. framebuffer = renderTarget.__webglFramebuffer;
  13285. }
  13286. width = renderTarget.width;
  13287. height = renderTarget.height;
  13288. vx = 0;
  13289. vy = 0;
  13290. } else {
  13291. framebuffer = null;
  13292. width = _viewportWidth;
  13293. height = _viewportHeight;
  13294. vx = _viewportX;
  13295. vy = _viewportY;
  13296. }
  13297. if ( framebuffer !== _currentFramebuffer ) {
  13298. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13299. _gl.viewport( vx, vy, width, height );
  13300. _currentFramebuffer = framebuffer;
  13301. }
  13302. _currentWidth = width;
  13303. _currentHeight = height;
  13304. };
  13305. this.readRenderTargetPixels = function( renderTarget, x, y, width, height, buffer ) {
  13306. if ( ! ( renderTarget instanceof THREE.WebGLRenderTarget ) ) {
  13307. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  13308. return;
  13309. }
  13310. if ( renderTarget.__webglFramebuffer ) {
  13311. if ( renderTarget.format !== THREE.RGBAFormat ) {
  13312. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA format. readPixels can read only RGBA format.' );
  13313. return;
  13314. }
  13315. var restore = false;
  13316. if ( renderTarget.__webglFramebuffer !== _currentFramebuffer ) {
  13317. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTarget.__webglFramebuffer );
  13318. restore = true;
  13319. }
  13320. if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
  13321. _gl.readPixels( x, y, width, height, _gl.RGBA, _gl.UNSIGNED_BYTE, buffer );
  13322. } else {
  13323. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  13324. }
  13325. if ( restore ) {
  13326. _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
  13327. }
  13328. }
  13329. };
  13330. function updateRenderTargetMipmap ( renderTarget ) {
  13331. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  13332. state.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  13333. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  13334. state.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  13335. } else {
  13336. state.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  13337. _gl.generateMipmap( _gl.TEXTURE_2D );
  13338. state.bindTexture( _gl.TEXTURE_2D, null );
  13339. }
  13340. }
  13341. // Fallback filters for non-power-of-2 textures
  13342. function filterFallback ( f ) {
  13343. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  13344. return _gl.NEAREST;
  13345. }
  13346. return _gl.LINEAR;
  13347. }
  13348. // Map three.js constants to WebGL constants
  13349. function paramThreeToGL ( p ) {
  13350. var extension;
  13351. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  13352. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  13353. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  13354. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  13355. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  13356. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  13357. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  13358. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  13359. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  13360. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  13361. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  13362. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  13363. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  13364. if ( p === THREE.ByteType ) return _gl.BYTE;
  13365. if ( p === THREE.ShortType ) return _gl.SHORT;
  13366. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  13367. if ( p === THREE.IntType ) return _gl.INT;
  13368. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  13369. if ( p === THREE.FloatType ) return _gl.FLOAT;
  13370. extension = extensions.get( 'OES_texture_half_float' );
  13371. if ( extension !== null ) {
  13372. if ( p === THREE.HalfFloatType ) return extension.HALF_FLOAT_OES;
  13373. }
  13374. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  13375. if ( p === THREE.RGBFormat ) return _gl.RGB;
  13376. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  13377. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  13378. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  13379. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  13380. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  13381. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  13382. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  13383. if ( p === THREE.OneFactor ) return _gl.ONE;
  13384. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  13385. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  13386. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  13387. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  13388. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  13389. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  13390. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  13391. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  13392. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  13393. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  13394. if ( extension !== null ) {
  13395. if ( p === THREE.RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  13396. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  13397. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  13398. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  13399. }
  13400. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  13401. if ( extension !== null ) {
  13402. if ( p === THREE.RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  13403. if ( p === THREE.RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  13404. if ( p === THREE.RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  13405. if ( p === THREE.RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  13406. }
  13407. extension = extensions.get( 'EXT_blend_minmax' );
  13408. if ( extension !== null ) {
  13409. if ( p === THREE.MinEquation ) return extension.MIN_EXT;
  13410. if ( p === THREE.MaxEquation ) return extension.MAX_EXT;
  13411. }
  13412. return 0;
  13413. }
  13414. // Allocations
  13415. function allocateBones ( object ) {
  13416. if ( _supportsBoneTextures && object && object.skeleton && object.skeleton.useVertexTexture ) {
  13417. return 1024;
  13418. } else {
  13419. // default for when object is not specified
  13420. // ( for example when prebuilding shader to be used with multiple objects )
  13421. //
  13422. // - leave some extra space for other uniforms
  13423. // - limit here is ANGLE's 254 max uniform vectors
  13424. // (up to 54 should be safe)
  13425. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  13426. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  13427. var maxBones = nVertexMatrices;
  13428. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  13429. maxBones = Math.min( object.skeleton.bones.length, maxBones );
  13430. if ( maxBones < object.skeleton.bones.length ) {
  13431. console.warn( 'WebGLRenderer: too many bones - ' + object.skeleton.bones.length + ', this GPU supports just ' + maxBones + ' (try OpenGL instead of ANGLE)' );
  13432. }
  13433. }
  13434. return maxBones;
  13435. }
  13436. }
  13437. function allocateLights( lights ) {
  13438. var dirLights = 0;
  13439. var pointLights = 0;
  13440. var spotLights = 0;
  13441. var hemiLights = 0;
  13442. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  13443. var light = lights[ l ];
  13444. if ( light.onlyShadow || light.visible === false ) continue;
  13445. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  13446. if ( light instanceof THREE.PointLight ) pointLights ++;
  13447. if ( light instanceof THREE.SpotLight ) spotLights ++;
  13448. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  13449. }
  13450. return { 'directional': dirLights, 'point': pointLights, 'spot': spotLights, 'hemi': hemiLights };
  13451. }
  13452. function allocateShadows( lights ) {
  13453. var maxShadows = 0;
  13454. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  13455. var light = lights[ l ];
  13456. if ( ! light.castShadow ) continue;
  13457. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  13458. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  13459. }
  13460. return maxShadows;
  13461. }
  13462. // DEPRECATED
  13463. this.initMaterial = function () {
  13464. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  13465. };
  13466. this.addPrePlugin = function () {
  13467. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  13468. };
  13469. this.addPostPlugin = function () {
  13470. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  13471. };
  13472. this.updateShadowMap = function () {
  13473. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  13474. };
  13475. Object.defineProperties( this, {
  13476. shadowMapEnabled: {
  13477. get: function () {
  13478. return shadowMap.enabled;
  13479. },
  13480. set: function ( value ) {
  13481. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  13482. shadowMap.enabled = value;
  13483. }
  13484. },
  13485. shadowMapType: {
  13486. get: function () {
  13487. return shadowMap.type;
  13488. },
  13489. set: function ( value ) {
  13490. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  13491. shadowMap.type = value;
  13492. }
  13493. },
  13494. shadowMapCullFace: {
  13495. get: function () {
  13496. return shadowMap.cullFace;
  13497. },
  13498. set: function ( value ) {
  13499. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace is now .shadowMap.cullFace.' );
  13500. shadowMap.cullFace = value;
  13501. }
  13502. },
  13503. shadowMapDebug: {
  13504. get: function () {
  13505. return shadowMap.debug;
  13506. },
  13507. set: function ( value ) {
  13508. console.warn( 'THREE.WebGLRenderer: .shadowMapDebug is now .shadowMap.debug.' );
  13509. shadowMap.debug = value;
  13510. }
  13511. },
  13512. shadowMapCascade: {
  13513. get: function () {
  13514. return shadowMap.cascade;
  13515. },
  13516. set: function ( value ) {
  13517. console.warn( 'THREE.WebGLRenderer: .shadowMapCascade is now .shadowMap.cascade.' );
  13518. shadowMap.cascade = value;
  13519. }
  13520. }
  13521. } );
  13522. };
  13523. // File:src/renderers/WebGLRenderTarget.js
  13524. /**
  13525. * @author szimek / https://github.com/szimek/
  13526. * @author alteredq / http://alteredqualia.com/
  13527. */
  13528. THREE.WebGLRenderTarget = function ( width, height, options ) {
  13529. this.width = width;
  13530. this.height = height;
  13531. options = options || {};
  13532. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  13533. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  13534. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  13535. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  13536. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  13537. this.offset = new THREE.Vector2( 0, 0 );
  13538. this.repeat = new THREE.Vector2( 1, 1 );
  13539. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  13540. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  13541. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  13542. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  13543. this.generateMipmaps = true;
  13544. this.shareDepthFrom = options.shareDepthFrom !== undefined ? options.shareDepthFrom : null;
  13545. };
  13546. THREE.WebGLRenderTarget.prototype = {
  13547. constructor: THREE.WebGLRenderTarget,
  13548. setSize: function ( width, height ) {
  13549. if ( this.width !== width || this.height !== height ) {
  13550. this.width = width;
  13551. this.height = height;
  13552. this.dispose();
  13553. }
  13554. },
  13555. clone: function () {
  13556. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  13557. tmp.wrapS = this.wrapS;
  13558. tmp.wrapT = this.wrapT;
  13559. tmp.magFilter = this.magFilter;
  13560. tmp.minFilter = this.minFilter;
  13561. tmp.anisotropy = this.anisotropy;
  13562. tmp.offset.copy( this.offset );
  13563. tmp.repeat.copy( this.repeat );
  13564. tmp.format = this.format;
  13565. tmp.type = this.type;
  13566. tmp.depthBuffer = this.depthBuffer;
  13567. tmp.stencilBuffer = this.stencilBuffer;
  13568. tmp.generateMipmaps = this.generateMipmaps;
  13569. tmp.shareDepthFrom = this.shareDepthFrom;
  13570. return tmp;
  13571. },
  13572. dispose: function () {
  13573. this.dispatchEvent( { type: 'dispose' } );
  13574. }
  13575. };
  13576. THREE.EventDispatcher.prototype.apply( THREE.WebGLRenderTarget.prototype );
  13577. // File:src/renderers/WebGLRenderTargetCube.js
  13578. /**
  13579. * @author alteredq / http://alteredqualia.com
  13580. */
  13581. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  13582. THREE.WebGLRenderTarget.call( this, width, height, options );
  13583. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  13584. };
  13585. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  13586. THREE.WebGLRenderTargetCube.prototype.constructor = THREE.WebGLRenderTargetCube;
  13587. // File:src/renderers/webgl/WebGLExtensions.js
  13588. /**
  13589. * @author mrdoob / http://mrdoob.com/
  13590. */
  13591. THREE.WebGLExtensions = function ( gl ) {
  13592. var extensions = {};
  13593. this.get = function ( name ) {
  13594. if ( extensions[ name ] !== undefined ) {
  13595. return extensions[ name ];
  13596. }
  13597. var extension;
  13598. switch ( name ) {
  13599. case 'EXT_texture_filter_anisotropic':
  13600. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  13601. break;
  13602. case 'WEBGL_compressed_texture_s3tc':
  13603. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  13604. break;
  13605. case 'WEBGL_compressed_texture_pvrtc':
  13606. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  13607. break;
  13608. default:
  13609. extension = gl.getExtension( name );
  13610. }
  13611. if ( extension === null ) {
  13612. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  13613. }
  13614. extensions[ name ] = extension;
  13615. return extension;
  13616. };
  13617. };
  13618. // File:src/renderers/webgl/WebGLGeometries.js
  13619. /**
  13620. * @author mrdoob / http://mrdoob.com/
  13621. */
  13622. THREE.WebGLGeometries = function ( gl, info ) {
  13623. var geometries = {};
  13624. this.get = function ( object ) {
  13625. var geometry = object.geometry;
  13626. if ( geometries[ geometry.id ] !== undefined ) {
  13627. return geometries[ geometry.id ];
  13628. }
  13629. geometry.addEventListener( 'dispose', onGeometryDispose );
  13630. if ( geometry instanceof THREE.BufferGeometry ) {
  13631. geometries[ geometry.id ] = geometry;
  13632. } else {
  13633. geometries[ geometry.id ] = new THREE.BufferGeometry().setFromObject( object );
  13634. }
  13635. info.memory.geometries ++;
  13636. return geometries[ geometry.id ];
  13637. };
  13638. function onGeometryDispose( event ) {
  13639. var geometry = event.target;
  13640. geometry.removeEventListener( 'dispose', onGeometryDispose );
  13641. geometry = geometries[ geometry.id ];
  13642. for ( var name in geometry.attributes ) {
  13643. var attribute = geometry.attributes[ name ];
  13644. if ( attribute.buffer !== undefined ) {
  13645. gl.deleteBuffer( attribute.buffer );
  13646. delete attribute.buffer;
  13647. }
  13648. }
  13649. info.memory.geometries --;
  13650. }
  13651. };
  13652. // File:src/renderers/webgl/WebGLObjects.js
  13653. /**
  13654. * @author mrdoob / http://mrdoob.com/
  13655. */
  13656. THREE.WebGLObjects = function ( gl, info ) {
  13657. var objects = {};
  13658. var objectsImmediate = [];
  13659. var morphInfluences = new Float32Array( 8 );
  13660. var geometries = new THREE.WebGLGeometries( gl, info );
  13661. //
  13662. function onObjectRemoved( event ) {
  13663. var object = event.target;
  13664. object.traverse( function ( child ) {
  13665. child.removeEventListener( 'remove', onObjectRemoved );
  13666. removeObject( child );
  13667. } );
  13668. }
  13669. function removeObject( object ) {
  13670. if ( object instanceof THREE.Mesh ||
  13671. object instanceof THREE.PointCloud ||
  13672. object instanceof THREE.Line ) {
  13673. delete objects[ object.id ];
  13674. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  13675. removeInstances( objectsImmediate, object );
  13676. }
  13677. delete object.__webglInit;
  13678. delete object._modelViewMatrix;
  13679. delete object._normalMatrix;
  13680. delete object.__webglActive;
  13681. }
  13682. function removeInstances( objlist, object ) {
  13683. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  13684. if ( objlist[ o ].object === object ) {
  13685. objlist.splice( o, 1 );
  13686. }
  13687. }
  13688. }
  13689. //
  13690. this.objects = objects;
  13691. this.objectsImmediate = objectsImmediate;
  13692. this.geometries = geometries;
  13693. this.init = function ( object ) {
  13694. if ( object.__webglInit === undefined ) {
  13695. object.__webglInit = true;
  13696. object._modelViewMatrix = new THREE.Matrix4();
  13697. object._normalMatrix = new THREE.Matrix3();
  13698. object.addEventListener( 'removed', onObjectRemoved );
  13699. }
  13700. if ( object.__webglActive === undefined ) {
  13701. object.__webglActive = true;
  13702. if ( object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.PointCloud ) {
  13703. objects[ object.id ] = {
  13704. id: object.id,
  13705. object: object,
  13706. z: 0
  13707. };
  13708. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  13709. objectsImmediate.push( {
  13710. id: null,
  13711. object: object,
  13712. opaque: null,
  13713. transparent: null,
  13714. z: 0
  13715. } );
  13716. }
  13717. }
  13718. };
  13719. function numericalSort ( a, b ) {
  13720. return b[ 0 ] - a[ 0 ];
  13721. }
  13722. function updateObject( object ) {
  13723. var geometry = geometries.get( object );
  13724. if ( object.geometry.dynamic === true ) {
  13725. geometry.updateFromObject( object );
  13726. }
  13727. // morph targets
  13728. if ( object.morphTargetInfluences !== undefined ) {
  13729. var activeInfluences = [];
  13730. var morphTargetInfluences = object.morphTargetInfluences;
  13731. for ( var i = 0, l = morphTargetInfluences.length; i < l; i ++ ) {
  13732. var influence = morphTargetInfluences[ i ];
  13733. activeInfluences.push( [ influence, i ] );
  13734. }
  13735. activeInfluences.sort( numericalSort );
  13736. if ( activeInfluences.length > 8 ) {
  13737. activeInfluences.length = 8;
  13738. }
  13739. for ( var i = 0, l = activeInfluences.length; i < l; i ++ ) {
  13740. morphInfluences[ i ] = activeInfluences[ i ][ 0 ];
  13741. var attribute = geometry.morphAttributes[ activeInfluences[ i ][ 1 ] ];
  13742. geometry.addAttribute( 'morphTarget' + i, attribute );
  13743. }
  13744. var material = object.material;
  13745. if ( material.program !== undefined ) {
  13746. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  13747. gl.uniform1fv( material.program.uniforms.morphTargetInfluences, morphInfluences );
  13748. }
  13749. } else {
  13750. console.warn( 'TOFIX: material.program is undefined' );
  13751. }
  13752. }
  13753. //
  13754. var attributes = geometry.attributes;
  13755. for ( var name in attributes ) {
  13756. var attribute = attributes[ name ];
  13757. var bufferType = ( name === 'index' ) ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER;
  13758. var data = ( attribute instanceof THREE.InterleavedBufferAttribute ) ? attribute.data : attribute;
  13759. if ( data.buffer === undefined ) {
  13760. data.buffer = gl.createBuffer();
  13761. gl.bindBuffer( bufferType, data.buffer );
  13762. var usage = gl.STATIC_DRAW;
  13763. if ( data instanceof THREE.DynamicBufferAttribute
  13764. || ( data instanceof THREE.InstancedBufferAttribute && data.dynamic === true )
  13765. || ( data instanceof THREE.InterleavedBuffer && data.dynamic === true ) ) {
  13766. usage = gl.DYNAMIC_DRAW;
  13767. }
  13768. gl.bufferData( bufferType, data.array, usage );
  13769. data.needsUpdate = false;
  13770. } else if ( data.needsUpdate === true ) {
  13771. gl.bindBuffer( bufferType, data.buffer );
  13772. if ( data.updateRange === undefined || data.updateRange.count === -1 ) { // Not using update ranges
  13773. gl.bufferSubData( bufferType, 0, data.array );
  13774. } else if ( data.updateRange.count === 0 ) {
  13775. console.error( 'THREE.WebGLRenderer.updateObject: using updateRange for THREE.DynamicBufferAttribute and marked as needsUpdate but count is 0, ensure you are using set methods or updating manually.' );
  13776. } else {
  13777. gl.bufferSubData( bufferType, data.updateRange.offset * data.array.BYTES_PER_ELEMENT,
  13778. data.array.subarray( data.updateRange.offset, data.updateRange.offset + data.updateRange.count ) );
  13779. data.updateRange.count = 0; // reset range
  13780. }
  13781. data.needsUpdate = false;
  13782. }
  13783. }
  13784. };
  13785. this.update = function ( renderList ) {
  13786. for ( var i = 0, ul = renderList.length; i < ul; i++ ) {
  13787. var object = renderList[i].object;
  13788. if ( object.material.visible !== false ) {
  13789. updateObject( object );
  13790. }
  13791. }
  13792. };
  13793. };
  13794. // File:src/renderers/webgl/WebGLProgram.js
  13795. THREE.WebGLProgram = ( function () {
  13796. var programIdCount = 0;
  13797. function generateDefines( defines ) {
  13798. var chunks = [];
  13799. for ( var name in defines ) {
  13800. var value = defines[ name ];
  13801. if ( value === false ) continue;
  13802. chunks.push( '#define ' + name + ' ' + value );
  13803. }
  13804. return chunks.join( '\n' );
  13805. }
  13806. function cacheUniformLocations( gl, program, identifiers ) {
  13807. var uniforms = {};
  13808. for ( var i = 0, l = identifiers.length; i < l; i ++ ) {
  13809. var id = identifiers[ i ];
  13810. uniforms[ id ] = gl.getUniformLocation( program, id );
  13811. }
  13812. return uniforms;
  13813. }
  13814. function cacheAttributeLocations( gl, program, identifiers ) {
  13815. var attributes = {};
  13816. for ( var i = 0, l = identifiers.length; i < l; i ++ ) {
  13817. var id = identifiers[ i ];
  13818. attributes[ id ] = gl.getAttribLocation( program, id );
  13819. }
  13820. return attributes;
  13821. }
  13822. function programArrayToString( previousValue, currentValue, index, array ) {
  13823. if ( currentValue !== '' && currentValue !== undefined && currentValue !== null ) {
  13824. return previousValue + currentValue + '\n';
  13825. }
  13826. return previousValue;
  13827. }
  13828. return function ( renderer, code, material, parameters ) {
  13829. var gl = renderer.context;
  13830. var defines = material.defines;
  13831. var uniforms = material.__webglShader.uniforms;
  13832. var attributes = material.attributes;
  13833. var vertexShader = material.__webglShader.vertexShader;
  13834. var fragmentShader = material.__webglShader.fragmentShader;
  13835. var index0AttributeName = material.index0AttributeName;
  13836. /*
  13837. if ( index0AttributeName === undefined && parameters.morphTargets === true ) {
  13838. // programs with morphTargets displace position out of attribute 0
  13839. index0AttributeName = 'position';
  13840. }
  13841. */
  13842. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  13843. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  13844. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  13845. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  13846. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  13847. }
  13848. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  13849. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  13850. var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  13851. if ( parameters.envMap ) {
  13852. switch ( material.envMap.mapping ) {
  13853. case THREE.CubeReflectionMapping:
  13854. case THREE.CubeRefractionMapping:
  13855. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  13856. break;
  13857. case THREE.EquirectangularReflectionMapping:
  13858. case THREE.EquirectangularRefractionMapping:
  13859. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  13860. break;
  13861. case THREE.SphericalReflectionMapping:
  13862. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  13863. break;
  13864. }
  13865. switch ( material.envMap.mapping ) {
  13866. case THREE.CubeRefractionMapping:
  13867. case THREE.EquirectangularRefractionMapping:
  13868. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  13869. break;
  13870. }
  13871. switch ( material.combine ) {
  13872. case THREE.MultiplyOperation:
  13873. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  13874. break;
  13875. case THREE.MixOperation:
  13876. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  13877. break;
  13878. case THREE.AddOperation:
  13879. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  13880. break;
  13881. }
  13882. }
  13883. var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  13884. // console.log( 'building new program ' );
  13885. //
  13886. var customDefines = generateDefines( defines );
  13887. //
  13888. var program = gl.createProgram();
  13889. var prefix_vertex, prefix_fragment;
  13890. if ( material instanceof THREE.RawShaderMaterial ) {
  13891. prefix_vertex = '';
  13892. prefix_fragment = '';
  13893. } else {
  13894. prefix_vertex = [
  13895. 'precision ' + parameters.precision + ' float;',
  13896. 'precision ' + parameters.precision + ' int;',
  13897. customDefines,
  13898. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  13899. renderer.gammaInput ? '#define GAMMA_INPUT' : '',
  13900. renderer.gammaOutput ? '#define GAMMA_OUTPUT' : '',
  13901. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  13902. '#define MAX_DIR_LIGHTS ' + parameters.maxDirLights,
  13903. '#define MAX_POINT_LIGHTS ' + parameters.maxPointLights,
  13904. '#define MAX_SPOT_LIGHTS ' + parameters.maxSpotLights,
  13905. '#define MAX_HEMI_LIGHTS ' + parameters.maxHemiLights,
  13906. '#define MAX_SHADOWS ' + parameters.maxShadows,
  13907. '#define MAX_BONES ' + parameters.maxBones,
  13908. parameters.map ? '#define USE_MAP' : '',
  13909. parameters.envMap ? '#define USE_ENVMAP' : '',
  13910. parameters.envMap ? '#define ' + envMapModeDefine : '',
  13911. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  13912. parameters.aoMap ? '#define USE_AOMAP' : '',
  13913. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  13914. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  13915. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  13916. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  13917. parameters.vertexColors ? '#define USE_COLOR' : '',
  13918. parameters.flatShading ? '#define FLAT_SHADED': '',
  13919. parameters.skinning ? '#define USE_SKINNING' : '',
  13920. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  13921. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  13922. parameters.morphNormals ? '#define USE_MORPHNORMALS' : '',
  13923. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  13924. parameters.flipSided ? '#define FLIP_SIDED' : '',
  13925. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  13926. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  13927. parameters.shadowMapDebug ? '#define SHADOWMAP_DEBUG' : '',
  13928. parameters.shadowMapCascade ? '#define SHADOWMAP_CASCADE' : '',
  13929. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  13930. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  13931. parameters.logarithmicDepthBuffer && renderer.extensions.get('EXT_frag_depth') ? '#define USE_LOGDEPTHBUF_EXT' : '',
  13932. 'uniform mat4 modelMatrix;',
  13933. 'uniform mat4 modelViewMatrix;',
  13934. 'uniform mat4 projectionMatrix;',
  13935. 'uniform mat4 viewMatrix;',
  13936. 'uniform mat3 normalMatrix;',
  13937. 'uniform vec3 cameraPosition;',
  13938. 'attribute vec3 position;',
  13939. 'attribute vec3 normal;',
  13940. 'attribute vec2 uv;',
  13941. '#ifdef USE_COLOR',
  13942. ' attribute vec3 color;',
  13943. '#endif',
  13944. '#ifdef USE_MORPHTARGETS',
  13945. ' attribute vec3 morphTarget0;',
  13946. ' attribute vec3 morphTarget1;',
  13947. ' attribute vec3 morphTarget2;',
  13948. ' attribute vec3 morphTarget3;',
  13949. ' #ifdef USE_MORPHNORMALS',
  13950. ' attribute vec3 morphNormal0;',
  13951. ' attribute vec3 morphNormal1;',
  13952. ' attribute vec3 morphNormal2;',
  13953. ' attribute vec3 morphNormal3;',
  13954. ' #else',
  13955. ' attribute vec3 morphTarget4;',
  13956. ' attribute vec3 morphTarget5;',
  13957. ' attribute vec3 morphTarget6;',
  13958. ' attribute vec3 morphTarget7;',
  13959. ' #endif',
  13960. '#endif',
  13961. '#ifdef USE_SKINNING',
  13962. ' attribute vec4 skinIndex;',
  13963. ' attribute vec4 skinWeight;',
  13964. '#endif',
  13965. ''
  13966. ].reduce( programArrayToString, '' );
  13967. prefix_fragment = [
  13968. ( parameters.bumpMap || parameters.normalMap || parameters.flatShading || material.derivatives ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  13969. 'precision ' + parameters.precision + ' float;',
  13970. 'precision ' + parameters.precision + ' int;',
  13971. customDefines,
  13972. '#define MAX_DIR_LIGHTS ' + parameters.maxDirLights,
  13973. '#define MAX_POINT_LIGHTS ' + parameters.maxPointLights,
  13974. '#define MAX_SPOT_LIGHTS ' + parameters.maxSpotLights,
  13975. '#define MAX_HEMI_LIGHTS ' + parameters.maxHemiLights,
  13976. '#define MAX_SHADOWS ' + parameters.maxShadows,
  13977. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest : '',
  13978. renderer.gammaInput ? '#define GAMMA_INPUT' : '',
  13979. renderer.gammaOutput ? '#define GAMMA_OUTPUT' : '',
  13980. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  13981. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  13982. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  13983. parameters.map ? '#define USE_MAP' : '',
  13984. parameters.envMap ? '#define USE_ENVMAP' : '',
  13985. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  13986. parameters.envMap ? '#define ' + envMapModeDefine : '',
  13987. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  13988. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  13989. parameters.aoMap ? '#define USE_AOMAP' : '',
  13990. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  13991. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  13992. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  13993. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  13994. parameters.vertexColors ? '#define USE_COLOR' : '',
  13995. parameters.flatShading ? '#define FLAT_SHADED': '',
  13996. parameters.metal ? '#define METAL' : '',
  13997. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  13998. parameters.flipSided ? '#define FLIP_SIDED' : '',
  13999. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  14000. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  14001. parameters.shadowMapDebug ? '#define SHADOWMAP_DEBUG' : '',
  14002. parameters.shadowMapCascade ? '#define SHADOWMAP_CASCADE' : '',
  14003. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  14004. parameters.logarithmicDepthBuffer && renderer.extensions.get('EXT_frag_depth') ? '#define USE_LOGDEPTHBUF_EXT' : '',
  14005. 'uniform mat4 viewMatrix;',
  14006. 'uniform vec3 cameraPosition;',
  14007. ''
  14008. ].reduce( programArrayToString, '' );
  14009. }
  14010. var glVertexShader = new THREE.WebGLShader( gl, gl.VERTEX_SHADER, prefix_vertex + vertexShader );
  14011. var glFragmentShader = new THREE.WebGLShader( gl, gl.FRAGMENT_SHADER, prefix_fragment + fragmentShader );
  14012. gl.attachShader( program, glVertexShader );
  14013. gl.attachShader( program, glFragmentShader );
  14014. if ( index0AttributeName !== undefined ) {
  14015. // Force a particular attribute to index 0.
  14016. // because potentially expensive emulation is done by browser if attribute 0 is disabled.
  14017. // And, color, for example is often automatically bound to index 0 so disabling it
  14018. gl.bindAttribLocation( program, 0, index0AttributeName );
  14019. }
  14020. gl.linkProgram( program );
  14021. var programLogInfo = gl.getProgramInfoLog( program );
  14022. var vertexErrorLogInfo = gl.getShaderInfoLog( glVertexShader );
  14023. var fragmentErrorLogInfo = gl.getShaderInfoLog( glFragmentShader );
  14024. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  14025. console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), 'gl.VALIDATE_STATUS', gl.getProgramParameter( program, gl.VALIDATE_STATUS ), 'gl.getProgramInfoLog', programLogInfo, vertexErrorLogInfo, fragmentErrorLogInfo );
  14026. }
  14027. if ( programLogInfo !== '' ) {
  14028. console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLogInfo );
  14029. }
  14030. // clean up
  14031. gl.deleteShader( glVertexShader );
  14032. gl.deleteShader( glFragmentShader );
  14033. // cache uniform locations
  14034. var identifiers = [
  14035. 'viewMatrix',
  14036. 'modelViewMatrix',
  14037. 'projectionMatrix',
  14038. 'normalMatrix',
  14039. 'modelMatrix',
  14040. 'cameraPosition',
  14041. 'morphTargetInfluences',
  14042. 'bindMatrix',
  14043. 'bindMatrixInverse'
  14044. ];
  14045. if ( parameters.useVertexTexture ) {
  14046. identifiers.push( 'boneTexture', 'boneTextureWidth', 'boneTextureHeight' );
  14047. } else {
  14048. identifiers.push( 'boneGlobalMatrices' );
  14049. }
  14050. if ( parameters.logarithmicDepthBuffer ) {
  14051. identifiers.push( 'logDepthBufFC' );
  14052. }
  14053. for ( var u in uniforms ) {
  14054. identifiers.push( u );
  14055. }
  14056. this.uniforms = cacheUniformLocations( gl, program, identifiers );
  14057. // cache attributes locations
  14058. if ( material instanceof THREE.RawShaderMaterial ) {
  14059. identifiers = attributes;
  14060. } else {
  14061. identifiers = [
  14062. 'position',
  14063. 'normal',
  14064. 'uv',
  14065. 'uv2',
  14066. 'tangent',
  14067. 'color',
  14068. 'skinIndex',
  14069. 'skinWeight',
  14070. 'lineDistance'
  14071. ];
  14072. for ( var i = 0; i < parameters.maxMorphTargets; i ++ ) {
  14073. identifiers.push( 'morphTarget' + i );
  14074. }
  14075. for ( var i = 0; i < parameters.maxMorphNormals; i ++ ) {
  14076. identifiers.push( 'morphNormal' + i );
  14077. }
  14078. // ShaderMaterial attributes
  14079. if ( Array.isArray( attributes ) ) {
  14080. identifiers = identifiers.concat( attributes );
  14081. }
  14082. }
  14083. this.attributes = cacheAttributeLocations( gl, program, identifiers );
  14084. //
  14085. this.id = programIdCount ++;
  14086. this.code = code;
  14087. this.usedTimes = 1;
  14088. this.program = program;
  14089. this.vertexShader = glVertexShader;
  14090. this.fragmentShader = glFragmentShader;
  14091. return this;
  14092. };
  14093. } )();
  14094. // File:src/renderers/webgl/WebGLShader.js
  14095. THREE.WebGLShader = ( function () {
  14096. var addLineNumbers = function ( string ) {
  14097. var lines = string.split( '\n' );
  14098. for ( var i = 0; i < lines.length; i ++ ) {
  14099. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  14100. }
  14101. return lines.join( '\n' );
  14102. };
  14103. return function ( gl, type, string ) {
  14104. var shader = gl.createShader( type );
  14105. gl.shaderSource( shader, string );
  14106. gl.compileShader( shader );
  14107. if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) {
  14108. console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' );
  14109. }
  14110. if ( gl.getShaderInfoLog( shader ) !== '' ) {
  14111. console.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', type === gl.VERTEX_SHADER ? 'vertex' : 'fragment', gl.getShaderInfoLog( shader ), addLineNumbers( string ) );
  14112. }
  14113. // --enable-privileged-webgl-extension
  14114. // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  14115. return shader;
  14116. };
  14117. } )();
  14118. // File:src/renderers/webgl/WebGLShadowMap.js
  14119. /**
  14120. * @author alteredq / http://alteredqualia.com/
  14121. * @author mrdoob / http://mrdoob.com/
  14122. */
  14123. THREE.WebGLShadowMap = function ( _renderer, _lights, _objects ) {
  14124. var _gl = _renderer.context,
  14125. _frustum = new THREE.Frustum(),
  14126. _projScreenMatrix = new THREE.Matrix4(),
  14127. _min = new THREE.Vector3(),
  14128. _max = new THREE.Vector3(),
  14129. _webglObjects = _objects.objects,
  14130. _webglObjectsImmediate = _objects.objectsImmediate,
  14131. _matrixPosition = new THREE.Vector3(),
  14132. _renderList = [];
  14133. // init
  14134. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  14135. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  14136. var _depthMaterial = new THREE.ShaderMaterial( {
  14137. uniforms: depthUniforms,
  14138. vertexShader: depthShader.vertexShader,
  14139. fragmentShader: depthShader.fragmentShader
  14140. } );
  14141. var _depthMaterialMorph = new THREE.ShaderMaterial( {
  14142. uniforms: depthUniforms,
  14143. vertexShader: depthShader.vertexShader,
  14144. fragmentShader: depthShader.fragmentShader,
  14145. morphTargets: true
  14146. } );
  14147. var _depthMaterialSkin = new THREE.ShaderMaterial( {
  14148. uniforms: depthUniforms,
  14149. vertexShader: depthShader.vertexShader,
  14150. fragmentShader: depthShader.fragmentShader,
  14151. skinning: true
  14152. } );
  14153. var _depthMaterialMorphSkin = new THREE.ShaderMaterial( {
  14154. uniforms: depthUniforms,
  14155. vertexShader: depthShader.vertexShader,
  14156. fragmentShader: depthShader.fragmentShader,
  14157. morphTargets: true,
  14158. skinning: true
  14159. } );
  14160. _depthMaterial._shadowPass = true;
  14161. _depthMaterialMorph._shadowPass = true;
  14162. _depthMaterialSkin._shadowPass = true;
  14163. _depthMaterialMorphSkin._shadowPass = true;
  14164. //
  14165. var scope = this;
  14166. this.enabled = false;
  14167. this.type = THREE.PCFShadowMap;
  14168. this.cullFace = THREE.CullFaceFront;
  14169. this.debug = false;
  14170. this.cascade = false;
  14171. this.render = function ( scene, camera ) {
  14172. if ( scope.enabled === false ) return;
  14173. var i, il, j, jl, n,
  14174. shadowMap, shadowMatrix, shadowCamera,
  14175. webglObject, object, material, light,
  14176. lights = [],
  14177. k = 0,
  14178. fog = null;
  14179. // set GL state for depth map
  14180. _gl.clearColor( 1, 1, 1, 1 );
  14181. _gl.disable( _gl.BLEND );
  14182. _gl.enable( _gl.CULL_FACE );
  14183. _gl.frontFace( _gl.CCW );
  14184. if ( scope.cullFace === THREE.CullFaceFront ) {
  14185. _gl.cullFace( _gl.FRONT );
  14186. } else {
  14187. _gl.cullFace( _gl.BACK );
  14188. }
  14189. _renderer.state.setDepthTest( true );
  14190. // preprocess lights
  14191. // - skip lights that are not casting shadows
  14192. // - create virtual lights for cascaded shadow maps
  14193. for ( i = 0, il = _lights.length; i < il; i ++ ) {
  14194. light = _lights[ i ];
  14195. if ( ! light.castShadow ) continue;
  14196. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  14197. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  14198. var virtualLight;
  14199. if ( ! light.shadowCascadeArray[ n ] ) {
  14200. virtualLight = createVirtualLight( light, n );
  14201. virtualLight.originalCamera = camera;
  14202. var gyro = new THREE.Gyroscope();
  14203. gyro.position.copy( light.shadowCascadeOffset );
  14204. gyro.add( virtualLight );
  14205. gyro.add( virtualLight.target );
  14206. camera.add( gyro );
  14207. light.shadowCascadeArray[ n ] = virtualLight;
  14208. //console.log( "Created virtualLight", virtualLight );
  14209. } else {
  14210. virtualLight = light.shadowCascadeArray[ n ];
  14211. }
  14212. updateVirtualLight( light, n );
  14213. lights[ k ] = virtualLight;
  14214. k ++;
  14215. }
  14216. } else {
  14217. lights[ k ] = light;
  14218. k ++;
  14219. }
  14220. }
  14221. // render depth map
  14222. for ( i = 0, il = lights.length; i < il; i ++ ) {
  14223. light = lights[ i ];
  14224. if ( ! light.shadowMap ) {
  14225. var shadowFilter = THREE.LinearFilter;
  14226. if ( scope.type === THREE.PCFSoftShadowMap ) {
  14227. shadowFilter = THREE.NearestFilter;
  14228. }
  14229. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  14230. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  14231. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  14232. light.shadowMatrix = new THREE.Matrix4();
  14233. }
  14234. if ( ! light.shadowCamera ) {
  14235. if ( light instanceof THREE.SpotLight ) {
  14236. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  14237. } else if ( light instanceof THREE.DirectionalLight ) {
  14238. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  14239. } else {
  14240. console.error( "THREE.ShadowMapPlugin: Unsupported light type for shadow", light );
  14241. continue;
  14242. }
  14243. scene.add( light.shadowCamera );
  14244. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  14245. }
  14246. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  14247. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  14248. scene.add( light.cameraHelper );
  14249. }
  14250. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  14251. updateShadowCamera( camera, light );
  14252. }
  14253. shadowMap = light.shadowMap;
  14254. shadowMatrix = light.shadowMatrix;
  14255. shadowCamera = light.shadowCamera;
  14256. //
  14257. shadowCamera.position.setFromMatrixPosition( light.matrixWorld );
  14258. _matrixPosition.setFromMatrixPosition( light.target.matrixWorld );
  14259. shadowCamera.lookAt( _matrixPosition );
  14260. shadowCamera.updateMatrixWorld();
  14261. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  14262. //
  14263. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  14264. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  14265. // compute shadow matrix
  14266. shadowMatrix.set(
  14267. 0.5, 0.0, 0.0, 0.5,
  14268. 0.0, 0.5, 0.0, 0.5,
  14269. 0.0, 0.0, 0.5, 0.5,
  14270. 0.0, 0.0, 0.0, 1.0
  14271. );
  14272. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  14273. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  14274. // update camera matrices and frustum
  14275. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  14276. _frustum.setFromMatrix( _projScreenMatrix );
  14277. // render shadow map
  14278. _renderer.setRenderTarget( shadowMap );
  14279. _renderer.clear();
  14280. // set object matrices & frustum culling
  14281. _renderList.length = 0;
  14282. projectObject( scene, shadowCamera );
  14283. // render regular objects
  14284. var objectMaterial, useMorphing, useSkinning;
  14285. for ( j = 0, jl = _renderList.length; j < jl; j ++ ) {
  14286. webglObject = _renderList[ j ];
  14287. object = webglObject.object;
  14288. // culling is overriden globally for all objects
  14289. // while rendering depth map
  14290. // need to deal with MeshFaceMaterial somehow
  14291. // in that case just use the first of material.materials for now
  14292. // (proper solution would require to break objects by materials
  14293. // similarly to regular rendering and then set corresponding
  14294. // depth materials per each chunk instead of just once per object)
  14295. objectMaterial = getObjectMaterial( object );
  14296. useMorphing = object.geometry.morphTargets !== undefined && object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  14297. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  14298. if ( object.customDepthMaterial ) {
  14299. material = object.customDepthMaterial;
  14300. } else if ( useSkinning ) {
  14301. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  14302. } else if ( useMorphing ) {
  14303. material = _depthMaterialMorph;
  14304. } else {
  14305. material = _depthMaterial;
  14306. }
  14307. _renderer.setMaterialFaces( objectMaterial );
  14308. _renderer.renderBufferDirect( shadowCamera, _lights, fog, material, object );
  14309. }
  14310. // set matrices and render immediate objects
  14311. for ( j = 0, jl = _webglObjectsImmediate.length; j < jl; j ++ ) {
  14312. webglObject = _webglObjectsImmediate[ j ];
  14313. object = webglObject.object;
  14314. if ( object.visible && object.castShadow ) {
  14315. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  14316. _renderer.renderImmediateObject( shadowCamera, _lights, fog, _depthMaterial, object );
  14317. }
  14318. }
  14319. }
  14320. // restore GL state
  14321. var clearColor = _renderer.getClearColor(),
  14322. clearAlpha = _renderer.getClearAlpha();
  14323. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  14324. _gl.enable( _gl.BLEND );
  14325. if ( scope.cullFace === THREE.CullFaceFront ) {
  14326. _gl.cullFace( _gl.BACK );
  14327. }
  14328. _renderer.resetGLState();
  14329. };
  14330. function projectObject( object, shadowCamera ) {
  14331. if ( object.visible === true ) {
  14332. var webglObject = _objects.objects[ object.id ];
  14333. if ( webglObject && object.castShadow && ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) ) {
  14334. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  14335. _renderList.push( webglObject );
  14336. }
  14337. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  14338. projectObject( object.children[ i ], shadowCamera );
  14339. }
  14340. }
  14341. }
  14342. function createVirtualLight( light, cascade ) {
  14343. var virtualLight = new THREE.DirectionalLight();
  14344. virtualLight.isVirtual = true;
  14345. virtualLight.onlyShadow = true;
  14346. virtualLight.castShadow = true;
  14347. virtualLight.shadowCameraNear = light.shadowCameraNear;
  14348. virtualLight.shadowCameraFar = light.shadowCameraFar;
  14349. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  14350. virtualLight.shadowCameraRight = light.shadowCameraRight;
  14351. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  14352. virtualLight.shadowCameraTop = light.shadowCameraTop;
  14353. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  14354. virtualLight.shadowDarkness = light.shadowDarkness;
  14355. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  14356. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  14357. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  14358. virtualLight.pointsWorld = [];
  14359. virtualLight.pointsFrustum = [];
  14360. var pointsWorld = virtualLight.pointsWorld,
  14361. pointsFrustum = virtualLight.pointsFrustum;
  14362. for ( var i = 0; i < 8; i ++ ) {
  14363. pointsWorld[ i ] = new THREE.Vector3();
  14364. pointsFrustum[ i ] = new THREE.Vector3();
  14365. }
  14366. var nearZ = light.shadowCascadeNearZ[ cascade ];
  14367. var farZ = light.shadowCascadeFarZ[ cascade ];
  14368. pointsFrustum[ 0 ].set( - 1, - 1, nearZ );
  14369. pointsFrustum[ 1 ].set( 1, - 1, nearZ );
  14370. pointsFrustum[ 2 ].set( - 1, 1, nearZ );
  14371. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  14372. pointsFrustum[ 4 ].set( - 1, - 1, farZ );
  14373. pointsFrustum[ 5 ].set( 1, - 1, farZ );
  14374. pointsFrustum[ 6 ].set( - 1, 1, farZ );
  14375. pointsFrustum[ 7 ].set( 1, 1, farZ );
  14376. return virtualLight;
  14377. }
  14378. // Synchronize virtual light with the original light
  14379. function updateVirtualLight( light, cascade ) {
  14380. var virtualLight = light.shadowCascadeArray[ cascade ];
  14381. virtualLight.position.copy( light.position );
  14382. virtualLight.target.position.copy( light.target.position );
  14383. virtualLight.lookAt( virtualLight.target );
  14384. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  14385. virtualLight.shadowDarkness = light.shadowDarkness;
  14386. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  14387. var nearZ = light.shadowCascadeNearZ[ cascade ];
  14388. var farZ = light.shadowCascadeFarZ[ cascade ];
  14389. var pointsFrustum = virtualLight.pointsFrustum;
  14390. pointsFrustum[ 0 ].z = nearZ;
  14391. pointsFrustum[ 1 ].z = nearZ;
  14392. pointsFrustum[ 2 ].z = nearZ;
  14393. pointsFrustum[ 3 ].z = nearZ;
  14394. pointsFrustum[ 4 ].z = farZ;
  14395. pointsFrustum[ 5 ].z = farZ;
  14396. pointsFrustum[ 6 ].z = farZ;
  14397. pointsFrustum[ 7 ].z = farZ;
  14398. }
  14399. // Fit shadow camera's ortho frustum to camera frustum
  14400. function updateShadowCamera( camera, light ) {
  14401. var shadowCamera = light.shadowCamera,
  14402. pointsFrustum = light.pointsFrustum,
  14403. pointsWorld = light.pointsWorld;
  14404. _min.set( Infinity, Infinity, Infinity );
  14405. _max.set( - Infinity, - Infinity, - Infinity );
  14406. for ( var i = 0; i < 8; i ++ ) {
  14407. var p = pointsWorld[ i ];
  14408. p.copy( pointsFrustum[ i ] );
  14409. p.unproject( camera );
  14410. p.applyMatrix4( shadowCamera.matrixWorldInverse );
  14411. if ( p.x < _min.x ) _min.x = p.x;
  14412. if ( p.x > _max.x ) _max.x = p.x;
  14413. if ( p.y < _min.y ) _min.y = p.y;
  14414. if ( p.y > _max.y ) _max.y = p.y;
  14415. if ( p.z < _min.z ) _min.z = p.z;
  14416. if ( p.z > _max.z ) _max.z = p.z;
  14417. }
  14418. shadowCamera.left = _min.x;
  14419. shadowCamera.right = _max.x;
  14420. shadowCamera.top = _max.y;
  14421. shadowCamera.bottom = _min.y;
  14422. // can't really fit near/far
  14423. //shadowCamera.near = _min.z;
  14424. //shadowCamera.far = _max.z;
  14425. shadowCamera.updateProjectionMatrix();
  14426. }
  14427. // For the moment just ignore objects that have multiple materials with different animation methods
  14428. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  14429. function getObjectMaterial( object ) {
  14430. return object.material instanceof THREE.MeshFaceMaterial
  14431. ? object.material.materials[ 0 ]
  14432. : object.material;
  14433. }
  14434. };
  14435. // File:src/renderers/webgl/WebGLState.js
  14436. /**
  14437. * @author mrdoob / http://mrdoob.com/
  14438. */
  14439. THREE.WebGLState = function ( gl, paramThreeToGL ) {
  14440. var _this = this;
  14441. var newAttributes = new Uint8Array( 16 );
  14442. var enabledAttributes = new Uint8Array( 16 );
  14443. var currentBlending = null;
  14444. var currentBlendEquation = null;
  14445. var currentBlendSrc = null;
  14446. var currentBlendDst = null;
  14447. var currentBlendEquationAlpha = null;
  14448. var currentBlendSrcAlpha = null;
  14449. var currentBlendDstAlpha = null;
  14450. var currentDepthFunc = null;
  14451. var currentDepthTest = null;
  14452. var currentDepthWrite = null;
  14453. var currentColorWrite = null;
  14454. var currentDoubleSided = null;
  14455. var currentFlipSided = null;
  14456. var currentLineWidth = null;
  14457. var currentPolygonOffset = null;
  14458. var currentPolygonOffsetFactor = null;
  14459. var currentPolygonOffsetUnits = null;
  14460. var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  14461. var currentTextureSlot = undefined;
  14462. var currentBoundTextures = {};
  14463. this.initAttributes = function () {
  14464. for ( var i = 0, l = newAttributes.length; i < l; i ++ ) {
  14465. newAttributes[ i ] = 0;
  14466. }
  14467. };
  14468. this.enableAttribute = function ( attribute ) {
  14469. newAttributes[ attribute ] = 1;
  14470. if ( enabledAttributes[ attribute ] === 0 ) {
  14471. gl.enableVertexAttribArray( attribute );
  14472. enabledAttributes[ attribute ] = 1;
  14473. }
  14474. };
  14475. this.disableUnusedAttributes = function () {
  14476. for ( var i = 0, l = enabledAttributes.length; i < l; i ++ ) {
  14477. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  14478. gl.disableVertexAttribArray( i );
  14479. enabledAttributes[ i ] = 0;
  14480. }
  14481. }
  14482. };
  14483. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha ) {
  14484. if ( blending !== currentBlending ) {
  14485. if ( blending === THREE.NoBlending ) {
  14486. gl.disable( gl.BLEND );
  14487. } else if ( blending === THREE.AdditiveBlending ) {
  14488. gl.enable( gl.BLEND );
  14489. gl.blendEquation( gl.FUNC_ADD );
  14490. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  14491. } else if ( blending === THREE.SubtractiveBlending ) {
  14492. // TODO: Find blendFuncSeparate() combination
  14493. gl.enable( gl.BLEND );
  14494. gl.blendEquation( gl.FUNC_ADD );
  14495. gl.blendFunc( gl.ZERO, gl.ONE_MINUS_SRC_COLOR );
  14496. } else if ( blending === THREE.MultiplyBlending ) {
  14497. // TODO: Find blendFuncSeparate() combination
  14498. gl.enable( gl.BLEND );
  14499. gl.blendEquation( gl.FUNC_ADD );
  14500. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  14501. } else if ( blending === THREE.CustomBlending ) {
  14502. gl.enable( gl.BLEND );
  14503. } else {
  14504. gl.enable( gl.BLEND );
  14505. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  14506. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  14507. }
  14508. currentBlending = blending;
  14509. }
  14510. if ( blending === THREE.CustomBlending ) {
  14511. blendEquationAlpha = blendEquationAlpha || blendEquation;
  14512. blendSrcAlpha = blendSrcAlpha || blendSrc;
  14513. blendDstAlpha = blendDstAlpha || blendDst;
  14514. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  14515. gl.blendEquationSeparate( paramThreeToGL( blendEquation ), paramThreeToGL( blendEquationAlpha ) );
  14516. currentBlendEquation = blendEquation;
  14517. currentBlendEquationAlpha = blendEquationAlpha;
  14518. }
  14519. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  14520. gl.blendFuncSeparate( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ), paramThreeToGL( blendSrcAlpha ), paramThreeToGL( blendDstAlpha ) );
  14521. currentBlendSrc = blendSrc;
  14522. currentBlendDst = blendDst;
  14523. currentBlendSrcAlpha = blendSrcAlpha;
  14524. currentBlendDstAlpha = blendDstAlpha;
  14525. }
  14526. } else {
  14527. currentBlendEquation = null;
  14528. currentBlendSrc = null;
  14529. currentBlendDst = null;
  14530. currentBlendEquationAlpha = null;
  14531. currentBlendSrcAlpha = null;
  14532. currentBlendDstAlpha = null;
  14533. }
  14534. };
  14535. this.setDepthFunc = function ( depthFunc ) {
  14536. if ( currentDepthFunc !== depthFunc ) {
  14537. if ( depthFunc ) {
  14538. switch ( depthFunc ) {
  14539. case THREE.NeverDepth:
  14540. gl.depthFunc( gl.NEVER );
  14541. break;
  14542. case THREE.AlwaysDepth:
  14543. gl.depthFunc( gl.ALWAYS );
  14544. break;
  14545. case THREE.LessDepth:
  14546. gl.depthFunc( gl.LESS );
  14547. break;
  14548. case THREE.LessEqualDepth:
  14549. gl.depthFunc( gl.LEQUAL );
  14550. break;
  14551. case THREE.EqualDepth:
  14552. gl.depthFunc( gl.EQUAL );
  14553. break;
  14554. case THREE.GreaterEqualDepth:
  14555. gl.depthFunc( gl.GEQUAL );
  14556. break;
  14557. case THREE.GreaterDepth:
  14558. gl.depthFunc( gl.GREATER );
  14559. break;
  14560. case THREE.NotEqualDepth:
  14561. gl.depthFunc( gl.NOTEQUAL );
  14562. break;
  14563. default:
  14564. gl.depthFunc( gl.LEQUAL );
  14565. }
  14566. } else {
  14567. gl.depthFunc( gl.LEQUAL );
  14568. }
  14569. currentDepthFunc = depthFunc;
  14570. }
  14571. };
  14572. this.setDepthTest = function ( depthTest ) {
  14573. if ( currentDepthTest !== depthTest ) {
  14574. if ( depthTest ) {
  14575. gl.enable( gl.DEPTH_TEST );
  14576. } else {
  14577. gl.disable( gl.DEPTH_TEST );
  14578. }
  14579. currentDepthTest = depthTest;
  14580. }
  14581. };
  14582. this.setDepthWrite = function ( depthWrite ) {
  14583. if ( currentDepthWrite !== depthWrite ) {
  14584. gl.depthMask( depthWrite );
  14585. currentDepthWrite = depthWrite;
  14586. }
  14587. };
  14588. this.setColorWrite = function ( colorWrite ) {
  14589. if ( currentColorWrite !== colorWrite ) {
  14590. gl.colorMask( colorWrite, colorWrite, colorWrite, colorWrite );
  14591. currentColorWrite = colorWrite;
  14592. }
  14593. };
  14594. this.setDoubleSided = function ( doubleSided ) {
  14595. if ( currentDoubleSided !== doubleSided ) {
  14596. if ( doubleSided ) {
  14597. gl.disable( gl.CULL_FACE );
  14598. } else {
  14599. gl.enable( gl.CULL_FACE );
  14600. }
  14601. currentDoubleSided = doubleSided;
  14602. }
  14603. };
  14604. this.setFlipSided = function ( flipSided ) {
  14605. if ( currentFlipSided !== flipSided ) {
  14606. if ( flipSided ) {
  14607. gl.frontFace( gl.CW );
  14608. } else {
  14609. gl.frontFace( gl.CCW );
  14610. }
  14611. currentFlipSided = flipSided;
  14612. }
  14613. };
  14614. this.setLineWidth = function ( width ) {
  14615. if ( width !== currentLineWidth ) {
  14616. gl.lineWidth( width );
  14617. currentLineWidth = width;
  14618. }
  14619. };
  14620. this.setPolygonOffset = function ( polygonoffset, factor, units ) {
  14621. if ( currentPolygonOffset !== polygonoffset ) {
  14622. if ( polygonoffset ) {
  14623. gl.enable( gl.POLYGON_OFFSET_FILL );
  14624. } else {
  14625. gl.disable( gl.POLYGON_OFFSET_FILL );
  14626. }
  14627. currentPolygonOffset = polygonoffset;
  14628. }
  14629. if ( polygonoffset && ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) ) {
  14630. gl.polygonOffset( factor, units );
  14631. currentPolygonOffsetFactor = factor;
  14632. currentPolygonOffsetUnits = units;
  14633. }
  14634. };
  14635. // texture
  14636. this.activeTexture = function ( webglSlot ) {
  14637. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  14638. if ( currentTextureSlot !== webglSlot ) {
  14639. gl.activeTexture( webglSlot );
  14640. currentTextureSlot = webglSlot;
  14641. }
  14642. }
  14643. this.bindTexture = function ( webglType, webglTexture ) {
  14644. if ( currentTextureSlot === undefined ) {
  14645. _this.activeTexture();
  14646. }
  14647. var boundTexture = currentBoundTextures[currentTextureSlot];
  14648. if ( boundTexture === undefined ) {
  14649. boundTexture = { type: undefined, texture: undefined };
  14650. currentBoundTextures[currentTextureSlot] = boundTexture;
  14651. }
  14652. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  14653. gl.bindTexture( webglType, webglTexture );
  14654. boundTexture.type = webglType;
  14655. boundTexture.texture = webglTexture;
  14656. }
  14657. };
  14658. this.compressedTexImage2D = function () {
  14659. try {
  14660. gl.compressedTexImage2D.apply( gl, arguments );
  14661. } catch ( error ) {
  14662. console.error( error );
  14663. }
  14664. };
  14665. this.texImage2D = function () {
  14666. try {
  14667. gl.texImage2D.apply( gl, arguments );
  14668. } catch ( error ) {
  14669. console.error( error );
  14670. }
  14671. };
  14672. //
  14673. this.reset = function () {
  14674. for ( var i = 0; i < enabledAttributes.length; i ++ ) {
  14675. enabledAttributes[ i ] = 0;
  14676. }
  14677. currentBlending = null;
  14678. currentDepthTest = null;
  14679. currentDepthWrite = null;
  14680. currentColorWrite = null;
  14681. currentDoubleSided = null;
  14682. currentFlipSided = null;
  14683. };
  14684. };
  14685. // File:src/renderers/webgl/plugins/LensFlarePlugin.js
  14686. /**
  14687. * @author mikael emtinger / http://gomo.se/
  14688. * @author alteredq / http://alteredqualia.com/
  14689. */
  14690. THREE.LensFlarePlugin = function ( renderer, flares ) {
  14691. var gl = renderer.context;
  14692. var vertexBuffer, elementBuffer;
  14693. var program, attributes, uniforms;
  14694. var hasVertexTexture;
  14695. var tempTexture, occlusionTexture;
  14696. var init = function () {
  14697. var vertices = new Float32Array( [
  14698. -1, -1, 0, 0,
  14699. 1, -1, 1, 0,
  14700. 1, 1, 1, 1,
  14701. -1, 1, 0, 1
  14702. ] );
  14703. var faces = new Uint16Array( [
  14704. 0, 1, 2,
  14705. 0, 2, 3
  14706. ] );
  14707. // buffers
  14708. vertexBuffer = gl.createBuffer();
  14709. elementBuffer = gl.createBuffer();
  14710. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  14711. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  14712. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  14713. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  14714. // textures
  14715. tempTexture = gl.createTexture();
  14716. occlusionTexture = gl.createTexture();
  14717. renderer.state.bindTexture( gl.TEXTURE_2D, tempTexture );
  14718. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB, 16, 16, 0, gl.RGB, gl.UNSIGNED_BYTE, null );
  14719. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  14720. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  14721. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  14722. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  14723. renderer.state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  14724. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, 16, 16, 0, gl.RGBA, gl.UNSIGNED_BYTE, null );
  14725. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  14726. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  14727. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  14728. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  14729. hasVertexTexture = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) > 0;
  14730. var shader;
  14731. if ( hasVertexTexture ) {
  14732. shader = {
  14733. vertexShader: [
  14734. "uniform lowp int renderType;",
  14735. "uniform vec3 screenPosition;",
  14736. "uniform vec2 scale;",
  14737. "uniform float rotation;",
  14738. "uniform sampler2D occlusionMap;",
  14739. "attribute vec2 position;",
  14740. "attribute vec2 uv;",
  14741. "varying vec2 vUV;",
  14742. "varying float vVisibility;",
  14743. "void main() {",
  14744. "vUV = uv;",
  14745. "vec2 pos = position;",
  14746. "if( renderType == 2 ) {",
  14747. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  14748. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  14749. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  14750. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  14751. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  14752. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  14753. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  14754. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  14755. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  14756. "vVisibility = visibility.r / 9.0;",
  14757. "vVisibility *= 1.0 - visibility.g / 9.0;",
  14758. "vVisibility *= visibility.b / 9.0;",
  14759. "vVisibility *= 1.0 - visibility.a / 9.0;",
  14760. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  14761. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  14762. "}",
  14763. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  14764. "}"
  14765. ].join( "\n" ),
  14766. fragmentShader: [
  14767. "uniform lowp int renderType;",
  14768. "uniform sampler2D map;",
  14769. "uniform float opacity;",
  14770. "uniform vec3 color;",
  14771. "varying vec2 vUV;",
  14772. "varying float vVisibility;",
  14773. "void main() {",
  14774. // pink square
  14775. "if( renderType == 0 ) {",
  14776. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  14777. // restore
  14778. "} else if( renderType == 1 ) {",
  14779. "gl_FragColor = texture2D( map, vUV );",
  14780. // flare
  14781. "} else {",
  14782. "vec4 texture = texture2D( map, vUV );",
  14783. "texture.a *= opacity * vVisibility;",
  14784. "gl_FragColor = texture;",
  14785. "gl_FragColor.rgb *= color;",
  14786. "}",
  14787. "}"
  14788. ].join( "\n" )
  14789. };
  14790. } else {
  14791. shader = {
  14792. vertexShader: [
  14793. "uniform lowp int renderType;",
  14794. "uniform vec3 screenPosition;",
  14795. "uniform vec2 scale;",
  14796. "uniform float rotation;",
  14797. "attribute vec2 position;",
  14798. "attribute vec2 uv;",
  14799. "varying vec2 vUV;",
  14800. "void main() {",
  14801. "vUV = uv;",
  14802. "vec2 pos = position;",
  14803. "if( renderType == 2 ) {",
  14804. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  14805. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  14806. "}",
  14807. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  14808. "}"
  14809. ].join( "\n" ),
  14810. fragmentShader: [
  14811. "precision mediump float;",
  14812. "uniform lowp int renderType;",
  14813. "uniform sampler2D map;",
  14814. "uniform sampler2D occlusionMap;",
  14815. "uniform float opacity;",
  14816. "uniform vec3 color;",
  14817. "varying vec2 vUV;",
  14818. "void main() {",
  14819. // pink square
  14820. "if( renderType == 0 ) {",
  14821. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  14822. // restore
  14823. "} else if( renderType == 1 ) {",
  14824. "gl_FragColor = texture2D( map, vUV );",
  14825. // flare
  14826. "} else {",
  14827. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a;",
  14828. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a;",
  14829. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a;",
  14830. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  14831. "visibility = ( 1.0 - visibility / 4.0 );",
  14832. "vec4 texture = texture2D( map, vUV );",
  14833. "texture.a *= opacity * visibility;",
  14834. "gl_FragColor = texture;",
  14835. "gl_FragColor.rgb *= color;",
  14836. "}",
  14837. "}"
  14838. ].join( "\n" )
  14839. };
  14840. }
  14841. program = createProgram( shader );
  14842. attributes = {
  14843. vertex: gl.getAttribLocation ( program, "position" ),
  14844. uv: gl.getAttribLocation ( program, "uv" )
  14845. };
  14846. uniforms = {
  14847. renderType: gl.getUniformLocation( program, "renderType" ),
  14848. map: gl.getUniformLocation( program, "map" ),
  14849. occlusionMap: gl.getUniformLocation( program, "occlusionMap" ),
  14850. opacity: gl.getUniformLocation( program, "opacity" ),
  14851. color: gl.getUniformLocation( program, "color" ),
  14852. scale: gl.getUniformLocation( program, "scale" ),
  14853. rotation: gl.getUniformLocation( program, "rotation" ),
  14854. screenPosition: gl.getUniformLocation( program, "screenPosition" )
  14855. };
  14856. };
  14857. /*
  14858. * Render lens flares
  14859. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  14860. * reads these back and calculates occlusion.
  14861. */
  14862. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  14863. if ( flares.length === 0 ) return;
  14864. var tempPosition = new THREE.Vector3();
  14865. var invAspect = viewportHeight / viewportWidth,
  14866. halfViewportWidth = viewportWidth * 0.5,
  14867. halfViewportHeight = viewportHeight * 0.5;
  14868. var size = 16 / viewportHeight,
  14869. scale = new THREE.Vector2( size * invAspect, size );
  14870. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  14871. screenPositionPixels = new THREE.Vector2( 1, 1 );
  14872. if ( program === undefined ) {
  14873. init();
  14874. }
  14875. gl.useProgram( program );
  14876. renderer.state.initAttributes();
  14877. renderer.state.enableAttribute( attributes.vertex );
  14878. renderer.state.enableAttribute( attributes.uv );
  14879. renderer.state.disableUnusedAttributes();
  14880. // loop through all lens flares to update their occlusion and positions
  14881. // setup gl and common used attribs/unforms
  14882. gl.uniform1i( uniforms.occlusionMap, 0 );
  14883. gl.uniform1i( uniforms.map, 1 );
  14884. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  14885. gl.vertexAttribPointer( attributes.vertex, 2, gl.FLOAT, false, 2 * 8, 0 );
  14886. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  14887. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  14888. gl.disable( gl.CULL_FACE );
  14889. gl.depthMask( false );
  14890. for ( var i = 0, l = flares.length; i < l; i ++ ) {
  14891. size = 16 / viewportHeight;
  14892. scale.set( size * invAspect, size );
  14893. // calc object screen position
  14894. var flare = flares[ i ];
  14895. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  14896. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  14897. tempPosition.applyProjection( camera.projectionMatrix );
  14898. // setup arrays for gl programs
  14899. screenPosition.copy( tempPosition );
  14900. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  14901. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  14902. // screen cull
  14903. if ( hasVertexTexture || (
  14904. screenPositionPixels.x > 0 &&
  14905. screenPositionPixels.x < viewportWidth &&
  14906. screenPositionPixels.y > 0 &&
  14907. screenPositionPixels.y < viewportHeight ) ) {
  14908. // save current RGB to temp texture
  14909. renderer.state.activeTexture( gl.TEXTURE1 );
  14910. renderer.state.bindTexture( gl.TEXTURE_2D, tempTexture );
  14911. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  14912. // render pink quad
  14913. gl.uniform1i( uniforms.renderType, 0 );
  14914. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  14915. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  14916. gl.disable( gl.BLEND );
  14917. gl.enable( gl.DEPTH_TEST );
  14918. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  14919. // copy result to occlusionMap
  14920. renderer.state.activeTexture( gl.TEXTURE0 );
  14921. renderer.state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  14922. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  14923. // restore graphics
  14924. gl.uniform1i( uniforms.renderType, 1 );
  14925. gl.disable( gl.DEPTH_TEST );
  14926. renderer.state.activeTexture( gl.TEXTURE1 );
  14927. renderer.state.bindTexture( gl.TEXTURE_2D, tempTexture );
  14928. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  14929. // update object positions
  14930. flare.positionScreen.copy( screenPosition );
  14931. if ( flare.customUpdateCallback ) {
  14932. flare.customUpdateCallback( flare );
  14933. } else {
  14934. flare.updateLensFlares();
  14935. }
  14936. // render flares
  14937. gl.uniform1i( uniforms.renderType, 2 );
  14938. gl.enable( gl.BLEND );
  14939. for ( var j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  14940. var sprite = flare.lensFlares[ j ];
  14941. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  14942. screenPosition.x = sprite.x;
  14943. screenPosition.y = sprite.y;
  14944. screenPosition.z = sprite.z;
  14945. size = sprite.size * sprite.scale / viewportHeight;
  14946. scale.x = size * invAspect;
  14947. scale.y = size;
  14948. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  14949. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  14950. gl.uniform1f( uniforms.rotation, sprite.rotation );
  14951. gl.uniform1f( uniforms.opacity, sprite.opacity );
  14952. gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  14953. renderer.state.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  14954. renderer.setTexture( sprite.texture, 1 );
  14955. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  14956. }
  14957. }
  14958. }
  14959. }
  14960. // restore gl
  14961. gl.enable( gl.CULL_FACE );
  14962. gl.enable( gl.DEPTH_TEST );
  14963. gl.depthMask( true );
  14964. renderer.resetGLState();
  14965. };
  14966. function createProgram ( shader ) {
  14967. var program = gl.createProgram();
  14968. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  14969. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  14970. var prefix = "precision " + renderer.getPrecision() + " float;\n";
  14971. gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  14972. gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  14973. gl.compileShader( fragmentShader );
  14974. gl.compileShader( vertexShader );
  14975. gl.attachShader( program, fragmentShader );
  14976. gl.attachShader( program, vertexShader );
  14977. gl.linkProgram( program );
  14978. return program;
  14979. }
  14980. };
  14981. // File:src/renderers/webgl/plugins/SpritePlugin.js
  14982. /**
  14983. * @author mikael emtinger / http://gomo.se/
  14984. * @author alteredq / http://alteredqualia.com/
  14985. */
  14986. THREE.SpritePlugin = function ( renderer, sprites ) {
  14987. var gl = renderer.context;
  14988. var vertexBuffer, elementBuffer;
  14989. var program, attributes, uniforms;
  14990. var texture;
  14991. // decompose matrixWorld
  14992. var spritePosition = new THREE.Vector3();
  14993. var spriteRotation = new THREE.Quaternion();
  14994. var spriteScale = new THREE.Vector3();
  14995. var init = function () {
  14996. var vertices = new Float32Array( [
  14997. - 0.5, - 0.5, 0, 0,
  14998. 0.5, - 0.5, 1, 0,
  14999. 0.5, 0.5, 1, 1,
  15000. - 0.5, 0.5, 0, 1
  15001. ] );
  15002. var faces = new Uint16Array( [
  15003. 0, 1, 2,
  15004. 0, 2, 3
  15005. ] );
  15006. vertexBuffer = gl.createBuffer();
  15007. elementBuffer = gl.createBuffer();
  15008. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  15009. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  15010. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  15011. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  15012. program = createProgram();
  15013. attributes = {
  15014. position: gl.getAttribLocation ( program, 'position' ),
  15015. uv: gl.getAttribLocation ( program, 'uv' )
  15016. };
  15017. uniforms = {
  15018. uvOffset: gl.getUniformLocation( program, 'uvOffset' ),
  15019. uvScale: gl.getUniformLocation( program, 'uvScale' ),
  15020. rotation: gl.getUniformLocation( program, 'rotation' ),
  15021. scale: gl.getUniformLocation( program, 'scale' ),
  15022. color: gl.getUniformLocation( program, 'color' ),
  15023. map: gl.getUniformLocation( program, 'map' ),
  15024. opacity: gl.getUniformLocation( program, 'opacity' ),
  15025. modelViewMatrix: gl.getUniformLocation( program, 'modelViewMatrix' ),
  15026. projectionMatrix: gl.getUniformLocation( program, 'projectionMatrix' ),
  15027. fogType: gl.getUniformLocation( program, 'fogType' ),
  15028. fogDensity: gl.getUniformLocation( program, 'fogDensity' ),
  15029. fogNear: gl.getUniformLocation( program, 'fogNear' ),
  15030. fogFar: gl.getUniformLocation( program, 'fogFar' ),
  15031. fogColor: gl.getUniformLocation( program, 'fogColor' ),
  15032. alphaTest: gl.getUniformLocation( program, 'alphaTest' )
  15033. };
  15034. var canvas = document.createElement( 'canvas' );
  15035. canvas.width = 8;
  15036. canvas.height = 8;
  15037. var context = canvas.getContext( '2d' );
  15038. context.fillStyle = 'white';
  15039. context.fillRect( 0, 0, 8, 8 );
  15040. texture = new THREE.Texture( canvas );
  15041. texture.needsUpdate = true;
  15042. };
  15043. this.render = function ( scene, camera ) {
  15044. if ( sprites.length === 0 ) return;
  15045. // setup gl
  15046. if ( program === undefined ) {
  15047. init();
  15048. }
  15049. gl.useProgram( program );
  15050. renderer.state.initAttributes();
  15051. renderer.state.enableAttribute( attributes.position );
  15052. renderer.state.enableAttribute( attributes.uv );
  15053. renderer.state.disableUnusedAttributes();
  15054. gl.disable( gl.CULL_FACE );
  15055. gl.enable( gl.BLEND );
  15056. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  15057. gl.vertexAttribPointer( attributes.position, 2, gl.FLOAT, false, 2 * 8, 0 );
  15058. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  15059. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  15060. gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  15061. renderer.state.activeTexture( gl.TEXTURE0 );
  15062. gl.uniform1i( uniforms.map, 0 );
  15063. var oldFogType = 0;
  15064. var sceneFogType = 0;
  15065. var fog = scene.fog;
  15066. if ( fog ) {
  15067. gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  15068. if ( fog instanceof THREE.Fog ) {
  15069. gl.uniform1f( uniforms.fogNear, fog.near );
  15070. gl.uniform1f( uniforms.fogFar, fog.far );
  15071. gl.uniform1i( uniforms.fogType, 1 );
  15072. oldFogType = 1;
  15073. sceneFogType = 1;
  15074. } else if ( fog instanceof THREE.FogExp2 ) {
  15075. gl.uniform1f( uniforms.fogDensity, fog.density );
  15076. gl.uniform1i( uniforms.fogType, 2 );
  15077. oldFogType = 2;
  15078. sceneFogType = 2;
  15079. }
  15080. } else {
  15081. gl.uniform1i( uniforms.fogType, 0 );
  15082. oldFogType = 0;
  15083. sceneFogType = 0;
  15084. }
  15085. // update positions and sort
  15086. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  15087. var sprite = sprites[ i ];
  15088. sprite._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  15089. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  15090. }
  15091. sprites.sort( painterSortStable );
  15092. // render all sprites
  15093. var scale = [];
  15094. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  15095. var sprite = sprites[ i ];
  15096. var material = sprite.material;
  15097. gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  15098. gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  15099. sprite.matrixWorld.decompose( spritePosition, spriteRotation, spriteScale );
  15100. scale[ 0 ] = spriteScale.x;
  15101. scale[ 1 ] = spriteScale.y;
  15102. var fogType = 0;
  15103. if ( scene.fog && material.fog ) {
  15104. fogType = sceneFogType;
  15105. }
  15106. if ( oldFogType !== fogType ) {
  15107. gl.uniform1i( uniforms.fogType, fogType );
  15108. oldFogType = fogType;
  15109. }
  15110. if ( material.map !== null ) {
  15111. gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y );
  15112. gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y );
  15113. } else {
  15114. gl.uniform2f( uniforms.uvOffset, 0, 0 );
  15115. gl.uniform2f( uniforms.uvScale, 1, 1 );
  15116. }
  15117. gl.uniform1f( uniforms.opacity, material.opacity );
  15118. gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  15119. gl.uniform1f( uniforms.rotation, material.rotation );
  15120. gl.uniform2fv( uniforms.scale, scale );
  15121. renderer.state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  15122. renderer.state.setDepthTest( material.depthTest );
  15123. renderer.state.setDepthWrite( material.depthWrite );
  15124. if ( material.map && material.map.image && material.map.image.width ) {
  15125. renderer.setTexture( material.map, 0 );
  15126. } else {
  15127. renderer.setTexture( texture, 0 );
  15128. }
  15129. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  15130. }
  15131. // restore gl
  15132. gl.enable( gl.CULL_FACE );
  15133. renderer.resetGLState();
  15134. };
  15135. function createProgram () {
  15136. var program = gl.createProgram();
  15137. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  15138. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  15139. gl.shaderSource( vertexShader, [
  15140. 'precision ' + renderer.getPrecision() + ' float;',
  15141. 'uniform mat4 modelViewMatrix;',
  15142. 'uniform mat4 projectionMatrix;',
  15143. 'uniform float rotation;',
  15144. 'uniform vec2 scale;',
  15145. 'uniform vec2 uvOffset;',
  15146. 'uniform vec2 uvScale;',
  15147. 'attribute vec2 position;',
  15148. 'attribute vec2 uv;',
  15149. 'varying vec2 vUV;',
  15150. 'void main() {',
  15151. 'vUV = uvOffset + uv * uvScale;',
  15152. 'vec2 alignedPosition = position * scale;',
  15153. 'vec2 rotatedPosition;',
  15154. 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  15155. 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  15156. 'vec4 finalPosition;',
  15157. 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  15158. 'finalPosition.xy += rotatedPosition;',
  15159. 'finalPosition = projectionMatrix * finalPosition;',
  15160. 'gl_Position = finalPosition;',
  15161. '}'
  15162. ].join( '\n' ) );
  15163. gl.shaderSource( fragmentShader, [
  15164. 'precision ' + renderer.getPrecision() + ' float;',
  15165. 'uniform vec3 color;',
  15166. 'uniform sampler2D map;',
  15167. 'uniform float opacity;',
  15168. 'uniform int fogType;',
  15169. 'uniform vec3 fogColor;',
  15170. 'uniform float fogDensity;',
  15171. 'uniform float fogNear;',
  15172. 'uniform float fogFar;',
  15173. 'uniform float alphaTest;',
  15174. 'varying vec2 vUV;',
  15175. 'void main() {',
  15176. 'vec4 texture = texture2D( map, vUV );',
  15177. 'if ( texture.a < alphaTest ) discard;',
  15178. 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  15179. 'if ( fogType > 0 ) {',
  15180. 'float depth = gl_FragCoord.z / gl_FragCoord.w;',
  15181. 'float fogFactor = 0.0;',
  15182. 'if ( fogType == 1 ) {',
  15183. 'fogFactor = smoothstep( fogNear, fogFar, depth );',
  15184. '} else {',
  15185. 'const float LOG2 = 1.442695;',
  15186. 'fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );',
  15187. 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  15188. '}',
  15189. 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );',
  15190. '}',
  15191. '}'
  15192. ].join( '\n' ) );
  15193. gl.compileShader( vertexShader );
  15194. gl.compileShader( fragmentShader );
  15195. gl.attachShader( program, vertexShader );
  15196. gl.attachShader( program, fragmentShader );
  15197. gl.linkProgram( program );
  15198. return program;
  15199. }
  15200. function painterSortStable ( a, b ) {
  15201. if ( a.z !== b.z ) {
  15202. return b.z - a.z;
  15203. } else {
  15204. return b.id - a.id;
  15205. }
  15206. }
  15207. };
  15208. // File:src/extras/GeometryUtils.js
  15209. /**
  15210. * @author mrdoob / http://mrdoob.com/
  15211. */
  15212. THREE.GeometryUtils = {
  15213. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  15214. console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  15215. var matrix;
  15216. if ( geometry2 instanceof THREE.Mesh ) {
  15217. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  15218. matrix = geometry2.matrix;
  15219. geometry2 = geometry2.geometry;
  15220. }
  15221. geometry1.merge( geometry2, matrix, materialIndexOffset );
  15222. },
  15223. center: function ( geometry ) {
  15224. console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
  15225. return geometry.center();
  15226. }
  15227. };
  15228. // File:src/extras/ImageUtils.js
  15229. /**
  15230. * @author alteredq / http://alteredqualia.com/
  15231. * @author mrdoob / http://mrdoob.com/
  15232. * @author Daosheng Mu / https://github.com/DaoshengMu/
  15233. */
  15234. THREE.ImageUtils = {
  15235. crossOrigin: undefined,
  15236. loadTexture: function ( url, mapping, onLoad, onError ) {
  15237. var loader = new THREE.ImageLoader();
  15238. loader.crossOrigin = this.crossOrigin;
  15239. var texture = new THREE.Texture( undefined, mapping );
  15240. loader.load( url, function ( image ) {
  15241. texture.image = image;
  15242. texture.needsUpdate = true;
  15243. if ( onLoad ) onLoad( texture );
  15244. }, undefined, function ( event ) {
  15245. if ( onError ) onError( event );
  15246. } );
  15247. texture.sourceFile = url;
  15248. return texture;
  15249. },
  15250. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  15251. var images = [];
  15252. var loader = new THREE.ImageLoader();
  15253. loader.crossOrigin = this.crossOrigin;
  15254. var texture = new THREE.CubeTexture( images, mapping );
  15255. // no flipping needed for cube textures
  15256. texture.flipY = false;
  15257. var loaded = 0;
  15258. var loadTexture = function ( i ) {
  15259. loader.load( array[ i ], function ( image ) {
  15260. texture.images[ i ] = image;
  15261. loaded += 1;
  15262. if ( loaded === 6 ) {
  15263. texture.needsUpdate = true;
  15264. if ( onLoad ) onLoad( texture );
  15265. }
  15266. }, undefined, onError );
  15267. };
  15268. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15269. loadTexture( i );
  15270. }
  15271. return texture;
  15272. },
  15273. loadCompressedTexture: function () {
  15274. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' )
  15275. },
  15276. loadCompressedTextureCube: function () {
  15277. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' )
  15278. },
  15279. getNormalMap: function ( image, depth ) {
  15280. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  15281. var cross = function ( a, b ) {
  15282. return [ a[ 1 ] * b[ 2 ] - a[ 2 ] * b[ 1 ], a[ 2 ] * b[ 0 ] - a[ 0 ] * b[ 2 ], a[ 0 ] * b[ 1 ] - a[ 1 ] * b[ 0 ] ];
  15283. };
  15284. var subtract = function ( a, b ) {
  15285. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  15286. };
  15287. var normalize = function ( a ) {
  15288. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  15289. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  15290. };
  15291. depth = depth | 1;
  15292. var width = image.width;
  15293. var height = image.height;
  15294. var canvas = document.createElement( 'canvas' );
  15295. canvas.width = width;
  15296. canvas.height = height;
  15297. var context = canvas.getContext( '2d' );
  15298. context.drawImage( image, 0, 0 );
  15299. var data = context.getImageData( 0, 0, width, height ).data;
  15300. var imageData = context.createImageData( width, height );
  15301. var output = imageData.data;
  15302. for ( var x = 0; x < width; x ++ ) {
  15303. for ( var y = 0; y < height; y ++ ) {
  15304. var ly = y - 1 < 0 ? 0 : y - 1;
  15305. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  15306. var lx = x - 1 < 0 ? 0 : x - 1;
  15307. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  15308. var points = [];
  15309. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  15310. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  15311. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  15312. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  15313. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  15314. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  15315. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  15316. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  15317. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  15318. var normals = [];
  15319. var num_points = points.length;
  15320. for ( var i = 0; i < num_points; i ++ ) {
  15321. var v1 = points[ i ];
  15322. var v2 = points[ ( i + 1 ) % num_points ];
  15323. v1 = subtract( v1, origin );
  15324. v2 = subtract( v2, origin );
  15325. normals.push( normalize( cross( v1, v2 ) ) );
  15326. }
  15327. var normal = [ 0, 0, 0 ];
  15328. for ( var i = 0; i < normals.length; i ++ ) {
  15329. normal[ 0 ] += normals[ i ][ 0 ];
  15330. normal[ 1 ] += normals[ i ][ 1 ];
  15331. normal[ 2 ] += normals[ i ][ 2 ];
  15332. }
  15333. normal[ 0 ] /= normals.length;
  15334. normal[ 1 ] /= normals.length;
  15335. normal[ 2 ] /= normals.length;
  15336. var idx = ( y * width + x ) * 4;
  15337. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  15338. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  15339. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  15340. output[ idx + 3 ] = 255;
  15341. }
  15342. }
  15343. context.putImageData( imageData, 0, 0 );
  15344. return canvas;
  15345. },
  15346. generateDataTexture: function ( width, height, color ) {
  15347. var size = width * height;
  15348. var data = new Uint8Array( 3 * size );
  15349. var r = Math.floor( color.r * 255 );
  15350. var g = Math.floor( color.g * 255 );
  15351. var b = Math.floor( color.b * 255 );
  15352. for ( var i = 0; i < size; i ++ ) {
  15353. data[ i * 3 ] = r;
  15354. data[ i * 3 + 1 ] = g;
  15355. data[ i * 3 + 2 ] = b;
  15356. }
  15357. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  15358. texture.needsUpdate = true;
  15359. return texture;
  15360. }
  15361. };
  15362. // File:src/extras/SceneUtils.js
  15363. /**
  15364. * @author alteredq / http://alteredqualia.com/
  15365. */
  15366. THREE.SceneUtils = {
  15367. createMultiMaterialObject: function ( geometry, materials ) {
  15368. var group = new THREE.Object3D();
  15369. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  15370. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  15371. }
  15372. return group;
  15373. },
  15374. detach: function ( child, parent, scene ) {
  15375. child.applyMatrix( parent.matrixWorld );
  15376. parent.remove( child );
  15377. scene.add( child );
  15378. },
  15379. attach: function ( child, scene, parent ) {
  15380. var matrixWorldInverse = new THREE.Matrix4();
  15381. matrixWorldInverse.getInverse( parent.matrixWorld );
  15382. child.applyMatrix( matrixWorldInverse );
  15383. scene.remove( child );
  15384. parent.add( child );
  15385. }
  15386. };
  15387. // File:src/extras/FontUtils.js
  15388. /**
  15389. * @author zz85 / http://www.lab4games.net/zz85/blog
  15390. * @author alteredq / http://alteredqualia.com/
  15391. *
  15392. * For Text operations in three.js (See TextGeometry)
  15393. *
  15394. * It uses techniques used in:
  15395. *
  15396. * Triangulation ported from AS3
  15397. * Simple Polygon Triangulation
  15398. * http://actionsnippet.com/?p=1462
  15399. *
  15400. * A Method to triangulate shapes with holes
  15401. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  15402. *
  15403. */
  15404. THREE.FontUtils = {
  15405. faces: {},
  15406. // Just for now. face[weight][style]
  15407. face: 'helvetiker',
  15408. weight: 'normal',
  15409. style: 'normal',
  15410. size: 150,
  15411. divisions: 10,
  15412. getFace: function () {
  15413. try {
  15414. return this.faces[ this.face ][ this.weight ][ this.style ];
  15415. } catch (e) {
  15416. throw "The font " + this.face + " with " + this.weight + " weight and " + this.style + " style is missing."
  15417. }
  15418. },
  15419. loadFace: function ( data ) {
  15420. var family = data.familyName.toLowerCase();
  15421. var ThreeFont = this;
  15422. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  15423. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  15424. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  15425. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  15426. return data;
  15427. },
  15428. drawText: function ( text ) {
  15429. // RenderText
  15430. var i,
  15431. face = this.getFace(),
  15432. scale = this.size / face.resolution,
  15433. offset = 0,
  15434. chars = String( text ).split( '' ),
  15435. length = chars.length;
  15436. var fontPaths = [];
  15437. for ( i = 0; i < length; i ++ ) {
  15438. var path = new THREE.Path();
  15439. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  15440. offset += ret.offset;
  15441. fontPaths.push( ret.path );
  15442. }
  15443. // get the width
  15444. var width = offset / 2;
  15445. //
  15446. // for ( p = 0; p < allPts.length; p++ ) {
  15447. //
  15448. // allPts[ p ].x -= width;
  15449. //
  15450. // }
  15451. //var extract = this.extractPoints( allPts, characterPts );
  15452. //extract.contour = allPts;
  15453. //extract.paths = fontPaths;
  15454. //extract.offset = width;
  15455. return { paths: fontPaths, offset: width };
  15456. },
  15457. extractGlyphPoints: function ( c, face, scale, offset, path ) {
  15458. var pts = [];
  15459. var i, i2, divisions,
  15460. outline, action, length,
  15461. scaleX, scaleY,
  15462. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  15463. laste,
  15464. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  15465. if ( ! glyph ) return;
  15466. if ( glyph.o ) {
  15467. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  15468. length = outline.length;
  15469. scaleX = scale;
  15470. scaleY = scale;
  15471. for ( i = 0; i < length; ) {
  15472. action = outline[ i ++ ];
  15473. //console.log( action );
  15474. switch ( action ) {
  15475. case 'm':
  15476. // Move To
  15477. x = outline[ i ++ ] * scaleX + offset;
  15478. y = outline[ i ++ ] * scaleY;
  15479. path.moveTo( x, y );
  15480. break;
  15481. case 'l':
  15482. // Line To
  15483. x = outline[ i ++ ] * scaleX + offset;
  15484. y = outline[ i ++ ] * scaleY;
  15485. path.lineTo( x, y );
  15486. break;
  15487. case 'q':
  15488. // QuadraticCurveTo
  15489. cpx = outline[ i ++ ] * scaleX + offset;
  15490. cpy = outline[ i ++ ] * scaleY;
  15491. cpx1 = outline[ i ++ ] * scaleX + offset;
  15492. cpy1 = outline[ i ++ ] * scaleY;
  15493. path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
  15494. laste = pts[ pts.length - 1 ];
  15495. if ( laste ) {
  15496. cpx0 = laste.x;
  15497. cpy0 = laste.y;
  15498. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  15499. var t = i2 / divisions;
  15500. THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  15501. THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  15502. }
  15503. }
  15504. break;
  15505. case 'b':
  15506. // Cubic Bezier Curve
  15507. cpx = outline[ i ++ ] * scaleX + offset;
  15508. cpy = outline[ i ++ ] * scaleY;
  15509. cpx1 = outline[ i ++ ] * scaleX + offset;
  15510. cpy1 = outline[ i ++ ] * scaleY;
  15511. cpx2 = outline[ i ++ ] * scaleX + offset;
  15512. cpy2 = outline[ i ++ ] * scaleY;
  15513. path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
  15514. laste = pts[ pts.length - 1 ];
  15515. if ( laste ) {
  15516. cpx0 = laste.x;
  15517. cpy0 = laste.y;
  15518. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  15519. var t = i2 / divisions;
  15520. THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  15521. THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  15522. }
  15523. }
  15524. break;
  15525. }
  15526. }
  15527. }
  15528. return { offset: glyph.ha * scale, path:path };
  15529. }
  15530. };
  15531. THREE.FontUtils.generateShapes = function ( text, parameters ) {
  15532. // Parameters
  15533. parameters = parameters || {};
  15534. var size = parameters.size !== undefined ? parameters.size : 100;
  15535. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments : 4;
  15536. var font = parameters.font !== undefined ? parameters.font : 'helvetiker';
  15537. var weight = parameters.weight !== undefined ? parameters.weight : 'normal';
  15538. var style = parameters.style !== undefined ? parameters.style : 'normal';
  15539. THREE.FontUtils.size = size;
  15540. THREE.FontUtils.divisions = curveSegments;
  15541. THREE.FontUtils.face = font;
  15542. THREE.FontUtils.weight = weight;
  15543. THREE.FontUtils.style = style;
  15544. // Get a Font data json object
  15545. var data = THREE.FontUtils.drawText( text );
  15546. var paths = data.paths;
  15547. var shapes = [];
  15548. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  15549. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  15550. }
  15551. return shapes;
  15552. };
  15553. /**
  15554. * This code is a quick port of code written in C++ which was submitted to
  15555. * flipcode.com by John W. Ratcliff // July 22, 2000
  15556. * See original code and more information here:
  15557. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  15558. *
  15559. * ported to actionscript by Zevan Rosser
  15560. * www.actionsnippet.com
  15561. *
  15562. * ported to javascript by Joshua Koo
  15563. * http://www.lab4games.net/zz85/blog
  15564. *
  15565. */
  15566. ( function ( namespace ) {
  15567. var EPSILON = 0.0000000001;
  15568. // takes in an contour array and returns
  15569. var process = function ( contour, indices ) {
  15570. var n = contour.length;
  15571. if ( n < 3 ) return null;
  15572. var result = [],
  15573. verts = [],
  15574. vertIndices = [];
  15575. /* we want a counter-clockwise polygon in verts */
  15576. var u, v, w;
  15577. if ( area( contour ) > 0.0 ) {
  15578. for ( v = 0; v < n; v ++ ) verts[ v ] = v;
  15579. } else {
  15580. for ( v = 0; v < n; v ++ ) verts[ v ] = ( n - 1 ) - v;
  15581. }
  15582. var nv = n;
  15583. /* remove nv - 2 vertices, creating 1 triangle every time */
  15584. var count = 2 * nv; /* error detection */
  15585. for ( v = nv - 1; nv > 2; ) {
  15586. /* if we loop, it is probably a non-simple polygon */
  15587. if ( ( count -- ) <= 0 ) {
  15588. //** Triangulate: ERROR - probable bad polygon!
  15589. //throw ( "Warning, unable to triangulate polygon!" );
  15590. //return null;
  15591. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  15592. console.warn( 'THREE.FontUtils: Warning, unable to triangulate polygon! in Triangulate.process()' );
  15593. if ( indices ) return vertIndices;
  15594. return result;
  15595. }
  15596. /* three consecutive vertices in current polygon, <u,v,w> */
  15597. u = v; if ( nv <= u ) u = 0; /* previous */
  15598. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  15599. w = v + 1; if ( nv <= w ) w = 0; /* next */
  15600. if ( snip( contour, u, v, w, nv, verts ) ) {
  15601. var a, b, c, s, t;
  15602. /* true names of the vertices */
  15603. a = verts[ u ];
  15604. b = verts[ v ];
  15605. c = verts[ w ];
  15606. /* output Triangle */
  15607. result.push( [ contour[ a ],
  15608. contour[ b ],
  15609. contour[ c ] ] );
  15610. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  15611. /* remove v from the remaining polygon */
  15612. for ( s = v, t = v + 1; t < nv; s ++, t ++ ) {
  15613. verts[ s ] = verts[ t ];
  15614. }
  15615. nv --;
  15616. /* reset error detection counter */
  15617. count = 2 * nv;
  15618. }
  15619. }
  15620. if ( indices ) return vertIndices;
  15621. return result;
  15622. };
  15623. // calculate area of the contour polygon
  15624. var area = function ( contour ) {
  15625. var n = contour.length;
  15626. var a = 0.0;
  15627. for ( var p = n - 1, q = 0; q < n; p = q ++ ) {
  15628. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  15629. }
  15630. return a * 0.5;
  15631. };
  15632. var snip = function ( contour, u, v, w, n, verts ) {
  15633. var p;
  15634. var ax, ay, bx, by;
  15635. var cx, cy, px, py;
  15636. ax = contour[ verts[ u ] ].x;
  15637. ay = contour[ verts[ u ] ].y;
  15638. bx = contour[ verts[ v ] ].x;
  15639. by = contour[ verts[ v ] ].y;
  15640. cx = contour[ verts[ w ] ].x;
  15641. cy = contour[ verts[ w ] ].y;
  15642. if ( EPSILON > ( ( ( bx - ax ) * ( cy - ay ) ) - ( ( by - ay ) * ( cx - ax ) ) ) ) return false;
  15643. var aX, aY, bX, bY, cX, cY;
  15644. var apx, apy, bpx, bpy, cpx, cpy;
  15645. var cCROSSap, bCROSScp, aCROSSbp;
  15646. aX = cx - bx; aY = cy - by;
  15647. bX = ax - cx; bY = ay - cy;
  15648. cX = bx - ax; cY = by - ay;
  15649. for ( p = 0; p < n; p ++ ) {
  15650. px = contour[ verts[ p ] ].x;
  15651. py = contour[ verts[ p ] ].y;
  15652. if ( ( ( px === ax ) && ( py === ay ) ) ||
  15653. ( ( px === bx ) && ( py === by ) ) ||
  15654. ( ( px === cx ) && ( py === cy ) ) ) continue;
  15655. apx = px - ax; apy = py - ay;
  15656. bpx = px - bx; bpy = py - by;
  15657. cpx = px - cx; cpy = py - cy;
  15658. // see if p is inside triangle abc
  15659. aCROSSbp = aX * bpy - aY * bpx;
  15660. cCROSSap = cX * apy - cY * apx;
  15661. bCROSScp = bX * cpy - bY * cpx;
  15662. if ( ( aCROSSbp >= - EPSILON ) && ( bCROSScp >= - EPSILON ) && ( cCROSSap >= - EPSILON ) ) return false;
  15663. }
  15664. return true;
  15665. };
  15666. namespace.Triangulate = process;
  15667. namespace.Triangulate.area = area;
  15668. return namespace;
  15669. } )( THREE.FontUtils );
  15670. // To use the typeface.js face files, hook up the API
  15671. THREE.typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };
  15672. if ( typeof self !== 'undefined' ) self._typeface_js = THREE.typeface_js;
  15673. // File:src/extras/audio/Audio.js
  15674. /**
  15675. * @author mrdoob / http://mrdoob.com/
  15676. */
  15677. THREE.Audio = function ( listener ) {
  15678. THREE.Object3D.call( this );
  15679. this.type = 'Audio';
  15680. this.context = listener.context;
  15681. this.source = this.context.createBufferSource();
  15682. this.source.onended = this.onEnded.bind(this);
  15683. this.gain = this.context.createGain();
  15684. this.gain.connect( this.context.destination );
  15685. this.panner = this.context.createPanner();
  15686. this.panner.connect( this.gain );
  15687. this.autoplay = false;
  15688. this.startTime = 0;
  15689. this.isPlaying = false;
  15690. };
  15691. THREE.Audio.prototype = Object.create( THREE.Object3D.prototype );
  15692. THREE.Audio.prototype.constructor = THREE.Audio;
  15693. THREE.Audio.prototype.load = function ( file ) {
  15694. var scope = this;
  15695. var request = new XMLHttpRequest();
  15696. request.open( 'GET', file, true );
  15697. request.responseType = 'arraybuffer';
  15698. request.onload = function ( e ) {
  15699. scope.context.decodeAudioData( this.response, function ( buffer ) {
  15700. scope.source.buffer = buffer;
  15701. if( scope.autoplay ) scope.play();
  15702. } );
  15703. };
  15704. request.send();
  15705. return this;
  15706. };
  15707. THREE.Audio.prototype.play = function () {
  15708. if ( this.isPlaying === true ) {
  15709. console.warn( 'THREE.Audio: Audio is already playing.' );
  15710. return;
  15711. }
  15712. var source = this.context.createBufferSource();
  15713. source.buffer = this.source.buffer;
  15714. source.loop = this.source.loop;
  15715. source.onended = this.source.onended;
  15716. source.connect( this.panner );
  15717. source.start( 0, this.startTime );
  15718. this.isPlaying = true;
  15719. this.source = source;
  15720. };
  15721. THREE.Audio.prototype.pause = function () {
  15722. this.source.stop();
  15723. this.startTime = this.context.currentTime;
  15724. };
  15725. THREE.Audio.prototype.stop = function () {
  15726. this.source.stop();
  15727. this.startTime = 0;
  15728. };
  15729. THREE.Audio.prototype.onEnded = function() {
  15730. this.isPlaying = false;
  15731. };
  15732. THREE.Audio.prototype.setLoop = function ( value ) {
  15733. this.source.loop = value;
  15734. };
  15735. THREE.Audio.prototype.setRefDistance = function ( value ) {
  15736. this.panner.refDistance = value;
  15737. };
  15738. THREE.Audio.prototype.setRolloffFactor = function ( value ) {
  15739. this.panner.rolloffFactor = value;
  15740. };
  15741. THREE.Audio.prototype.setVolume = function ( value ) {
  15742. this.gain.gain.value = value;
  15743. };
  15744. THREE.Audio.prototype.updateMatrixWorld = ( function () {
  15745. var position = new THREE.Vector3();
  15746. return function ( force ) {
  15747. THREE.Object3D.prototype.updateMatrixWorld.call( this, force );
  15748. position.setFromMatrixPosition( this.matrixWorld );
  15749. this.panner.setPosition( position.x, position.y, position.z );
  15750. };
  15751. } )();
  15752. // File:src/extras/audio/AudioListener.js
  15753. /**
  15754. * @author mrdoob / http://mrdoob.com/
  15755. */
  15756. THREE.AudioListener = function () {
  15757. THREE.Object3D.call( this );
  15758. this.type = 'AudioListener';
  15759. this.context = new ( window.AudioContext || window.webkitAudioContext )();
  15760. };
  15761. THREE.AudioListener.prototype = Object.create( THREE.Object3D.prototype );
  15762. THREE.AudioListener.prototype.constructor = THREE.AudioListener;
  15763. THREE.AudioListener.prototype.updateMatrixWorld = ( function () {
  15764. var position = new THREE.Vector3();
  15765. var quaternion = new THREE.Quaternion();
  15766. var scale = new THREE.Vector3();
  15767. var orientation = new THREE.Vector3();
  15768. return function ( force ) {
  15769. THREE.Object3D.prototype.updateMatrixWorld.call( this, force );
  15770. var listener = this.context.listener;
  15771. var up = this.up;
  15772. this.matrixWorld.decompose( position, quaternion, scale );
  15773. orientation.set( 0, 0, -1 ).applyQuaternion( quaternion );
  15774. listener.setPosition( position.x, position.y, position.z );
  15775. listener.setOrientation( orientation.x, orientation.y, orientation.z, up.x, up.y, up.z );
  15776. };
  15777. } )();
  15778. // File:src/extras/core/Curve.js
  15779. /**
  15780. * @author zz85 / http://www.lab4games.net/zz85/blog
  15781. * Extensible curve object
  15782. *
  15783. * Some common of Curve methods
  15784. * .getPoint(t), getTangent(t)
  15785. * .getPointAt(u), getTagentAt(u)
  15786. * .getPoints(), .getSpacedPoints()
  15787. * .getLength()
  15788. * .updateArcLengths()
  15789. *
  15790. * This following classes subclasses THREE.Curve:
  15791. *
  15792. * -- 2d classes --
  15793. * THREE.LineCurve
  15794. * THREE.QuadraticBezierCurve
  15795. * THREE.CubicBezierCurve
  15796. * THREE.SplineCurve
  15797. * THREE.ArcCurve
  15798. * THREE.EllipseCurve
  15799. *
  15800. * -- 3d classes --
  15801. * THREE.LineCurve3
  15802. * THREE.QuadraticBezierCurve3
  15803. * THREE.CubicBezierCurve3
  15804. * THREE.SplineCurve3
  15805. * THREE.ClosedSplineCurve3
  15806. *
  15807. * A series of curves can be represented as a THREE.CurvePath
  15808. *
  15809. **/
  15810. /**************************************************************
  15811. * Abstract Curve base class
  15812. **************************************************************/
  15813. THREE.Curve = function () {
  15814. };
  15815. // Virtual base class method to overwrite and implement in subclasses
  15816. // - t [0 .. 1]
  15817. THREE.Curve.prototype.getPoint = function ( t ) {
  15818. console.warn( "THREE.Curve: Warning, getPoint() not implemented!" );
  15819. return null;
  15820. };
  15821. // Get point at relative position in curve according to arc length
  15822. // - u [0 .. 1]
  15823. THREE.Curve.prototype.getPointAt = function ( u ) {
  15824. var t = this.getUtoTmapping( u );
  15825. return this.getPoint( t );
  15826. };
  15827. // Get sequence of points using getPoint( t )
  15828. THREE.Curve.prototype.getPoints = function ( divisions ) {
  15829. if ( ! divisions ) divisions = 5;
  15830. var d, pts = [];
  15831. for ( d = 0; d <= divisions; d ++ ) {
  15832. pts.push( this.getPoint( d / divisions ) );
  15833. }
  15834. return pts;
  15835. };
  15836. // Get sequence of points using getPointAt( u )
  15837. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  15838. if ( ! divisions ) divisions = 5;
  15839. var d, pts = [];
  15840. for ( d = 0; d <= divisions; d ++ ) {
  15841. pts.push( this.getPointAt( d / divisions ) );
  15842. }
  15843. return pts;
  15844. };
  15845. // Get total curve arc length
  15846. THREE.Curve.prototype.getLength = function () {
  15847. var lengths = this.getLengths();
  15848. return lengths[ lengths.length - 1 ];
  15849. };
  15850. // Get list of cumulative segment lengths
  15851. THREE.Curve.prototype.getLengths = function ( divisions ) {
  15852. if ( ! divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions) : 200;
  15853. if ( this.cacheArcLengths
  15854. && ( this.cacheArcLengths.length === divisions + 1 )
  15855. && ! this.needsUpdate) {
  15856. //console.log( "cached", this.cacheArcLengths );
  15857. return this.cacheArcLengths;
  15858. }
  15859. this.needsUpdate = false;
  15860. var cache = [];
  15861. var current, last = this.getPoint( 0 );
  15862. var p, sum = 0;
  15863. cache.push( 0 );
  15864. for ( p = 1; p <= divisions; p ++ ) {
  15865. current = this.getPoint ( p / divisions );
  15866. sum += current.distanceTo( last );
  15867. cache.push( sum );
  15868. last = current;
  15869. }
  15870. this.cacheArcLengths = cache;
  15871. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  15872. };
  15873. THREE.Curve.prototype.updateArcLengths = function() {
  15874. this.needsUpdate = true;
  15875. this.getLengths();
  15876. };
  15877. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  15878. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  15879. var arcLengths = this.getLengths();
  15880. var i = 0, il = arcLengths.length;
  15881. var targetArcLength; // The targeted u distance value to get
  15882. if ( distance ) {
  15883. targetArcLength = distance;
  15884. } else {
  15885. targetArcLength = u * arcLengths[ il - 1 ];
  15886. }
  15887. //var time = Date.now();
  15888. // binary search for the index with largest value smaller than target u distance
  15889. var low = 0, high = il - 1, comparison;
  15890. while ( low <= high ) {
  15891. 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
  15892. comparison = arcLengths[ i ] - targetArcLength;
  15893. if ( comparison < 0 ) {
  15894. low = i + 1;
  15895. } else if ( comparison > 0 ) {
  15896. high = i - 1;
  15897. } else {
  15898. high = i;
  15899. break;
  15900. // DONE
  15901. }
  15902. }
  15903. i = high;
  15904. //console.log('b' , i, low, high, Date.now()- time);
  15905. if ( arcLengths[ i ] === targetArcLength ) {
  15906. var t = i / ( il - 1 );
  15907. return t;
  15908. }
  15909. // we could get finer grain at lengths, or use simple interpolatation between two points
  15910. var lengthBefore = arcLengths[ i ];
  15911. var lengthAfter = arcLengths[ i + 1 ];
  15912. var segmentLength = lengthAfter - lengthBefore;
  15913. // determine where we are between the 'before' and 'after' points
  15914. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  15915. // add that fractional amount to t
  15916. var t = ( i + segmentFraction ) / ( il - 1 );
  15917. return t;
  15918. };
  15919. // Returns a unit vector tangent at t
  15920. // In case any sub curve does not implement its tangent derivation,
  15921. // 2 points a small delta apart will be used to find its gradient
  15922. // which seems to give a reasonable approximation
  15923. THREE.Curve.prototype.getTangent = function( t ) {
  15924. var delta = 0.0001;
  15925. var t1 = t - delta;
  15926. var t2 = t + delta;
  15927. // Capping in case of danger
  15928. if ( t1 < 0 ) t1 = 0;
  15929. if ( t2 > 1 ) t2 = 1;
  15930. var pt1 = this.getPoint( t1 );
  15931. var pt2 = this.getPoint( t2 );
  15932. var vec = pt2.clone().sub(pt1);
  15933. return vec.normalize();
  15934. };
  15935. THREE.Curve.prototype.getTangentAt = function ( u ) {
  15936. var t = this.getUtoTmapping( u );
  15937. return this.getTangent( t );
  15938. };
  15939. /**************************************************************
  15940. * Utils
  15941. **************************************************************/
  15942. THREE.Curve.Utils = {
  15943. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  15944. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  15945. },
  15946. // Puay Bing, thanks for helping with this derivative!
  15947. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  15948. return - 3 * p0 * (1 - t) * (1 - t) +
  15949. 3 * p1 * (1 - t) * (1 - t) - 6 * t * p1 * (1 - t) +
  15950. 6 * t * p2 * (1 - t) - 3 * t * t * p2 +
  15951. 3 * t * t * p3;
  15952. },
  15953. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  15954. // To check if my formulas are correct
  15955. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  15956. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  15957. var h01 = - 6 * t * t + 6 * t; // − 2t3 + 3t2
  15958. var h11 = 3 * t * t - 2 * t; // t3 − t2
  15959. return h00 + h10 + h01 + h11;
  15960. },
  15961. // Catmull-Rom
  15962. interpolate: function( p0, p1, p2, p3, t ) {
  15963. var v0 = ( p2 - p0 ) * 0.5;
  15964. var v1 = ( p3 - p1 ) * 0.5;
  15965. var t2 = t * t;
  15966. var t3 = t * t2;
  15967. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  15968. }
  15969. };
  15970. // TODO: Transformation for Curves?
  15971. /**************************************************************
  15972. * 3D Curves
  15973. **************************************************************/
  15974. // A Factory method for creating new curve subclasses
  15975. THREE.Curve.create = function ( constructor, getPointFunc ) {
  15976. constructor.prototype = Object.create( THREE.Curve.prototype );
  15977. constructor.prototype.constructor = constructor;
  15978. constructor.prototype.getPoint = getPointFunc;
  15979. return constructor;
  15980. };
  15981. // File:src/extras/core/CurvePath.js
  15982. /**
  15983. * @author zz85 / http://www.lab4games.net/zz85/blog
  15984. *
  15985. **/
  15986. /**************************************************************
  15987. * Curved Path - a curve path is simply a array of connected
  15988. * curves, but retains the api of a curve
  15989. **************************************************************/
  15990. THREE.CurvePath = function () {
  15991. this.curves = [];
  15992. this.bends = [];
  15993. this.autoClose = false; // Automatically closes the path
  15994. };
  15995. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  15996. THREE.CurvePath.prototype.constructor = THREE.CurvePath;
  15997. THREE.CurvePath.prototype.add = function ( curve ) {
  15998. this.curves.push( curve );
  15999. };
  16000. THREE.CurvePath.prototype.checkConnection = function() {
  16001. // TODO
  16002. // If the ending of curve is not connected to the starting
  16003. // or the next curve, then, this is not a real path
  16004. };
  16005. THREE.CurvePath.prototype.closePath = function() {
  16006. // TODO Test
  16007. // and verify for vector3 (needs to implement equals)
  16008. // Add a line curve if start and end of lines are not connected
  16009. var startPoint = this.curves[0].getPoint(0);
  16010. var endPoint = this.curves[this.curves.length - 1].getPoint(1);
  16011. if (! startPoint.equals(endPoint)) {
  16012. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  16013. }
  16014. };
  16015. // To get accurate point with reference to
  16016. // entire path distance at time t,
  16017. // following has to be done:
  16018. // 1. Length of each sub path have to be known
  16019. // 2. Locate and identify type of curve
  16020. // 3. Get t for the curve
  16021. // 4. Return curve.getPointAt(t')
  16022. THREE.CurvePath.prototype.getPoint = function( t ) {
  16023. var d = t * this.getLength();
  16024. var curveLengths = this.getCurveLengths();
  16025. var i = 0, diff, curve;
  16026. // To think about boundaries points.
  16027. while ( i < curveLengths.length ) {
  16028. if ( curveLengths[ i ] >= d ) {
  16029. diff = curveLengths[ i ] - d;
  16030. curve = this.curves[ i ];
  16031. var u = 1 - diff / curve.getLength();
  16032. return curve.getPointAt( u );
  16033. }
  16034. i ++;
  16035. }
  16036. return null;
  16037. // loop where sum != 0, sum > d , sum+1 <d
  16038. };
  16039. /*
  16040. THREE.CurvePath.prototype.getTangent = function( t ) {
  16041. };*/
  16042. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  16043. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  16044. // getPoint() depends on getLength
  16045. THREE.CurvePath.prototype.getLength = function() {
  16046. var lens = this.getCurveLengths();
  16047. return lens[ lens.length - 1 ];
  16048. };
  16049. // Compute lengths and cache them
  16050. // We cannot overwrite getLengths() because UtoT mapping uses it.
  16051. THREE.CurvePath.prototype.getCurveLengths = function() {
  16052. // We use cache values if curves and cache array are same length
  16053. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  16054. return this.cacheLengths;
  16055. }
  16056. // Get length of subsurve
  16057. // Push sums into cached array
  16058. var lengths = [], sums = 0;
  16059. var i, il = this.curves.length;
  16060. for ( i = 0; i < il; i ++ ) {
  16061. sums += this.curves[ i ].getLength();
  16062. lengths.push( sums );
  16063. }
  16064. this.cacheLengths = lengths;
  16065. return lengths;
  16066. };
  16067. // Returns min and max coordinates
  16068. THREE.CurvePath.prototype.getBoundingBox = function () {
  16069. var points = this.getPoints();
  16070. var maxX, maxY, maxZ;
  16071. var minX, minY, minZ;
  16072. maxX = maxY = Number.NEGATIVE_INFINITY;
  16073. minX = minY = Number.POSITIVE_INFINITY;
  16074. var p, i, il, sum;
  16075. var v3 = points[0] instanceof THREE.Vector3;
  16076. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  16077. for ( i = 0, il = points.length; i < il; i ++ ) {
  16078. p = points[ i ];
  16079. if ( p.x > maxX ) maxX = p.x;
  16080. else if ( p.x < minX ) minX = p.x;
  16081. if ( p.y > maxY ) maxY = p.y;
  16082. else if ( p.y < minY ) minY = p.y;
  16083. if ( v3 ) {
  16084. if ( p.z > maxZ ) maxZ = p.z;
  16085. else if ( p.z < minZ ) minZ = p.z;
  16086. }
  16087. sum.add( p );
  16088. }
  16089. var ret = {
  16090. minX: minX,
  16091. minY: minY,
  16092. maxX: maxX,
  16093. maxY: maxY
  16094. };
  16095. if ( v3 ) {
  16096. ret.maxZ = maxZ;
  16097. ret.minZ = minZ;
  16098. }
  16099. return ret;
  16100. };
  16101. /**************************************************************
  16102. * Create Geometries Helpers
  16103. **************************************************************/
  16104. /// Generate geometry from path points (for Line or Points objects)
  16105. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  16106. var pts = this.getPoints( divisions, true );
  16107. return this.createGeometry( pts );
  16108. };
  16109. // Generate geometry from equidistance sampling along the path
  16110. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  16111. var pts = this.getSpacedPoints( divisions, true );
  16112. return this.createGeometry( pts );
  16113. };
  16114. THREE.CurvePath.prototype.createGeometry = function( points ) {
  16115. var geometry = new THREE.Geometry();
  16116. for ( var i = 0; i < points.length; i ++ ) {
  16117. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  16118. }
  16119. return geometry;
  16120. };
  16121. /**************************************************************
  16122. * Bend / Wrap Helper Methods
  16123. **************************************************************/
  16124. // Wrap path / Bend modifiers?
  16125. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  16126. this.bends.push( bendpath );
  16127. };
  16128. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  16129. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  16130. var i, il;
  16131. if ( ! bends ) {
  16132. bends = this.bends;
  16133. }
  16134. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16135. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16136. }
  16137. return oldPts;
  16138. };
  16139. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  16140. var oldPts = this.getSpacedPoints( segments );
  16141. var i, il;
  16142. if ( ! bends ) {
  16143. bends = this.bends;
  16144. }
  16145. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16146. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16147. }
  16148. return oldPts;
  16149. };
  16150. // This returns getPoints() bend/wrapped around the contour of a path.
  16151. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  16152. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  16153. var bounds = this.getBoundingBox();
  16154. var i, il, p, oldX, oldY, xNorm;
  16155. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  16156. p = oldPts[ i ];
  16157. oldX = p.x;
  16158. oldY = p.y;
  16159. xNorm = oldX / bounds.maxX;
  16160. // If using actual distance, for length > path, requires line extrusions
  16161. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  16162. xNorm = path.getUtoTmapping( xNorm, oldX );
  16163. // check for out of bounds?
  16164. var pathPt = path.getPoint( xNorm );
  16165. var normal = path.getTangent( xNorm );
  16166. normal.set( - normal.y, normal.x ).multiplyScalar( oldY );
  16167. p.x = pathPt.x + normal.x;
  16168. p.y = pathPt.y + normal.y;
  16169. }
  16170. return oldPts;
  16171. };
  16172. // File:src/extras/core/Gyroscope.js
  16173. /**
  16174. * @author alteredq / http://alteredqualia.com/
  16175. */
  16176. THREE.Gyroscope = function () {
  16177. THREE.Object3D.call( this );
  16178. };
  16179. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  16180. THREE.Gyroscope.prototype.constructor = THREE.Gyroscope;
  16181. THREE.Gyroscope.prototype.updateMatrixWorld = ( function () {
  16182. var translationObject = new THREE.Vector3();
  16183. var quaternionObject = new THREE.Quaternion();
  16184. var scaleObject = new THREE.Vector3();
  16185. var translationWorld = new THREE.Vector3();
  16186. var quaternionWorld = new THREE.Quaternion();
  16187. var scaleWorld = new THREE.Vector3();
  16188. return function ( force ) {
  16189. this.matrixAutoUpdate && this.updateMatrix();
  16190. // update matrixWorld
  16191. if ( this.matrixWorldNeedsUpdate || force ) {
  16192. if ( this.parent ) {
  16193. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  16194. this.matrixWorld.decompose( translationWorld, quaternionWorld, scaleWorld );
  16195. this.matrix.decompose( translationObject, quaternionObject, scaleObject );
  16196. this.matrixWorld.compose( translationWorld, quaternionObject, scaleWorld );
  16197. } else {
  16198. this.matrixWorld.copy( this.matrix );
  16199. }
  16200. this.matrixWorldNeedsUpdate = false;
  16201. force = true;
  16202. }
  16203. // update children
  16204. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  16205. this.children[ i ].updateMatrixWorld( force );
  16206. }
  16207. };
  16208. }() );
  16209. // File:src/extras/core/Path.js
  16210. /**
  16211. * @author zz85 / http://www.lab4games.net/zz85/blog
  16212. * Creates free form 2d path using series of points, lines or curves.
  16213. *
  16214. **/
  16215. THREE.Path = function ( points ) {
  16216. THREE.CurvePath.call(this);
  16217. this.actions = [];
  16218. if ( points ) {
  16219. this.fromPoints( points );
  16220. }
  16221. };
  16222. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  16223. THREE.Path.prototype.constructor = THREE.Path;
  16224. THREE.PathActions = {
  16225. MOVE_TO: 'moveTo',
  16226. LINE_TO: 'lineTo',
  16227. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  16228. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  16229. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  16230. ARC: 'arc', // Circle
  16231. ELLIPSE: 'ellipse'
  16232. };
  16233. // TODO Clean up PATH API
  16234. // Create path using straight lines to connect all points
  16235. // - vectors: array of Vector2
  16236. THREE.Path.prototype.fromPoints = function ( vectors ) {
  16237. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  16238. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  16239. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  16240. }
  16241. };
  16242. // startPath() endPath()?
  16243. THREE.Path.prototype.moveTo = function ( x, y ) {
  16244. var args = Array.prototype.slice.call( arguments );
  16245. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  16246. };
  16247. THREE.Path.prototype.lineTo = function ( x, y ) {
  16248. var args = Array.prototype.slice.call( arguments );
  16249. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16250. var x0 = lastargs[ lastargs.length - 2 ];
  16251. var y0 = lastargs[ lastargs.length - 1 ];
  16252. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  16253. this.curves.push( curve );
  16254. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  16255. };
  16256. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  16257. var args = Array.prototype.slice.call( arguments );
  16258. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16259. var x0 = lastargs[ lastargs.length - 2 ];
  16260. var y0 = lastargs[ lastargs.length - 1 ];
  16261. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  16262. new THREE.Vector2( aCPx, aCPy ),
  16263. new THREE.Vector2( aX, aY ) );
  16264. this.curves.push( curve );
  16265. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  16266. };
  16267. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  16268. aCP2x, aCP2y,
  16269. aX, aY ) {
  16270. var args = Array.prototype.slice.call( arguments );
  16271. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16272. var x0 = lastargs[ lastargs.length - 2 ];
  16273. var y0 = lastargs[ lastargs.length - 1 ];
  16274. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  16275. new THREE.Vector2( aCP1x, aCP1y ),
  16276. new THREE.Vector2( aCP2x, aCP2y ),
  16277. new THREE.Vector2( aX, aY ) );
  16278. this.curves.push( curve );
  16279. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  16280. };
  16281. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  16282. var args = Array.prototype.slice.call( arguments );
  16283. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16284. var x0 = lastargs[ lastargs.length - 2 ];
  16285. var y0 = lastargs[ lastargs.length - 1 ];
  16286. //---
  16287. var npts = [ new THREE.Vector2( x0, y0 ) ];
  16288. Array.prototype.push.apply( npts, pts );
  16289. var curve = new THREE.SplineCurve( npts );
  16290. this.curves.push( curve );
  16291. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  16292. };
  16293. // FUTURE: Change the API or follow canvas API?
  16294. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  16295. aStartAngle, aEndAngle, aClockwise ) {
  16296. var lastargs = this.actions[ this.actions.length - 1].args;
  16297. var x0 = lastargs[ lastargs.length - 2 ];
  16298. var y0 = lastargs[ lastargs.length - 1 ];
  16299. this.absarc(aX + x0, aY + y0, aRadius,
  16300. aStartAngle, aEndAngle, aClockwise );
  16301. };
  16302. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  16303. aStartAngle, aEndAngle, aClockwise ) {
  16304. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  16305. };
  16306. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  16307. aStartAngle, aEndAngle, aClockwise ) {
  16308. var lastargs = this.actions[ this.actions.length - 1].args;
  16309. var x0 = lastargs[ lastargs.length - 2 ];
  16310. var y0 = lastargs[ lastargs.length - 1 ];
  16311. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  16312. aStartAngle, aEndAngle, aClockwise );
  16313. };
  16314. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  16315. aStartAngle, aEndAngle, aClockwise ) {
  16316. var args = Array.prototype.slice.call( arguments );
  16317. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  16318. aStartAngle, aEndAngle, aClockwise );
  16319. this.curves.push( curve );
  16320. var lastPoint = curve.getPoint(1);
  16321. args.push(lastPoint.x);
  16322. args.push(lastPoint.y);
  16323. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  16324. };
  16325. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  16326. if ( ! divisions ) divisions = 40;
  16327. var points = [];
  16328. for ( var i = 0; i < divisions; i ++ ) {
  16329. points.push( this.getPoint( i / divisions ) );
  16330. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  16331. }
  16332. // if ( closedPath ) {
  16333. //
  16334. // points.push( points[ 0 ] );
  16335. //
  16336. // }
  16337. return points;
  16338. };
  16339. /* Return an array of vectors based on contour of the path */
  16340. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  16341. if (this.useSpacedPoints) {
  16342. console.log('tata');
  16343. return this.getSpacedPoints( divisions, closedPath );
  16344. }
  16345. divisions = divisions || 12;
  16346. var points = [];
  16347. var i, il, item, action, args;
  16348. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  16349. laste, j,
  16350. t, tx, ty;
  16351. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  16352. item = this.actions[ i ];
  16353. action = item.action;
  16354. args = item.args;
  16355. switch ( action ) {
  16356. case THREE.PathActions.MOVE_TO:
  16357. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  16358. break;
  16359. case THREE.PathActions.LINE_TO:
  16360. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  16361. break;
  16362. case THREE.PathActions.QUADRATIC_CURVE_TO:
  16363. cpx = args[ 2 ];
  16364. cpy = args[ 3 ];
  16365. cpx1 = args[ 0 ];
  16366. cpy1 = args[ 1 ];
  16367. if ( points.length > 0 ) {
  16368. laste = points[ points.length - 1 ];
  16369. cpx0 = laste.x;
  16370. cpy0 = laste.y;
  16371. } else {
  16372. laste = this.actions[ i - 1 ].args;
  16373. cpx0 = laste[ laste.length - 2 ];
  16374. cpy0 = laste[ laste.length - 1 ];
  16375. }
  16376. for ( j = 1; j <= divisions; j ++ ) {
  16377. t = j / divisions;
  16378. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16379. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16380. points.push( new THREE.Vector2( tx, ty ) );
  16381. }
  16382. break;
  16383. case THREE.PathActions.BEZIER_CURVE_TO:
  16384. cpx = args[ 4 ];
  16385. cpy = args[ 5 ];
  16386. cpx1 = args[ 0 ];
  16387. cpy1 = args[ 1 ];
  16388. cpx2 = args[ 2 ];
  16389. cpy2 = args[ 3 ];
  16390. if ( points.length > 0 ) {
  16391. laste = points[ points.length - 1 ];
  16392. cpx0 = laste.x;
  16393. cpy0 = laste.y;
  16394. } else {
  16395. laste = this.actions[ i - 1 ].args;
  16396. cpx0 = laste[ laste.length - 2 ];
  16397. cpy0 = laste[ laste.length - 1 ];
  16398. }
  16399. for ( j = 1; j <= divisions; j ++ ) {
  16400. t = j / divisions;
  16401. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16402. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16403. points.push( new THREE.Vector2( tx, ty ) );
  16404. }
  16405. break;
  16406. case THREE.PathActions.CSPLINE_THRU:
  16407. laste = this.actions[ i - 1 ].args;
  16408. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  16409. var spts = [ last ];
  16410. var n = divisions * args[ 0 ].length;
  16411. spts = spts.concat( args[ 0 ] );
  16412. var spline = new THREE.SplineCurve( spts );
  16413. for ( j = 1; j <= n; j ++ ) {
  16414. points.push( spline.getPointAt( j / n ) ) ;
  16415. }
  16416. break;
  16417. case THREE.PathActions.ARC:
  16418. var aX = args[ 0 ], aY = args[ 1 ],
  16419. aRadius = args[ 2 ],
  16420. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  16421. aClockwise = !! args[ 5 ];
  16422. var deltaAngle = aEndAngle - aStartAngle;
  16423. var angle;
  16424. var tdivisions = divisions * 2;
  16425. for ( j = 1; j <= tdivisions; j ++ ) {
  16426. t = j / tdivisions;
  16427. if ( ! aClockwise ) {
  16428. t = 1 - t;
  16429. }
  16430. angle = aStartAngle + t * deltaAngle;
  16431. tx = aX + aRadius * Math.cos( angle );
  16432. ty = aY + aRadius * Math.sin( angle );
  16433. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  16434. points.push( new THREE.Vector2( tx, ty ) );
  16435. }
  16436. //console.log(points);
  16437. break;
  16438. case THREE.PathActions.ELLIPSE:
  16439. var aX = args[ 0 ], aY = args[ 1 ],
  16440. xRadius = args[ 2 ],
  16441. yRadius = args[ 3 ],
  16442. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  16443. aClockwise = !! args[ 6 ];
  16444. var deltaAngle = aEndAngle - aStartAngle;
  16445. var angle;
  16446. var tdivisions = divisions * 2;
  16447. for ( j = 1; j <= tdivisions; j ++ ) {
  16448. t = j / tdivisions;
  16449. if ( ! aClockwise ) {
  16450. t = 1 - t;
  16451. }
  16452. angle = aStartAngle + t * deltaAngle;
  16453. tx = aX + xRadius * Math.cos( angle );
  16454. ty = aY + yRadius * Math.sin( angle );
  16455. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  16456. points.push( new THREE.Vector2( tx, ty ) );
  16457. }
  16458. //console.log(points);
  16459. break;
  16460. } // end switch
  16461. }
  16462. // Normalize to remove the closing point by default.
  16463. var lastPoint = points[ points.length - 1];
  16464. var EPSILON = 0.0000000001;
  16465. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  16466. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  16467. points.splice( points.length - 1, 1);
  16468. if ( closedPath ) {
  16469. points.push( points[ 0 ] );
  16470. }
  16471. return points;
  16472. };
  16473. //
  16474. // Breaks path into shapes
  16475. //
  16476. // Assumptions (if parameter isCCW==true the opposite holds):
  16477. // - solid shapes are defined clockwise (CW)
  16478. // - holes are defined counterclockwise (CCW)
  16479. //
  16480. // If parameter noHoles==true:
  16481. // - all subPaths are regarded as solid shapes
  16482. // - definition order CW/CCW has no relevance
  16483. //
  16484. THREE.Path.prototype.toShapes = function( isCCW, noHoles ) {
  16485. function extractSubpaths( inActions ) {
  16486. var i, il, item, action, args;
  16487. var subPaths = [], lastPath = new THREE.Path();
  16488. for ( i = 0, il = inActions.length; i < il; i ++ ) {
  16489. item = inActions[ i ];
  16490. args = item.args;
  16491. action = item.action;
  16492. if ( action === THREE.PathActions.MOVE_TO ) {
  16493. if ( lastPath.actions.length !== 0 ) {
  16494. subPaths.push( lastPath );
  16495. lastPath = new THREE.Path();
  16496. }
  16497. }
  16498. lastPath[ action ].apply( lastPath, args );
  16499. }
  16500. if ( lastPath.actions.length !== 0 ) {
  16501. subPaths.push( lastPath );
  16502. }
  16503. // console.log(subPaths);
  16504. return subPaths;
  16505. }
  16506. function toShapesNoHoles( inSubpaths ) {
  16507. var shapes = [];
  16508. for ( var i = 0, il = inSubpaths.length; i < il; i ++ ) {
  16509. var tmpPath = inSubpaths[ i ];
  16510. var tmpShape = new THREE.Shape();
  16511. tmpShape.actions = tmpPath.actions;
  16512. tmpShape.curves = tmpPath.curves;
  16513. shapes.push( tmpShape );
  16514. }
  16515. //console.log("shape", shapes);
  16516. return shapes;
  16517. }
  16518. function isPointInsidePolygon( inPt, inPolygon ) {
  16519. var EPSILON = 0.0000000001;
  16520. var polyLen = inPolygon.length;
  16521. // inPt on polygon contour => immediate success or
  16522. // toggling of inside/outside at every single! intersection point of an edge
  16523. // with the horizontal line through inPt, left of inPt
  16524. // not counting lowerY endpoints of edges and whole edges on that line
  16525. var inside = false;
  16526. for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  16527. var edgeLowPt = inPolygon[ p ];
  16528. var edgeHighPt = inPolygon[ q ];
  16529. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  16530. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  16531. if ( Math.abs(edgeDy) > EPSILON ) { // not parallel
  16532. if ( edgeDy < 0 ) {
  16533. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  16534. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  16535. }
  16536. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  16537. if ( inPt.y === edgeLowPt.y ) {
  16538. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  16539. // continue; // no intersection or edgeLowPt => doesn't count !!!
  16540. } else {
  16541. var perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  16542. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  16543. if ( perpEdge < 0 ) continue;
  16544. inside = ! inside; // true intersection left of inPt
  16545. }
  16546. } else { // parallel or colinear
  16547. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  16548. // egde lies on the same horizontal line as inPt
  16549. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  16550. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  16551. // continue;
  16552. }
  16553. }
  16554. return inside;
  16555. }
  16556. var subPaths = extractSubpaths( this.actions );
  16557. if ( subPaths.length === 0 ) return [];
  16558. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  16559. var solid, tmpPath, tmpShape, shapes = [];
  16560. if ( subPaths.length === 1) {
  16561. tmpPath = subPaths[0];
  16562. tmpShape = new THREE.Shape();
  16563. tmpShape.actions = tmpPath.actions;
  16564. tmpShape.curves = tmpPath.curves;
  16565. shapes.push( tmpShape );
  16566. return shapes;
  16567. }
  16568. var holesFirst = ! THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  16569. holesFirst = isCCW ? ! holesFirst : holesFirst;
  16570. // console.log("Holes first", holesFirst);
  16571. var betterShapeHoles = [];
  16572. var newShapes = [];
  16573. var newShapeHoles = [];
  16574. var mainIdx = 0;
  16575. var tmpPoints;
  16576. newShapes[mainIdx] = undefined;
  16577. newShapeHoles[mainIdx] = [];
  16578. var i, il;
  16579. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  16580. tmpPath = subPaths[ i ];
  16581. tmpPoints = tmpPath.getPoints();
  16582. solid = THREE.Shape.Utils.isClockWise( tmpPoints );
  16583. solid = isCCW ? ! solid : solid;
  16584. if ( solid ) {
  16585. if ( (! holesFirst ) && ( newShapes[mainIdx] ) ) mainIdx ++;
  16586. newShapes[mainIdx] = { s: new THREE.Shape(), p: tmpPoints };
  16587. newShapes[mainIdx].s.actions = tmpPath.actions;
  16588. newShapes[mainIdx].s.curves = tmpPath.curves;
  16589. if ( holesFirst ) mainIdx ++;
  16590. newShapeHoles[mainIdx] = [];
  16591. //console.log('cw', i);
  16592. } else {
  16593. newShapeHoles[mainIdx].push( { h: tmpPath, p: tmpPoints[0] } );
  16594. //console.log('ccw', i);
  16595. }
  16596. }
  16597. // only Holes? -> probably all Shapes with wrong orientation
  16598. if ( ! newShapes[0] ) return toShapesNoHoles( subPaths );
  16599. if ( newShapes.length > 1 ) {
  16600. var ambigious = false;
  16601. var toChange = [];
  16602. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  16603. betterShapeHoles[sIdx] = [];
  16604. }
  16605. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  16606. var sho = newShapeHoles[sIdx];
  16607. for (var hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  16608. var ho = sho[hIdx];
  16609. var hole_unassigned = true;
  16610. for (var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  16611. if ( isPointInsidePolygon( ho.p, newShapes[s2Idx].p ) ) {
  16612. if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  16613. if ( hole_unassigned ) {
  16614. hole_unassigned = false;
  16615. betterShapeHoles[s2Idx].push( ho );
  16616. } else {
  16617. ambigious = true;
  16618. }
  16619. }
  16620. }
  16621. if ( hole_unassigned ) { betterShapeHoles[sIdx].push( ho ); }
  16622. }
  16623. }
  16624. // console.log("ambigious: ", ambigious);
  16625. if ( toChange.length > 0 ) {
  16626. // console.log("to change: ", toChange);
  16627. if (! ambigious) newShapeHoles = betterShapeHoles;
  16628. }
  16629. }
  16630. var tmpHoles, j, jl;
  16631. for ( i = 0, il = newShapes.length; i < il; i ++ ) {
  16632. tmpShape = newShapes[i].s;
  16633. shapes.push( tmpShape );
  16634. tmpHoles = newShapeHoles[i];
  16635. for ( j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  16636. tmpShape.holes.push( tmpHoles[j].h );
  16637. }
  16638. }
  16639. //console.log("shape", shapes);
  16640. return shapes;
  16641. };
  16642. // File:src/extras/core/Shape.js
  16643. /**
  16644. * @author zz85 / http://www.lab4games.net/zz85/blog
  16645. * Defines a 2d shape plane using paths.
  16646. **/
  16647. // STEP 1 Create a path.
  16648. // STEP 2 Turn path into shape.
  16649. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  16650. // STEP 3a - Extract points from each shape, turn to vertices
  16651. // STEP 3b - Triangulate each shape, add faces.
  16652. THREE.Shape = function () {
  16653. THREE.Path.apply( this, arguments );
  16654. this.holes = [];
  16655. };
  16656. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  16657. THREE.Shape.prototype.constructor = THREE.Shape;
  16658. // Convenience method to return ExtrudeGeometry
  16659. THREE.Shape.prototype.extrude = function ( options ) {
  16660. var extruded = new THREE.ExtrudeGeometry( this, options );
  16661. return extruded;
  16662. };
  16663. // Convenience method to return ShapeGeometry
  16664. THREE.Shape.prototype.makeGeometry = function ( options ) {
  16665. var geometry = new THREE.ShapeGeometry( this, options );
  16666. return geometry;
  16667. };
  16668. // Get points of holes
  16669. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  16670. var i, il = this.holes.length, holesPts = [];
  16671. for ( i = 0; i < il; i ++ ) {
  16672. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  16673. }
  16674. return holesPts;
  16675. };
  16676. // Get points of holes (spaced by regular distance)
  16677. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  16678. var i, il = this.holes.length, holesPts = [];
  16679. for ( i = 0; i < il; i ++ ) {
  16680. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  16681. }
  16682. return holesPts;
  16683. };
  16684. // Get points of shape and holes (keypoints based on segments parameter)
  16685. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  16686. return {
  16687. shape: this.getTransformedPoints( divisions ),
  16688. holes: this.getPointsHoles( divisions )
  16689. };
  16690. };
  16691. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  16692. if (this.useSpacedPoints) {
  16693. return this.extractAllSpacedPoints(divisions);
  16694. }
  16695. return this.extractAllPoints(divisions);
  16696. };
  16697. //
  16698. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  16699. //
  16700. // return {
  16701. //
  16702. // shape: this.transform( bend, divisions ),
  16703. // holes: this.getPointsHoles( divisions, bend )
  16704. //
  16705. // };
  16706. //
  16707. // };
  16708. // Get points of shape and holes (spaced by regular distance)
  16709. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  16710. return {
  16711. shape: this.getTransformedSpacedPoints( divisions ),
  16712. holes: this.getSpacedPointsHoles( divisions )
  16713. };
  16714. };
  16715. /**************************************************************
  16716. * Utils
  16717. **************************************************************/
  16718. THREE.Shape.Utils = {
  16719. triangulateShape: function ( contour, holes ) {
  16720. function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) {
  16721. // inOtherPt needs to be colinear to the inSegment
  16722. if ( inSegPt1.x !== inSegPt2.x ) {
  16723. if ( inSegPt1.x < inSegPt2.x ) {
  16724. return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) );
  16725. } else {
  16726. return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) );
  16727. }
  16728. } else {
  16729. if ( inSegPt1.y < inSegPt2.y ) {
  16730. return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) );
  16731. } else {
  16732. return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) );
  16733. }
  16734. }
  16735. }
  16736. function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) {
  16737. var EPSILON = 0.0000000001;
  16738. var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y;
  16739. var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y;
  16740. var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x;
  16741. var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y;
  16742. var limit = seg1dy * seg2dx - seg1dx * seg2dy;
  16743. var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy;
  16744. if ( Math.abs(limit) > EPSILON ) { // not parallel
  16745. var perpSeg2;
  16746. if ( limit > 0 ) {
  16747. if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return [];
  16748. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  16749. if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return [];
  16750. } else {
  16751. if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return [];
  16752. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  16753. if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return [];
  16754. }
  16755. // i.e. to reduce rounding errors
  16756. // intersection at endpoint of segment#1?
  16757. if ( perpSeg2 === 0 ) {
  16758. if ( ( inExcludeAdjacentSegs ) &&
  16759. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  16760. return [ inSeg1Pt1 ];
  16761. }
  16762. if ( perpSeg2 === limit ) {
  16763. if ( ( inExcludeAdjacentSegs ) &&
  16764. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  16765. return [ inSeg1Pt2 ];
  16766. }
  16767. // intersection at endpoint of segment#2?
  16768. if ( perpSeg1 === 0 ) return [ inSeg2Pt1 ];
  16769. if ( perpSeg1 === limit ) return [ inSeg2Pt2 ];
  16770. // return real intersection point
  16771. var factorSeg1 = perpSeg2 / limit;
  16772. return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx,
  16773. y: inSeg1Pt1.y + factorSeg1 * seg1dy } ];
  16774. } else { // parallel or colinear
  16775. if ( ( perpSeg1 !== 0 ) ||
  16776. ( seg2dy * seg1seg2dx !== seg2dx * seg1seg2dy ) ) return [];
  16777. // they are collinear or degenerate
  16778. var seg1Pt = ( (seg1dx === 0) && (seg1dy === 0) ); // segment1 ist just a point?
  16779. var seg2Pt = ( (seg2dx === 0) && (seg2dy === 0) ); // segment2 ist just a point?
  16780. // both segments are points
  16781. if ( seg1Pt && seg2Pt ) {
  16782. if ( (inSeg1Pt1.x !== inSeg2Pt1.x) ||
  16783. (inSeg1Pt1.y !== inSeg2Pt1.y) ) return []; // they are distinct points
  16784. return [ inSeg1Pt1 ]; // they are the same point
  16785. }
  16786. // segment#1 is a single point
  16787. if ( seg1Pt ) {
  16788. if (! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2
  16789. return [ inSeg1Pt1 ];
  16790. }
  16791. // segment#2 is a single point
  16792. if ( seg2Pt ) {
  16793. if (! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1
  16794. return [ inSeg2Pt1 ];
  16795. }
  16796. // they are collinear segments, which might overlap
  16797. var seg1min, seg1max, seg1minVal, seg1maxVal;
  16798. var seg2min, seg2max, seg2minVal, seg2maxVal;
  16799. if (seg1dx !== 0) { // the segments are NOT on a vertical line
  16800. if ( inSeg1Pt1.x < inSeg1Pt2.x ) {
  16801. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x;
  16802. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x;
  16803. } else {
  16804. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x;
  16805. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x;
  16806. }
  16807. if ( inSeg2Pt1.x < inSeg2Pt2.x ) {
  16808. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x;
  16809. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x;
  16810. } else {
  16811. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x;
  16812. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x;
  16813. }
  16814. } else { // the segments are on a vertical line
  16815. if ( inSeg1Pt1.y < inSeg1Pt2.y ) {
  16816. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y;
  16817. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y;
  16818. } else {
  16819. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y;
  16820. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y;
  16821. }
  16822. if ( inSeg2Pt1.y < inSeg2Pt2.y ) {
  16823. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y;
  16824. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y;
  16825. } else {
  16826. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y;
  16827. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y;
  16828. }
  16829. }
  16830. if ( seg1minVal <= seg2minVal ) {
  16831. if ( seg1maxVal < seg2minVal ) return [];
  16832. if ( seg1maxVal === seg2minVal ) {
  16833. if ( inExcludeAdjacentSegs ) return [];
  16834. return [ seg2min ];
  16835. }
  16836. if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ];
  16837. return [ seg2min, seg2max ];
  16838. } else {
  16839. if ( seg1minVal > seg2maxVal ) return [];
  16840. if ( seg1minVal === seg2maxVal ) {
  16841. if ( inExcludeAdjacentSegs ) return [];
  16842. return [ seg1min ];
  16843. }
  16844. if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ];
  16845. return [ seg1min, seg2max ];
  16846. }
  16847. }
  16848. }
  16849. function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) {
  16850. // The order of legs is important
  16851. var EPSILON = 0.0000000001;
  16852. // translation of all points, so that Vertex is at (0,0)
  16853. var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y;
  16854. var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y;
  16855. var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y;
  16856. // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg.
  16857. var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX;
  16858. var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX;
  16859. if ( Math.abs(from2toAngle) > EPSILON ) { // angle != 180 deg.
  16860. var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX;
  16861. // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle );
  16862. if ( from2toAngle > 0 ) { // main angle < 180 deg.
  16863. return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) );
  16864. } else { // main angle > 180 deg.
  16865. return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) );
  16866. }
  16867. } else { // angle == 180 deg.
  16868. // console.log( "from2to: 180 deg., from2other: " + from2otherAngle );
  16869. return ( from2otherAngle > 0 );
  16870. }
  16871. }
  16872. function removeHoles( contour, holes ) {
  16873. var shape = contour.concat(); // work on this shape
  16874. var hole;
  16875. function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) {
  16876. // Check if hole point lies within angle around shape point
  16877. var lastShapeIdx = shape.length - 1;
  16878. var prevShapeIdx = inShapeIdx - 1;
  16879. if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx;
  16880. var nextShapeIdx = inShapeIdx + 1;
  16881. if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0;
  16882. var insideAngle = isPointInsideAngle( shape[inShapeIdx], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[inHoleIdx] );
  16883. if (! insideAngle ) {
  16884. // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y );
  16885. return false;
  16886. }
  16887. // Check if shape point lies within angle around hole point
  16888. var lastHoleIdx = hole.length - 1;
  16889. var prevHoleIdx = inHoleIdx - 1;
  16890. if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx;
  16891. var nextHoleIdx = inHoleIdx + 1;
  16892. if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0;
  16893. insideAngle = isPointInsideAngle( hole[inHoleIdx], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[inShapeIdx] );
  16894. if (! insideAngle ) {
  16895. // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y );
  16896. return false;
  16897. }
  16898. return true;
  16899. }
  16900. function intersectsShapeEdge( inShapePt, inHolePt ) {
  16901. // checks for intersections with shape edges
  16902. var sIdx, nextIdx, intersection;
  16903. for ( sIdx = 0; sIdx < shape.length; sIdx ++ ) {
  16904. nextIdx = sIdx + 1; nextIdx %= shape.length;
  16905. intersection = intersect_segments_2D( inShapePt, inHolePt, shape[sIdx], shape[nextIdx], true );
  16906. if ( intersection.length > 0 ) return true;
  16907. }
  16908. return false;
  16909. }
  16910. var indepHoles = [];
  16911. function intersectsHoleEdge( inShapePt, inHolePt ) {
  16912. // checks for intersections with hole edges
  16913. var ihIdx, chkHole,
  16914. hIdx, nextIdx, intersection;
  16915. for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx ++ ) {
  16916. chkHole = holes[indepHoles[ihIdx]];
  16917. for ( hIdx = 0; hIdx < chkHole.length; hIdx ++ ) {
  16918. nextIdx = hIdx + 1; nextIdx %= chkHole.length;
  16919. intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[hIdx], chkHole[nextIdx], true );
  16920. if ( intersection.length > 0 ) return true;
  16921. }
  16922. }
  16923. return false;
  16924. }
  16925. var holeIndex, shapeIndex,
  16926. shapePt, holePt,
  16927. holeIdx, cutKey, failedCuts = [],
  16928. tmpShape1, tmpShape2,
  16929. tmpHole1, tmpHole2;
  16930. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  16931. indepHoles.push( h );
  16932. }
  16933. var minShapeIndex = 0;
  16934. var counter = indepHoles.length * 2;
  16935. while ( indepHoles.length > 0 ) {
  16936. counter --;
  16937. if ( counter < 0 ) {
  16938. console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" );
  16939. break;
  16940. }
  16941. // search for shape-vertex and hole-vertex,
  16942. // which can be connected without intersections
  16943. for ( shapeIndex = minShapeIndex; shapeIndex < shape.length; shapeIndex ++ ) {
  16944. shapePt = shape[ shapeIndex ];
  16945. holeIndex = - 1;
  16946. // search for hole which can be reached without intersections
  16947. for ( var h = 0; h < indepHoles.length; h ++ ) {
  16948. holeIdx = indepHoles[h];
  16949. // prevent multiple checks
  16950. cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx;
  16951. if ( failedCuts[cutKey] !== undefined ) continue;
  16952. hole = holes[holeIdx];
  16953. for ( var h2 = 0; h2 < hole.length; h2 ++ ) {
  16954. holePt = hole[ h2 ];
  16955. if (! isCutLineInsideAngles( shapeIndex, h2 ) ) continue;
  16956. if ( intersectsShapeEdge( shapePt, holePt ) ) continue;
  16957. if ( intersectsHoleEdge( shapePt, holePt ) ) continue;
  16958. holeIndex = h2;
  16959. indepHoles.splice(h, 1);
  16960. tmpShape1 = shape.slice( 0, shapeIndex + 1 );
  16961. tmpShape2 = shape.slice( shapeIndex );
  16962. tmpHole1 = hole.slice( holeIndex );
  16963. tmpHole2 = hole.slice( 0, holeIndex + 1 );
  16964. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  16965. minShapeIndex = shapeIndex;
  16966. // Debug only, to show the selected cuts
  16967. // glob_CutLines.push( [ shapePt, holePt ] );
  16968. break;
  16969. }
  16970. if ( holeIndex >= 0 ) break; // hole-vertex found
  16971. failedCuts[cutKey] = true; // remember failure
  16972. }
  16973. if ( holeIndex >= 0 ) break; // hole-vertex found
  16974. }
  16975. }
  16976. return shape; /* shape with no holes */
  16977. }
  16978. var i, il, f, face,
  16979. key, index,
  16980. allPointsMap = {};
  16981. // 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.
  16982. var allpoints = contour.concat();
  16983. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  16984. Array.prototype.push.apply( allpoints, holes[h] );
  16985. }
  16986. //console.log( "allpoints",allpoints, allpoints.length );
  16987. // prepare all points map
  16988. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  16989. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  16990. if ( allPointsMap[ key ] !== undefined ) {
  16991. console.warn( "THREE.Shape: Duplicate point", key );
  16992. }
  16993. allPointsMap[ key ] = i;
  16994. }
  16995. // remove holes by cutting paths to holes and adding them to the shape
  16996. var shapeWithoutHoles = removeHoles( contour, holes );
  16997. var triangles = THREE.FontUtils.Triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape
  16998. //console.log( "triangles",triangles, triangles.length );
  16999. // check all face vertices against all points map
  17000. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  17001. face = triangles[ i ];
  17002. for ( f = 0; f < 3; f ++ ) {
  17003. key = face[ f ].x + ":" + face[ f ].y;
  17004. index = allPointsMap[ key ];
  17005. if ( index !== undefined ) {
  17006. face[ f ] = index;
  17007. }
  17008. }
  17009. }
  17010. return triangles.concat();
  17011. },
  17012. isClockWise: function ( pts ) {
  17013. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  17014. },
  17015. // Bezier Curves formulas obtained from
  17016. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  17017. // Quad Bezier Functions
  17018. b2p0: function ( t, p ) {
  17019. var k = 1 - t;
  17020. return k * k * p;
  17021. },
  17022. b2p1: function ( t, p ) {
  17023. return 2 * ( 1 - t ) * t * p;
  17024. },
  17025. b2p2: function ( t, p ) {
  17026. return t * t * p;
  17027. },
  17028. b2: function ( t, p0, p1, p2 ) {
  17029. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  17030. },
  17031. // Cubic Bezier Functions
  17032. b3p0: function ( t, p ) {
  17033. var k = 1 - t;
  17034. return k * k * k * p;
  17035. },
  17036. b3p1: function ( t, p ) {
  17037. var k = 1 - t;
  17038. return 3 * k * k * t * p;
  17039. },
  17040. b3p2: function ( t, p ) {
  17041. var k = 1 - t;
  17042. return 3 * k * t * t * p;
  17043. },
  17044. b3p3: function ( t, p ) {
  17045. return t * t * t * p;
  17046. },
  17047. b3: function ( t, p0, p1, p2, p3 ) {
  17048. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  17049. }
  17050. };
  17051. // File:src/extras/curves/LineCurve.js
  17052. /**************************************************************
  17053. * Line
  17054. **************************************************************/
  17055. THREE.LineCurve = function ( v1, v2 ) {
  17056. this.v1 = v1;
  17057. this.v2 = v2;
  17058. };
  17059. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  17060. THREE.LineCurve.prototype.constructor = THREE.LineCurve;
  17061. THREE.LineCurve.prototype.getPoint = function ( t ) {
  17062. var point = this.v2.clone().sub(this.v1);
  17063. point.multiplyScalar( t ).add( this.v1 );
  17064. return point;
  17065. };
  17066. // Line curve is linear, so we can overwrite default getPointAt
  17067. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  17068. return this.getPoint( u );
  17069. };
  17070. THREE.LineCurve.prototype.getTangent = function( t ) {
  17071. var tangent = this.v2.clone().sub(this.v1);
  17072. return tangent.normalize();
  17073. };
  17074. // File:src/extras/curves/QuadraticBezierCurve.js
  17075. /**************************************************************
  17076. * Quadratic Bezier curve
  17077. **************************************************************/
  17078. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  17079. this.v0 = v0;
  17080. this.v1 = v1;
  17081. this.v2 = v2;
  17082. };
  17083. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  17084. THREE.QuadraticBezierCurve.prototype.constructor = THREE.QuadraticBezierCurve;
  17085. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  17086. var vector = new THREE.Vector2();
  17087. vector.x = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  17088. vector.y = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  17089. return vector;
  17090. };
  17091. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  17092. var vector = new THREE.Vector2();
  17093. vector.x = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  17094. vector.y = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  17095. // returns unit vector
  17096. return vector.normalize();
  17097. };
  17098. // File:src/extras/curves/CubicBezierCurve.js
  17099. /**************************************************************
  17100. * Cubic Bezier curve
  17101. **************************************************************/
  17102. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  17103. this.v0 = v0;
  17104. this.v1 = v1;
  17105. this.v2 = v2;
  17106. this.v3 = v3;
  17107. };
  17108. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  17109. THREE.CubicBezierCurve.prototype.constructor = THREE.CubicBezierCurve;
  17110. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  17111. var tx, ty;
  17112. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17113. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17114. return new THREE.Vector2( tx, ty );
  17115. };
  17116. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  17117. var tx, ty;
  17118. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17119. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17120. var tangent = new THREE.Vector2( tx, ty );
  17121. tangent.normalize();
  17122. return tangent;
  17123. };
  17124. // File:src/extras/curves/SplineCurve.js
  17125. /**************************************************************
  17126. * Spline curve
  17127. **************************************************************/
  17128. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  17129. this.points = ( points == undefined ) ? [] : points;
  17130. };
  17131. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  17132. THREE.SplineCurve.prototype.constructor = THREE.SplineCurve;
  17133. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  17134. var points = this.points;
  17135. var point = ( points.length - 1 ) * t;
  17136. var intPoint = Math.floor( point );
  17137. var weight = point - intPoint;
  17138. var point0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  17139. var point1 = points[ intPoint ];
  17140. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  17141. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  17142. var vector = new THREE.Vector2();
  17143. vector.x = THREE.Curve.Utils.interpolate( point0.x, point1.x, point2.x, point3.x, weight );
  17144. vector.y = THREE.Curve.Utils.interpolate( point0.y, point1.y, point2.y, point3.y, weight );
  17145. return vector;
  17146. };
  17147. // File:src/extras/curves/EllipseCurve.js
  17148. /**************************************************************
  17149. * Ellipse curve
  17150. **************************************************************/
  17151. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise ) {
  17152. this.aX = aX;
  17153. this.aY = aY;
  17154. this.xRadius = xRadius;
  17155. this.yRadius = yRadius;
  17156. this.aStartAngle = aStartAngle;
  17157. this.aEndAngle = aEndAngle;
  17158. this.aClockwise = aClockwise;
  17159. };
  17160. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  17161. THREE.EllipseCurve.prototype.constructor = THREE.EllipseCurve;
  17162. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  17163. var deltaAngle = this.aEndAngle - this.aStartAngle;
  17164. if ( deltaAngle < 0 ) deltaAngle += Math.PI * 2;
  17165. if ( deltaAngle > Math.PI * 2 ) deltaAngle -= Math.PI * 2;
  17166. var angle;
  17167. if ( this.aClockwise === true ) {
  17168. angle = this.aEndAngle + ( 1 - t ) * ( Math.PI * 2 - deltaAngle );
  17169. } else {
  17170. angle = this.aStartAngle + t * deltaAngle;
  17171. }
  17172. var vector = new THREE.Vector2();
  17173. vector.x = this.aX + this.xRadius * Math.cos( angle );
  17174. vector.y = this.aY + this.yRadius * Math.sin( angle );
  17175. return vector;
  17176. };
  17177. // File:src/extras/curves/ArcCurve.js
  17178. /**************************************************************
  17179. * Arc curve
  17180. **************************************************************/
  17181. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  17182. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  17183. };
  17184. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  17185. THREE.ArcCurve.prototype.constructor = THREE.ArcCurve;
  17186. // File:src/extras/curves/LineCurve3.js
  17187. /**************************************************************
  17188. * Line3D
  17189. **************************************************************/
  17190. THREE.LineCurve3 = THREE.Curve.create(
  17191. function ( v1, v2 ) {
  17192. this.v1 = v1;
  17193. this.v2 = v2;
  17194. },
  17195. function ( t ) {
  17196. var vector = new THREE.Vector3();
  17197. vector.subVectors( this.v2, this.v1 ); // diff
  17198. vector.multiplyScalar( t );
  17199. vector.add( this.v1 );
  17200. return vector;
  17201. }
  17202. );
  17203. // File:src/extras/curves/QuadraticBezierCurve3.js
  17204. /**************************************************************
  17205. * Quadratic Bezier 3D curve
  17206. **************************************************************/
  17207. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  17208. function ( v0, v1, v2 ) {
  17209. this.v0 = v0;
  17210. this.v1 = v1;
  17211. this.v2 = v2;
  17212. },
  17213. function ( t ) {
  17214. var vector = new THREE.Vector3();
  17215. vector.x = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  17216. vector.y = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  17217. vector.z = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  17218. return vector;
  17219. }
  17220. );
  17221. // File:src/extras/curves/CubicBezierCurve3.js
  17222. /**************************************************************
  17223. * Cubic Bezier 3D curve
  17224. **************************************************************/
  17225. THREE.CubicBezierCurve3 = THREE.Curve.create(
  17226. function ( v0, v1, v2, v3 ) {
  17227. this.v0 = v0;
  17228. this.v1 = v1;
  17229. this.v2 = v2;
  17230. this.v3 = v3;
  17231. },
  17232. function ( t ) {
  17233. var vector = new THREE.Vector3();
  17234. vector.x = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17235. vector.y = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17236. vector.z = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  17237. return vector;
  17238. }
  17239. );
  17240. // File:src/extras/curves/SplineCurve3.js
  17241. /**************************************************************
  17242. * Spline 3D curve
  17243. **************************************************************/
  17244. THREE.SplineCurve3 = THREE.Curve.create(
  17245. function ( points /* array of Vector3 */) {
  17246. console.warn( 'THREE.SplineCurve3 will be deprecated. Please use THREE.CatmullRomCurve3' );
  17247. this.points = ( points == undefined ) ? [] : points;
  17248. },
  17249. function ( t ) {
  17250. var points = this.points;
  17251. var point = ( points.length - 1 ) * t;
  17252. var intPoint = Math.floor( point );
  17253. var weight = point - intPoint;
  17254. var point0 = points[ intPoint == 0 ? intPoint : intPoint - 1 ];
  17255. var point1 = points[ intPoint ];
  17256. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  17257. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  17258. var vector = new THREE.Vector3();
  17259. vector.x = THREE.Curve.Utils.interpolate( point0.x, point1.x, point2.x, point3.x, weight );
  17260. vector.y = THREE.Curve.Utils.interpolate( point0.y, point1.y, point2.y, point3.y, weight );
  17261. vector.z = THREE.Curve.Utils.interpolate( point0.z, point1.z, point2.z, point3.z, weight );
  17262. return vector;
  17263. }
  17264. );
  17265. // File:src/extras/curves/CatmullRomCurve3.js
  17266. /**
  17267. * @author zz85 https://github.com/zz85
  17268. *
  17269. * Centripetal CatmullRom Curve - which is useful for avoiding
  17270. * cusps and self-intersections in non-uniform catmull rom curves.
  17271. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  17272. *
  17273. * curve.type accepts centripetal(default), chordal and catmullrom
  17274. * curve.tension is used for catmullrom which defaults to 0.5
  17275. */
  17276. THREE.CatmullRomCurve3 = ( function() {
  17277. var
  17278. tmp = new THREE.Vector3(),
  17279. px = new CubicPoly(),
  17280. py = new CubicPoly(),
  17281. pz = new CubicPoly();
  17282. /*
  17283. Based on an optimized c++ solution in
  17284. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  17285. - http://ideone.com/NoEbVM
  17286. This CubicPoly class could be used for reusing some variables and calculations,
  17287. but for three.js curve use, it could be possible inlined and flatten into a single function call
  17288. which can be placed in CurveUtils.
  17289. */
  17290. function CubicPoly() {
  17291. }
  17292. /*
  17293. * Compute coefficients for a cubic polynomial
  17294. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  17295. * such that
  17296. * p(0) = x0, p(1) = x1
  17297. * and
  17298. * p'(0) = t0, p'(1) = t1.
  17299. */
  17300. CubicPoly.prototype.init = function( x0, x1, t0, t1 ) {
  17301. this.c0 = x0;
  17302. this.c1 = t0;
  17303. this.c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  17304. this.c3 = 2 * x0 - 2 * x1 + t0 + t1;
  17305. };
  17306. CubicPoly.prototype.initNonuniformCatmullRom = function( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  17307. // compute tangents when parameterized in [t1,t2]
  17308. var t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  17309. var t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  17310. // rescale tangents for parametrization in [0,1]
  17311. t1 *= dt1;
  17312. t2 *= dt1;
  17313. // initCubicPoly
  17314. this.init( x1, x2, t1, t2 );
  17315. };
  17316. // standard Catmull-Rom spline: interpolate between x1 and x2 with previous/following points x1/x4
  17317. CubicPoly.prototype.initCatmullRom = function( x0, x1, x2, x3, tension ) {
  17318. this.init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  17319. };
  17320. CubicPoly.prototype.calc = function( t ) {
  17321. var t2 = t * t;
  17322. var t3 = t2 * t;
  17323. return this.c0 + this.c1 * t + this.c2 * t2 + this.c3 * t3;
  17324. };
  17325. // Subclass Three.js curve
  17326. return THREE.Curve.create(
  17327. function ( p /* array of Vector3 */ ) {
  17328. this.points = p || [];
  17329. },
  17330. function ( t ) {
  17331. var points = this.points,
  17332. point, intPoint, weight, l;
  17333. l = points.length;
  17334. if ( l < 2 ) console.log( 'duh, you need at least 2 points' );
  17335. point = ( l - 1 ) * t;
  17336. intPoint = Math.floor( point );
  17337. weight = point - intPoint;
  17338. if ( weight === 0 && intPoint === l - 1 ) {
  17339. intPoint = l - 2;
  17340. weight = 1;
  17341. }
  17342. var p0, p1, p2, p3;
  17343. if ( intPoint === 0 ) {
  17344. // extrapolate first point
  17345. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  17346. p0 = tmp;
  17347. } else {
  17348. p0 = points[ intPoint - 1 ];
  17349. }
  17350. p1 = points[ intPoint ];
  17351. p2 = points[ intPoint + 1 ];
  17352. if ( intPoint + 2 < l ) {
  17353. p3 = points[ intPoint + 2 ]
  17354. } else {
  17355. // extrapolate last point
  17356. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 2 ] );
  17357. p3 = tmp;
  17358. }
  17359. if ( this.type === undefined || this.type === 'centripetal' || this.type === 'chordal' ) {
  17360. // init Centripetal / Chordal Catmull-Rom
  17361. var pow = this.type === 'chordal' ? 0.5 : 0.25;
  17362. var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  17363. var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  17364. var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  17365. // safety check for repeated points
  17366. if ( dt1 < 1e-4 ) dt1 = 1.0;
  17367. if ( dt0 < 1e-4 ) dt0 = dt1;
  17368. if ( dt2 < 1e-4 ) dt2 = dt1;
  17369. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  17370. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  17371. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  17372. } else if ( this.type === 'catmullrom' ) {
  17373. var tension = this.tension !== undefined ? this.tension : 0.5;
  17374. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, tension );
  17375. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, tension );
  17376. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, tension );
  17377. }
  17378. var v = new THREE.Vector3(
  17379. px.calc( weight ),
  17380. py.calc( weight ),
  17381. pz.calc( weight )
  17382. );
  17383. return v;
  17384. }
  17385. );
  17386. } )();
  17387. // File:src/extras/curves/ClosedSplineCurve3.js
  17388. /**************************************************************
  17389. * Closed Spline 3D curve
  17390. **************************************************************/
  17391. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  17392. function ( points /* array of Vector3 */) {
  17393. this.points = ( points == undefined ) ? [] : points;
  17394. },
  17395. function ( t ) {
  17396. var points = this.points;
  17397. var point = ( points.length - 0 ) * t; // This needs to be from 0-length +1
  17398. var intPoint = Math.floor( point );
  17399. var weight = point - intPoint;
  17400. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  17401. var point0 = points[ ( intPoint - 1 ) % points.length ];
  17402. var point1 = points[ ( intPoint ) % points.length ];
  17403. var point2 = points[ ( intPoint + 1 ) % points.length ];
  17404. var point3 = points[ ( intPoint + 2 ) % points.length ];
  17405. var vector = new THREE.Vector3();
  17406. vector.x = THREE.Curve.Utils.interpolate( point0.x, point1.x, point2.x, point3.x, weight );
  17407. vector.y = THREE.Curve.Utils.interpolate( point0.y, point1.y, point2.y, point3.y, weight );
  17408. vector.z = THREE.Curve.Utils.interpolate( point0.z, point1.z, point2.z, point3.z, weight );
  17409. return vector;
  17410. }
  17411. );
  17412. // File:src/extras/animation/AnimationHandler.js
  17413. /**
  17414. * @author mikael emtinger / http://gomo.se/
  17415. */
  17416. THREE.AnimationHandler = {
  17417. LINEAR: 0,
  17418. CATMULLROM: 1,
  17419. CATMULLROM_FORWARD: 2,
  17420. //
  17421. add: function () { console.warn( 'THREE.AnimationHandler.add() has been deprecated.' ); },
  17422. get: function () { console.warn( 'THREE.AnimationHandler.get() has been deprecated.' ); },
  17423. remove: function () { console.warn( 'THREE.AnimationHandler.remove() has been deprecated.' ); },
  17424. //
  17425. animations: [],
  17426. init: function ( data ) {
  17427. if ( data.initialized === true ) return data;
  17428. // loop through all keys
  17429. for ( var h = 0; h < data.hierarchy.length; h ++ ) {
  17430. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17431. // remove minus times
  17432. if ( data.hierarchy[ h ].keys[ k ].time < 0 ) {
  17433. data.hierarchy[ h ].keys[ k ].time = 0;
  17434. }
  17435. // create quaternions
  17436. if ( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  17437. ! ( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  17438. var quat = data.hierarchy[ h ].keys[ k ].rot;
  17439. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion().fromArray( quat );
  17440. }
  17441. }
  17442. // prepare morph target keys
  17443. if ( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  17444. // get all used
  17445. var usedMorphTargets = {};
  17446. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17447. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17448. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  17449. usedMorphTargets[ morphTargetName ] = - 1;
  17450. }
  17451. }
  17452. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  17453. // set all used on all frames
  17454. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17455. var influences = {};
  17456. for ( var morphTargetName in usedMorphTargets ) {
  17457. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17458. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  17459. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  17460. break;
  17461. }
  17462. }
  17463. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  17464. influences[ morphTargetName ] = 0;
  17465. }
  17466. }
  17467. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  17468. }
  17469. }
  17470. // remove all keys that are on the same time
  17471. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17472. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  17473. data.hierarchy[ h ].keys.splice( k, 1 );
  17474. k --;
  17475. }
  17476. }
  17477. // set index
  17478. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17479. data.hierarchy[ h ].keys[ k ].index = k;
  17480. }
  17481. }
  17482. data.initialized = true;
  17483. return data;
  17484. },
  17485. parse: function ( root ) {
  17486. var parseRecurseHierarchy = function ( root, hierarchy ) {
  17487. hierarchy.push( root );
  17488. for ( var c = 0; c < root.children.length; c ++ )
  17489. parseRecurseHierarchy( root.children[ c ], hierarchy );
  17490. };
  17491. // setup hierarchy
  17492. var hierarchy = [];
  17493. if ( root instanceof THREE.SkinnedMesh ) {
  17494. for ( var b = 0; b < root.skeleton.bones.length; b ++ ) {
  17495. hierarchy.push( root.skeleton.bones[ b ] );
  17496. }
  17497. } else {
  17498. parseRecurseHierarchy( root, hierarchy );
  17499. }
  17500. return hierarchy;
  17501. },
  17502. play: function ( animation ) {
  17503. if ( this.animations.indexOf( animation ) === - 1 ) {
  17504. this.animations.push( animation );
  17505. }
  17506. },
  17507. stop: function ( animation ) {
  17508. var index = this.animations.indexOf( animation );
  17509. if ( index !== - 1 ) {
  17510. this.animations.splice( index, 1 );
  17511. }
  17512. },
  17513. update: function ( deltaTimeMS ) {
  17514. for ( var i = 0; i < this.animations.length; i ++ ) {
  17515. this.animations[ i ].resetBlendWeights( );
  17516. }
  17517. for ( var i = 0; i < this.animations.length; i ++ ) {
  17518. this.animations[ i ].update( deltaTimeMS );
  17519. }
  17520. }
  17521. };
  17522. // File:src/extras/animation/Animation.js
  17523. /**
  17524. * @author mikael emtinger / http://gomo.se/
  17525. * @author mrdoob / http://mrdoob.com/
  17526. * @author alteredq / http://alteredqualia.com/
  17527. */
  17528. THREE.Animation = function ( root, data ) {
  17529. this.root = root;
  17530. this.data = THREE.AnimationHandler.init( data );
  17531. this.hierarchy = THREE.AnimationHandler.parse( root );
  17532. this.currentTime = 0;
  17533. this.timeScale = 1;
  17534. this.isPlaying = false;
  17535. this.loop = true;
  17536. this.weight = 0;
  17537. this.interpolationType = THREE.AnimationHandler.LINEAR;
  17538. };
  17539. THREE.Animation.prototype = {
  17540. constructor: THREE.Animation,
  17541. keyTypes: [ "pos", "rot", "scl" ],
  17542. play: function ( startTime, weight ) {
  17543. this.currentTime = startTime !== undefined ? startTime : 0;
  17544. this.weight = weight !== undefined ? weight : 1;
  17545. this.isPlaying = true;
  17546. this.reset();
  17547. THREE.AnimationHandler.play( this );
  17548. },
  17549. stop: function() {
  17550. this.isPlaying = false;
  17551. THREE.AnimationHandler.stop( this );
  17552. },
  17553. reset: function () {
  17554. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  17555. var object = this.hierarchy[ h ];
  17556. if ( object.animationCache === undefined ) {
  17557. object.animationCache = {
  17558. animations: {},
  17559. blending: {
  17560. positionWeight: 0.0,
  17561. quaternionWeight: 0.0,
  17562. scaleWeight: 0.0
  17563. }
  17564. };
  17565. }
  17566. var name = this.data.name;
  17567. var animations = object.animationCache.animations;
  17568. var animationCache = animations[ name ];
  17569. if ( animationCache === undefined ) {
  17570. animationCache = {
  17571. prevKey: { pos: 0, rot: 0, scl: 0 },
  17572. nextKey: { pos: 0, rot: 0, scl: 0 },
  17573. originalMatrix: object.matrix
  17574. };
  17575. animations[ name ] = animationCache;
  17576. }
  17577. // Get keys to match our current time
  17578. for ( var t = 0; t < 3; t ++ ) {
  17579. var type = this.keyTypes[ t ];
  17580. var prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  17581. var nextKey = this.getNextKeyWith( type, h, 1 );
  17582. while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {
  17583. prevKey = nextKey;
  17584. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17585. }
  17586. animationCache.prevKey[ type ] = prevKey;
  17587. animationCache.nextKey[ type ] = nextKey;
  17588. }
  17589. }
  17590. },
  17591. resetBlendWeights: function () {
  17592. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  17593. var object = this.hierarchy[ h ];
  17594. var animationCache = object.animationCache;
  17595. if ( animationCache !== undefined ) {
  17596. var blending = animationCache.blending;
  17597. blending.positionWeight = 0.0;
  17598. blending.quaternionWeight = 0.0;
  17599. blending.scaleWeight = 0.0;
  17600. }
  17601. }
  17602. },
  17603. update: ( function() {
  17604. var points = [];
  17605. var target = new THREE.Vector3();
  17606. var newVector = new THREE.Vector3();
  17607. var newQuat = new THREE.Quaternion();
  17608. // Catmull-Rom spline
  17609. var interpolateCatmullRom = function ( points, scale ) {
  17610. var c = [], v3 = [],
  17611. point, intPoint, weight, w2, w3,
  17612. pa, pb, pc, pd;
  17613. point = ( points.length - 1 ) * scale;
  17614. intPoint = Math.floor( point );
  17615. weight = point - intPoint;
  17616. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  17617. c[ 1 ] = intPoint;
  17618. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  17619. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  17620. pa = points[ c[ 0 ] ];
  17621. pb = points[ c[ 1 ] ];
  17622. pc = points[ c[ 2 ] ];
  17623. pd = points[ c[ 3 ] ];
  17624. w2 = weight * weight;
  17625. w3 = weight * w2;
  17626. v3[ 0 ] = interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  17627. v3[ 1 ] = interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  17628. v3[ 2 ] = interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  17629. return v3;
  17630. };
  17631. var interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  17632. var v0 = ( p2 - p0 ) * 0.5,
  17633. v1 = ( p3 - p1 ) * 0.5;
  17634. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  17635. };
  17636. return function ( delta ) {
  17637. if ( this.isPlaying === false ) return;
  17638. this.currentTime += delta * this.timeScale;
  17639. if ( this.weight === 0 )
  17640. return;
  17641. //
  17642. var duration = this.data.length;
  17643. if ( this.currentTime > duration || this.currentTime < 0 ) {
  17644. if ( this.loop ) {
  17645. this.currentTime %= duration;
  17646. if ( this.currentTime < 0 )
  17647. this.currentTime += duration;
  17648. this.reset();
  17649. } else {
  17650. this.stop();
  17651. }
  17652. }
  17653. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  17654. var object = this.hierarchy[ h ];
  17655. var animationCache = object.animationCache.animations[this.data.name];
  17656. var blending = object.animationCache.blending;
  17657. // loop through pos/rot/scl
  17658. for ( var t = 0; t < 3; t ++ ) {
  17659. // get keys
  17660. var type = this.keyTypes[ t ];
  17661. var prevKey = animationCache.prevKey[ type ];
  17662. var nextKey = animationCache.nextKey[ type ];
  17663. if ( ( this.timeScale > 0 && nextKey.time <= this.currentTime ) ||
  17664. ( this.timeScale < 0 && prevKey.time >= this.currentTime ) ) {
  17665. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  17666. nextKey = this.getNextKeyWith( type, h, 1 );
  17667. while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {
  17668. prevKey = nextKey;
  17669. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17670. }
  17671. animationCache.prevKey[ type ] = prevKey;
  17672. animationCache.nextKey[ type ] = nextKey;
  17673. }
  17674. var scale = ( this.currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  17675. var prevXYZ = prevKey[ type ];
  17676. var nextXYZ = nextKey[ type ];
  17677. if ( scale < 0 ) scale = 0;
  17678. if ( scale > 1 ) scale = 1;
  17679. // interpolate
  17680. if ( type === "pos" ) {
  17681. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  17682. newVector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  17683. newVector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  17684. newVector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  17685. // blend
  17686. var proportionalWeight = this.weight / ( this.weight + blending.positionWeight );
  17687. object.position.lerp( newVector, proportionalWeight );
  17688. blending.positionWeight += this.weight;
  17689. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17690. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17691. points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  17692. points[ 1 ] = prevXYZ;
  17693. points[ 2 ] = nextXYZ;
  17694. points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  17695. scale = scale * 0.33 + 0.33;
  17696. var currentPoint = interpolateCatmullRom( points, scale );
  17697. var proportionalWeight = this.weight / ( this.weight + blending.positionWeight );
  17698. blending.positionWeight += this.weight;
  17699. // blend
  17700. var vector = object.position;
  17701. vector.x = vector.x + ( currentPoint[ 0 ] - vector.x ) * proportionalWeight;
  17702. vector.y = vector.y + ( currentPoint[ 1 ] - vector.y ) * proportionalWeight;
  17703. vector.z = vector.z + ( currentPoint[ 2 ] - vector.z ) * proportionalWeight;
  17704. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17705. var forwardPoint = interpolateCatmullRom( points, scale * 1.01 );
  17706. target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  17707. target.sub( vector );
  17708. target.y = 0;
  17709. target.normalize();
  17710. var angle = Math.atan2( target.x, target.z );
  17711. object.rotation.set( 0, angle, 0 );
  17712. }
  17713. }
  17714. } else if ( type === "rot" ) {
  17715. THREE.Quaternion.slerp( prevXYZ, nextXYZ, newQuat, scale );
  17716. // Avoid paying the cost of an additional slerp if we don't have to
  17717. if ( blending.quaternionWeight === 0 ) {
  17718. object.quaternion.copy(newQuat);
  17719. blending.quaternionWeight = this.weight;
  17720. } else {
  17721. var proportionalWeight = this.weight / ( this.weight + blending.quaternionWeight );
  17722. THREE.Quaternion.slerp( object.quaternion, newQuat, object.quaternion, proportionalWeight );
  17723. blending.quaternionWeight += this.weight;
  17724. }
  17725. } else if ( type === "scl" ) {
  17726. newVector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  17727. newVector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  17728. newVector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  17729. var proportionalWeight = this.weight / ( this.weight + blending.scaleWeight );
  17730. object.scale.lerp( newVector, proportionalWeight );
  17731. blending.scaleWeight += this.weight;
  17732. }
  17733. }
  17734. }
  17735. return true;
  17736. };
  17737. } )(),
  17738. getNextKeyWith: function ( type, h, key ) {
  17739. var keys = this.data.hierarchy[ h ].keys;
  17740. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17741. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17742. key = key < keys.length - 1 ? key : keys.length - 1;
  17743. } else {
  17744. key = key % keys.length;
  17745. }
  17746. for ( ; key < keys.length; key ++ ) {
  17747. if ( keys[ key ][ type ] !== undefined ) {
  17748. return keys[ key ];
  17749. }
  17750. }
  17751. return this.data.hierarchy[ h ].keys[ 0 ];
  17752. },
  17753. getPrevKeyWith: function ( type, h, key ) {
  17754. var keys = this.data.hierarchy[ h ].keys;
  17755. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17756. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17757. key = key > 0 ? key : 0;
  17758. } else {
  17759. key = key >= 0 ? key : key + keys.length;
  17760. }
  17761. for ( ; key >= 0; key -- ) {
  17762. if ( keys[ key ][ type ] !== undefined ) {
  17763. return keys[ key ];
  17764. }
  17765. }
  17766. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  17767. }
  17768. };
  17769. // File:src/extras/animation/KeyFrameAnimation.js
  17770. /**
  17771. * @author mikael emtinger / http://gomo.se/
  17772. * @author mrdoob / http://mrdoob.com/
  17773. * @author alteredq / http://alteredqualia.com/
  17774. * @author khang duong
  17775. * @author erik kitson
  17776. */
  17777. THREE.KeyFrameAnimation = function ( data ) {
  17778. this.root = data.node;
  17779. this.data = THREE.AnimationHandler.init( data );
  17780. this.hierarchy = THREE.AnimationHandler.parse( this.root );
  17781. this.currentTime = 0;
  17782. this.timeScale = 0.001;
  17783. this.isPlaying = false;
  17784. this.isPaused = true;
  17785. this.loop = true;
  17786. // initialize to first keyframes
  17787. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  17788. var keys = this.data.hierarchy[h].keys,
  17789. sids = this.data.hierarchy[h].sids,
  17790. obj = this.hierarchy[h];
  17791. if ( keys.length && sids ) {
  17792. for ( var s = 0; s < sids.length; s ++ ) {
  17793. var sid = sids[ s ],
  17794. next = this.getNextKeyWith( sid, h, 0 );
  17795. if ( next ) {
  17796. next.apply( sid );
  17797. }
  17798. }
  17799. obj.matrixAutoUpdate = false;
  17800. this.data.hierarchy[h].node.updateMatrix();
  17801. obj.matrixWorldNeedsUpdate = true;
  17802. }
  17803. }
  17804. };
  17805. THREE.KeyFrameAnimation.prototype = {
  17806. constructor: THREE.KeyFrameAnimation,
  17807. play: function ( startTime ) {
  17808. this.currentTime = startTime !== undefined ? startTime : 0;
  17809. if ( this.isPlaying === false ) {
  17810. this.isPlaying = true;
  17811. // reset key cache
  17812. var h, hl = this.hierarchy.length,
  17813. object,
  17814. node;
  17815. for ( h = 0; h < hl; h ++ ) {
  17816. object = this.hierarchy[ h ];
  17817. node = this.data.hierarchy[ h ];
  17818. if ( node.animationCache === undefined ) {
  17819. node.animationCache = {};
  17820. node.animationCache.prevKey = null;
  17821. node.animationCache.nextKey = null;
  17822. node.animationCache.originalMatrix = object.matrix;
  17823. }
  17824. var keys = this.data.hierarchy[h].keys;
  17825. if (keys.length) {
  17826. node.animationCache.prevKey = keys[ 0 ];
  17827. node.animationCache.nextKey = keys[ 1 ];
  17828. this.startTime = Math.min( keys[0].time, this.startTime );
  17829. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  17830. }
  17831. }
  17832. this.update( 0 );
  17833. }
  17834. this.isPaused = false;
  17835. THREE.AnimationHandler.play( this );
  17836. },
  17837. stop: function () {
  17838. this.isPlaying = false;
  17839. this.isPaused = false;
  17840. THREE.AnimationHandler.stop( this );
  17841. // reset JIT matrix and remove cache
  17842. for ( var h = 0; h < this.data.hierarchy.length; h ++ ) {
  17843. var obj = this.hierarchy[ h ];
  17844. var node = this.data.hierarchy[ h ];
  17845. if ( node.animationCache !== undefined ) {
  17846. var original = node.animationCache.originalMatrix;
  17847. original.copy( obj.matrix );
  17848. obj.matrix = original;
  17849. delete node.animationCache;
  17850. }
  17851. }
  17852. },
  17853. update: function ( delta ) {
  17854. if ( this.isPlaying === false ) return;
  17855. this.currentTime += delta * this.timeScale;
  17856. //
  17857. var duration = this.data.length;
  17858. if ( this.loop === true && this.currentTime > duration ) {
  17859. this.currentTime %= duration;
  17860. }
  17861. this.currentTime = Math.min( this.currentTime, duration );
  17862. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  17863. var object = this.hierarchy[ h ];
  17864. var node = this.data.hierarchy[ h ];
  17865. var keys = node.keys,
  17866. animationCache = node.animationCache;
  17867. if ( keys.length ) {
  17868. var prevKey = animationCache.prevKey;
  17869. var nextKey = animationCache.nextKey;
  17870. if ( nextKey.time <= this.currentTime ) {
  17871. while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {
  17872. prevKey = nextKey;
  17873. nextKey = keys[ prevKey.index + 1 ];
  17874. }
  17875. animationCache.prevKey = prevKey;
  17876. animationCache.nextKey = nextKey;
  17877. }
  17878. if ( nextKey.time >= this.currentTime ) {
  17879. prevKey.interpolate( nextKey, this.currentTime );
  17880. } else {
  17881. prevKey.interpolate( nextKey, nextKey.time );
  17882. }
  17883. this.data.hierarchy[ h ].node.updateMatrix();
  17884. object.matrixWorldNeedsUpdate = true;
  17885. }
  17886. }
  17887. },
  17888. getNextKeyWith: function ( sid, h, key ) {
  17889. var keys = this.data.hierarchy[ h ].keys;
  17890. key = key % keys.length;
  17891. for ( ; key < keys.length; key ++ ) {
  17892. if ( keys[ key ].hasTarget( sid ) ) {
  17893. return keys[ key ];
  17894. }
  17895. }
  17896. return keys[ 0 ];
  17897. },
  17898. getPrevKeyWith: function ( sid, h, key ) {
  17899. var keys = this.data.hierarchy[ h ].keys;
  17900. key = key >= 0 ? key : key + keys.length;
  17901. for ( ; key >= 0; key -- ) {
  17902. if ( keys[ key ].hasTarget( sid ) ) {
  17903. return keys[ key ];
  17904. }
  17905. }
  17906. return keys[ keys.length - 1 ];
  17907. }
  17908. };
  17909. // File:src/extras/animation/MorphAnimation.js
  17910. /**
  17911. * @author mrdoob / http://mrdoob.com
  17912. * @author willy-vvu / http://willy-vvu.github.io
  17913. */
  17914. THREE.MorphAnimation = function ( mesh ) {
  17915. this.mesh = mesh;
  17916. this.frames = mesh.morphTargetInfluences.length;
  17917. this.currentTime = 0;
  17918. this.duration = 1000;
  17919. this.loop = true;
  17920. this.lastFrame = 0;
  17921. this.currentFrame = 0;
  17922. this.isPlaying = false;
  17923. };
  17924. THREE.MorphAnimation.prototype = {
  17925. constructor: THREE.MorphAnimation,
  17926. play: function () {
  17927. this.isPlaying = true;
  17928. },
  17929. pause: function () {
  17930. this.isPlaying = false;
  17931. },
  17932. update: function ( delta ) {
  17933. if ( this.isPlaying === false ) return;
  17934. this.currentTime += delta;
  17935. if ( this.loop === true && this.currentTime > this.duration ) {
  17936. this.currentTime %= this.duration;
  17937. }
  17938. this.currentTime = Math.min( this.currentTime, this.duration );
  17939. var interpolation = this.duration / this.frames;
  17940. var frame = Math.floor( this.currentTime / interpolation );
  17941. var influences = this.mesh.morphTargetInfluences;
  17942. if ( frame !== this.currentFrame ) {
  17943. influences[ this.lastFrame ] = 0;
  17944. influences[ this.currentFrame ] = 1;
  17945. influences[ frame ] = 0;
  17946. this.lastFrame = this.currentFrame;
  17947. this.currentFrame = frame;
  17948. }
  17949. influences[ frame ] = ( this.currentTime % interpolation ) / interpolation;
  17950. influences[ this.lastFrame ] = 1 - influences[ frame ];
  17951. }
  17952. };
  17953. // File:src/extras/geometries/BoxGeometry.js
  17954. /**
  17955. * @author mrdoob / http://mrdoob.com/
  17956. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  17957. */
  17958. THREE.BoxGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  17959. THREE.Geometry.call( this );
  17960. this.type = 'BoxGeometry';
  17961. this.parameters = {
  17962. width: width,
  17963. height: height,
  17964. depth: depth,
  17965. widthSegments: widthSegments,
  17966. heightSegments: heightSegments,
  17967. depthSegments: depthSegments
  17968. };
  17969. this.widthSegments = widthSegments || 1;
  17970. this.heightSegments = heightSegments || 1;
  17971. this.depthSegments = depthSegments || 1;
  17972. var scope = this;
  17973. var width_half = width / 2;
  17974. var height_half = height / 2;
  17975. var depth_half = depth / 2;
  17976. buildPlane( 'z', 'y', - 1, - 1, depth, height, width_half ); // px
  17977. buildPlane( 'z', 'y', 1, - 1, depth, height, - width_half ); // nx
  17978. buildPlane( 'x', 'z', 1, 1, width, depth, height_half ); // py
  17979. buildPlane( 'x', 'z', 1, - 1, width, depth, - height_half ); // ny
  17980. buildPlane( 'x', 'y', 1, - 1, width, height, depth_half ); // pz
  17981. buildPlane( 'x', 'y', - 1, - 1, width, height, - depth_half ); // nz
  17982. function buildPlane( u, v, udir, vdir, width, height, depth ) {
  17983. var w, ix, iy,
  17984. gridX = scope.widthSegments,
  17985. gridY = scope.heightSegments,
  17986. width_half = width / 2,
  17987. height_half = height / 2,
  17988. offset = scope.vertices.length;
  17989. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  17990. w = 'z';
  17991. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  17992. w = 'y';
  17993. gridY = scope.depthSegments;
  17994. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  17995. w = 'x';
  17996. gridX = scope.depthSegments;
  17997. }
  17998. var gridX1 = gridX + 1,
  17999. gridY1 = gridY + 1,
  18000. segment_width = width / gridX,
  18001. segment_height = height / gridY,
  18002. normal = new THREE.Vector3();
  18003. normal[ w ] = depth > 0 ? 1 : - 1;
  18004. for ( iy = 0; iy < gridY1; iy ++ ) {
  18005. for ( ix = 0; ix < gridX1; ix ++ ) {
  18006. var vector = new THREE.Vector3();
  18007. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  18008. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  18009. vector[ w ] = depth;
  18010. scope.vertices.push( vector );
  18011. }
  18012. }
  18013. for ( iy = 0; iy < gridY; iy ++ ) {
  18014. for ( ix = 0; ix < gridX; ix ++ ) {
  18015. var a = ix + gridX1 * iy;
  18016. var b = ix + gridX1 * ( iy + 1 );
  18017. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  18018. var d = ( ix + 1 ) + gridX1 * iy;
  18019. var uva = new THREE.Vector2( ix / gridX, 1 - iy / gridY );
  18020. var uvb = new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY );
  18021. var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iy + 1 ) / gridY );
  18022. var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY );
  18023. var face = new THREE.Face3( a + offset, b + offset, d + offset );
  18024. face.normal.copy( normal );
  18025. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  18026. scope.faces.push( face );
  18027. scope.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  18028. face = new THREE.Face3( b + offset, c + offset, d + offset );
  18029. face.normal.copy( normal );
  18030. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  18031. scope.faces.push( face );
  18032. scope.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  18033. }
  18034. }
  18035. }
  18036. this.mergeVertices();
  18037. };
  18038. THREE.BoxGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18039. THREE.BoxGeometry.prototype.constructor = THREE.BoxGeometry;
  18040. THREE.CubeGeometry = THREE.BoxGeometry; // backwards compatibility
  18041. // File:src/extras/geometries/CircleGeometry.js
  18042. /**
  18043. * @author hughes
  18044. */
  18045. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  18046. THREE.Geometry.call( this );
  18047. this.type = 'CircleGeometry';
  18048. this.parameters = {
  18049. radius: radius,
  18050. segments: segments,
  18051. thetaStart: thetaStart,
  18052. thetaLength: thetaLength
  18053. };
  18054. radius = radius || 50;
  18055. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  18056. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18057. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  18058. var i, uvs = [],
  18059. center = new THREE.Vector3(), centerUV = new THREE.Vector2( 0.5, 0.5 );
  18060. this.vertices.push(center);
  18061. uvs.push( centerUV );
  18062. for ( i = 0; i <= segments; i ++ ) {
  18063. var vertex = new THREE.Vector3();
  18064. var segment = thetaStart + i / segments * thetaLength;
  18065. vertex.x = radius * Math.cos( segment );
  18066. vertex.y = radius * Math.sin( segment );
  18067. this.vertices.push( vertex );
  18068. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, ( vertex.y / radius + 1 ) / 2 ) );
  18069. }
  18070. var n = new THREE.Vector3( 0, 0, 1 );
  18071. for ( i = 1; i <= segments; i ++ ) {
  18072. this.faces.push( new THREE.Face3( i, i + 1, 0, [ n.clone(), n.clone(), n.clone() ] ) );
  18073. this.faceVertexUvs[ 0 ].push( [ uvs[ i ].clone(), uvs[ i + 1 ].clone(), centerUV.clone() ] );
  18074. }
  18075. this.computeFaceNormals();
  18076. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  18077. };
  18078. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18079. THREE.CircleGeometry.prototype.constructor = THREE.CircleGeometry;
  18080. // File:src/extras/geometries/CircleBufferGeometry.js
  18081. /**
  18082. * @author benaadams / https://twitter.com/ben_a_adams
  18083. */
  18084. THREE.CircleBufferGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  18085. THREE.BufferGeometry.call( this );
  18086. this.type = 'CircleBufferGeometry';
  18087. this.parameters = {
  18088. radius: radius,
  18089. segments: segments,
  18090. thetaStart: thetaStart,
  18091. thetaLength: thetaLength
  18092. };
  18093. radius = radius || 50;
  18094. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  18095. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18096. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  18097. var vertices = segments + 2;
  18098. var positions = new Float32Array( vertices * 3 );
  18099. var normals = new Float32Array( vertices * 3 );
  18100. var uvs = new Float32Array( vertices * 2 );
  18101. // center data is already zero, but need to set a few extras
  18102. normals[3] = 1.0;
  18103. uvs[0] = 0.5;
  18104. uvs[1] = 0.5;
  18105. for ( var s = 0, i = 3, ii = 2 ; s <= segments; s++, i += 3, ii += 2 ) {
  18106. var segment = thetaStart + s / segments * thetaLength;
  18107. positions[i] = radius * Math.cos( segment );
  18108. positions[i + 1] = radius * Math.sin( segment );
  18109. normals[i + 2] = 1; // normal z
  18110. uvs[ii] = ( positions[i] / radius + 1 ) / 2;
  18111. uvs[ii + 1] = ( positions[i + 1] / radius + 1 ) / 2;
  18112. }
  18113. var indices = [];
  18114. for ( var i = 1; i <= segments; i ++ ) {
  18115. indices.push( i );
  18116. indices.push( i + 1 );
  18117. indices.push( 0 );
  18118. }
  18119. this.addAttribute( 'index', new THREE.BufferAttribute( new Uint16Array( indices ), 1 ) );
  18120. this.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
  18121. this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
  18122. this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) );
  18123. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  18124. };
  18125. THREE.CircleBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  18126. THREE.CircleBufferGeometry.prototype.constructor = THREE.CircleBufferGeometry;
  18127. // File:src/extras/geometries/CylinderGeometry.js
  18128. /**
  18129. * @author mrdoob / http://mrdoob.com/
  18130. */
  18131. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  18132. THREE.Geometry.call( this );
  18133. this.type = 'CylinderGeometry';
  18134. this.parameters = {
  18135. radiusTop: radiusTop,
  18136. radiusBottom: radiusBottom,
  18137. height: height,
  18138. radialSegments: radialSegments,
  18139. heightSegments: heightSegments,
  18140. openEnded: openEnded,
  18141. thetaStart: thetaStart,
  18142. thetaLength: thetaLength
  18143. };
  18144. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  18145. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  18146. height = height !== undefined ? height : 100;
  18147. radialSegments = radialSegments || 8;
  18148. heightSegments = heightSegments || 1;
  18149. openEnded = openEnded !== undefined ? openEnded : false;
  18150. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18151. thetaLength = thetaLength !== undefined ? thetaLength : 2 * Math.PI;
  18152. var heightHalf = height / 2;
  18153. var x, y, vertices = [], uvs = [];
  18154. for ( y = 0; y <= heightSegments; y ++ ) {
  18155. var verticesRow = [];
  18156. var uvsRow = [];
  18157. var v = y / heightSegments;
  18158. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  18159. for ( x = 0; x <= radialSegments; x ++ ) {
  18160. var u = x / radialSegments;
  18161. var vertex = new THREE.Vector3();
  18162. vertex.x = radius * Math.sin( u * thetaLength + thetaStart );
  18163. vertex.y = - v * height + heightHalf;
  18164. vertex.z = radius * Math.cos( u * thetaLength + thetaStart );
  18165. this.vertices.push( vertex );
  18166. verticesRow.push( this.vertices.length - 1 );
  18167. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  18168. }
  18169. vertices.push( verticesRow );
  18170. uvs.push( uvsRow );
  18171. }
  18172. var tanTheta = ( radiusBottom - radiusTop ) / height;
  18173. var na, nb;
  18174. for ( x = 0; x < radialSegments; x ++ ) {
  18175. if ( radiusTop !== 0 ) {
  18176. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  18177. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  18178. } else {
  18179. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  18180. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  18181. }
  18182. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  18183. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  18184. for ( y = 0; y < heightSegments; y ++ ) {
  18185. var v1 = vertices[ y ][ x ];
  18186. var v2 = vertices[ y + 1 ][ x ];
  18187. var v3 = vertices[ y + 1 ][ x + 1 ];
  18188. var v4 = vertices[ y ][ x + 1 ];
  18189. var n1 = na.clone();
  18190. var n2 = na.clone();
  18191. var n3 = nb.clone();
  18192. var n4 = nb.clone();
  18193. var uv1 = uvs[ y ][ x ].clone();
  18194. var uv2 = uvs[ y + 1 ][ x ].clone();
  18195. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  18196. var uv4 = uvs[ y ][ x + 1 ].clone();
  18197. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  18198. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  18199. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  18200. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  18201. }
  18202. }
  18203. // top cap
  18204. if ( openEnded === false && radiusTop > 0 ) {
  18205. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  18206. for ( x = 0; x < radialSegments; x ++ ) {
  18207. var v1 = vertices[ 0 ][ x ];
  18208. var v2 = vertices[ 0 ][ x + 1 ];
  18209. var v3 = this.vertices.length - 1;
  18210. var n1 = new THREE.Vector3( 0, 1, 0 );
  18211. var n2 = new THREE.Vector3( 0, 1, 0 );
  18212. var n3 = new THREE.Vector3( 0, 1, 0 );
  18213. var uv1 = uvs[ 0 ][ x ].clone();
  18214. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  18215. var uv3 = new THREE.Vector2( uv2.x, 0 );
  18216. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18217. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18218. }
  18219. }
  18220. // bottom cap
  18221. if ( openEnded === false && radiusBottom > 0 ) {
  18222. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  18223. for ( x = 0; x < radialSegments; x ++ ) {
  18224. var v1 = vertices[ heightSegments ][ x + 1 ];
  18225. var v2 = vertices[ heightSegments ][ x ];
  18226. var v3 = this.vertices.length - 1;
  18227. var n1 = new THREE.Vector3( 0, - 1, 0 );
  18228. var n2 = new THREE.Vector3( 0, - 1, 0 );
  18229. var n3 = new THREE.Vector3( 0, - 1, 0 );
  18230. var uv1 = uvs[ heightSegments ][ x + 1 ].clone();
  18231. var uv2 = uvs[ heightSegments ][ x ].clone();
  18232. var uv3 = new THREE.Vector2( uv2.x, 1 );
  18233. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18234. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18235. }
  18236. }
  18237. this.computeFaceNormals();
  18238. };
  18239. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18240. THREE.CylinderGeometry.prototype.constructor = THREE.CylinderGeometry;
  18241. // File:src/extras/geometries/EdgesGeometry.js
  18242. /**
  18243. * @author WestLangley / http://github.com/WestLangley
  18244. */
  18245. THREE.EdgesGeometry = function ( geometry, thresholdAngle ) {
  18246. THREE.BufferGeometry.call( this );
  18247. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  18248. var thresholdDot = Math.cos( THREE.Math.degToRad( thresholdAngle ) );
  18249. var edge = [ 0, 0 ], hash = {};
  18250. var sortFunction = function ( a, b ) { return a - b };
  18251. var keys = [ 'a', 'b', 'c' ];
  18252. var geometry2;
  18253. if ( geometry instanceof THREE.BufferGeometry ) {
  18254. geometry2 = new THREE.Geometry();
  18255. geometry2.fromBufferGeometry( geometry );
  18256. } else {
  18257. geometry2 = geometry.clone();
  18258. }
  18259. geometry2.mergeVertices();
  18260. geometry2.computeFaceNormals();
  18261. var vertices = geometry2.vertices;
  18262. var faces = geometry2.faces;
  18263. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  18264. var face = faces[ i ];
  18265. for ( var j = 0; j < 3; j ++ ) {
  18266. edge[ 0 ] = face[ keys[ j ] ];
  18267. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  18268. edge.sort( sortFunction );
  18269. var key = edge.toString();
  18270. if ( hash[ key ] === undefined ) {
  18271. hash[ key ] = { vert1: edge[ 0 ], vert2: edge[ 1 ], face1: i, face2: undefined };
  18272. } else {
  18273. hash[ key ].face2 = i;
  18274. }
  18275. }
  18276. }
  18277. var coords = [];
  18278. for ( var key in hash ) {
  18279. var h = hash[ key ];
  18280. if ( h.face2 === undefined || faces[ h.face1 ].normal.dot( faces[ h.face2 ].normal ) <= thresholdDot ) {
  18281. var vertex = vertices[ h.vert1 ];
  18282. coords.push( vertex.x );
  18283. coords.push( vertex.y );
  18284. coords.push( vertex.z );
  18285. vertex = vertices[ h.vert2 ];
  18286. coords.push( vertex.x );
  18287. coords.push( vertex.y );
  18288. coords.push( vertex.z );
  18289. }
  18290. }
  18291. this.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( coords ), 3 ) );
  18292. };
  18293. THREE.EdgesGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  18294. THREE.EdgesGeometry.prototype.constructor = THREE.EdgesGeometry;
  18295. // File:src/extras/geometries/ExtrudeGeometry.js
  18296. /**
  18297. * @author zz85 / http://www.lab4games.net/zz85/blog
  18298. *
  18299. * Creates extruded geometry from a path shape.
  18300. *
  18301. * parameters = {
  18302. *
  18303. * curveSegments: <int>, // number of points on the curves
  18304. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  18305. * amount: <int>, // Depth to extrude the shape
  18306. *
  18307. * bevelEnabled: <bool>, // turn on bevel
  18308. * bevelThickness: <float>, // how deep into the original shape bevel goes
  18309. * bevelSize: <float>, // how far from shape outline is bevel
  18310. * bevelSegments: <int>, // number of bevel layers
  18311. *
  18312. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  18313. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  18314. *
  18315. * uvGenerator: <Object> // object that provides UV generator functions
  18316. *
  18317. * }
  18318. **/
  18319. THREE.ExtrudeGeometry = function ( shapes, options ) {
  18320. if ( typeof( shapes ) === "undefined" ) {
  18321. shapes = [];
  18322. return;
  18323. }
  18324. THREE.Geometry.call( this );
  18325. this.type = 'ExtrudeGeometry';
  18326. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  18327. this.addShapeList( shapes, options );
  18328. this.computeFaceNormals();
  18329. // can't really use automatic vertex normals
  18330. // as then front and back sides get smoothed too
  18331. // should do separate smoothing just for sides
  18332. //this.computeVertexNormals();
  18333. //console.log( "took", ( Date.now() - startTime ) );
  18334. };
  18335. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18336. THREE.ExtrudeGeometry.prototype.constructor = THREE.ExtrudeGeometry;
  18337. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18338. var sl = shapes.length;
  18339. for ( var s = 0; s < sl; s ++ ) {
  18340. var shape = shapes[ s ];
  18341. this.addShape( shape, options );
  18342. }
  18343. };
  18344. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  18345. var amount = options.amount !== undefined ? options.amount : 100;
  18346. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  18347. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  18348. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18349. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  18350. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18351. var steps = options.steps !== undefined ? options.steps : 1;
  18352. var extrudePath = options.extrudePath;
  18353. var extrudePts, extrudeByPath = false;
  18354. // Use default WorldUVGenerator if no UV generators are specified.
  18355. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  18356. var splineTube, binormal, normal, position2;
  18357. if ( extrudePath ) {
  18358. extrudePts = extrudePath.getSpacedPoints( steps );
  18359. extrudeByPath = true;
  18360. bevelEnabled = false; // bevels not supported for path extrusion
  18361. // SETUP TNB variables
  18362. // Reuse TNB from TubeGeomtry for now.
  18363. // TODO1 - have a .isClosed in spline?
  18364. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  18365. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18366. binormal = new THREE.Vector3();
  18367. normal = new THREE.Vector3();
  18368. position2 = new THREE.Vector3();
  18369. }
  18370. // Safeguards if bevels are not enabled
  18371. if ( ! bevelEnabled ) {
  18372. bevelSegments = 0;
  18373. bevelThickness = 0;
  18374. bevelSize = 0;
  18375. }
  18376. // Variables initalization
  18377. var ahole, h, hl; // looping of holes
  18378. var scope = this;
  18379. var shapesOffset = this.vertices.length;
  18380. var shapePoints = shape.extractPoints( curveSegments );
  18381. var vertices = shapePoints.shape;
  18382. var holes = shapePoints.holes;
  18383. var reverse = ! THREE.Shape.Utils.isClockWise( vertices ) ;
  18384. if ( reverse ) {
  18385. vertices = vertices.reverse();
  18386. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18387. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18388. ahole = holes[ h ];
  18389. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  18390. holes[ h ] = ahole.reverse();
  18391. }
  18392. }
  18393. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  18394. }
  18395. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  18396. /* Vertices */
  18397. var contour = vertices; // vertices has all points but contour has only points of circumference
  18398. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18399. ahole = holes[ h ];
  18400. vertices = vertices.concat( ahole );
  18401. }
  18402. function scalePt2 ( pt, vec, size ) {
  18403. if ( ! vec ) console.error( "THREE.ExtrudeGeometry: vec does not exist" );
  18404. return vec.clone().multiplyScalar( size ).add( pt );
  18405. }
  18406. var b, bs, t, z,
  18407. vert, vlen = vertices.length,
  18408. face, flen = faces.length;
  18409. // Find directions for point movement
  18410. function getBevelVec( inPt, inPrev, inNext ) {
  18411. var EPSILON = 0.0000000001;
  18412. // computes for inPt the corresponding point inPt' on a new contour
  18413. // shiftet by 1 unit (length of normalized vector) to the left
  18414. // if we walk along contour clockwise, this new contour is outside the old one
  18415. //
  18416. // inPt' is the intersection of the two lines parallel to the two
  18417. // adjacent edges of inPt at a distance of 1 unit on the left side.
  18418. var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt
  18419. // good reading for geometry algorithms (here: line-line intersection)
  18420. // http://geomalgorithms.com/a05-_intersect-1.html
  18421. var v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y;
  18422. var v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y;
  18423. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  18424. // check for colinear edges
  18425. var colinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  18426. if ( Math.abs( colinear0 ) > EPSILON ) { // not colinear
  18427. // length of vectors for normalizing
  18428. var v_prev_len = Math.sqrt( v_prev_lensq );
  18429. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  18430. // shift adjacent points by unit vectors to the left
  18431. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  18432. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  18433. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  18434. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  18435. // scaling factor for v_prev to intersection point
  18436. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  18437. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  18438. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  18439. // vector from inPt to intersection point
  18440. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  18441. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  18442. // Don't normalize!, otherwise sharp corners become ugly
  18443. // but prevent crazy spikes
  18444. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  18445. if ( v_trans_lensq <= 2 ) {
  18446. return new THREE.Vector2( v_trans_x, v_trans_y );
  18447. } else {
  18448. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  18449. }
  18450. } else { // handle special case of colinear edges
  18451. var direction_eq = false; // assumes: opposite
  18452. if ( v_prev_x > EPSILON ) {
  18453. if ( v_next_x > EPSILON ) { direction_eq = true; }
  18454. } else {
  18455. if ( v_prev_x < - EPSILON ) {
  18456. if ( v_next_x < - EPSILON ) { direction_eq = true; }
  18457. } else {
  18458. if ( Math.sign(v_prev_y) === Math.sign(v_next_y) ) { direction_eq = true; }
  18459. }
  18460. }
  18461. if ( direction_eq ) {
  18462. // console.log("Warning: lines are a straight sequence");
  18463. v_trans_x = - v_prev_y;
  18464. v_trans_y = v_prev_x;
  18465. shrink_by = Math.sqrt( v_prev_lensq );
  18466. } else {
  18467. // console.log("Warning: lines are a straight spike");
  18468. v_trans_x = v_prev_x;
  18469. v_trans_y = v_prev_y;
  18470. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  18471. }
  18472. }
  18473. return new THREE.Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  18474. }
  18475. var contourMovements = [];
  18476. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18477. if ( j === il ) j = 0;
  18478. if ( k === il ) k = 0;
  18479. // (j)---(i)---(k)
  18480. // console.log('i,j,k', i, j , k)
  18481. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  18482. }
  18483. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  18484. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18485. ahole = holes[ h ];
  18486. oneHoleMovements = [];
  18487. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18488. if ( j === il ) j = 0;
  18489. if ( k === il ) k = 0;
  18490. // (j)---(i)---(k)
  18491. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  18492. }
  18493. holesMovements.push( oneHoleMovements );
  18494. verticesMovements = verticesMovements.concat( oneHoleMovements );
  18495. }
  18496. // Loop bevelSegments, 1 for the front, 1 for the back
  18497. for ( b = 0; b < bevelSegments; b ++ ) {
  18498. //for ( b = bevelSegments; b > 0; b -- ) {
  18499. t = b / bevelSegments;
  18500. z = bevelThickness * ( 1 - t );
  18501. //z = bevelThickness * t;
  18502. bs = bevelSize * ( Math.sin ( t * Math.PI / 2 ) ) ; // curved
  18503. //bs = bevelSize * t ; // linear
  18504. // contract shape
  18505. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18506. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18507. v( vert.x, vert.y, - z );
  18508. }
  18509. // expand holes
  18510. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18511. ahole = holes[ h ];
  18512. oneHoleMovements = holesMovements[ h ];
  18513. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  18514. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18515. v( vert.x, vert.y, - z );
  18516. }
  18517. }
  18518. }
  18519. bs = bevelSize;
  18520. // Back facing vertices
  18521. for ( i = 0; i < vlen; i ++ ) {
  18522. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18523. if ( ! extrudeByPath ) {
  18524. v( vert.x, vert.y, 0 );
  18525. } else {
  18526. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  18527. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  18528. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  18529. position2.copy( extrudePts[0] ).add(normal).add(binormal);
  18530. v( position2.x, position2.y, position2.z );
  18531. }
  18532. }
  18533. // Add stepped vertices...
  18534. // Including front facing vertices
  18535. var s;
  18536. for ( s = 1; s <= steps; s ++ ) {
  18537. for ( i = 0; i < vlen; i ++ ) {
  18538. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18539. if ( ! extrudeByPath ) {
  18540. v( vert.x, vert.y, amount / steps * s );
  18541. } else {
  18542. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  18543. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  18544. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  18545. position2.copy( extrudePts[s] ).add( normal ).add( binormal );
  18546. v( position2.x, position2.y, position2.z );
  18547. }
  18548. }
  18549. }
  18550. // Add bevel segments planes
  18551. //for ( b = 1; b <= bevelSegments; b ++ ) {
  18552. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  18553. t = b / bevelSegments;
  18554. z = bevelThickness * ( 1 - t );
  18555. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  18556. bs = bevelSize * Math.sin ( t * Math.PI / 2 ) ;
  18557. // contract shape
  18558. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18559. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18560. v( vert.x, vert.y, amount + z );
  18561. }
  18562. // expand holes
  18563. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18564. ahole = holes[ h ];
  18565. oneHoleMovements = holesMovements[ h ];
  18566. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  18567. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18568. if ( ! extrudeByPath ) {
  18569. v( vert.x, vert.y, amount + z );
  18570. } else {
  18571. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  18572. }
  18573. }
  18574. }
  18575. }
  18576. /* Faces */
  18577. // Top and bottom faces
  18578. buildLidFaces();
  18579. // Sides faces
  18580. buildSideFaces();
  18581. ///// Internal functions
  18582. function buildLidFaces() {
  18583. if ( bevelEnabled ) {
  18584. var layer = 0 ; // steps + 1
  18585. var offset = vlen * layer;
  18586. // Bottom faces
  18587. for ( i = 0; i < flen; i ++ ) {
  18588. face = faces[ i ];
  18589. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  18590. }
  18591. layer = steps + bevelSegments * 2;
  18592. offset = vlen * layer;
  18593. // Top faces
  18594. for ( i = 0; i < flen; i ++ ) {
  18595. face = faces[ i ];
  18596. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  18597. }
  18598. } else {
  18599. // Bottom faces
  18600. for ( i = 0; i < flen; i ++ ) {
  18601. face = faces[ i ];
  18602. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  18603. }
  18604. // Top faces
  18605. for ( i = 0; i < flen; i ++ ) {
  18606. face = faces[ i ];
  18607. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  18608. }
  18609. }
  18610. }
  18611. // Create faces for the z-sides of the shape
  18612. function buildSideFaces() {
  18613. var layeroffset = 0;
  18614. sidewalls( contour, layeroffset );
  18615. layeroffset += contour.length;
  18616. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18617. ahole = holes[ h ];
  18618. sidewalls( ahole, layeroffset );
  18619. //, true
  18620. layeroffset += ahole.length;
  18621. }
  18622. }
  18623. function sidewalls( contour, layeroffset ) {
  18624. var j, k;
  18625. i = contour.length;
  18626. while ( -- i >= 0 ) {
  18627. j = i;
  18628. k = i - 1;
  18629. if ( k < 0 ) k = contour.length - 1;
  18630. //console.log('b', i,j, i-1, k,vertices.length);
  18631. var s = 0, sl = steps + bevelSegments * 2;
  18632. for ( s = 0; s < sl; s ++ ) {
  18633. var slen1 = vlen * s;
  18634. var slen2 = vlen * ( s + 1 );
  18635. var a = layeroffset + j + slen1,
  18636. b = layeroffset + k + slen1,
  18637. c = layeroffset + k + slen2,
  18638. d = layeroffset + j + slen2;
  18639. f4( a, b, c, d, contour, s, sl, j, k );
  18640. }
  18641. }
  18642. }
  18643. function v( x, y, z ) {
  18644. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  18645. }
  18646. function f3( a, b, c ) {
  18647. a += shapesOffset;
  18648. b += shapesOffset;
  18649. c += shapesOffset;
  18650. scope.faces.push( new THREE.Face3( a, b, c ) );
  18651. var uvs = uvgen.generateTopUV( scope, a, b, c );
  18652. scope.faceVertexUvs[ 0 ].push( uvs );
  18653. }
  18654. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  18655. a += shapesOffset;
  18656. b += shapesOffset;
  18657. c += shapesOffset;
  18658. d += shapesOffset;
  18659. scope.faces.push( new THREE.Face3( a, b, d ) );
  18660. scope.faces.push( new THREE.Face3( b, c, d ) );
  18661. var uvs = uvgen.generateSideWallUV( scope, a, b, c, d );
  18662. scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] );
  18663. scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] );
  18664. }
  18665. };
  18666. THREE.ExtrudeGeometry.WorldUVGenerator = {
  18667. generateTopUV: function ( geometry, indexA, indexB, indexC ) {
  18668. var vertices = geometry.vertices;
  18669. var a = vertices[ indexA ];
  18670. var b = vertices[ indexB ];
  18671. var c = vertices[ indexC ];
  18672. return [
  18673. new THREE.Vector2( a.x, a.y ),
  18674. new THREE.Vector2( b.x, b.y ),
  18675. new THREE.Vector2( c.x, c.y )
  18676. ];
  18677. },
  18678. generateSideWallUV: function ( geometry, indexA, indexB, indexC, indexD ) {
  18679. var vertices = geometry.vertices;
  18680. var a = vertices[ indexA ];
  18681. var b = vertices[ indexB ];
  18682. var c = vertices[ indexC ];
  18683. var d = vertices[ indexD ];
  18684. if ( Math.abs( a.y - b.y ) < 0.01 ) {
  18685. return [
  18686. new THREE.Vector2( a.x, 1 - a.z ),
  18687. new THREE.Vector2( b.x, 1 - b.z ),
  18688. new THREE.Vector2( c.x, 1 - c.z ),
  18689. new THREE.Vector2( d.x, 1 - d.z )
  18690. ];
  18691. } else {
  18692. return [
  18693. new THREE.Vector2( a.y, 1 - a.z ),
  18694. new THREE.Vector2( b.y, 1 - b.z ),
  18695. new THREE.Vector2( c.y, 1 - c.z ),
  18696. new THREE.Vector2( d.y, 1 - d.z )
  18697. ];
  18698. }
  18699. }
  18700. };
  18701. // File:src/extras/geometries/ShapeGeometry.js
  18702. /**
  18703. * @author jonobr1 / http://jonobr1.com
  18704. *
  18705. * Creates a one-sided polygonal geometry from a path shape. Similar to
  18706. * ExtrudeGeometry.
  18707. *
  18708. * parameters = {
  18709. *
  18710. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  18711. *
  18712. * material: <int> // material index for front and back faces
  18713. * uvGenerator: <Object> // object that provides UV generator functions
  18714. *
  18715. * }
  18716. **/
  18717. THREE.ShapeGeometry = function ( shapes, options ) {
  18718. THREE.Geometry.call( this );
  18719. this.type = 'ShapeGeometry';
  18720. if ( Array.isArray( shapes ) === false ) shapes = [ shapes ];
  18721. this.addShapeList( shapes, options );
  18722. this.computeFaceNormals();
  18723. };
  18724. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18725. THREE.ShapeGeometry.prototype.constructor = THREE.ShapeGeometry;
  18726. /**
  18727. * Add an array of shapes to THREE.ShapeGeometry.
  18728. */
  18729. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18730. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  18731. this.addShape( shapes[ i ], options );
  18732. }
  18733. return this;
  18734. };
  18735. /**
  18736. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  18737. */
  18738. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  18739. if ( options === undefined ) options = {};
  18740. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18741. var material = options.material;
  18742. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  18743. //
  18744. var i, l, hole;
  18745. var shapesOffset = this.vertices.length;
  18746. var shapePoints = shape.extractPoints( curveSegments );
  18747. var vertices = shapePoints.shape;
  18748. var holes = shapePoints.holes;
  18749. var reverse = ! THREE.Shape.Utils.isClockWise( vertices );
  18750. if ( reverse ) {
  18751. vertices = vertices.reverse();
  18752. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  18753. for ( i = 0, l = holes.length; i < l; i ++ ) {
  18754. hole = holes[ i ];
  18755. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  18756. holes[ i ] = hole.reverse();
  18757. }
  18758. }
  18759. reverse = false;
  18760. }
  18761. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  18762. // Vertices
  18763. var contour = vertices;
  18764. for ( i = 0, l = holes.length; i < l; i ++ ) {
  18765. hole = holes[ i ];
  18766. vertices = vertices.concat( hole );
  18767. }
  18768. //
  18769. var vert, vlen = vertices.length;
  18770. var face, flen = faces.length;
  18771. for ( i = 0; i < vlen; i ++ ) {
  18772. vert = vertices[ i ];
  18773. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  18774. }
  18775. for ( i = 0; i < flen; i ++ ) {
  18776. face = faces[ i ];
  18777. var a = face[ 0 ] + shapesOffset;
  18778. var b = face[ 1 ] + shapesOffset;
  18779. var c = face[ 2 ] + shapesOffset;
  18780. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  18781. this.faceVertexUvs[ 0 ].push( uvgen.generateTopUV( this, a, b, c ) );
  18782. }
  18783. };
  18784. // File:src/extras/geometries/LatheGeometry.js
  18785. /**
  18786. * @author astrodud / http://astrodud.isgreat.org/
  18787. * @author zz85 / https://github.com/zz85
  18788. * @author bhouston / http://exocortex.com
  18789. */
  18790. // points - to create a closed torus, one must use a set of points
  18791. // like so: [ a, b, c, d, a ], see first is the same as last.
  18792. // segments - the number of circumference segments to create
  18793. // phiStart - the starting radian
  18794. // phiLength - the radian (0 to 2*PI) range of the lathed section
  18795. // 2*pi is a closed lathe, less than 2PI is a portion.
  18796. THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
  18797. THREE.Geometry.call( this );
  18798. this.type = 'LatheGeometry';
  18799. this.parameters = {
  18800. points: points,
  18801. segments: segments,
  18802. phiStart: phiStart,
  18803. phiLength: phiLength
  18804. };
  18805. segments = segments || 12;
  18806. phiStart = phiStart || 0;
  18807. phiLength = phiLength || 2 * Math.PI;
  18808. var inversePointLength = 1.0 / ( points.length - 1 );
  18809. var inverseSegments = 1.0 / segments;
  18810. for ( var i = 0, il = segments; i <= il; i ++ ) {
  18811. var phi = phiStart + i * inverseSegments * phiLength;
  18812. var c = Math.cos( phi ),
  18813. s = Math.sin( phi );
  18814. for ( var j = 0, jl = points.length; j < jl; j ++ ) {
  18815. var pt = points[ j ];
  18816. var vertex = new THREE.Vector3();
  18817. vertex.x = c * pt.x - s * pt.y;
  18818. vertex.y = s * pt.x + c * pt.y;
  18819. vertex.z = pt.z;
  18820. this.vertices.push( vertex );
  18821. }
  18822. }
  18823. var np = points.length;
  18824. for ( var i = 0, il = segments; i < il; i ++ ) {
  18825. for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) {
  18826. var base = j + np * i;
  18827. var a = base;
  18828. var b = base + np;
  18829. var c = base + 1 + np;
  18830. var d = base + 1;
  18831. var u0 = i * inverseSegments;
  18832. var v0 = j * inversePointLength;
  18833. var u1 = u0 + inverseSegments;
  18834. var v1 = v0 + inversePointLength;
  18835. this.faces.push( new THREE.Face3( a, b, d ) );
  18836. this.faceVertexUvs[ 0 ].push( [
  18837. new THREE.Vector2( u0, v0 ),
  18838. new THREE.Vector2( u1, v0 ),
  18839. new THREE.Vector2( u0, v1 )
  18840. ] );
  18841. this.faces.push( new THREE.Face3( b, c, d ) );
  18842. this.faceVertexUvs[ 0 ].push( [
  18843. new THREE.Vector2( u1, v0 ),
  18844. new THREE.Vector2( u1, v1 ),
  18845. new THREE.Vector2( u0, v1 )
  18846. ] );
  18847. }
  18848. }
  18849. this.mergeVertices();
  18850. this.computeFaceNormals();
  18851. this.computeVertexNormals();
  18852. };
  18853. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18854. THREE.LatheGeometry.prototype.constructor = THREE.LatheGeometry;
  18855. // File:src/extras/geometries/PlaneGeometry.js
  18856. /**
  18857. * @author mrdoob / http://mrdoob.com/
  18858. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  18859. */
  18860. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  18861. console.log( 'THREE.PlaneGeometry: Consider using THREE.PlaneBufferGeometry for lower memory footprint.' );
  18862. THREE.Geometry.call( this );
  18863. this.type = 'PlaneGeometry';
  18864. this.parameters = {
  18865. width: width,
  18866. height: height,
  18867. widthSegments: widthSegments,
  18868. heightSegments: heightSegments
  18869. };
  18870. this.fromBufferGeometry( new THREE.PlaneBufferGeometry( width, height, widthSegments, heightSegments ) );
  18871. };
  18872. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18873. THREE.PlaneGeometry.prototype.constructor = THREE.PlaneGeometry;
  18874. // File:src/extras/geometries/PlaneBufferGeometry.js
  18875. /**
  18876. * @author mrdoob / http://mrdoob.com/
  18877. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  18878. */
  18879. THREE.PlaneBufferGeometry = function ( width, height, widthSegments, heightSegments ) {
  18880. THREE.BufferGeometry.call( this );
  18881. this.type = 'PlaneBufferGeometry';
  18882. this.parameters = {
  18883. width: width,
  18884. height: height,
  18885. widthSegments: widthSegments,
  18886. heightSegments: heightSegments
  18887. };
  18888. var width_half = width / 2;
  18889. var height_half = height / 2;
  18890. var gridX = Math.floor( widthSegments ) || 1;
  18891. var gridY = Math.floor( heightSegments ) || 1;
  18892. var gridX1 = gridX + 1;
  18893. var gridY1 = gridY + 1;
  18894. var segment_width = width / gridX;
  18895. var segment_height = height / gridY;
  18896. var vertices = new Float32Array( gridX1 * gridY1 * 3 );
  18897. var normals = new Float32Array( gridX1 * gridY1 * 3 );
  18898. var uvs = new Float32Array( gridX1 * gridY1 * 2 );
  18899. var offset = 0;
  18900. var offset2 = 0;
  18901. for ( var iy = 0; iy < gridY1; iy ++ ) {
  18902. var y = iy * segment_height - height_half;
  18903. for ( var ix = 0; ix < gridX1; ix ++ ) {
  18904. var x = ix * segment_width - width_half;
  18905. vertices[ offset ] = x;
  18906. vertices[ offset + 1 ] = - y;
  18907. normals[ offset + 2 ] = 1;
  18908. uvs[ offset2 ] = ix / gridX;
  18909. uvs[ offset2 + 1 ] = 1 - ( iy / gridY );
  18910. offset += 3;
  18911. offset2 += 2;
  18912. }
  18913. }
  18914. offset = 0;
  18915. var indices = new ( ( vertices.length / 3 ) > 65535 ? Uint32Array : Uint16Array )( gridX * gridY * 6 );
  18916. for ( var iy = 0; iy < gridY; iy ++ ) {
  18917. for ( var ix = 0; ix < gridX; ix ++ ) {
  18918. var a = ix + gridX1 * iy;
  18919. var b = ix + gridX1 * ( iy + 1 );
  18920. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  18921. var d = ( ix + 1 ) + gridX1 * iy;
  18922. indices[ offset ] = a;
  18923. indices[ offset + 1 ] = b;
  18924. indices[ offset + 2 ] = d;
  18925. indices[ offset + 3 ] = b;
  18926. indices[ offset + 4 ] = c;
  18927. indices[ offset + 5 ] = d;
  18928. offset += 6;
  18929. }
  18930. }
  18931. this.addAttribute( 'index', new THREE.BufferAttribute( indices, 1 ) );
  18932. this.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  18933. this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
  18934. this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) );
  18935. };
  18936. THREE.PlaneBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  18937. THREE.PlaneBufferGeometry.prototype.constructor = THREE.PlaneBufferGeometry;
  18938. // File:src/extras/geometries/RingGeometry.js
  18939. /**
  18940. * @author Kaleb Murphy
  18941. */
  18942. THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  18943. THREE.Geometry.call( this );
  18944. this.type = 'RingGeometry';
  18945. this.parameters = {
  18946. innerRadius: innerRadius,
  18947. outerRadius: outerRadius,
  18948. thetaSegments: thetaSegments,
  18949. phiSegments: phiSegments,
  18950. thetaStart: thetaStart,
  18951. thetaLength: thetaLength
  18952. };
  18953. innerRadius = innerRadius || 0;
  18954. outerRadius = outerRadius || 50;
  18955. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18956. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  18957. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  18958. phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 8;
  18959. var i, o, uvs = [], radius = innerRadius, radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  18960. for ( i = 0; i < phiSegments + 1; i ++ ) { // concentric circles inside ring
  18961. for ( o = 0; o < thetaSegments + 1; o ++ ) { // number of segments per circle
  18962. var vertex = new THREE.Vector3();
  18963. var segment = thetaStart + o / thetaSegments * thetaLength;
  18964. vertex.x = radius * Math.cos( segment );
  18965. vertex.y = radius * Math.sin( segment );
  18966. this.vertices.push( vertex );
  18967. uvs.push( new THREE.Vector2( ( vertex.x / outerRadius + 1 ) / 2, ( vertex.y / outerRadius + 1 ) / 2 ) );
  18968. }
  18969. radius += radiusStep;
  18970. }
  18971. var n = new THREE.Vector3( 0, 0, 1 );
  18972. for ( i = 0; i < phiSegments; i ++ ) { // concentric circles inside ring
  18973. var thetaSegment = i * (thetaSegments + 1);
  18974. for ( o = 0; o < thetaSegments ; o ++ ) { // number of segments per circle
  18975. var segment = o + thetaSegment;
  18976. var v1 = segment;
  18977. var v2 = segment + thetaSegments + 1;
  18978. var v3 = segment + thetaSegments + 2;
  18979. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  18980. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]);
  18981. v1 = segment;
  18982. v2 = segment + thetaSegments + 2;
  18983. v3 = segment + 1;
  18984. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  18985. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]);
  18986. }
  18987. }
  18988. this.computeFaceNormals();
  18989. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  18990. };
  18991. THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18992. THREE.RingGeometry.prototype.constructor = THREE.RingGeometry;
  18993. // File:src/extras/geometries/SphereGeometry.js
  18994. /**
  18995. * @author mrdoob / http://mrdoob.com/
  18996. */
  18997. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  18998. console.log( 'THREE.SphereGeometry: Consider using THREE.SphereBufferGeometry for lower memory footprint.' );
  18999. THREE.Geometry.call( this );
  19000. this.type = 'SphereGeometry';
  19001. this.parameters = {
  19002. radius: radius,
  19003. widthSegments: widthSegments,
  19004. heightSegments: heightSegments,
  19005. phiStart: phiStart,
  19006. phiLength: phiLength,
  19007. thetaStart: thetaStart,
  19008. thetaLength: thetaLength
  19009. };
  19010. radius = radius || 50;
  19011. widthSegments = Math.max( 2, Math.floor( widthSegments ) || 8 );
  19012. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  19013. phiStart = phiStart !== undefined ? phiStart : 0;
  19014. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19015. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19016. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19017. var x, y, vertices = [], uvs = [];
  19018. for ( y = 0; y <= heightSegments; y ++ ) {
  19019. var verticesRow = [];
  19020. var uvsRow = [];
  19021. for ( x = 0; x <= widthSegments; x ++ ) {
  19022. var u = x / widthSegments;
  19023. var v = y / heightSegments;
  19024. var vertex = new THREE.Vector3();
  19025. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19026. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  19027. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19028. this.vertices.push( vertex );
  19029. verticesRow.push( this.vertices.length - 1 );
  19030. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19031. }
  19032. vertices.push( verticesRow );
  19033. uvs.push( uvsRow );
  19034. }
  19035. for ( y = 0; y < heightSegments; y ++ ) {
  19036. for ( x = 0; x < widthSegments; x ++ ) {
  19037. var v1 = vertices[ y ][ x + 1 ];
  19038. var v2 = vertices[ y ][ x ];
  19039. var v3 = vertices[ y + 1 ][ x ];
  19040. var v4 = vertices[ y + 1 ][ x + 1 ];
  19041. var n1 = this.vertices[ v1 ].clone().normalize();
  19042. var n2 = this.vertices[ v2 ].clone().normalize();
  19043. var n3 = this.vertices[ v3 ].clone().normalize();
  19044. var n4 = this.vertices[ v4 ].clone().normalize();
  19045. var uv1 = uvs[ y ][ x + 1 ].clone();
  19046. var uv2 = uvs[ y ][ x ].clone();
  19047. var uv3 = uvs[ y + 1 ][ x ].clone();
  19048. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  19049. if ( Math.abs( this.vertices[ v1 ].y ) === radius ) {
  19050. uv1.x = ( uv1.x + uv2.x ) / 2;
  19051. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  19052. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  19053. } else if ( Math.abs( this.vertices[ v3 ].y ) === radius ) {
  19054. uv3.x = ( uv3.x + uv4.x ) / 2;
  19055. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19056. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19057. } else {
  19058. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  19059. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  19060. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  19061. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  19062. }
  19063. }
  19064. }
  19065. this.computeFaceNormals();
  19066. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19067. };
  19068. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19069. THREE.SphereGeometry.prototype.constructor = THREE.SphereGeometry;
  19070. // File:src/extras/geometries/SphereBufferGeometry.js
  19071. /**
  19072. * @author benaadams / https://twitter.com/ben_a_adams
  19073. * based on THREE.SphereGeometry
  19074. */
  19075. THREE.SphereBufferGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  19076. THREE.BufferGeometry.call( this );
  19077. this.type = 'SphereBufferGeometry';
  19078. this.parameters = {
  19079. radius: radius,
  19080. widthSegments: widthSegments,
  19081. heightSegments: heightSegments,
  19082. phiStart: phiStart,
  19083. phiLength: phiLength,
  19084. thetaStart: thetaStart,
  19085. thetaLength: thetaLength
  19086. };
  19087. radius = radius || 50;
  19088. widthSegments = Math.max( 2, Math.floor( widthSegments ) || 8 );
  19089. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  19090. phiStart = phiStart !== undefined ? phiStart : 0;
  19091. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19092. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19093. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19094. var vertexCount = ( ( widthSegments + 1 ) * ( heightSegments + 1 ) );
  19095. var positions = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  19096. var normals = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3);
  19097. var uvs = new THREE.BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  19098. var index = 0, vertices = [], normal = new THREE.Vector3();
  19099. for ( var y = 0; y <= heightSegments; y ++ ) {
  19100. var verticesRow = [];
  19101. var v = y / heightSegments;
  19102. for ( var x = 0; x <= widthSegments; x ++ ) {
  19103. var u = x / widthSegments;
  19104. var px = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19105. var py = radius * Math.cos( thetaStart + v * thetaLength );
  19106. var pz = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19107. normal.set( px, py, pz ).normalize();
  19108. positions.setXYZ( index, px, py, pz );
  19109. normals.setXYZ( index, normal.x, normal.y, normal.z );
  19110. uvs.setXY( index, u, 1 - v );
  19111. verticesRow.push( index );
  19112. index++;
  19113. }
  19114. vertices.push( verticesRow );
  19115. }
  19116. var indices = [];
  19117. for ( var y = 0; y < heightSegments; y ++ ) {
  19118. for ( var x = 0; x < widthSegments; x ++ ) {
  19119. var v1 = vertices[ y ][ x + 1 ];
  19120. var v2 = vertices[ y ][ x ];
  19121. var v3 = vertices[ y + 1 ][ x ];
  19122. var v4 = vertices[ y + 1 ][ x + 1 ];
  19123. if ( y !== 0 ) indices.push( v1, v2, v4 );
  19124. if ( y !== heightSegments - 1 ) indices.push( v2, v3, v4 );
  19125. }
  19126. }
  19127. this.addAttribute( 'index', new THREE.BufferAttribute( new Uint16Array( indices ), 1 ) );
  19128. this.addAttribute( 'position', positions );
  19129. this.addAttribute( 'normal', normals );
  19130. this.addAttribute( 'uv', uvs );
  19131. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19132. };
  19133. THREE.SphereBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  19134. THREE.SphereBufferGeometry.prototype.constructor = THREE.SphereBufferGeometry;
  19135. // File:src/extras/geometries/TextGeometry.js
  19136. /**
  19137. * @author zz85 / http://www.lab4games.net/zz85/blog
  19138. * @author alteredq / http://alteredqualia.com/
  19139. *
  19140. * For creating 3D text geometry in three.js
  19141. *
  19142. * Text = 3D Text
  19143. *
  19144. * parameters = {
  19145. * size: <float>, // size of the text
  19146. * height: <float>, // thickness to extrude text
  19147. * curveSegments: <int>, // number of points on the curves
  19148. *
  19149. * font: <string>, // font name
  19150. * weight: <string>, // font weight (normal, bold)
  19151. * style: <string>, // font style (normal, italics)
  19152. *
  19153. * bevelEnabled: <bool>, // turn on bevel
  19154. * bevelThickness: <float>, // how deep into text bevel goes
  19155. * bevelSize: <float>, // how far from text outline is bevel
  19156. * }
  19157. *
  19158. */
  19159. /* Usage Examples
  19160. // TextGeometry wrapper
  19161. var text3d = new TextGeometry( text, options );
  19162. // Complete manner
  19163. var textShapes = THREE.FontUtils.generateShapes( text, options );
  19164. var text3d = new ExtrudeGeometry( textShapes, options );
  19165. */
  19166. THREE.TextGeometry = function ( text, parameters ) {
  19167. parameters = parameters || {};
  19168. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  19169. // translate parameters to ExtrudeGeometry API
  19170. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  19171. // defaults
  19172. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  19173. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  19174. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  19175. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  19176. this.type = 'TextGeometry';
  19177. };
  19178. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  19179. THREE.TextGeometry.prototype.constructor = THREE.TextGeometry;
  19180. // File:src/extras/geometries/TorusGeometry.js
  19181. /**
  19182. * @author oosmoxiecode
  19183. * @author mrdoob / http://mrdoob.com/
  19184. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  19185. */
  19186. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  19187. THREE.Geometry.call( this );
  19188. this.type = 'TorusGeometry';
  19189. this.parameters = {
  19190. radius: radius,
  19191. tube: tube,
  19192. radialSegments: radialSegments,
  19193. tubularSegments: tubularSegments,
  19194. arc: arc
  19195. };
  19196. radius = radius || 100;
  19197. tube = tube || 40;
  19198. radialSegments = radialSegments || 8;
  19199. tubularSegments = tubularSegments || 6;
  19200. arc = arc || Math.PI * 2;
  19201. var center = new THREE.Vector3(), uvs = [], normals = [];
  19202. for ( var j = 0; j <= radialSegments; j ++ ) {
  19203. for ( var i = 0; i <= tubularSegments; i ++ ) {
  19204. var u = i / tubularSegments * arc;
  19205. var v = j / radialSegments * Math.PI * 2;
  19206. center.x = radius * Math.cos( u );
  19207. center.y = radius * Math.sin( u );
  19208. var vertex = new THREE.Vector3();
  19209. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  19210. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  19211. vertex.z = tube * Math.sin( v );
  19212. this.vertices.push( vertex );
  19213. uvs.push( new THREE.Vector2( i / tubularSegments, j / radialSegments ) );
  19214. normals.push( vertex.clone().sub( center ).normalize() );
  19215. }
  19216. }
  19217. for ( var j = 1; j <= radialSegments; j ++ ) {
  19218. for ( var i = 1; i <= tubularSegments; i ++ ) {
  19219. var a = ( tubularSegments + 1 ) * j + i - 1;
  19220. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  19221. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  19222. var d = ( tubularSegments + 1 ) * j + i;
  19223. var face = new THREE.Face3( a, b, d, [ normals[ a ].clone(), normals[ b ].clone(), normals[ d ].clone() ] );
  19224. this.faces.push( face );
  19225. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ d ].clone() ] );
  19226. face = new THREE.Face3( b, c, d, [ normals[ b ].clone(), normals[ c ].clone(), normals[ d ].clone() ] );
  19227. this.faces.push( face );
  19228. this.faceVertexUvs[ 0 ].push( [ uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  19229. }
  19230. }
  19231. this.computeFaceNormals();
  19232. };
  19233. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19234. THREE.TorusGeometry.prototype.constructor = THREE.TorusGeometry;
  19235. // File:src/extras/geometries/TorusKnotGeometry.js
  19236. /**
  19237. * @author oosmoxiecode
  19238. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  19239. */
  19240. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  19241. THREE.Geometry.call( this );
  19242. this.type = 'TorusKnotGeometry';
  19243. this.parameters = {
  19244. radius: radius,
  19245. tube: tube,
  19246. radialSegments: radialSegments,
  19247. tubularSegments: tubularSegments,
  19248. p: p,
  19249. q: q,
  19250. heightScale: heightScale
  19251. };
  19252. radius = radius || 100;
  19253. tube = tube || 40;
  19254. radialSegments = radialSegments || 64;
  19255. tubularSegments = tubularSegments || 8;
  19256. p = p || 2;
  19257. q = q || 3;
  19258. heightScale = heightScale || 1;
  19259. var grid = new Array( radialSegments );
  19260. var tang = new THREE.Vector3();
  19261. var n = new THREE.Vector3();
  19262. var bitan = new THREE.Vector3();
  19263. for ( var i = 0; i < radialSegments; ++ i ) {
  19264. grid[ i ] = new Array( tubularSegments );
  19265. var u = i / radialSegments * 2 * p * Math.PI;
  19266. var p1 = getPos( u, q, p, radius, heightScale );
  19267. var p2 = getPos( u + 0.01, q, p, radius, heightScale );
  19268. tang.subVectors( p2, p1 );
  19269. n.addVectors( p2, p1 );
  19270. bitan.crossVectors( tang, n );
  19271. n.crossVectors( bitan, tang );
  19272. bitan.normalize();
  19273. n.normalize();
  19274. for ( var j = 0; j < tubularSegments; ++ j ) {
  19275. var v = j / tubularSegments * 2 * Math.PI;
  19276. var cx = - tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19277. var cy = tube * Math.sin( v );
  19278. var pos = new THREE.Vector3();
  19279. pos.x = p1.x + cx * n.x + cy * bitan.x;
  19280. pos.y = p1.y + cx * n.y + cy * bitan.y;
  19281. pos.z = p1.z + cx * n.z + cy * bitan.z;
  19282. grid[ i ][ j ] = this.vertices.push( pos ) - 1;
  19283. }
  19284. }
  19285. for ( var i = 0; i < radialSegments; ++ i ) {
  19286. for ( var j = 0; j < tubularSegments; ++ j ) {
  19287. var ip = ( i + 1 ) % radialSegments;
  19288. var jp = ( j + 1 ) % tubularSegments;
  19289. var a = grid[ i ][ j ];
  19290. var b = grid[ ip ][ j ];
  19291. var c = grid[ ip ][ jp ];
  19292. var d = grid[ i ][ jp ];
  19293. var uva = new THREE.Vector2( i / radialSegments, j / tubularSegments );
  19294. var uvb = new THREE.Vector2( ( i + 1 ) / radialSegments, j / tubularSegments );
  19295. var uvc = new THREE.Vector2( ( i + 1 ) / radialSegments, ( j + 1 ) / tubularSegments );
  19296. var uvd = new THREE.Vector2( i / radialSegments, ( j + 1 ) / tubularSegments );
  19297. this.faces.push( new THREE.Face3( a, b, d ) );
  19298. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19299. this.faces.push( new THREE.Face3( b, c, d ) );
  19300. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19301. }
  19302. }
  19303. this.computeFaceNormals();
  19304. this.computeVertexNormals();
  19305. function getPos( u, in_q, in_p, radius, heightScale ) {
  19306. var cu = Math.cos( u );
  19307. var su = Math.sin( u );
  19308. var quOverP = in_q / in_p * u;
  19309. var cs = Math.cos( quOverP );
  19310. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  19311. var ty = radius * ( 2 + cs ) * su * 0.5;
  19312. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  19313. return new THREE.Vector3( tx, ty, tz );
  19314. }
  19315. };
  19316. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19317. THREE.TorusKnotGeometry.prototype.constructor = THREE.TorusKnotGeometry;
  19318. // File:src/extras/geometries/TubeGeometry.js
  19319. /**
  19320. * @author WestLangley / https://github.com/WestLangley
  19321. * @author zz85 / https://github.com/zz85
  19322. * @author miningold / https://github.com/miningold
  19323. * @author jonobr1 / https://github.com/jonobr1
  19324. *
  19325. * Modified from the TorusKnotGeometry by @oosmoxiecode
  19326. *
  19327. * Creates a tube which extrudes along a 3d spline
  19328. *
  19329. * Uses parallel transport frames as described in
  19330. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  19331. */
  19332. THREE.TubeGeometry = function ( path, segments, radius, radialSegments, closed, taper ) {
  19333. THREE.Geometry.call( this );
  19334. this.type = 'TubeGeometry';
  19335. this.parameters = {
  19336. path: path,
  19337. segments: segments,
  19338. radius: radius,
  19339. radialSegments: radialSegments,
  19340. closed: closed
  19341. };
  19342. segments = segments || 64;
  19343. radius = radius || 1;
  19344. radialSegments = radialSegments || 8;
  19345. closed = closed || false;
  19346. taper = taper || THREE.TubeGeometry.NoTaper;
  19347. var grid = [];
  19348. var scope = this,
  19349. tangent,
  19350. normal,
  19351. binormal,
  19352. numpoints = segments + 1,
  19353. u, v, r,
  19354. cx, cy,
  19355. pos, pos2 = new THREE.Vector3(),
  19356. i, j,
  19357. ip, jp,
  19358. a, b, c, d,
  19359. uva, uvb, uvc, uvd;
  19360. var frames = new THREE.TubeGeometry.FrenetFrames( path, segments, closed ),
  19361. tangents = frames.tangents,
  19362. normals = frames.normals,
  19363. binormals = frames.binormals;
  19364. // proxy internals
  19365. this.tangents = tangents;
  19366. this.normals = normals;
  19367. this.binormals = binormals;
  19368. function vert( x, y, z ) {
  19369. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19370. }
  19371. // consruct the grid
  19372. for ( i = 0; i < numpoints; i ++ ) {
  19373. grid[ i ] = [];
  19374. u = i / ( numpoints - 1 );
  19375. pos = path.getPointAt( u );
  19376. tangent = tangents[ i ];
  19377. normal = normals[ i ];
  19378. binormal = binormals[ i ];
  19379. r = radius * taper( u );
  19380. for ( j = 0; j < radialSegments; j ++ ) {
  19381. v = j / radialSegments * 2 * Math.PI;
  19382. cx = - r * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19383. cy = r * Math.sin( v );
  19384. pos2.copy( pos );
  19385. pos2.x += cx * normal.x + cy * binormal.x;
  19386. pos2.y += cx * normal.y + cy * binormal.y;
  19387. pos2.z += cx * normal.z + cy * binormal.z;
  19388. grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  19389. }
  19390. }
  19391. // construct the mesh
  19392. for ( i = 0; i < segments; i ++ ) {
  19393. for ( j = 0; j < radialSegments; j ++ ) {
  19394. ip = ( closed ) ? (i + 1) % segments : i + 1;
  19395. jp = (j + 1) % radialSegments;
  19396. a = grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  19397. b = grid[ ip ][ j ];
  19398. c = grid[ ip ][ jp ];
  19399. d = grid[ i ][ jp ];
  19400. uva = new THREE.Vector2( i / segments, j / radialSegments );
  19401. uvb = new THREE.Vector2( ( i + 1 ) / segments, j / radialSegments );
  19402. uvc = new THREE.Vector2( ( i + 1 ) / segments, ( j + 1 ) / radialSegments );
  19403. uvd = new THREE.Vector2( i / segments, ( j + 1 ) / radialSegments );
  19404. this.faces.push( new THREE.Face3( a, b, d ) );
  19405. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19406. this.faces.push( new THREE.Face3( b, c, d ) );
  19407. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19408. }
  19409. }
  19410. this.computeFaceNormals();
  19411. this.computeVertexNormals();
  19412. };
  19413. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19414. THREE.TubeGeometry.prototype.constructor = THREE.TubeGeometry;
  19415. THREE.TubeGeometry.NoTaper = function ( u ) {
  19416. return 1;
  19417. };
  19418. THREE.TubeGeometry.SinusoidalTaper = function ( u ) {
  19419. return Math.sin( Math.PI * u );
  19420. };
  19421. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  19422. THREE.TubeGeometry.FrenetFrames = function ( path, segments, closed ) {
  19423. var normal = new THREE.Vector3(),
  19424. tangents = [],
  19425. normals = [],
  19426. binormals = [],
  19427. vec = new THREE.Vector3(),
  19428. mat = new THREE.Matrix4(),
  19429. numpoints = segments + 1,
  19430. theta,
  19431. epsilon = 0.0001,
  19432. smallest,
  19433. tx, ty, tz,
  19434. i, u;
  19435. // expose internals
  19436. this.tangents = tangents;
  19437. this.normals = normals;
  19438. this.binormals = binormals;
  19439. // compute the tangent vectors for each segment on the path
  19440. for ( i = 0; i < numpoints; i ++ ) {
  19441. u = i / ( numpoints - 1 );
  19442. tangents[ i ] = path.getTangentAt( u );
  19443. tangents[ i ].normalize();
  19444. }
  19445. initialNormal3();
  19446. /*
  19447. function initialNormal1(lastBinormal) {
  19448. // fixed start binormal. Has dangers of 0 vectors
  19449. normals[ 0 ] = new THREE.Vector3();
  19450. binormals[ 0 ] = new THREE.Vector3();
  19451. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  19452. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  19453. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19454. }
  19455. function initialNormal2() {
  19456. // This uses the Frenet-Serret formula for deriving binormal
  19457. var t2 = path.getTangentAt( epsilon );
  19458. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  19459. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  19460. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  19461. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19462. }
  19463. */
  19464. function initialNormal3() {
  19465. // select an initial normal vector perpenicular to the first tangent vector,
  19466. // and in the direction of the smallest tangent xyz component
  19467. normals[ 0 ] = new THREE.Vector3();
  19468. binormals[ 0 ] = new THREE.Vector3();
  19469. smallest = Number.MAX_VALUE;
  19470. tx = Math.abs( tangents[ 0 ].x );
  19471. ty = Math.abs( tangents[ 0 ].y );
  19472. tz = Math.abs( tangents[ 0 ].z );
  19473. if ( tx <= smallest ) {
  19474. smallest = tx;
  19475. normal.set( 1, 0, 0 );
  19476. }
  19477. if ( ty <= smallest ) {
  19478. smallest = ty;
  19479. normal.set( 0, 1, 0 );
  19480. }
  19481. if ( tz <= smallest ) {
  19482. normal.set( 0, 0, 1 );
  19483. }
  19484. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  19485. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  19486. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  19487. }
  19488. // compute the slowly-varying normal and binormal vectors for each segment on the path
  19489. for ( i = 1; i < numpoints; i ++ ) {
  19490. normals[ i ] = normals[ i - 1 ].clone();
  19491. binormals[ i ] = binormals[ i - 1 ].clone();
  19492. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  19493. if ( vec.length() > epsilon ) {
  19494. vec.normalize();
  19495. theta = Math.acos( THREE.Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  19496. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  19497. }
  19498. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19499. }
  19500. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  19501. if ( closed ) {
  19502. theta = Math.acos( THREE.Math.clamp( normals[ 0 ].dot( normals[ numpoints - 1 ] ), - 1, 1 ) );
  19503. theta /= ( numpoints - 1 );
  19504. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints - 1 ] ) ) > 0 ) {
  19505. theta = - theta;
  19506. }
  19507. for ( i = 1; i < numpoints; i ++ ) {
  19508. // twist a little...
  19509. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  19510. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19511. }
  19512. }
  19513. };
  19514. // File:src/extras/geometries/PolyhedronGeometry.js
  19515. /**
  19516. * @author clockworkgeek / https://github.com/clockworkgeek
  19517. * @author timothypratley / https://github.com/timothypratley
  19518. * @author WestLangley / http://github.com/WestLangley
  19519. */
  19520. THREE.PolyhedronGeometry = function ( vertices, indices, radius, detail ) {
  19521. THREE.Geometry.call( this );
  19522. this.type = 'PolyhedronGeometry';
  19523. this.parameters = {
  19524. vertices: vertices,
  19525. indices: indices,
  19526. radius: radius,
  19527. detail: detail
  19528. };
  19529. radius = radius || 1;
  19530. detail = detail || 0;
  19531. var that = this;
  19532. for ( var i = 0, l = vertices.length; i < l; i += 3 ) {
  19533. prepare( new THREE.Vector3( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] ) );
  19534. }
  19535. var p = this.vertices;
  19536. var faces = [];
  19537. for ( var i = 0, j = 0, l = indices.length; i < l; i += 3, j ++ ) {
  19538. var v1 = p[ indices[ i ] ];
  19539. var v2 = p[ indices[ i + 1 ] ];
  19540. var v3 = p[ indices[ i + 2 ] ];
  19541. faces[ j ] = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19542. }
  19543. var centroid = new THREE.Vector3();
  19544. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  19545. subdivide( faces[ i ], detail );
  19546. }
  19547. // Handle case when face straddles the seam
  19548. for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) {
  19549. var uvs = this.faceVertexUvs[ 0 ][ i ];
  19550. var x0 = uvs[ 0 ].x;
  19551. var x1 = uvs[ 1 ].x;
  19552. var x2 = uvs[ 2 ].x;
  19553. var max = Math.max( x0, Math.max( x1, x2 ) );
  19554. var min = Math.min( x0, Math.min( x1, x2 ) );
  19555. if ( max > 0.9 && min < 0.1 ) { // 0.9 is somewhat arbitrary
  19556. if ( x0 < 0.2 ) uvs[ 0 ].x += 1;
  19557. if ( x1 < 0.2 ) uvs[ 1 ].x += 1;
  19558. if ( x2 < 0.2 ) uvs[ 2 ].x += 1;
  19559. }
  19560. }
  19561. // Apply radius
  19562. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  19563. this.vertices[ i ].multiplyScalar( radius );
  19564. }
  19565. // Merge vertices
  19566. this.mergeVertices();
  19567. this.computeFaceNormals();
  19568. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19569. // Project vector onto sphere's surface
  19570. function prepare( vector ) {
  19571. var vertex = vector.normalize().clone();
  19572. vertex.index = that.vertices.push( vertex ) - 1;
  19573. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  19574. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  19575. var v = inclination( vector ) / Math.PI + 0.5;
  19576. vertex.uv = new THREE.Vector2( u, 1 - v );
  19577. return vertex;
  19578. }
  19579. // Approximate a curved face with recursively sub-divided triangles.
  19580. function make( v1, v2, v3 ) {
  19581. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19582. that.faces.push( face );
  19583. centroid.copy( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  19584. var azi = azimuth( centroid );
  19585. that.faceVertexUvs[ 0 ].push( [
  19586. correctUV( v1.uv, v1, azi ),
  19587. correctUV( v2.uv, v2, azi ),
  19588. correctUV( v3.uv, v3, azi )
  19589. ] );
  19590. }
  19591. // Analytically subdivide a face to the required detail level.
  19592. function subdivide( face, detail ) {
  19593. var cols = Math.pow(2, detail);
  19594. var a = prepare( that.vertices[ face.a ] );
  19595. var b = prepare( that.vertices[ face.b ] );
  19596. var c = prepare( that.vertices[ face.c ] );
  19597. var v = [];
  19598. // Construct all of the vertices for this subdivision.
  19599. for ( var i = 0 ; i <= cols; i ++ ) {
  19600. v[ i ] = [];
  19601. var aj = prepare( a.clone().lerp( c, i / cols ) );
  19602. var bj = prepare( b.clone().lerp( c, i / cols ) );
  19603. var rows = cols - i;
  19604. for ( var j = 0; j <= rows; j ++) {
  19605. if ( j === 0 && i === cols ) {
  19606. v[ i ][ j ] = aj;
  19607. } else {
  19608. v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) );
  19609. }
  19610. }
  19611. }
  19612. // Construct all of the faces.
  19613. for ( var i = 0; i < cols ; i ++ ) {
  19614. for ( var j = 0; j < 2 * (cols - i) - 1; j ++ ) {
  19615. var k = Math.floor( j / 2 );
  19616. if ( j % 2 === 0 ) {
  19617. make(
  19618. v[ i ][ k + 1],
  19619. v[ i + 1 ][ k ],
  19620. v[ i ][ k ]
  19621. );
  19622. } else {
  19623. make(
  19624. v[ i ][ k + 1 ],
  19625. v[ i + 1][ k + 1],
  19626. v[ i + 1 ][ k ]
  19627. );
  19628. }
  19629. }
  19630. }
  19631. }
  19632. // Angle around the Y axis, counter-clockwise when looking from above.
  19633. function azimuth( vector ) {
  19634. return Math.atan2( vector.z, - vector.x );
  19635. }
  19636. // Angle above the XZ plane.
  19637. function inclination( vector ) {
  19638. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  19639. }
  19640. // Texture fixing helper. Spheres have some odd behaviours.
  19641. function correctUV( uv, vector, azimuth ) {
  19642. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  19643. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  19644. return uv.clone();
  19645. }
  19646. };
  19647. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19648. THREE.PolyhedronGeometry.prototype.constructor = THREE.PolyhedronGeometry;
  19649. // File:src/extras/geometries/DodecahedronGeometry.js
  19650. /**
  19651. * @author Abe Pazos / https://hamoid.com
  19652. */
  19653. THREE.DodecahedronGeometry = function ( radius, detail ) {
  19654. this.parameters = {
  19655. radius: radius,
  19656. detail: detail
  19657. };
  19658. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19659. var r = 1 / t;
  19660. var vertices = [
  19661. // (±1, ±1, ±1)
  19662. -1, -1, -1, -1, -1, 1,
  19663. -1, 1, -1, -1, 1, 1,
  19664. 1, -1, -1, 1, -1, 1,
  19665. 1, 1, -1, 1, 1, 1,
  19666. // (0, ±1/φ, ±φ)
  19667. 0, -r, -t, 0, -r, t,
  19668. 0, r, -t, 0, r, t,
  19669. // (±1/φ, ±φ, 0)
  19670. -r, -t, 0, -r, t, 0,
  19671. r, -t, 0, r, t, 0,
  19672. // (±φ, 0, ±1/φ)
  19673. -t, 0, -r, t, 0, -r,
  19674. -t, 0, r, t, 0, r
  19675. ];
  19676. var indices = [
  19677. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  19678. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  19679. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  19680. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  19681. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  19682. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  19683. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  19684. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  19685. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  19686. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  19687. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  19688. 1, 12, 14, 1, 14, 5, 1, 5, 9
  19689. ];
  19690. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  19691. };
  19692. THREE.DodecahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19693. THREE.DodecahedronGeometry.prototype.constructor = THREE.DodecahedronGeometry;
  19694. // File:src/extras/geometries/IcosahedronGeometry.js
  19695. /**
  19696. * @author timothypratley / https://github.com/timothypratley
  19697. */
  19698. THREE.IcosahedronGeometry = function ( radius, detail ) {
  19699. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19700. var vertices = [
  19701. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  19702. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  19703. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  19704. ];
  19705. var indices = [
  19706. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  19707. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  19708. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  19709. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  19710. ];
  19711. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  19712. this.type = 'IcosahedronGeometry';
  19713. this.parameters = {
  19714. radius: radius,
  19715. detail: detail
  19716. };
  19717. };
  19718. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19719. THREE.IcosahedronGeometry.prototype.constructor = THREE.IcosahedronGeometry;
  19720. // File:src/extras/geometries/OctahedronGeometry.js
  19721. /**
  19722. * @author timothypratley / https://github.com/timothypratley
  19723. */
  19724. THREE.OctahedronGeometry = function ( radius, detail ) {
  19725. this.parameters = {
  19726. radius: radius,
  19727. detail: detail
  19728. };
  19729. var vertices = [
  19730. 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0,- 1, 0, 0, 0, 1, 0, 0,- 1
  19731. ];
  19732. var indices = [
  19733. 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2
  19734. ];
  19735. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  19736. this.type = 'OctahedronGeometry';
  19737. this.parameters = {
  19738. radius: radius,
  19739. detail: detail
  19740. };
  19741. };
  19742. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19743. THREE.OctahedronGeometry.prototype.constructor = THREE.OctahedronGeometry;
  19744. // File:src/extras/geometries/TetrahedronGeometry.js
  19745. /**
  19746. * @author timothypratley / https://github.com/timothypratley
  19747. */
  19748. THREE.TetrahedronGeometry = function ( radius, detail ) {
  19749. var vertices = [
  19750. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  19751. ];
  19752. var indices = [
  19753. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  19754. ];
  19755. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  19756. this.type = 'TetrahedronGeometry';
  19757. this.parameters = {
  19758. radius: radius,
  19759. detail: detail
  19760. };
  19761. };
  19762. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19763. THREE.TetrahedronGeometry.prototype.constructor = THREE.TetrahedronGeometry;
  19764. // File:src/extras/geometries/ParametricGeometry.js
  19765. /**
  19766. * @author zz85 / https://github.com/zz85
  19767. * Parametric Surfaces Geometry
  19768. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  19769. *
  19770. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements );
  19771. *
  19772. */
  19773. THREE.ParametricGeometry = function ( func, slices, stacks ) {
  19774. THREE.Geometry.call( this );
  19775. this.type = 'ParametricGeometry';
  19776. this.parameters = {
  19777. func: func,
  19778. slices: slices,
  19779. stacks: stacks
  19780. };
  19781. var verts = this.vertices;
  19782. var faces = this.faces;
  19783. var uvs = this.faceVertexUvs[ 0 ];
  19784. var i, j, p;
  19785. var u, v;
  19786. var sliceCount = slices + 1;
  19787. for ( i = 0; i <= stacks; i ++ ) {
  19788. v = i / stacks;
  19789. for ( j = 0; j <= slices; j ++ ) {
  19790. u = j / slices;
  19791. p = func( u, v );
  19792. verts.push( p );
  19793. }
  19794. }
  19795. var a, b, c, d;
  19796. var uva, uvb, uvc, uvd;
  19797. for ( i = 0; i < stacks; i ++ ) {
  19798. for ( j = 0; j < slices; j ++ ) {
  19799. a = i * sliceCount + j;
  19800. b = i * sliceCount + j + 1;
  19801. c = (i + 1) * sliceCount + j + 1;
  19802. d = (i + 1) * sliceCount + j;
  19803. uva = new THREE.Vector2( j / slices, i / stacks );
  19804. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  19805. uvc = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  19806. uvd = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  19807. faces.push( new THREE.Face3( a, b, d ) );
  19808. uvs.push( [ uva, uvb, uvd ] );
  19809. faces.push( new THREE.Face3( b, c, d ) );
  19810. uvs.push( [ uvb.clone(), uvc, uvd.clone() ] );
  19811. }
  19812. }
  19813. // console.log(this);
  19814. // magic bullet
  19815. // var diff = this.mergeVertices();
  19816. // console.log('removed ', diff, ' vertices by merging');
  19817. this.computeFaceNormals();
  19818. this.computeVertexNormals();
  19819. };
  19820. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19821. THREE.ParametricGeometry.prototype.constructor = THREE.ParametricGeometry;
  19822. // File:src/extras/geometries/WireframeGeometry.js
  19823. /**
  19824. * @author mrdoob / http://mrdoob.com/
  19825. */
  19826. THREE.WireframeGeometry = function ( geometry ) {
  19827. THREE.BufferGeometry.call( this );
  19828. var edge = [ 0, 0 ], hash = {};
  19829. var sortFunction = function ( a, b ) { return a - b };
  19830. var keys = [ 'a', 'b', 'c' ];
  19831. if ( geometry instanceof THREE.Geometry ) {
  19832. var vertices = geometry.vertices;
  19833. var faces = geometry.faces;
  19834. var numEdges = 0;
  19835. // allocate maximal size
  19836. var edges = new Uint32Array( 6 * faces.length );
  19837. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  19838. var face = faces[ i ];
  19839. for ( var j = 0; j < 3; j ++ ) {
  19840. edge[ 0 ] = face[ keys[ j ] ];
  19841. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  19842. edge.sort( sortFunction );
  19843. var key = edge.toString();
  19844. if ( hash[ key ] === undefined ) {
  19845. edges[ 2 * numEdges ] = edge[ 0 ];
  19846. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  19847. hash[ key ] = true;
  19848. numEdges ++;
  19849. }
  19850. }
  19851. }
  19852. var coords = new Float32Array( numEdges * 2 * 3 );
  19853. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  19854. for ( var j = 0; j < 2; j ++ ) {
  19855. var vertex = vertices[ edges [ 2 * i + j] ];
  19856. var index = 6 * i + 3 * j;
  19857. coords[ index + 0 ] = vertex.x;
  19858. coords[ index + 1 ] = vertex.y;
  19859. coords[ index + 2 ] = vertex.z;
  19860. }
  19861. }
  19862. this.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  19863. } else if ( geometry instanceof THREE.BufferGeometry ) {
  19864. if ( geometry.attributes.index !== undefined ) { // Indexed BufferGeometry
  19865. var vertices = geometry.attributes.position;
  19866. var indices = geometry.attributes.index.array;
  19867. var drawcalls = geometry.drawcalls;
  19868. var numEdges = 0;
  19869. if ( drawcalls.length === 0 ) {
  19870. drawcalls = [ { count : indices.length, index : 0, start : 0 } ];
  19871. }
  19872. // allocate maximal size
  19873. var edges = new Uint32Array( 2 * indices.length );
  19874. for ( var o = 0, ol = drawcalls.length; o < ol; ++ o ) {
  19875. var start = drawcalls[ o ].start;
  19876. var count = drawcalls[ o ].count;
  19877. var index = drawcalls[ o ].index;
  19878. for ( var i = start, il = start + count; i < il; i += 3 ) {
  19879. for ( var j = 0; j < 3; j ++ ) {
  19880. edge[ 0 ] = index + indices[ i + j ];
  19881. edge[ 1 ] = index + indices[ i + ( j + 1 ) % 3 ];
  19882. edge.sort( sortFunction );
  19883. var key = edge.toString();
  19884. if ( hash[ key ] === undefined ) {
  19885. edges[ 2 * numEdges ] = edge[ 0 ];
  19886. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  19887. hash[ key ] = true;
  19888. numEdges ++;
  19889. }
  19890. }
  19891. }
  19892. }
  19893. var coords = new Float32Array( numEdges * 2 * 3 );
  19894. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  19895. for ( var j = 0; j < 2; j ++ ) {
  19896. var index = 6 * i + 3 * j;
  19897. var index2 = edges[2 * i + j];
  19898. coords[ index + 0 ] = vertices.getX( index2 );
  19899. coords[ index + 1 ] = vertices.getY( index2 );
  19900. coords[ index + 2 ] = vertices.getZ( index2 );
  19901. }
  19902. }
  19903. this.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  19904. } else { // non-indexed BufferGeometry
  19905. var vertices = geometry.attributes.position.array;
  19906. var numEdges = vertices.length / 3;
  19907. var numTris = numEdges / 3;
  19908. var coords = new Float32Array( numEdges * 2 * 3 );
  19909. for ( var i = 0, l = numTris; i < l; i ++ ) {
  19910. for ( var j = 0; j < 3; j ++ ) {
  19911. var index = 18 * i + 6 * j;
  19912. var index1 = 9 * i + 3 * j;
  19913. coords[ index + 0 ] = vertices[ index1 ];
  19914. coords[ index + 1 ] = vertices[ index1 + 1 ];
  19915. coords[ index + 2 ] = vertices[ index1 + 2 ];
  19916. var index2 = 9 * i + 3 * ( ( j + 1 ) % 3 );
  19917. coords[ index + 3 ] = vertices[ index2 ];
  19918. coords[ index + 4 ] = vertices[ index2 + 1 ];
  19919. coords[ index + 5 ] = vertices[ index2 + 2 ];
  19920. }
  19921. }
  19922. this.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  19923. }
  19924. }
  19925. };
  19926. THREE.WireframeGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  19927. THREE.WireframeGeometry.prototype.constructor = THREE.WireframeGeometry;
  19928. // File:src/extras/helpers/AxisHelper.js
  19929. /**
  19930. * @author sroucheray / http://sroucheray.org/
  19931. * @author mrdoob / http://mrdoob.com/
  19932. */
  19933. THREE.AxisHelper = function ( size ) {
  19934. size = size || 1;
  19935. var vertices = new Float32Array( [
  19936. 0, 0, 0, size, 0, 0,
  19937. 0, 0, 0, 0, size, 0,
  19938. 0, 0, 0, 0, 0, size
  19939. ] );
  19940. var colors = new Float32Array( [
  19941. 1, 0, 0, 1, 0.6, 0,
  19942. 0, 1, 0, 0.6, 1, 0,
  19943. 0, 0, 1, 0, 0.6, 1
  19944. ] );
  19945. var geometry = new THREE.BufferGeometry();
  19946. geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  19947. geometry.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) );
  19948. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  19949. THREE.LineSegments.call( this, geometry, material );
  19950. };
  19951. THREE.AxisHelper.prototype = Object.create( THREE.LineSegments.prototype );
  19952. THREE.AxisHelper.prototype.constructor = THREE.AxisHelper;
  19953. // File:src/extras/helpers/ArrowHelper.js
  19954. /**
  19955. * @author WestLangley / http://github.com/WestLangley
  19956. * @author zz85 / http://github.com/zz85
  19957. * @author bhouston / http://exocortex.com
  19958. *
  19959. * Creates an arrow for visualizing directions
  19960. *
  19961. * Parameters:
  19962. * dir - Vector3
  19963. * origin - Vector3
  19964. * length - Number
  19965. * color - color in hex value
  19966. * headLength - Number
  19967. * headWidth - Number
  19968. */
  19969. THREE.ArrowHelper = ( function () {
  19970. var lineGeometry = new THREE.Geometry();
  19971. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, 1, 0 ) );
  19972. var coneGeometry = new THREE.CylinderGeometry( 0, 0.5, 1, 5, 1 );
  19973. coneGeometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, - 0.5, 0 ) );
  19974. return function ( dir, origin, length, color, headLength, headWidth ) {
  19975. // dir is assumed to be normalized
  19976. THREE.Object3D.call( this );
  19977. if ( color === undefined ) color = 0xffff00;
  19978. if ( length === undefined ) length = 1;
  19979. if ( headLength === undefined ) headLength = 0.2 * length;
  19980. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  19981. this.position.copy( origin );
  19982. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: color } ) );
  19983. this.line.matrixAutoUpdate = false;
  19984. this.add( this.line );
  19985. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: color } ) );
  19986. this.cone.matrixAutoUpdate = false;
  19987. this.add( this.cone );
  19988. this.setDirection( dir );
  19989. this.setLength( length, headLength, headWidth );
  19990. }
  19991. }() );
  19992. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  19993. THREE.ArrowHelper.prototype.constructor = THREE.ArrowHelper;
  19994. THREE.ArrowHelper.prototype.setDirection = ( function () {
  19995. var axis = new THREE.Vector3();
  19996. var radians;
  19997. return function ( dir ) {
  19998. // dir is assumed to be normalized
  19999. if ( dir.y > 0.99999 ) {
  20000. this.quaternion.set( 0, 0, 0, 1 );
  20001. } else if ( dir.y < - 0.99999 ) {
  20002. this.quaternion.set( 1, 0, 0, 0 );
  20003. } else {
  20004. axis.set( dir.z, 0, - dir.x ).normalize();
  20005. radians = Math.acos( dir.y );
  20006. this.quaternion.setFromAxisAngle( axis, radians );
  20007. }
  20008. };
  20009. }() );
  20010. THREE.ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  20011. if ( headLength === undefined ) headLength = 0.2 * length;
  20012. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  20013. this.line.scale.set( 1, length - headLength, 1 );
  20014. this.line.updateMatrix();
  20015. this.cone.scale.set( headWidth, headLength, headWidth );
  20016. this.cone.position.y = length;
  20017. this.cone.updateMatrix();
  20018. };
  20019. THREE.ArrowHelper.prototype.setColor = function ( color ) {
  20020. this.line.material.color.set( color );
  20021. this.cone.material.color.set( color );
  20022. };
  20023. // File:src/extras/helpers/BoxHelper.js
  20024. /**
  20025. * @author mrdoob / http://mrdoob.com/
  20026. */
  20027. THREE.BoxHelper = function ( object ) {
  20028. var geometry = new THREE.BufferGeometry();
  20029. geometry.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( 72 ), 3 ) );
  20030. THREE.LineSegments.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffff00 } ) );
  20031. if ( object !== undefined ) {
  20032. this.update( object );
  20033. }
  20034. };
  20035. THREE.BoxHelper.prototype = Object.create( THREE.LineSegments.prototype );
  20036. THREE.BoxHelper.prototype.constructor = THREE.BoxHelper;
  20037. THREE.BoxHelper.prototype.update = function ( object ) {
  20038. var geometry = object.geometry;
  20039. if ( geometry.boundingBox === null ) {
  20040. geometry.computeBoundingBox();
  20041. }
  20042. var min = geometry.boundingBox.min;
  20043. var max = geometry.boundingBox.max;
  20044. /*
  20045. 5____4
  20046. 1/___0/|
  20047. | 6__|_7
  20048. 2/___3/
  20049. 0: max.x, max.y, max.z
  20050. 1: min.x, max.y, max.z
  20051. 2: min.x, min.y, max.z
  20052. 3: max.x, min.y, max.z
  20053. 4: max.x, max.y, min.z
  20054. 5: min.x, max.y, min.z
  20055. 6: min.x, min.y, min.z
  20056. 7: max.x, min.y, min.z
  20057. */
  20058. var vertices = this.geometry.attributes.position.array;
  20059. vertices[ 0 ] = max.x; vertices[ 1 ] = max.y; vertices[ 2 ] = max.z;
  20060. vertices[ 3 ] = min.x; vertices[ 4 ] = max.y; vertices[ 5 ] = max.z;
  20061. vertices[ 6 ] = min.x; vertices[ 7 ] = max.y; vertices[ 8 ] = max.z;
  20062. vertices[ 9 ] = min.x; vertices[ 10 ] = min.y; vertices[ 11 ] = max.z;
  20063. vertices[ 12 ] = min.x; vertices[ 13 ] = min.y; vertices[ 14 ] = max.z;
  20064. vertices[ 15 ] = max.x; vertices[ 16 ] = min.y; vertices[ 17 ] = max.z;
  20065. vertices[ 18 ] = max.x; vertices[ 19 ] = min.y; vertices[ 20 ] = max.z;
  20066. vertices[ 21 ] = max.x; vertices[ 22 ] = max.y; vertices[ 23 ] = max.z;
  20067. //
  20068. vertices[ 24 ] = max.x; vertices[ 25 ] = max.y; vertices[ 26 ] = min.z;
  20069. vertices[ 27 ] = min.x; vertices[ 28 ] = max.y; vertices[ 29 ] = min.z;
  20070. vertices[ 30 ] = min.x; vertices[ 31 ] = max.y; vertices[ 32 ] = min.z;
  20071. vertices[ 33 ] = min.x; vertices[ 34 ] = min.y; vertices[ 35 ] = min.z;
  20072. vertices[ 36 ] = min.x; vertices[ 37 ] = min.y; vertices[ 38 ] = min.z;
  20073. vertices[ 39 ] = max.x; vertices[ 40 ] = min.y; vertices[ 41 ] = min.z;
  20074. vertices[ 42 ] = max.x; vertices[ 43 ] = min.y; vertices[ 44 ] = min.z;
  20075. vertices[ 45 ] = max.x; vertices[ 46 ] = max.y; vertices[ 47 ] = min.z;
  20076. //
  20077. vertices[ 48 ] = max.x; vertices[ 49 ] = max.y; vertices[ 50 ] = max.z;
  20078. vertices[ 51 ] = max.x; vertices[ 52 ] = max.y; vertices[ 53 ] = min.z;
  20079. vertices[ 54 ] = min.x; vertices[ 55 ] = max.y; vertices[ 56 ] = max.z;
  20080. vertices[ 57 ] = min.x; vertices[ 58 ] = max.y; vertices[ 59 ] = min.z;
  20081. vertices[ 60 ] = min.x; vertices[ 61 ] = min.y; vertices[ 62 ] = max.z;
  20082. vertices[ 63 ] = min.x; vertices[ 64 ] = min.y; vertices[ 65 ] = min.z;
  20083. vertices[ 66 ] = max.x; vertices[ 67 ] = min.y; vertices[ 68 ] = max.z;
  20084. vertices[ 69 ] = max.x; vertices[ 70 ] = min.y; vertices[ 71 ] = min.z;
  20085. this.geometry.attributes.position.needsUpdate = true;
  20086. this.geometry.computeBoundingSphere();
  20087. this.matrix = object.matrixWorld;
  20088. this.matrixAutoUpdate = false;
  20089. };
  20090. // File:src/extras/helpers/BoundingBoxHelper.js
  20091. /**
  20092. * @author WestLangley / http://github.com/WestLangley
  20093. */
  20094. // a helper to show the world-axis-aligned bounding box for an object
  20095. THREE.BoundingBoxHelper = function ( object, hex ) {
  20096. var color = ( hex !== undefined ) ? hex : 0x888888;
  20097. this.object = object;
  20098. this.box = new THREE.Box3();
  20099. THREE.Mesh.call( this, new THREE.BoxGeometry( 1, 1, 1 ), new THREE.MeshBasicMaterial( { color: color, wireframe: true } ) );
  20100. };
  20101. THREE.BoundingBoxHelper.prototype = Object.create( THREE.Mesh.prototype );
  20102. THREE.BoundingBoxHelper.prototype.constructor = THREE.BoundingBoxHelper;
  20103. THREE.BoundingBoxHelper.prototype.update = function () {
  20104. this.box.setFromObject( this.object );
  20105. this.box.size( this.scale );
  20106. this.box.center( this.position );
  20107. };
  20108. // File:src/extras/helpers/CameraHelper.js
  20109. /**
  20110. * @author alteredq / http://alteredqualia.com/
  20111. *
  20112. * - shows frustum, line of sight and up of the camera
  20113. * - suitable for fast updates
  20114. * - based on frustum visualization in lightgl.js shadowmap example
  20115. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  20116. */
  20117. THREE.CameraHelper = function ( camera ) {
  20118. var geometry = new THREE.Geometry();
  20119. var material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  20120. var pointMap = {};
  20121. // colors
  20122. var hexFrustum = 0xffaa00;
  20123. var hexCone = 0xff0000;
  20124. var hexUp = 0x00aaff;
  20125. var hexTarget = 0xffffff;
  20126. var hexCross = 0x333333;
  20127. // near
  20128. addLine( "n1", "n2", hexFrustum );
  20129. addLine( "n2", "n4", hexFrustum );
  20130. addLine( "n4", "n3", hexFrustum );
  20131. addLine( "n3", "n1", hexFrustum );
  20132. // far
  20133. addLine( "f1", "f2", hexFrustum );
  20134. addLine( "f2", "f4", hexFrustum );
  20135. addLine( "f4", "f3", hexFrustum );
  20136. addLine( "f3", "f1", hexFrustum );
  20137. // sides
  20138. addLine( "n1", "f1", hexFrustum );
  20139. addLine( "n2", "f2", hexFrustum );
  20140. addLine( "n3", "f3", hexFrustum );
  20141. addLine( "n4", "f4", hexFrustum );
  20142. // cone
  20143. addLine( "p", "n1", hexCone );
  20144. addLine( "p", "n2", hexCone );
  20145. addLine( "p", "n3", hexCone );
  20146. addLine( "p", "n4", hexCone );
  20147. // up
  20148. addLine( "u1", "u2", hexUp );
  20149. addLine( "u2", "u3", hexUp );
  20150. addLine( "u3", "u1", hexUp );
  20151. // target
  20152. addLine( "c", "t", hexTarget );
  20153. addLine( "p", "c", hexCross );
  20154. // cross
  20155. addLine( "cn1", "cn2", hexCross );
  20156. addLine( "cn3", "cn4", hexCross );
  20157. addLine( "cf1", "cf2", hexCross );
  20158. addLine( "cf3", "cf4", hexCross );
  20159. function addLine( a, b, hex ) {
  20160. addPoint( a, hex );
  20161. addPoint( b, hex );
  20162. }
  20163. function addPoint( id, hex ) {
  20164. geometry.vertices.push( new THREE.Vector3() );
  20165. geometry.colors.push( new THREE.Color( hex ) );
  20166. if ( pointMap[ id ] === undefined ) {
  20167. pointMap[ id ] = [];
  20168. }
  20169. pointMap[ id ].push( geometry.vertices.length - 1 );
  20170. }
  20171. THREE.LineSegments.call( this, geometry, material );
  20172. this.camera = camera;
  20173. this.matrix = camera.matrixWorld;
  20174. this.matrixAutoUpdate = false;
  20175. this.pointMap = pointMap;
  20176. this.update();
  20177. };
  20178. THREE.CameraHelper.prototype = Object.create( THREE.LineSegments.prototype );
  20179. THREE.CameraHelper.prototype.constructor = THREE.CameraHelper;
  20180. THREE.CameraHelper.prototype.update = function () {
  20181. var geometry, pointMap;
  20182. var vector = new THREE.Vector3();
  20183. var camera = new THREE.Camera();
  20184. var setPoint = function ( point, x, y, z ) {
  20185. vector.set( x, y, z ).unproject( camera );
  20186. var points = pointMap[ point ];
  20187. if ( points !== undefined ) {
  20188. for ( var i = 0, il = points.length; i < il; i ++ ) {
  20189. geometry.vertices[ points[ i ] ].copy( vector );
  20190. }
  20191. }
  20192. };
  20193. return function () {
  20194. geometry = this.geometry;
  20195. pointMap = this.pointMap;
  20196. var w = 1, h = 1;
  20197. // we need just camera projection matrix
  20198. // world matrix must be identity
  20199. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  20200. // center / target
  20201. setPoint( "c", 0, 0, - 1 );
  20202. setPoint( "t", 0, 0, 1 );
  20203. // near
  20204. setPoint( "n1", - w, - h, - 1 );
  20205. setPoint( "n2", w, - h, - 1 );
  20206. setPoint( "n3", - w, h, - 1 );
  20207. setPoint( "n4", w, h, - 1 );
  20208. // far
  20209. setPoint( "f1", - w, - h, 1 );
  20210. setPoint( "f2", w, - h, 1 );
  20211. setPoint( "f3", - w, h, 1 );
  20212. setPoint( "f4", w, h, 1 );
  20213. // up
  20214. setPoint( "u1", w * 0.7, h * 1.1, - 1 );
  20215. setPoint( "u2", - w * 0.7, h * 1.1, - 1 );
  20216. setPoint( "u3", 0, h * 2, - 1 );
  20217. // cross
  20218. setPoint( "cf1", - w, 0, 1 );
  20219. setPoint( "cf2", w, 0, 1 );
  20220. setPoint( "cf3", 0, - h, 1 );
  20221. setPoint( "cf4", 0, h, 1 );
  20222. setPoint( "cn1", - w, 0, - 1 );
  20223. setPoint( "cn2", w, 0, - 1 );
  20224. setPoint( "cn3", 0, - h, - 1 );
  20225. setPoint( "cn4", 0, h, - 1 );
  20226. geometry.verticesNeedUpdate = true;
  20227. };
  20228. }();
  20229. // File:src/extras/helpers/DirectionalLightHelper.js
  20230. /**
  20231. * @author alteredq / http://alteredqualia.com/
  20232. * @author mrdoob / http://mrdoob.com/
  20233. * @author WestLangley / http://github.com/WestLangley
  20234. */
  20235. THREE.DirectionalLightHelper = function ( light, size ) {
  20236. THREE.Object3D.call( this );
  20237. this.light = light;
  20238. this.light.updateMatrixWorld();
  20239. this.matrix = light.matrixWorld;
  20240. this.matrixAutoUpdate = false;
  20241. size = size || 1;
  20242. var geometry = new THREE.Geometry();
  20243. geometry.vertices.push(
  20244. new THREE.Vector3( - size, size, 0 ),
  20245. new THREE.Vector3( size, size, 0 ),
  20246. new THREE.Vector3( size, - size, 0 ),
  20247. new THREE.Vector3( - size, - size, 0 ),
  20248. new THREE.Vector3( - size, size, 0 )
  20249. );
  20250. var material = new THREE.LineBasicMaterial( { fog: false } );
  20251. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20252. this.lightPlane = new THREE.Line( geometry, material );
  20253. this.add( this.lightPlane );
  20254. geometry = new THREE.Geometry();
  20255. geometry.vertices.push(
  20256. new THREE.Vector3(),
  20257. new THREE.Vector3()
  20258. );
  20259. material = new THREE.LineBasicMaterial( { fog: false } );
  20260. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20261. this.targetLine = new THREE.Line( geometry, material );
  20262. this.add( this.targetLine );
  20263. this.update();
  20264. };
  20265. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20266. THREE.DirectionalLightHelper.prototype.constructor = THREE.DirectionalLightHelper;
  20267. THREE.DirectionalLightHelper.prototype.dispose = function () {
  20268. this.lightPlane.geometry.dispose();
  20269. this.lightPlane.material.dispose();
  20270. this.targetLine.geometry.dispose();
  20271. this.targetLine.material.dispose();
  20272. };
  20273. THREE.DirectionalLightHelper.prototype.update = function () {
  20274. var v1 = new THREE.Vector3();
  20275. var v2 = new THREE.Vector3();
  20276. var v3 = new THREE.Vector3();
  20277. return function () {
  20278. v1.setFromMatrixPosition( this.light.matrixWorld );
  20279. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  20280. v3.subVectors( v2, v1 );
  20281. this.lightPlane.lookAt( v3 );
  20282. this.lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20283. this.targetLine.geometry.vertices[ 1 ].copy( v3 );
  20284. this.targetLine.geometry.verticesNeedUpdate = true;
  20285. this.targetLine.material.color.copy( this.lightPlane.material.color );
  20286. };
  20287. }();
  20288. // File:src/extras/helpers/EdgesHelper.js
  20289. /**
  20290. * @author WestLangley / http://github.com/WestLangley
  20291. * @param object THREE.Mesh whose geometry will be used
  20292. * @param hex line color
  20293. * @param thresholdAngle the minimim angle (in degrees),
  20294. * between the face normals of adjacent faces,
  20295. * that is required to render an edge. A value of 10 means
  20296. * an edge is only rendered if the angle is at least 10 degrees.
  20297. */
  20298. THREE.EdgesHelper = function ( object, hex, thresholdAngle ) {
  20299. var color = ( hex !== undefined ) ? hex : 0xffffff;
  20300. THREE.LineSegments.call( this, new THREE.EdgesGeometry( object.geometry, thresholdAngle ), new THREE.LineBasicMaterial( { color: color } ) );
  20301. this.matrix = object.matrixWorld;
  20302. this.matrixAutoUpdate = false;
  20303. };
  20304. THREE.EdgesHelper.prototype = Object.create( THREE.LineSegments.prototype );
  20305. THREE.EdgesHelper.prototype.constructor = THREE.EdgesHelper;
  20306. // File:src/extras/helpers/FaceNormalsHelper.js
  20307. /**
  20308. * @author mrdoob / http://mrdoob.com/
  20309. * @author WestLangley / http://github.com/WestLangley
  20310. */
  20311. THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) {
  20312. this.object = object;
  20313. this.size = ( size !== undefined ) ? size : 1;
  20314. var color = ( hex !== undefined ) ? hex : 0xffff00;
  20315. var width = ( linewidth !== undefined ) ? linewidth : 1;
  20316. var geometry = new THREE.Geometry();
  20317. var faces = this.object.geometry.faces;
  20318. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20319. geometry.vertices.push( new THREE.Vector3(), new THREE.Vector3() );
  20320. }
  20321. THREE.LineSegments.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ) );
  20322. this.matrixAutoUpdate = false;
  20323. this.normalMatrix = new THREE.Matrix3();
  20324. this.update();
  20325. };
  20326. THREE.FaceNormalsHelper.prototype = Object.create( THREE.LineSegments.prototype );
  20327. THREE.FaceNormalsHelper.prototype.constructor = THREE.FaceNormalsHelper;
  20328. THREE.FaceNormalsHelper.prototype.update = function () {
  20329. var vertices = this.geometry.vertices;
  20330. var object = this.object;
  20331. var objectVertices = object.geometry.vertices;
  20332. var objectFaces = object.geometry.faces;
  20333. var objectWorldMatrix = object.matrixWorld;
  20334. object.updateMatrixWorld( true );
  20335. this.normalMatrix.getNormalMatrix( objectWorldMatrix );
  20336. for ( var i = 0, i2 = 0, l = objectFaces.length; i < l; i ++, i2 += 2 ) {
  20337. var face = objectFaces[ i ];
  20338. vertices[ i2 ].copy( objectVertices[ face.a ] )
  20339. .add( objectVertices[ face.b ] )
  20340. .add( objectVertices[ face.c ] )
  20341. .divideScalar( 3 )
  20342. .applyMatrix4( objectWorldMatrix );
  20343. vertices[ i2 + 1 ].copy( face.normal )
  20344. .applyMatrix3( this.normalMatrix )
  20345. .normalize()
  20346. .multiplyScalar( this.size )
  20347. .add( vertices[ i2 ] );
  20348. }
  20349. this.geometry.verticesNeedUpdate = true;
  20350. return this;
  20351. };
  20352. // File:src/extras/helpers/GridHelper.js
  20353. /**
  20354. * @author mrdoob / http://mrdoob.com/
  20355. */
  20356. THREE.GridHelper = function ( size, step ) {
  20357. var geometry = new THREE.Geometry();
  20358. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20359. this.color1 = new THREE.Color( 0x444444 );
  20360. this.color2 = new THREE.Color( 0x888888 );
  20361. for ( var i = - size; i <= size; i += step ) {
  20362. geometry.vertices.push(
  20363. new THREE.Vector3( - size, 0, i ), new THREE.Vector3( size, 0, i ),
  20364. new THREE.Vector3( i, 0, - size ), new THREE.Vector3( i, 0, size )
  20365. );
  20366. var color = i === 0 ? this.color1 : this.color2;
  20367. geometry.colors.push( color, color, color, color );
  20368. }
  20369. THREE.LineSegments.call( this, geometry, material );
  20370. };
  20371. THREE.GridHelper.prototype = Object.create( THREE.LineSegments.prototype );
  20372. THREE.GridHelper.prototype.constructor = THREE.GridHelper;
  20373. THREE.GridHelper.prototype.setColors = function( colorCenterLine, colorGrid ) {
  20374. this.color1.set( colorCenterLine );
  20375. this.color2.set( colorGrid );
  20376. this.geometry.colorsNeedUpdate = true;
  20377. };
  20378. // File:src/extras/helpers/HemisphereLightHelper.js
  20379. /**
  20380. * @author alteredq / http://alteredqualia.com/
  20381. * @author mrdoob / http://mrdoob.com/
  20382. */
  20383. THREE.HemisphereLightHelper = function ( light, sphereSize ) {
  20384. THREE.Object3D.call( this );
  20385. this.light = light;
  20386. this.light.updateMatrixWorld();
  20387. this.matrix = light.matrixWorld;
  20388. this.matrixAutoUpdate = false;
  20389. this.colors = [ new THREE.Color(), new THREE.Color() ];
  20390. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20391. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  20392. for ( var i = 0, il = 8; i < il; i ++ ) {
  20393. geometry.faces[ i ].color = this.colors[ i < 4 ? 0 : 1 ];
  20394. }
  20395. var material = new THREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors, wireframe: true } );
  20396. this.lightSphere = new THREE.Mesh( geometry, material );
  20397. this.add( this.lightSphere );
  20398. this.update();
  20399. };
  20400. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20401. THREE.HemisphereLightHelper.prototype.constructor = THREE.HemisphereLightHelper;
  20402. THREE.HemisphereLightHelper.prototype.dispose = function () {
  20403. this.lightSphere.geometry.dispose();
  20404. this.lightSphere.material.dispose();
  20405. };
  20406. THREE.HemisphereLightHelper.prototype.update = function () {
  20407. var vector = new THREE.Vector3();
  20408. return function () {
  20409. this.colors[ 0 ].copy( this.light.color ).multiplyScalar( this.light.intensity );
  20410. this.colors[ 1 ].copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  20411. this.lightSphere.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  20412. this.lightSphere.geometry.colorsNeedUpdate = true;
  20413. }
  20414. }();
  20415. // File:src/extras/helpers/PointLightHelper.js
  20416. /**
  20417. * @author alteredq / http://alteredqualia.com/
  20418. * @author mrdoob / http://mrdoob.com/
  20419. */
  20420. THREE.PointLightHelper = function ( light, sphereSize ) {
  20421. this.light = light;
  20422. this.light.updateMatrixWorld();
  20423. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20424. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  20425. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20426. THREE.Mesh.call( this, geometry, material );
  20427. this.matrix = this.light.matrixWorld;
  20428. this.matrixAutoUpdate = false;
  20429. /*
  20430. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  20431. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  20432. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20433. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  20434. var d = light.distance;
  20435. if ( d === 0.0 ) {
  20436. this.lightDistance.visible = false;
  20437. } else {
  20438. this.lightDistance.scale.set( d, d, d );
  20439. }
  20440. this.add( this.lightDistance );
  20441. */
  20442. };
  20443. THREE.PointLightHelper.prototype = Object.create( THREE.Mesh.prototype );
  20444. THREE.PointLightHelper.prototype.constructor = THREE.PointLightHelper;
  20445. THREE.PointLightHelper.prototype.dispose = function () {
  20446. this.geometry.dispose();
  20447. this.material.dispose();
  20448. };
  20449. THREE.PointLightHelper.prototype.update = function () {
  20450. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20451. /*
  20452. var d = this.light.distance;
  20453. if ( d === 0.0 ) {
  20454. this.lightDistance.visible = false;
  20455. } else {
  20456. this.lightDistance.visible = true;
  20457. this.lightDistance.scale.set( d, d, d );
  20458. }
  20459. */
  20460. };
  20461. // File:src/extras/helpers/SkeletonHelper.js
  20462. /**
  20463. * @author Sean Griffin / http://twitter.com/sgrif
  20464. * @author Michael Guerrero / http://realitymeltdown.com
  20465. * @author mrdoob / http://mrdoob.com/
  20466. * @author ikerr / http://verold.com
  20467. */
  20468. THREE.SkeletonHelper = function ( object ) {
  20469. this.bones = this.getBoneList( object );
  20470. var geometry = new THREE.Geometry();
  20471. for ( var i = 0; i < this.bones.length; i ++ ) {
  20472. var bone = this.bones[ i ];
  20473. if ( bone.parent instanceof THREE.Bone ) {
  20474. geometry.vertices.push( new THREE.Vector3() );
  20475. geometry.vertices.push( new THREE.Vector3() );
  20476. geometry.colors.push( new THREE.Color( 0, 0, 1 ) );
  20477. geometry.colors.push( new THREE.Color( 0, 1, 0 ) );
  20478. }
  20479. }
  20480. geometry.dynamic = true;
  20481. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors, depthTest: false, depthWrite: false, transparent: true } );
  20482. THREE.LineSegments.call( this, geometry, material );
  20483. this.root = object;
  20484. this.matrix = object.matrixWorld;
  20485. this.matrixAutoUpdate = false;
  20486. this.update();
  20487. };
  20488. THREE.SkeletonHelper.prototype = Object.create( THREE.LineSegments.prototype );
  20489. THREE.SkeletonHelper.prototype.constructor = THREE.SkeletonHelper;
  20490. THREE.SkeletonHelper.prototype.getBoneList = function( object ) {
  20491. var boneList = [];
  20492. if ( object instanceof THREE.Bone ) {
  20493. boneList.push( object );
  20494. }
  20495. for ( var i = 0; i < object.children.length; i ++ ) {
  20496. boneList.push.apply( boneList, this.getBoneList( object.children[ i ] ) );
  20497. }
  20498. return boneList;
  20499. };
  20500. THREE.SkeletonHelper.prototype.update = function () {
  20501. var geometry = this.geometry;
  20502. var matrixWorldInv = new THREE.Matrix4().getInverse( this.root.matrixWorld );
  20503. var boneMatrix = new THREE.Matrix4();
  20504. var j = 0;
  20505. for ( var i = 0; i < this.bones.length; i ++ ) {
  20506. var bone = this.bones[ i ];
  20507. if ( bone.parent instanceof THREE.Bone ) {
  20508. boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld );
  20509. geometry.vertices[ j ].setFromMatrixPosition( boneMatrix );
  20510. boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld );
  20511. geometry.vertices[ j + 1 ].setFromMatrixPosition( boneMatrix );
  20512. j += 2;
  20513. }
  20514. }
  20515. geometry.verticesNeedUpdate = true;
  20516. geometry.computeBoundingSphere();
  20517. };
  20518. // File:src/extras/helpers/SpotLightHelper.js
  20519. /**
  20520. * @author alteredq / http://alteredqualia.com/
  20521. * @author mrdoob / http://mrdoob.com/
  20522. * @author WestLangley / http://github.com/WestLangley
  20523. */
  20524. THREE.SpotLightHelper = function ( light ) {
  20525. THREE.Object3D.call( this );
  20526. this.light = light;
  20527. this.light.updateMatrixWorld();
  20528. this.matrix = light.matrixWorld;
  20529. this.matrixAutoUpdate = false;
  20530. var geometry = new THREE.CylinderGeometry( 0, 1, 1, 8, 1, true );
  20531. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, - 0.5, 0 ) );
  20532. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  20533. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  20534. this.cone = new THREE.Mesh( geometry, material );
  20535. this.add( this.cone );
  20536. this.update();
  20537. };
  20538. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20539. THREE.SpotLightHelper.prototype.constructor = THREE.SpotLightHelper;
  20540. THREE.SpotLightHelper.prototype.dispose = function () {
  20541. this.cone.geometry.dispose();
  20542. this.cone.material.dispose();
  20543. };
  20544. THREE.SpotLightHelper.prototype.update = function () {
  20545. var vector = new THREE.Vector3();
  20546. var vector2 = new THREE.Vector3();
  20547. return function () {
  20548. var coneLength = this.light.distance ? this.light.distance : 10000;
  20549. var coneWidth = coneLength * Math.tan( this.light.angle );
  20550. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  20551. vector.setFromMatrixPosition( this.light.matrixWorld );
  20552. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  20553. this.cone.lookAt( vector2.sub( vector ) );
  20554. this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20555. };
  20556. }();
  20557. // File:src/extras/helpers/VertexNormalsHelper.js
  20558. /**
  20559. * @author mrdoob / http://mrdoob.com/
  20560. * @author WestLangley / http://github.com/WestLangley
  20561. */
  20562. THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) {
  20563. this.object = object;
  20564. this.size = ( size !== undefined ) ? size : 1;
  20565. var color = ( hex !== undefined ) ? hex : 0xff0000;
  20566. var width = ( linewidth !== undefined ) ? linewidth : 1;
  20567. var geometry = new THREE.Geometry();
  20568. var faces = object.geometry.faces;
  20569. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20570. var face = faces[ i ];
  20571. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  20572. geometry.vertices.push( new THREE.Vector3(), new THREE.Vector3() );
  20573. }
  20574. }
  20575. THREE.LineSegments.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ) );
  20576. this.matrixAutoUpdate = false;
  20577. this.normalMatrix = new THREE.Matrix3();
  20578. this.update();
  20579. };
  20580. THREE.VertexNormalsHelper.prototype = Object.create( THREE.LineSegments.prototype );
  20581. THREE.VertexNormalsHelper.prototype.constructor = THREE.VertexNormalsHelper;
  20582. THREE.VertexNormalsHelper.prototype.update = ( function ( object ) {
  20583. var v1 = new THREE.Vector3();
  20584. return function( object ) {
  20585. var keys = [ 'a', 'b', 'c', 'd' ];
  20586. this.object.updateMatrixWorld( true );
  20587. this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
  20588. var vertices = this.geometry.vertices;
  20589. var verts = this.object.geometry.vertices;
  20590. var faces = this.object.geometry.faces;
  20591. var worldMatrix = this.object.matrixWorld;
  20592. var idx = 0;
  20593. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20594. var face = faces[ i ];
  20595. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  20596. var vertexId = face[ keys[ j ] ];
  20597. var vertex = verts[ vertexId ];
  20598. var normal = face.vertexNormals[ j ];
  20599. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  20600. v1.copy( normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
  20601. v1.add( vertices[ idx ] );
  20602. idx = idx + 1;
  20603. vertices[ idx ].copy( v1 );
  20604. idx = idx + 1;
  20605. }
  20606. }
  20607. this.geometry.verticesNeedUpdate = true;
  20608. return this;
  20609. }
  20610. }());
  20611. // File:src/extras/helpers/VertexTangentsHelper.js
  20612. /**
  20613. * @author mrdoob / http://mrdoob.com/
  20614. * @author WestLangley / http://github.com/WestLangley
  20615. */
  20616. THREE.VertexTangentsHelper = function ( object, size, hex, linewidth ) {
  20617. this.object = object;
  20618. this.size = ( size !== undefined ) ? size : 1;
  20619. var color = ( hex !== undefined ) ? hex : 0x0000ff;
  20620. var width = ( linewidth !== undefined ) ? linewidth : 1;
  20621. var geometry = new THREE.Geometry();
  20622. var faces = object.geometry.faces;
  20623. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20624. var face = faces[ i ];
  20625. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  20626. geometry.vertices.push( new THREE.Vector3() );
  20627. geometry.vertices.push( new THREE.Vector3() );
  20628. }
  20629. }
  20630. THREE.LineSegments.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ) );
  20631. this.matrixAutoUpdate = false;
  20632. this.update();
  20633. };
  20634. THREE.VertexTangentsHelper.prototype = Object.create( THREE.LineSegments.prototype );
  20635. THREE.VertexTangentsHelper.prototype.constructor = THREE.VertexTangentsHelper;
  20636. THREE.VertexTangentsHelper.prototype.update = ( function ( object ) {
  20637. var v1 = new THREE.Vector3();
  20638. return function( object ) {
  20639. var keys = [ 'a', 'b', 'c', 'd' ];
  20640. this.object.updateMatrixWorld( true );
  20641. var vertices = this.geometry.vertices;
  20642. var verts = this.object.geometry.vertices;
  20643. var faces = this.object.geometry.faces;
  20644. var worldMatrix = this.object.matrixWorld;
  20645. var idx = 0;
  20646. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20647. var face = faces[ i ];
  20648. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  20649. var vertexId = face[ keys[ j ] ];
  20650. var vertex = verts[ vertexId ];
  20651. var tangent = face.vertexTangents[ j ];
  20652. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  20653. v1.copy( tangent ).transformDirection( worldMatrix ).multiplyScalar( this.size );
  20654. v1.add( vertices[ idx ] );
  20655. idx = idx + 1;
  20656. vertices[ idx ].copy( v1 );
  20657. idx = idx + 1;
  20658. }
  20659. }
  20660. this.geometry.verticesNeedUpdate = true;
  20661. return this;
  20662. }
  20663. }());
  20664. // File:src/extras/helpers/WireframeHelper.js
  20665. /**
  20666. * @author mrdoob / http://mrdoob.com/
  20667. */
  20668. THREE.WireframeHelper = function ( object, hex ) {
  20669. var color = ( hex !== undefined ) ? hex : 0xffffff;
  20670. THREE.LineSegments.call( this, new THREE.WireframeGeometry( object.geometry ), new THREE.LineBasicMaterial( { color: color } ) );
  20671. this.matrix = object.matrixWorld;
  20672. this.matrixAutoUpdate = false;
  20673. };
  20674. THREE.WireframeHelper.prototype = Object.create( THREE.LineSegments.prototype );
  20675. THREE.WireframeHelper.prototype.constructor = THREE.WireframeHelper;
  20676. // File:src/extras/objects/ImmediateRenderObject.js
  20677. /**
  20678. * @author alteredq / http://alteredqualia.com/
  20679. */
  20680. THREE.ImmediateRenderObject = function () {
  20681. THREE.Object3D.call( this );
  20682. this.render = function ( renderCallback ) {};
  20683. };
  20684. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  20685. THREE.ImmediateRenderObject.prototype.constructor = THREE.ImmediateRenderObject;
  20686. // File:src/extras/objects/MorphBlendMesh.js
  20687. /**
  20688. * @author alteredq / http://alteredqualia.com/
  20689. */
  20690. THREE.MorphBlendMesh = function( geometry, material ) {
  20691. THREE.Mesh.call( this, geometry, material );
  20692. this.animationsMap = {};
  20693. this.animationsList = [];
  20694. // prepare default animation
  20695. // (all frames played together in 1 second)
  20696. var numFrames = this.geometry.morphTargets.length;
  20697. var name = "__default";
  20698. var startFrame = 0;
  20699. var endFrame = numFrames - 1;
  20700. var fps = numFrames / 1;
  20701. this.createAnimation( name, startFrame, endFrame, fps );
  20702. this.setAnimationWeight( name, 1 );
  20703. };
  20704. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  20705. THREE.MorphBlendMesh.prototype.constructor = THREE.MorphBlendMesh;
  20706. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  20707. var animation = {
  20708. startFrame: start,
  20709. endFrame: end,
  20710. length: end - start + 1,
  20711. fps: fps,
  20712. duration: ( end - start ) / fps,
  20713. lastFrame: 0,
  20714. currentFrame: 0,
  20715. active: false,
  20716. time: 0,
  20717. direction: 1,
  20718. weight: 1,
  20719. directionBackwards: false,
  20720. mirroredLoop: false
  20721. };
  20722. this.animationsMap[ name ] = animation;
  20723. this.animationsList.push( animation );
  20724. };
  20725. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  20726. var pattern = /([a-z]+)_?(\d+)/;
  20727. var firstAnimation, frameRanges = {};
  20728. var geometry = this.geometry;
  20729. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  20730. var morph = geometry.morphTargets[ i ];
  20731. var chunks = morph.name.match( pattern );
  20732. if ( chunks && chunks.length > 1 ) {
  20733. var name = chunks[ 1 ];
  20734. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: - Infinity };
  20735. var range = frameRanges[ name ];
  20736. if ( i < range.start ) range.start = i;
  20737. if ( i > range.end ) range.end = i;
  20738. if ( ! firstAnimation ) firstAnimation = name;
  20739. }
  20740. }
  20741. for ( var name in frameRanges ) {
  20742. var range = frameRanges[ name ];
  20743. this.createAnimation( name, range.start, range.end, fps );
  20744. }
  20745. this.firstAnimation = firstAnimation;
  20746. };
  20747. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  20748. var animation = this.animationsMap[ name ];
  20749. if ( animation ) {
  20750. animation.direction = 1;
  20751. animation.directionBackwards = false;
  20752. }
  20753. };
  20754. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  20755. var animation = this.animationsMap[ name ];
  20756. if ( animation ) {
  20757. animation.direction = - 1;
  20758. animation.directionBackwards = true;
  20759. }
  20760. };
  20761. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  20762. var animation = this.animationsMap[ name ];
  20763. if ( animation ) {
  20764. animation.fps = fps;
  20765. animation.duration = ( animation.end - animation.start ) / animation.fps;
  20766. }
  20767. };
  20768. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  20769. var animation = this.animationsMap[ name ];
  20770. if ( animation ) {
  20771. animation.duration = duration;
  20772. animation.fps = ( animation.end - animation.start ) / animation.duration;
  20773. }
  20774. };
  20775. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  20776. var animation = this.animationsMap[ name ];
  20777. if ( animation ) {
  20778. animation.weight = weight;
  20779. }
  20780. };
  20781. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  20782. var animation = this.animationsMap[ name ];
  20783. if ( animation ) {
  20784. animation.time = time;
  20785. }
  20786. };
  20787. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  20788. var time = 0;
  20789. var animation = this.animationsMap[ name ];
  20790. if ( animation ) {
  20791. time = animation.time;
  20792. }
  20793. return time;
  20794. };
  20795. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  20796. var duration = - 1;
  20797. var animation = this.animationsMap[ name ];
  20798. if ( animation ) {
  20799. duration = animation.duration;
  20800. }
  20801. return duration;
  20802. };
  20803. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  20804. var animation = this.animationsMap[ name ];
  20805. if ( animation ) {
  20806. animation.time = 0;
  20807. animation.active = true;
  20808. } else {
  20809. console.warn( "THREE.MorphBlendMesh: animation[" + name + "] undefined in .playAnimation()" );
  20810. }
  20811. };
  20812. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  20813. var animation = this.animationsMap[ name ];
  20814. if ( animation ) {
  20815. animation.active = false;
  20816. }
  20817. };
  20818. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  20819. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  20820. var animation = this.animationsList[ i ];
  20821. if ( ! animation.active ) continue;
  20822. var frameTime = animation.duration / animation.length;
  20823. animation.time += animation.direction * delta;
  20824. if ( animation.mirroredLoop ) {
  20825. if ( animation.time > animation.duration || animation.time < 0 ) {
  20826. animation.direction *= - 1;
  20827. if ( animation.time > animation.duration ) {
  20828. animation.time = animation.duration;
  20829. animation.directionBackwards = true;
  20830. }
  20831. if ( animation.time < 0 ) {
  20832. animation.time = 0;
  20833. animation.directionBackwards = false;
  20834. }
  20835. }
  20836. } else {
  20837. animation.time = animation.time % animation.duration;
  20838. if ( animation.time < 0 ) animation.time += animation.duration;
  20839. }
  20840. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  20841. var weight = animation.weight;
  20842. if ( keyframe !== animation.currentFrame ) {
  20843. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  20844. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  20845. this.morphTargetInfluences[ keyframe ] = 0;
  20846. animation.lastFrame = animation.currentFrame;
  20847. animation.currentFrame = keyframe;
  20848. }
  20849. var mix = ( animation.time % frameTime ) / frameTime;
  20850. if ( animation.directionBackwards ) mix = 1 - mix;
  20851. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  20852. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  20853. }
  20854. };