three.js 788 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021
  1. // File:src/Three.js
  2. /**
  3. * @author mrdoob / http://mrdoob.com/
  4. */
  5. var THREE = { REVISION: '71dev' };
  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. // set the default log handlers
  18. THREE.log = function() { console.log.apply( console, arguments ); }
  19. THREE.warn = function() { console.warn.apply( console, arguments ); }
  20. THREE.error = function() { console.error.apply( console, arguments ); }
  21. // https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent.button
  22. THREE.MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2 };
  23. // GL STATE CONSTANTS
  24. THREE.CullFaceNone = 0;
  25. THREE.CullFaceBack = 1;
  26. THREE.CullFaceFront = 2;
  27. THREE.CullFaceFrontBack = 3;
  28. THREE.FrontFaceDirectionCW = 0;
  29. THREE.FrontFaceDirectionCCW = 1;
  30. // SHADOWING TYPES
  31. THREE.BasicShadowMap = 0;
  32. THREE.PCFShadowMap = 1;
  33. THREE.PCFSoftShadowMap = 2;
  34. // MATERIAL CONSTANTS
  35. // side
  36. THREE.FrontSide = 0;
  37. THREE.BackSide = 1;
  38. THREE.DoubleSide = 2;
  39. // shading
  40. THREE.NoShading = 0;
  41. THREE.FlatShading = 1;
  42. THREE.SmoothShading = 2;
  43. // colors
  44. THREE.NoColors = 0;
  45. THREE.FaceColors = 1;
  46. THREE.VertexColors = 2;
  47. // blending modes
  48. THREE.NoBlending = 0;
  49. THREE.NormalBlending = 1;
  50. THREE.AdditiveBlending = 2;
  51. THREE.SubtractiveBlending = 3;
  52. THREE.MultiplyBlending = 4;
  53. THREE.CustomBlending = 5;
  54. // custom blending equations
  55. // (numbers start from 100 not to clash with other
  56. // mappings to OpenGL constants defined in Texture.js)
  57. THREE.AddEquation = 100;
  58. THREE.SubtractEquation = 101;
  59. THREE.ReverseSubtractEquation = 102;
  60. THREE.MinEquation = 103;
  61. THREE.MaxEquation = 104;
  62. // custom blending destination factors
  63. THREE.ZeroFactor = 200;
  64. THREE.OneFactor = 201;
  65. THREE.SrcColorFactor = 202;
  66. THREE.OneMinusSrcColorFactor = 203;
  67. THREE.SrcAlphaFactor = 204;
  68. THREE.OneMinusSrcAlphaFactor = 205;
  69. THREE.DstAlphaFactor = 206;
  70. THREE.OneMinusDstAlphaFactor = 207;
  71. // custom blending source factors
  72. //THREE.ZeroFactor = 200;
  73. //THREE.OneFactor = 201;
  74. //THREE.SrcAlphaFactor = 204;
  75. //THREE.OneMinusSrcAlphaFactor = 205;
  76. //THREE.DstAlphaFactor = 206;
  77. //THREE.OneMinusDstAlphaFactor = 207;
  78. THREE.DstColorFactor = 208;
  79. THREE.OneMinusDstColorFactor = 209;
  80. THREE.SrcAlphaSaturateFactor = 210;
  81. // TEXTURE CONSTANTS
  82. THREE.MultiplyOperation = 0;
  83. THREE.MixOperation = 1;
  84. THREE.AddOperation = 2;
  85. // Mapping modes
  86. THREE.UVMapping = 300;
  87. THREE.CubeReflectionMapping = 301;
  88. THREE.CubeRefractionMapping = 302;
  89. THREE.EquirectangularReflectionMapping = 303;
  90. THREE.EquirectangularRefractionMapping = 304;
  91. THREE.SphericalReflectionMapping = 305;
  92. // Wrapping modes
  93. THREE.RepeatWrapping = 1000;
  94. THREE.ClampToEdgeWrapping = 1001;
  95. THREE.MirroredRepeatWrapping = 1002;
  96. // Filters
  97. THREE.NearestFilter = 1003;
  98. THREE.NearestMipMapNearestFilter = 1004;
  99. THREE.NearestMipMapLinearFilter = 1005;
  100. THREE.LinearFilter = 1006;
  101. THREE.LinearMipMapNearestFilter = 1007;
  102. THREE.LinearMipMapLinearFilter = 1008;
  103. // Data types
  104. THREE.UnsignedByteType = 1009;
  105. THREE.ByteType = 1010;
  106. THREE.ShortType = 1011;
  107. THREE.UnsignedShortType = 1012;
  108. THREE.IntType = 1013;
  109. THREE.UnsignedIntType = 1014;
  110. THREE.FloatType = 1015;
  111. THREE.HalfFloatType = 1025;
  112. // Pixel types
  113. //THREE.UnsignedByteType = 1009;
  114. THREE.UnsignedShort4444Type = 1016;
  115. THREE.UnsignedShort5551Type = 1017;
  116. THREE.UnsignedShort565Type = 1018;
  117. // Pixel formats
  118. THREE.AlphaFormat = 1019;
  119. THREE.RGBFormat = 1020;
  120. THREE.RGBAFormat = 1021;
  121. THREE.LuminanceFormat = 1022;
  122. THREE.LuminanceAlphaFormat = 1023;
  123. // THREE.RGBEFormat handled as THREE.RGBAFormat in shaders
  124. THREE.RGBEFormat = THREE.RGBAFormat; //1024;
  125. // DDS / ST3C Compressed texture formats
  126. THREE.RGB_S3TC_DXT1_Format = 2001;
  127. THREE.RGBA_S3TC_DXT1_Format = 2002;
  128. THREE.RGBA_S3TC_DXT3_Format = 2003;
  129. THREE.RGBA_S3TC_DXT5_Format = 2004;
  130. // PVRTC compressed texture formats
  131. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  132. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  133. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  134. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  135. // DEPRECATED
  136. THREE.Projector = function () {
  137. THREE.error( 'THREE.Projector has been moved to /examples/js/renderers/Projector.js.' );
  138. this.projectVector = function ( vector, camera ) {
  139. THREE.warn( 'THREE.Projector: .projectVector() is now vector.project().' );
  140. vector.project( camera );
  141. };
  142. this.unprojectVector = function ( vector, camera ) {
  143. THREE.warn( 'THREE.Projector: .unprojectVector() is now vector.unproject().' );
  144. vector.unproject( camera );
  145. };
  146. this.pickingRay = function ( vector, camera ) {
  147. THREE.error( 'THREE.Projector: .pickingRay() is now raycaster.setFromCamera().' );
  148. };
  149. };
  150. THREE.CanvasRenderer = function () {
  151. THREE.error( 'THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js' );
  152. this.domElement = document.createElement( 'canvas' );
  153. this.clear = function () {};
  154. this.render = function () {};
  155. this.setClearColor = function () {};
  156. this.setSize = function () {};
  157. };
  158. // File:src/math/Color.js
  159. /**
  160. * @author mrdoob / http://mrdoob.com/
  161. */
  162. THREE.Color = function ( color ) {
  163. if ( arguments.length === 3 ) {
  164. return this.setRGB( arguments[ 0 ], arguments[ 1 ], arguments[ 2 ] );
  165. }
  166. return this.set( color )
  167. };
  168. THREE.Color.prototype = {
  169. constructor: THREE.Color,
  170. r: 1, g: 1, b: 1,
  171. set: function ( value ) {
  172. if ( value instanceof THREE.Color ) {
  173. this.copy( value );
  174. } else if ( typeof value === 'number' ) {
  175. this.setHex( value );
  176. } else if ( typeof value === 'string' ) {
  177. this.setStyle( value );
  178. }
  179. return this;
  180. },
  181. setHex: function ( hex ) {
  182. hex = Math.floor( hex );
  183. this.r = ( hex >> 16 & 255 ) / 255;
  184. this.g = ( hex >> 8 & 255 ) / 255;
  185. this.b = ( hex & 255 ) / 255;
  186. return this;
  187. },
  188. setRGB: function ( r, g, b ) {
  189. this.r = r;
  190. this.g = g;
  191. this.b = b;
  192. return this;
  193. },
  194. setHSL: function ( h, s, l ) {
  195. // h,s,l ranges are in 0.0 - 1.0
  196. if ( s === 0 ) {
  197. this.r = this.g = this.b = l;
  198. } else {
  199. var hue2rgb = function ( p, q, t ) {
  200. if ( t < 0 ) t += 1;
  201. if ( t > 1 ) t -= 1;
  202. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  203. if ( t < 1 / 2 ) return q;
  204. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  205. return p;
  206. };
  207. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  208. var q = ( 2 * l ) - p;
  209. this.r = hue2rgb( q, p, h + 1 / 3 );
  210. this.g = hue2rgb( q, p, h );
  211. this.b = hue2rgb( q, p, h - 1 / 3 );
  212. }
  213. return this;
  214. },
  215. setStyle: function ( style ) {
  216. // rgb(255,0,0)
  217. if ( /^rgb\((\d+), ?(\d+), ?(\d+)\)$/i.test( style ) ) {
  218. var color = /^rgb\((\d+), ?(\d+), ?(\d+)\)$/i.exec( style );
  219. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  220. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  221. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  222. return this;
  223. }
  224. // rgb(100%,0%,0%)
  225. if ( /^rgb\((\d+)\%, ?(\d+)\%, ?(\d+)\%\)$/i.test( style ) ) {
  226. var color = /^rgb\((\d+)\%, ?(\d+)\%, ?(\d+)\%\)$/i.exec( style );
  227. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  228. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  229. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  230. return this;
  231. }
  232. // #ff0000
  233. if ( /^\#([0-9a-f]{6})$/i.test( style ) ) {
  234. var color = /^\#([0-9a-f]{6})$/i.exec( style );
  235. this.setHex( parseInt( color[ 1 ], 16 ) );
  236. return this;
  237. }
  238. // #f00
  239. if ( /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.test( style ) ) {
  240. var color = /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec( style );
  241. this.setHex( parseInt( color[ 1 ] + color[ 1 ] + color[ 2 ] + color[ 2 ] + color[ 3 ] + color[ 3 ], 16 ) );
  242. return this;
  243. }
  244. // red
  245. if ( /^(\w+)$/i.test( style ) ) {
  246. this.setHex( THREE.ColorKeywords[ style ] );
  247. return this;
  248. }
  249. },
  250. copy: function ( color ) {
  251. this.r = color.r;
  252. this.g = color.g;
  253. this.b = color.b;
  254. return this;
  255. },
  256. copyGammaToLinear: function ( color, gammaFactor ) {
  257. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  258. this.r = Math.pow( color.r, gammaFactor );
  259. this.g = Math.pow( color.g, gammaFactor );
  260. this.b = Math.pow( color.b, gammaFactor );
  261. return this;
  262. },
  263. copyLinearToGamma: function ( color, gammaFactor ) {
  264. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  265. var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  266. this.r = Math.pow( color.r, safeInverse );
  267. this.g = Math.pow( color.g, safeInverse );
  268. this.b = Math.pow( color.b, safeInverse );
  269. return this;
  270. },
  271. convertGammaToLinear: function () {
  272. var r = this.r, g = this.g, b = this.b;
  273. this.r = r * r;
  274. this.g = g * g;
  275. this.b = b * b;
  276. return this;
  277. },
  278. convertLinearToGamma: function () {
  279. this.r = Math.sqrt( this.r );
  280. this.g = Math.sqrt( this.g );
  281. this.b = Math.sqrt( this.b );
  282. return this;
  283. },
  284. getHex: function () {
  285. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  286. },
  287. getHexString: function () {
  288. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  289. },
  290. getHSL: function ( optionalTarget ) {
  291. // h,s,l ranges are in 0.0 - 1.0
  292. var hsl = optionalTarget || { h: 0, s: 0, l: 0 };
  293. var r = this.r, g = this.g, b = this.b;
  294. var max = Math.max( r, g, b );
  295. var min = Math.min( r, g, b );
  296. var hue, saturation;
  297. var lightness = ( min + max ) / 2.0;
  298. if ( min === max ) {
  299. hue = 0;
  300. saturation = 0;
  301. } else {
  302. var delta = max - min;
  303. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  304. switch ( max ) {
  305. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  306. case g: hue = ( b - r ) / delta + 2; break;
  307. case b: hue = ( r - g ) / delta + 4; break;
  308. }
  309. hue /= 6;
  310. }
  311. hsl.h = hue;
  312. hsl.s = saturation;
  313. hsl.l = lightness;
  314. return hsl;
  315. },
  316. getStyle: function () {
  317. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  318. },
  319. offsetHSL: function ( h, s, l ) {
  320. var hsl = this.getHSL();
  321. hsl.h += h; hsl.s += s; hsl.l += l;
  322. this.setHSL( hsl.h, hsl.s, hsl.l );
  323. return this;
  324. },
  325. add: function ( color ) {
  326. this.r += color.r;
  327. this.g += color.g;
  328. this.b += color.b;
  329. return this;
  330. },
  331. addColors: function ( color1, color2 ) {
  332. this.r = color1.r + color2.r;
  333. this.g = color1.g + color2.g;
  334. this.b = color1.b + color2.b;
  335. return this;
  336. },
  337. addScalar: function ( s ) {
  338. this.r += s;
  339. this.g += s;
  340. this.b += s;
  341. return this;
  342. },
  343. multiply: function ( color ) {
  344. this.r *= color.r;
  345. this.g *= color.g;
  346. this.b *= color.b;
  347. return this;
  348. },
  349. multiplyScalar: function ( s ) {
  350. this.r *= s;
  351. this.g *= s;
  352. this.b *= s;
  353. return this;
  354. },
  355. lerp: function ( color, alpha ) {
  356. this.r += ( color.r - this.r ) * alpha;
  357. this.g += ( color.g - this.g ) * alpha;
  358. this.b += ( color.b - this.b ) * alpha;
  359. return this;
  360. },
  361. equals: function ( c ) {
  362. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  363. },
  364. fromArray: function ( array ) {
  365. this.r = array[ 0 ];
  366. this.g = array[ 1 ];
  367. this.b = array[ 2 ];
  368. return this;
  369. },
  370. toArray: function ( array, offset ) {
  371. if ( array === undefined ) array = [];
  372. if ( offset === undefined ) offset = 0;
  373. array[ offset ] = this.r;
  374. array[ offset + 1 ] = this.g;
  375. array[ offset + 2 ] = this.b;
  376. return array;
  377. },
  378. clone: function () {
  379. return new THREE.Color().setRGB( this.r, this.g, this.b );
  380. }
  381. };
  382. THREE.ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  383. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  384. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  385. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  386. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  387. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  388. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  389. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  390. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  391. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  392. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  393. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  394. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  395. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  396. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  397. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  398. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  399. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  400. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  401. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  402. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  403. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  404. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  405. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  406. // File:src/math/Quaternion.js
  407. /**
  408. * @author mikael emtinger / http://gomo.se/
  409. * @author alteredq / http://alteredqualia.com/
  410. * @author WestLangley / http://github.com/WestLangley
  411. * @author bhouston / http://exocortex.com
  412. */
  413. THREE.Quaternion = function ( x, y, z, w ) {
  414. this._x = x || 0;
  415. this._y = y || 0;
  416. this._z = z || 0;
  417. this._w = ( w !== undefined ) ? w : 1;
  418. };
  419. THREE.Quaternion.prototype = {
  420. constructor: THREE.Quaternion,
  421. _x: 0,_y: 0, _z: 0, _w: 0,
  422. get x () {
  423. return this._x;
  424. },
  425. set x ( value ) {
  426. this._x = value;
  427. this.onChangeCallback();
  428. },
  429. get y () {
  430. return this._y;
  431. },
  432. set y ( value ) {
  433. this._y = value;
  434. this.onChangeCallback();
  435. },
  436. get z () {
  437. return this._z;
  438. },
  439. set z ( value ) {
  440. this._z = value;
  441. this.onChangeCallback();
  442. },
  443. get w () {
  444. return this._w;
  445. },
  446. set w ( value ) {
  447. this._w = value;
  448. this.onChangeCallback();
  449. },
  450. set: function ( x, y, z, w ) {
  451. this._x = x;
  452. this._y = y;
  453. this._z = z;
  454. this._w = w;
  455. this.onChangeCallback();
  456. return this;
  457. },
  458. copy: function ( quaternion ) {
  459. this._x = quaternion.x;
  460. this._y = quaternion.y;
  461. this._z = quaternion.z;
  462. this._w = quaternion.w;
  463. this.onChangeCallback();
  464. return this;
  465. },
  466. setFromEuler: function ( euler, update ) {
  467. if ( euler instanceof THREE.Euler === false ) {
  468. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  469. }
  470. // http://www.mathworks.com/matlabcentral/fileexchange/
  471. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  472. // content/SpinCalc.m
  473. var c1 = Math.cos( euler._x / 2 );
  474. var c2 = Math.cos( euler._y / 2 );
  475. var c3 = Math.cos( euler._z / 2 );
  476. var s1 = Math.sin( euler._x / 2 );
  477. var s2 = Math.sin( euler._y / 2 );
  478. var s3 = Math.sin( euler._z / 2 );
  479. if ( euler.order === 'XYZ' ) {
  480. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  481. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  482. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  483. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  484. } else if ( euler.order === 'YXZ' ) {
  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 === 'ZXY' ) {
  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 === 'ZYX' ) {
  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 === 'YZX' ) {
  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 === 'XZY' ) {
  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. }
  510. if ( update !== false ) this.onChangeCallback();
  511. return this;
  512. },
  513. setFromAxisAngle: function ( axis, angle ) {
  514. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  515. // assumes axis is normalized
  516. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  517. this._x = axis.x * s;
  518. this._y = axis.y * s;
  519. this._z = axis.z * s;
  520. this._w = Math.cos( halfAngle );
  521. this.onChangeCallback();
  522. return this;
  523. },
  524. setFromRotationMatrix: function ( m ) {
  525. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  526. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  527. var te = m.elements,
  528. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  529. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  530. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  531. trace = m11 + m22 + m33,
  532. s;
  533. if ( trace > 0 ) {
  534. s = 0.5 / Math.sqrt( trace + 1.0 );
  535. this._w = 0.25 / s;
  536. this._x = ( m32 - m23 ) * s;
  537. this._y = ( m13 - m31 ) * s;
  538. this._z = ( m21 - m12 ) * s;
  539. } else if ( m11 > m22 && m11 > m33 ) {
  540. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  541. this._w = ( m32 - m23 ) / s;
  542. this._x = 0.25 * s;
  543. this._y = ( m12 + m21 ) / s;
  544. this._z = ( m13 + m31 ) / s;
  545. } else if ( m22 > m33 ) {
  546. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  547. this._w = ( m13 - m31 ) / s;
  548. this._x = ( m12 + m21 ) / s;
  549. this._y = 0.25 * s;
  550. this._z = ( m23 + m32 ) / s;
  551. } else {
  552. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  553. this._w = ( m21 - m12 ) / s;
  554. this._x = ( m13 + m31 ) / s;
  555. this._y = ( m23 + m32 ) / s;
  556. this._z = 0.25 * s;
  557. }
  558. this.onChangeCallback();
  559. return this;
  560. },
  561. setFromUnitVectors: function () {
  562. // http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final
  563. // assumes direction vectors vFrom and vTo are normalized
  564. var v1, r;
  565. var EPS = 0.000001;
  566. return function ( vFrom, vTo ) {
  567. if ( v1 === undefined ) v1 = new THREE.Vector3();
  568. r = vFrom.dot( vTo ) + 1;
  569. if ( r < EPS ) {
  570. r = 0;
  571. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  572. v1.set( - vFrom.y, vFrom.x, 0 );
  573. } else {
  574. v1.set( 0, - vFrom.z, vFrom.y );
  575. }
  576. } else {
  577. v1.crossVectors( vFrom, vTo );
  578. }
  579. this._x = v1.x;
  580. this._y = v1.y;
  581. this._z = v1.z;
  582. this._w = r;
  583. this.normalize();
  584. return this;
  585. }
  586. }(),
  587. inverse: function () {
  588. this.conjugate().normalize();
  589. return this;
  590. },
  591. conjugate: function () {
  592. this._x *= - 1;
  593. this._y *= - 1;
  594. this._z *= - 1;
  595. this.onChangeCallback();
  596. return this;
  597. },
  598. dot: function ( v ) {
  599. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  600. },
  601. lengthSq: function () {
  602. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  603. },
  604. length: function () {
  605. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  606. },
  607. normalize: function () {
  608. var l = this.length();
  609. if ( l === 0 ) {
  610. this._x = 0;
  611. this._y = 0;
  612. this._z = 0;
  613. this._w = 1;
  614. } else {
  615. l = 1 / l;
  616. this._x = this._x * l;
  617. this._y = this._y * l;
  618. this._z = this._z * l;
  619. this._w = this._w * l;
  620. }
  621. this.onChangeCallback();
  622. return this;
  623. },
  624. multiply: function ( q, p ) {
  625. if ( p !== undefined ) {
  626. THREE.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  627. return this.multiplyQuaternions( q, p );
  628. }
  629. return this.multiplyQuaternions( this, q );
  630. },
  631. multiplyQuaternions: function ( a, b ) {
  632. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  633. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  634. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  635. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  636. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  637. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  638. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  639. this.onChangeCallback();
  640. return this;
  641. },
  642. multiplyVector3: function ( vector ) {
  643. THREE.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  644. return vector.applyQuaternion( this );
  645. },
  646. slerp: function ( qb, t ) {
  647. if ( t === 0 ) return this;
  648. if ( t === 1 ) return this.copy( qb );
  649. var x = this._x, y = this._y, z = this._z, w = this._w;
  650. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  651. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  652. if ( cosHalfTheta < 0 ) {
  653. this._w = - qb._w;
  654. this._x = - qb._x;
  655. this._y = - qb._y;
  656. this._z = - qb._z;
  657. cosHalfTheta = - cosHalfTheta;
  658. } else {
  659. this.copy( qb );
  660. }
  661. if ( cosHalfTheta >= 1.0 ) {
  662. this._w = w;
  663. this._x = x;
  664. this._y = y;
  665. this._z = z;
  666. return this;
  667. }
  668. var halfTheta = Math.acos( cosHalfTheta );
  669. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  670. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  671. this._w = 0.5 * ( w + this._w );
  672. this._x = 0.5 * ( x + this._x );
  673. this._y = 0.5 * ( y + this._y );
  674. this._z = 0.5 * ( z + this._z );
  675. return this;
  676. }
  677. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  678. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  679. this._w = ( w * ratioA + this._w * ratioB );
  680. this._x = ( x * ratioA + this._x * ratioB );
  681. this._y = ( y * ratioA + this._y * ratioB );
  682. this._z = ( z * ratioA + this._z * ratioB );
  683. this.onChangeCallback();
  684. return this;
  685. },
  686. equals: function ( quaternion ) {
  687. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  688. },
  689. fromArray: function ( array, offset ) {
  690. if ( offset === undefined ) offset = 0;
  691. this._x = array[ offset ];
  692. this._y = array[ offset + 1 ];
  693. this._z = array[ offset + 2 ];
  694. this._w = array[ offset + 3 ];
  695. this.onChangeCallback();
  696. return this;
  697. },
  698. toArray: function ( array, offset ) {
  699. if ( array === undefined ) array = [];
  700. if ( offset === undefined ) offset = 0;
  701. array[ offset ] = this._x;
  702. array[ offset + 1 ] = this._y;
  703. array[ offset + 2 ] = this._z;
  704. array[ offset + 3 ] = this._w;
  705. return array;
  706. },
  707. onChange: function ( callback ) {
  708. this.onChangeCallback = callback;
  709. return this;
  710. },
  711. onChangeCallback: function () {},
  712. clone: function () {
  713. return new THREE.Quaternion( this._x, this._y, this._z, this._w );
  714. }
  715. };
  716. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  717. return qm.copy( qa ).slerp( qb, t );
  718. }
  719. // File:src/math/Vector2.js
  720. /**
  721. * @author mrdoob / http://mrdoob.com/
  722. * @author philogb / http://blog.thejit.org/
  723. * @author egraether / http://egraether.com/
  724. * @author zz85 / http://www.lab4games.net/zz85/blog
  725. */
  726. THREE.Vector2 = function ( x, y ) {
  727. this.x = x || 0;
  728. this.y = y || 0;
  729. };
  730. THREE.Vector2.prototype = {
  731. constructor: THREE.Vector2,
  732. set: function ( x, y ) {
  733. this.x = x;
  734. this.y = y;
  735. return this;
  736. },
  737. setX: function ( x ) {
  738. this.x = x;
  739. return this;
  740. },
  741. setY: function ( y ) {
  742. this.y = y;
  743. return this;
  744. },
  745. setComponent: function ( index, value ) {
  746. switch ( index ) {
  747. case 0: this.x = value; break;
  748. case 1: this.y = value; break;
  749. default: throw new Error( 'index is out of range: ' + index );
  750. }
  751. },
  752. getComponent: function ( index ) {
  753. switch ( index ) {
  754. case 0: return this.x;
  755. case 1: return this.y;
  756. default: throw new Error( 'index is out of range: ' + index );
  757. }
  758. },
  759. copy: function ( v ) {
  760. this.x = v.x;
  761. this.y = v.y;
  762. return this;
  763. },
  764. add: function ( v, w ) {
  765. if ( w !== undefined ) {
  766. THREE.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  767. return this.addVectors( v, w );
  768. }
  769. this.x += v.x;
  770. this.y += v.y;
  771. return this;
  772. },
  773. addVectors: function ( a, b ) {
  774. this.x = a.x + b.x;
  775. this.y = a.y + b.y;
  776. return this;
  777. },
  778. addScalar: function ( s ) {
  779. this.x += s;
  780. this.y += s;
  781. return this;
  782. },
  783. sub: function ( v, w ) {
  784. if ( w !== undefined ) {
  785. THREE.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  786. return this.subVectors( v, w );
  787. }
  788. this.x -= v.x;
  789. this.y -= v.y;
  790. return this;
  791. },
  792. subVectors: function ( a, b ) {
  793. this.x = a.x - b.x;
  794. this.y = a.y - b.y;
  795. return this;
  796. },
  797. multiply: function ( v ) {
  798. this.x *= v.x;
  799. this.y *= v.y;
  800. return this;
  801. },
  802. multiplyScalar: function ( s ) {
  803. this.x *= s;
  804. this.y *= s;
  805. return this;
  806. },
  807. divide: function ( v ) {
  808. this.x /= v.x;
  809. this.y /= v.y;
  810. return this;
  811. },
  812. divideScalar: function ( scalar ) {
  813. if ( scalar !== 0 ) {
  814. var invScalar = 1 / scalar;
  815. this.x *= invScalar;
  816. this.y *= invScalar;
  817. } else {
  818. this.x = 0;
  819. this.y = 0;
  820. }
  821. return this;
  822. },
  823. min: function ( v ) {
  824. if ( this.x > v.x ) {
  825. this.x = v.x;
  826. }
  827. if ( this.y > v.y ) {
  828. this.y = v.y;
  829. }
  830. return this;
  831. },
  832. max: function ( v ) {
  833. if ( this.x < v.x ) {
  834. this.x = v.x;
  835. }
  836. if ( this.y < v.y ) {
  837. this.y = v.y;
  838. }
  839. return this;
  840. },
  841. clamp: function ( min, max ) {
  842. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  843. if ( this.x < min.x ) {
  844. this.x = min.x;
  845. } else if ( this.x > max.x ) {
  846. this.x = max.x;
  847. }
  848. if ( this.y < min.y ) {
  849. this.y = min.y;
  850. } else if ( this.y > max.y ) {
  851. this.y = max.y;
  852. }
  853. return this;
  854. },
  855. clampScalar: ( function () {
  856. var min, max;
  857. return function ( minVal, maxVal ) {
  858. if ( min === undefined ) {
  859. min = new THREE.Vector2();
  860. max = new THREE.Vector2();
  861. }
  862. min.set( minVal, minVal );
  863. max.set( maxVal, maxVal );
  864. return this.clamp( min, max );
  865. };
  866. } )(),
  867. floor: function () {
  868. this.x = Math.floor( this.x );
  869. this.y = Math.floor( this.y );
  870. return this;
  871. },
  872. ceil: function () {
  873. this.x = Math.ceil( this.x );
  874. this.y = Math.ceil( this.y );
  875. return this;
  876. },
  877. round: function () {
  878. this.x = Math.round( this.x );
  879. this.y = Math.round( this.y );
  880. return this;
  881. },
  882. roundToZero: function () {
  883. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  884. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  885. return this;
  886. },
  887. negate: function () {
  888. this.x = - this.x;
  889. this.y = - this.y;
  890. return this;
  891. },
  892. dot: function ( v ) {
  893. return this.x * v.x + this.y * v.y;
  894. },
  895. lengthSq: function () {
  896. return this.x * this.x + this.y * this.y;
  897. },
  898. length: function () {
  899. return Math.sqrt( this.x * this.x + this.y * this.y );
  900. },
  901. normalize: function () {
  902. return this.divideScalar( this.length() );
  903. },
  904. distanceTo: function ( v ) {
  905. return Math.sqrt( this.distanceToSquared( v ) );
  906. },
  907. distanceToSquared: function ( v ) {
  908. var dx = this.x - v.x, dy = this.y - v.y;
  909. return dx * dx + dy * dy;
  910. },
  911. setLength: function ( l ) {
  912. var oldLength = this.length();
  913. if ( oldLength !== 0 && l !== oldLength ) {
  914. this.multiplyScalar( l / oldLength );
  915. }
  916. return this;
  917. },
  918. lerp: function ( v, alpha ) {
  919. this.x += ( v.x - this.x ) * alpha;
  920. this.y += ( v.y - this.y ) * alpha;
  921. return this;
  922. },
  923. lerpVectors: function ( v1, v2, alpha ) {
  924. this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  925. return this;
  926. },
  927. equals: function ( v ) {
  928. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  929. },
  930. fromArray: function ( array, offset ) {
  931. if ( offset === undefined ) offset = 0;
  932. this.x = array[ offset ];
  933. this.y = array[ offset + 1 ];
  934. return this;
  935. },
  936. toArray: function ( array, offset ) {
  937. if ( array === undefined ) array = [];
  938. if ( offset === undefined ) offset = 0;
  939. array[ offset ] = this.x;
  940. array[ offset + 1 ] = this.y;
  941. return array;
  942. },
  943. fromAttribute: function ( attribute, index, offset ) {
  944. if ( offset === undefined ) offset = 0;
  945. index = index * attribute.itemSize + offset;
  946. this.x = attribute.array[ index ];
  947. this.y = attribute.array[ index + 1 ];
  948. return this;
  949. },
  950. clone: function () {
  951. return new THREE.Vector2( this.x, this.y );
  952. }
  953. };
  954. // File:src/math/Vector3.js
  955. /**
  956. * @author mrdoob / http://mrdoob.com/
  957. * @author *kile / http://kile.stravaganza.org/
  958. * @author philogb / http://blog.thejit.org/
  959. * @author mikael emtinger / http://gomo.se/
  960. * @author egraether / http://egraether.com/
  961. * @author WestLangley / http://github.com/WestLangley
  962. */
  963. THREE.Vector3 = function ( x, y, z ) {
  964. this.x = x || 0;
  965. this.y = y || 0;
  966. this.z = z || 0;
  967. };
  968. THREE.Vector3.prototype = {
  969. constructor: THREE.Vector3,
  970. set: function ( x, y, z ) {
  971. this.x = x;
  972. this.y = y;
  973. this.z = z;
  974. return this;
  975. },
  976. setX: function ( x ) {
  977. this.x = x;
  978. return this;
  979. },
  980. setY: function ( y ) {
  981. this.y = y;
  982. return this;
  983. },
  984. setZ: function ( z ) {
  985. this.z = z;
  986. return this;
  987. },
  988. setComponent: function ( index, value ) {
  989. switch ( index ) {
  990. case 0: this.x = value; break;
  991. case 1: this.y = value; break;
  992. case 2: this.z = value; break;
  993. default: throw new Error( 'index is out of range: ' + index );
  994. }
  995. },
  996. getComponent: function ( index ) {
  997. switch ( index ) {
  998. case 0: return this.x;
  999. case 1: return this.y;
  1000. case 2: return this.z;
  1001. default: throw new Error( 'index is out of range: ' + index );
  1002. }
  1003. },
  1004. copy: function ( v ) {
  1005. this.x = v.x;
  1006. this.y = v.y;
  1007. this.z = v.z;
  1008. return this;
  1009. },
  1010. add: function ( v, w ) {
  1011. if ( w !== undefined ) {
  1012. THREE.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1013. return this.addVectors( v, w );
  1014. }
  1015. this.x += v.x;
  1016. this.y += v.y;
  1017. this.z += v.z;
  1018. return this;
  1019. },
  1020. addScalar: function ( s ) {
  1021. this.x += s;
  1022. this.y += s;
  1023. this.z += s;
  1024. return this;
  1025. },
  1026. addVectors: function ( a, b ) {
  1027. this.x = a.x + b.x;
  1028. this.y = a.y + b.y;
  1029. this.z = a.z + b.z;
  1030. return this;
  1031. },
  1032. sub: function ( v, w ) {
  1033. if ( w !== undefined ) {
  1034. THREE.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1035. return this.subVectors( v, w );
  1036. }
  1037. this.x -= v.x;
  1038. this.y -= v.y;
  1039. this.z -= v.z;
  1040. return this;
  1041. },
  1042. subVectors: function ( a, b ) {
  1043. this.x = a.x - b.x;
  1044. this.y = a.y - b.y;
  1045. this.z = a.z - b.z;
  1046. return this;
  1047. },
  1048. multiply: function ( v, w ) {
  1049. if ( w !== undefined ) {
  1050. THREE.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  1051. return this.multiplyVectors( v, w );
  1052. }
  1053. this.x *= v.x;
  1054. this.y *= v.y;
  1055. this.z *= v.z;
  1056. return this;
  1057. },
  1058. multiplyScalar: function ( scalar ) {
  1059. this.x *= scalar;
  1060. this.y *= scalar;
  1061. this.z *= scalar;
  1062. return this;
  1063. },
  1064. multiplyVectors: function ( a, b ) {
  1065. this.x = a.x * b.x;
  1066. this.y = a.y * b.y;
  1067. this.z = a.z * b.z;
  1068. return this;
  1069. },
  1070. applyEuler: function () {
  1071. var quaternion;
  1072. return function ( euler ) {
  1073. if ( euler instanceof THREE.Euler === false ) {
  1074. THREE.error( 'THREE.Vector3: .applyEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  1075. }
  1076. if ( quaternion === undefined ) quaternion = new THREE.Quaternion();
  1077. this.applyQuaternion( quaternion.setFromEuler( euler ) );
  1078. return this;
  1079. };
  1080. }(),
  1081. applyAxisAngle: function () {
  1082. var quaternion;
  1083. return function ( axis, angle ) {
  1084. if ( quaternion === undefined ) quaternion = new THREE.Quaternion();
  1085. this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  1086. return this;
  1087. };
  1088. }(),
  1089. applyMatrix3: function ( m ) {
  1090. var x = this.x;
  1091. var y = this.y;
  1092. var z = this.z;
  1093. var e = m.elements;
  1094. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  1095. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  1096. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  1097. return this;
  1098. },
  1099. applyMatrix4: function ( m ) {
  1100. // input: THREE.Matrix4 affine matrix
  1101. var x = this.x, y = this.y, z = this.z;
  1102. var e = m.elements;
  1103. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ];
  1104. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ];
  1105. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ];
  1106. return this;
  1107. },
  1108. applyProjection: function ( m ) {
  1109. // input: THREE.Matrix4 projection matrix
  1110. var x = this.x, y = this.y, z = this.z;
  1111. var e = m.elements;
  1112. var d = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] ); // perspective divide
  1113. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * d;
  1114. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * d;
  1115. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * d;
  1116. return this;
  1117. },
  1118. applyQuaternion: function ( q ) {
  1119. var x = this.x;
  1120. var y = this.y;
  1121. var z = this.z;
  1122. var qx = q.x;
  1123. var qy = q.y;
  1124. var qz = q.z;
  1125. var qw = q.w;
  1126. // calculate quat * vector
  1127. var ix = qw * x + qy * z - qz * y;
  1128. var iy = qw * y + qz * x - qx * z;
  1129. var iz = qw * z + qx * y - qy * x;
  1130. var iw = - qx * x - qy * y - qz * z;
  1131. // calculate result * inverse quat
  1132. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  1133. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  1134. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  1135. return this;
  1136. },
  1137. project: function () {
  1138. var matrix;
  1139. return function ( camera ) {
  1140. if ( matrix === undefined ) matrix = new THREE.Matrix4();
  1141. matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) );
  1142. return this.applyProjection( matrix );
  1143. };
  1144. }(),
  1145. unproject: function () {
  1146. var matrix;
  1147. return function ( camera ) {
  1148. if ( matrix === undefined ) matrix = new THREE.Matrix4();
  1149. matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) );
  1150. return this.applyProjection( matrix );
  1151. };
  1152. }(),
  1153. transformDirection: function ( m ) {
  1154. // input: THREE.Matrix4 affine matrix
  1155. // vector interpreted as a direction
  1156. var x = this.x, y = this.y, z = this.z;
  1157. var e = m.elements;
  1158. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  1159. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  1160. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  1161. this.normalize();
  1162. return this;
  1163. },
  1164. divide: function ( v ) {
  1165. this.x /= v.x;
  1166. this.y /= v.y;
  1167. this.z /= v.z;
  1168. return this;
  1169. },
  1170. divideScalar: function ( scalar ) {
  1171. if ( scalar !== 0 ) {
  1172. var invScalar = 1 / scalar;
  1173. this.x *= invScalar;
  1174. this.y *= invScalar;
  1175. this.z *= invScalar;
  1176. } else {
  1177. this.x = 0;
  1178. this.y = 0;
  1179. this.z = 0;
  1180. }
  1181. return this;
  1182. },
  1183. min: function ( v ) {
  1184. if ( this.x > v.x ) {
  1185. this.x = v.x;
  1186. }
  1187. if ( this.y > v.y ) {
  1188. this.y = v.y;
  1189. }
  1190. if ( this.z > v.z ) {
  1191. this.z = v.z;
  1192. }
  1193. return this;
  1194. },
  1195. max: function ( v ) {
  1196. if ( this.x < v.x ) {
  1197. this.x = v.x;
  1198. }
  1199. if ( this.y < v.y ) {
  1200. this.y = v.y;
  1201. }
  1202. if ( this.z < v.z ) {
  1203. this.z = v.z;
  1204. }
  1205. return this;
  1206. },
  1207. clamp: function ( min, max ) {
  1208. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1209. if ( this.x < min.x ) {
  1210. this.x = min.x;
  1211. } else if ( this.x > max.x ) {
  1212. this.x = max.x;
  1213. }
  1214. if ( this.y < min.y ) {
  1215. this.y = min.y;
  1216. } else if ( this.y > max.y ) {
  1217. this.y = max.y;
  1218. }
  1219. if ( this.z < min.z ) {
  1220. this.z = min.z;
  1221. } else if ( this.z > max.z ) {
  1222. this.z = max.z;
  1223. }
  1224. return this;
  1225. },
  1226. clampScalar: ( function () {
  1227. var min, max;
  1228. return function ( minVal, maxVal ) {
  1229. if ( min === undefined ) {
  1230. min = new THREE.Vector3();
  1231. max = new THREE.Vector3();
  1232. }
  1233. min.set( minVal, minVal, minVal );
  1234. max.set( maxVal, maxVal, maxVal );
  1235. return this.clamp( min, max );
  1236. };
  1237. } )(),
  1238. floor: function () {
  1239. this.x = Math.floor( this.x );
  1240. this.y = Math.floor( this.y );
  1241. this.z = Math.floor( this.z );
  1242. return this;
  1243. },
  1244. ceil: function () {
  1245. this.x = Math.ceil( this.x );
  1246. this.y = Math.ceil( this.y );
  1247. this.z = Math.ceil( this.z );
  1248. return this;
  1249. },
  1250. round: function () {
  1251. this.x = Math.round( this.x );
  1252. this.y = Math.round( this.y );
  1253. this.z = Math.round( this.z );
  1254. return this;
  1255. },
  1256. roundToZero: function () {
  1257. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1258. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1259. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1260. return this;
  1261. },
  1262. negate: function () {
  1263. this.x = - this.x;
  1264. this.y = - this.y;
  1265. this.z = - this.z;
  1266. return this;
  1267. },
  1268. dot: function ( v ) {
  1269. return this.x * v.x + this.y * v.y + this.z * v.z;
  1270. },
  1271. lengthSq: function () {
  1272. return this.x * this.x + this.y * this.y + this.z * this.z;
  1273. },
  1274. length: function () {
  1275. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1276. },
  1277. lengthManhattan: function () {
  1278. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1279. },
  1280. normalize: function () {
  1281. return this.divideScalar( this.length() );
  1282. },
  1283. setLength: function ( l ) {
  1284. var oldLength = this.length();
  1285. if ( oldLength !== 0 && l !== oldLength ) {
  1286. this.multiplyScalar( l / oldLength );
  1287. }
  1288. return this;
  1289. },
  1290. lerp: function ( v, alpha ) {
  1291. this.x += ( v.x - this.x ) * alpha;
  1292. this.y += ( v.y - this.y ) * alpha;
  1293. this.z += ( v.z - this.z ) * alpha;
  1294. return this;
  1295. },
  1296. lerpVectors: function ( v1, v2, alpha ) {
  1297. this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1298. return this;
  1299. },
  1300. cross: function ( v, w ) {
  1301. if ( w !== undefined ) {
  1302. THREE.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1303. return this.crossVectors( v, w );
  1304. }
  1305. var x = this.x, y = this.y, z = this.z;
  1306. this.x = y * v.z - z * v.y;
  1307. this.y = z * v.x - x * v.z;
  1308. this.z = x * v.y - y * v.x;
  1309. return this;
  1310. },
  1311. crossVectors: function ( a, b ) {
  1312. var ax = a.x, ay = a.y, az = a.z;
  1313. var bx = b.x, by = b.y, bz = b.z;
  1314. this.x = ay * bz - az * by;
  1315. this.y = az * bx - ax * bz;
  1316. this.z = ax * by - ay * bx;
  1317. return this;
  1318. },
  1319. projectOnVector: function () {
  1320. var v1, dot;
  1321. return function ( vector ) {
  1322. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1323. v1.copy( vector ).normalize();
  1324. dot = this.dot( v1 );
  1325. return this.copy( v1 ).multiplyScalar( dot );
  1326. };
  1327. }(),
  1328. projectOnPlane: function () {
  1329. var v1;
  1330. return function ( planeNormal ) {
  1331. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1332. v1.copy( this ).projectOnVector( planeNormal );
  1333. return this.sub( v1 );
  1334. }
  1335. }(),
  1336. reflect: function () {
  1337. // reflect incident vector off plane orthogonal to normal
  1338. // normal is assumed to have unit length
  1339. var v1;
  1340. return function ( normal ) {
  1341. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1342. return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  1343. }
  1344. }(),
  1345. angleTo: function ( v ) {
  1346. var theta = this.dot( v ) / ( this.length() * v.length() );
  1347. // clamp, to handle numerical problems
  1348. return Math.acos( THREE.Math.clamp( theta, - 1, 1 ) );
  1349. },
  1350. distanceTo: function ( v ) {
  1351. return Math.sqrt( this.distanceToSquared( v ) );
  1352. },
  1353. distanceToSquared: function ( v ) {
  1354. var dx = this.x - v.x;
  1355. var dy = this.y - v.y;
  1356. var dz = this.z - v.z;
  1357. return dx * dx + dy * dy + dz * dz;
  1358. },
  1359. setEulerFromRotationMatrix: function ( m, order ) {
  1360. THREE.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  1361. },
  1362. setEulerFromQuaternion: function ( q, order ) {
  1363. THREE.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  1364. },
  1365. getPositionFromMatrix: function ( m ) {
  1366. THREE.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  1367. return this.setFromMatrixPosition( m );
  1368. },
  1369. getScaleFromMatrix: function ( m ) {
  1370. THREE.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  1371. return this.setFromMatrixScale( m );
  1372. },
  1373. getColumnFromMatrix: function ( index, matrix ) {
  1374. THREE.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  1375. return this.setFromMatrixColumn( index, matrix );
  1376. },
  1377. setFromMatrixPosition: function ( m ) {
  1378. this.x = m.elements[ 12 ];
  1379. this.y = m.elements[ 13 ];
  1380. this.z = m.elements[ 14 ];
  1381. return this;
  1382. },
  1383. setFromMatrixScale: function ( m ) {
  1384. var sx = this.set( m.elements[ 0 ], m.elements[ 1 ], m.elements[ 2 ] ).length();
  1385. var sy = this.set( m.elements[ 4 ], m.elements[ 5 ], m.elements[ 6 ] ).length();
  1386. var sz = this.set( m.elements[ 8 ], m.elements[ 9 ], m.elements[ 10 ] ).length();
  1387. this.x = sx;
  1388. this.y = sy;
  1389. this.z = sz;
  1390. return this;
  1391. },
  1392. setFromMatrixColumn: function ( index, matrix ) {
  1393. var offset = index * 4;
  1394. var me = matrix.elements;
  1395. this.x = me[ offset ];
  1396. this.y = me[ offset + 1 ];
  1397. this.z = me[ offset + 2 ];
  1398. return this;
  1399. },
  1400. equals: function ( v ) {
  1401. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1402. },
  1403. fromArray: function ( array, offset ) {
  1404. if ( offset === undefined ) offset = 0;
  1405. this.x = array[ offset ];
  1406. this.y = array[ offset + 1 ];
  1407. this.z = array[ offset + 2 ];
  1408. return this;
  1409. },
  1410. toArray: function ( array, offset ) {
  1411. if ( array === undefined ) array = [];
  1412. if ( offset === undefined ) offset = 0;
  1413. array[ offset ] = this.x;
  1414. array[ offset + 1 ] = this.y;
  1415. array[ offset + 2 ] = this.z;
  1416. return array;
  1417. },
  1418. fromAttribute: function ( attribute, index, offset ) {
  1419. if ( offset === undefined ) offset = 0;
  1420. index = index * attribute.itemSize + offset;
  1421. this.x = attribute.array[ index ];
  1422. this.y = attribute.array[ index + 1 ];
  1423. this.z = attribute.array[ index + 2 ];
  1424. return this;
  1425. },
  1426. clone: function () {
  1427. return new THREE.Vector3( this.x, this.y, this.z );
  1428. }
  1429. };
  1430. // File:src/math/Vector4.js
  1431. /**
  1432. * @author supereggbert / http://www.paulbrunt.co.uk/
  1433. * @author philogb / http://blog.thejit.org/
  1434. * @author mikael emtinger / http://gomo.se/
  1435. * @author egraether / http://egraether.com/
  1436. * @author WestLangley / http://github.com/WestLangley
  1437. */
  1438. THREE.Vector4 = function ( x, y, z, w ) {
  1439. this.x = x || 0;
  1440. this.y = y || 0;
  1441. this.z = z || 0;
  1442. this.w = ( w !== undefined ) ? w : 1;
  1443. };
  1444. THREE.Vector4.prototype = {
  1445. constructor: THREE.Vector4,
  1446. set: function ( x, y, z, w ) {
  1447. this.x = x;
  1448. this.y = y;
  1449. this.z = z;
  1450. this.w = w;
  1451. return this;
  1452. },
  1453. setX: function ( x ) {
  1454. this.x = x;
  1455. return this;
  1456. },
  1457. setY: function ( y ) {
  1458. this.y = y;
  1459. return this;
  1460. },
  1461. setZ: function ( z ) {
  1462. this.z = z;
  1463. return this;
  1464. },
  1465. setW: function ( w ) {
  1466. this.w = w;
  1467. return this;
  1468. },
  1469. setComponent: function ( index, value ) {
  1470. switch ( index ) {
  1471. case 0: this.x = value; break;
  1472. case 1: this.y = value; break;
  1473. case 2: this.z = value; break;
  1474. case 3: this.w = value; break;
  1475. default: throw new Error( 'index is out of range: ' + index );
  1476. }
  1477. },
  1478. getComponent: function ( index ) {
  1479. switch ( index ) {
  1480. case 0: return this.x;
  1481. case 1: return this.y;
  1482. case 2: return this.z;
  1483. case 3: return this.w;
  1484. default: throw new Error( 'index is out of range: ' + index );
  1485. }
  1486. },
  1487. copy: function ( v ) {
  1488. this.x = v.x;
  1489. this.y = v.y;
  1490. this.z = v.z;
  1491. this.w = ( v.w !== undefined ) ? v.w : 1;
  1492. return this;
  1493. },
  1494. add: function ( v, w ) {
  1495. if ( w !== undefined ) {
  1496. THREE.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1497. return this.addVectors( v, w );
  1498. }
  1499. this.x += v.x;
  1500. this.y += v.y;
  1501. this.z += v.z;
  1502. this.w += v.w;
  1503. return this;
  1504. },
  1505. addScalar: function ( s ) {
  1506. this.x += s;
  1507. this.y += s;
  1508. this.z += s;
  1509. this.w += s;
  1510. return this;
  1511. },
  1512. addVectors: function ( a, b ) {
  1513. this.x = a.x + b.x;
  1514. this.y = a.y + b.y;
  1515. this.z = a.z + b.z;
  1516. this.w = a.w + b.w;
  1517. return this;
  1518. },
  1519. sub: function ( v, w ) {
  1520. if ( w !== undefined ) {
  1521. THREE.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1522. return this.subVectors( v, w );
  1523. }
  1524. this.x -= v.x;
  1525. this.y -= v.y;
  1526. this.z -= v.z;
  1527. this.w -= v.w;
  1528. return this;
  1529. },
  1530. subVectors: function ( a, b ) {
  1531. this.x = a.x - b.x;
  1532. this.y = a.y - b.y;
  1533. this.z = a.z - b.z;
  1534. this.w = a.w - b.w;
  1535. return this;
  1536. },
  1537. multiplyScalar: function ( scalar ) {
  1538. this.x *= scalar;
  1539. this.y *= scalar;
  1540. this.z *= scalar;
  1541. this.w *= scalar;
  1542. return this;
  1543. },
  1544. applyMatrix4: function ( m ) {
  1545. var x = this.x;
  1546. var y = this.y;
  1547. var z = this.z;
  1548. var w = this.w;
  1549. var e = m.elements;
  1550. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1551. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1552. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1553. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1554. return this;
  1555. },
  1556. divideScalar: function ( scalar ) {
  1557. if ( scalar !== 0 ) {
  1558. var invScalar = 1 / scalar;
  1559. this.x *= invScalar;
  1560. this.y *= invScalar;
  1561. this.z *= invScalar;
  1562. this.w *= invScalar;
  1563. } else {
  1564. this.x = 0;
  1565. this.y = 0;
  1566. this.z = 0;
  1567. this.w = 1;
  1568. }
  1569. return this;
  1570. },
  1571. setAxisAngleFromQuaternion: function ( q ) {
  1572. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1573. // q is assumed to be normalized
  1574. this.w = 2 * Math.acos( q.w );
  1575. var s = Math.sqrt( 1 - q.w * q.w );
  1576. if ( s < 0.0001 ) {
  1577. this.x = 1;
  1578. this.y = 0;
  1579. this.z = 0;
  1580. } else {
  1581. this.x = q.x / s;
  1582. this.y = q.y / s;
  1583. this.z = q.z / s;
  1584. }
  1585. return this;
  1586. },
  1587. setAxisAngleFromRotationMatrix: function ( m ) {
  1588. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1589. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1590. var angle, x, y, z, // variables for result
  1591. epsilon = 0.01, // margin to allow for rounding errors
  1592. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1593. te = m.elements,
  1594. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1595. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1596. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1597. if ( ( Math.abs( m12 - m21 ) < epsilon )
  1598. && ( Math.abs( m13 - m31 ) < epsilon )
  1599. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1600. // singularity found
  1601. // first check for identity matrix which must have +1 for all terms
  1602. // in leading diagonal and zero in other terms
  1603. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  1604. && ( Math.abs( m13 + m31 ) < epsilon2 )
  1605. && ( Math.abs( m23 + m32 ) < epsilon2 )
  1606. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1607. // this singularity is identity matrix so angle = 0
  1608. this.set( 1, 0, 0, 0 );
  1609. return this; // zero angle, arbitrary axis
  1610. }
  1611. // otherwise this singularity is angle = 180
  1612. angle = Math.PI;
  1613. var xx = ( m11 + 1 ) / 2;
  1614. var yy = ( m22 + 1 ) / 2;
  1615. var zz = ( m33 + 1 ) / 2;
  1616. var xy = ( m12 + m21 ) / 4;
  1617. var xz = ( m13 + m31 ) / 4;
  1618. var yz = ( m23 + m32 ) / 4;
  1619. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  1620. if ( xx < epsilon ) {
  1621. x = 0;
  1622. y = 0.707106781;
  1623. z = 0.707106781;
  1624. } else {
  1625. x = Math.sqrt( xx );
  1626. y = xy / x;
  1627. z = xz / x;
  1628. }
  1629. } else if ( yy > zz ) { // m22 is the largest diagonal term
  1630. if ( yy < epsilon ) {
  1631. x = 0.707106781;
  1632. y = 0;
  1633. z = 0.707106781;
  1634. } else {
  1635. y = Math.sqrt( yy );
  1636. x = xy / y;
  1637. z = yz / y;
  1638. }
  1639. } else { // m33 is the largest diagonal term so base result on this
  1640. if ( zz < epsilon ) {
  1641. x = 0.707106781;
  1642. y = 0.707106781;
  1643. z = 0;
  1644. } else {
  1645. z = Math.sqrt( zz );
  1646. x = xz / z;
  1647. y = yz / z;
  1648. }
  1649. }
  1650. this.set( x, y, z, angle );
  1651. return this; // return 180 deg rotation
  1652. }
  1653. // as we have reached here there are no singularities so we can handle normally
  1654. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  1655. + ( m13 - m31 ) * ( m13 - m31 )
  1656. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1657. if ( Math.abs( s ) < 0.001 ) s = 1;
  1658. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1659. // caught by singularity test above, but I've left it in just in case
  1660. this.x = ( m32 - m23 ) / s;
  1661. this.y = ( m13 - m31 ) / s;
  1662. this.z = ( m21 - m12 ) / s;
  1663. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1664. return this;
  1665. },
  1666. min: function ( v ) {
  1667. if ( this.x > v.x ) {
  1668. this.x = v.x;
  1669. }
  1670. if ( this.y > v.y ) {
  1671. this.y = v.y;
  1672. }
  1673. if ( this.z > v.z ) {
  1674. this.z = v.z;
  1675. }
  1676. if ( this.w > v.w ) {
  1677. this.w = v.w;
  1678. }
  1679. return this;
  1680. },
  1681. max: function ( v ) {
  1682. if ( this.x < v.x ) {
  1683. this.x = v.x;
  1684. }
  1685. if ( this.y < v.y ) {
  1686. this.y = v.y;
  1687. }
  1688. if ( this.z < v.z ) {
  1689. this.z = v.z;
  1690. }
  1691. if ( this.w < v.w ) {
  1692. this.w = v.w;
  1693. }
  1694. return this;
  1695. },
  1696. clamp: function ( min, max ) {
  1697. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1698. if ( this.x < min.x ) {
  1699. this.x = min.x;
  1700. } else if ( this.x > max.x ) {
  1701. this.x = max.x;
  1702. }
  1703. if ( this.y < min.y ) {
  1704. this.y = min.y;
  1705. } else if ( this.y > max.y ) {
  1706. this.y = max.y;
  1707. }
  1708. if ( this.z < min.z ) {
  1709. this.z = min.z;
  1710. } else if ( this.z > max.z ) {
  1711. this.z = max.z;
  1712. }
  1713. if ( this.w < min.w ) {
  1714. this.w = min.w;
  1715. } else if ( this.w > max.w ) {
  1716. this.w = max.w;
  1717. }
  1718. return this;
  1719. },
  1720. clampScalar: ( function () {
  1721. var min, max;
  1722. return function ( minVal, maxVal ) {
  1723. if ( min === undefined ) {
  1724. min = new THREE.Vector4();
  1725. max = new THREE.Vector4();
  1726. }
  1727. min.set( minVal, minVal, minVal, minVal );
  1728. max.set( maxVal, maxVal, maxVal, maxVal );
  1729. return this.clamp( min, max );
  1730. };
  1731. } )(),
  1732. floor: function () {
  1733. this.x = Math.floor( this.x );
  1734. this.y = Math.floor( this.y );
  1735. this.z = Math.floor( this.z );
  1736. this.w = Math.floor( this.w );
  1737. return this;
  1738. },
  1739. ceil: function () {
  1740. this.x = Math.ceil( this.x );
  1741. this.y = Math.ceil( this.y );
  1742. this.z = Math.ceil( this.z );
  1743. this.w = Math.ceil( this.w );
  1744. return this;
  1745. },
  1746. round: function () {
  1747. this.x = Math.round( this.x );
  1748. this.y = Math.round( this.y );
  1749. this.z = Math.round( this.z );
  1750. this.w = Math.round( this.w );
  1751. return this;
  1752. },
  1753. roundToZero: function () {
  1754. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1755. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1756. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1757. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1758. return this;
  1759. },
  1760. negate: function () {
  1761. this.x = - this.x;
  1762. this.y = - this.y;
  1763. this.z = - this.z;
  1764. this.w = - this.w;
  1765. return this;
  1766. },
  1767. dot: function ( v ) {
  1768. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1769. },
  1770. lengthSq: function () {
  1771. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1772. },
  1773. length: function () {
  1774. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1775. },
  1776. lengthManhattan: function () {
  1777. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1778. },
  1779. normalize: function () {
  1780. return this.divideScalar( this.length() );
  1781. },
  1782. setLength: function ( l ) {
  1783. var oldLength = this.length();
  1784. if ( oldLength !== 0 && l !== oldLength ) {
  1785. this.multiplyScalar( l / oldLength );
  1786. }
  1787. return this;
  1788. },
  1789. lerp: function ( v, alpha ) {
  1790. this.x += ( v.x - this.x ) * alpha;
  1791. this.y += ( v.y - this.y ) * alpha;
  1792. this.z += ( v.z - this.z ) * alpha;
  1793. this.w += ( v.w - this.w ) * alpha;
  1794. return this;
  1795. },
  1796. lerpVectors: function ( v1, v2, alpha ) {
  1797. this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1798. return this;
  1799. },
  1800. equals: function ( v ) {
  1801. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1802. },
  1803. fromArray: function ( array, offset ) {
  1804. if ( offset === undefined ) offset = 0;
  1805. this.x = array[ offset ];
  1806. this.y = array[ offset + 1 ];
  1807. this.z = array[ offset + 2 ];
  1808. this.w = array[ offset + 3 ];
  1809. return this;
  1810. },
  1811. toArray: function ( array, offset ) {
  1812. if ( array === undefined ) array = [];
  1813. if ( offset === undefined ) offset = 0;
  1814. array[ offset ] = this.x;
  1815. array[ offset + 1 ] = this.y;
  1816. array[ offset + 2 ] = this.z;
  1817. array[ offset + 3 ] = this.w;
  1818. return array;
  1819. },
  1820. fromAttribute: function ( attribute, index, offset ) {
  1821. if ( offset === undefined ) offset = 0;
  1822. index = index * attribute.itemSize + offset;
  1823. this.x = attribute.array[ index ];
  1824. this.y = attribute.array[ index + 1 ];
  1825. this.z = attribute.array[ index + 2 ];
  1826. this.w = attribute.array[ index + 3 ];
  1827. return this;
  1828. },
  1829. clone: function () {
  1830. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  1831. }
  1832. };
  1833. // File:src/math/Euler.js
  1834. /**
  1835. * @author mrdoob / http://mrdoob.com/
  1836. * @author WestLangley / http://github.com/WestLangley
  1837. * @author bhouston / http://exocortex.com
  1838. */
  1839. THREE.Euler = function ( x, y, z, order ) {
  1840. this._x = x || 0;
  1841. this._y = y || 0;
  1842. this._z = z || 0;
  1843. this._order = order || THREE.Euler.DefaultOrder;
  1844. };
  1845. THREE.Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  1846. THREE.Euler.DefaultOrder = 'XYZ';
  1847. THREE.Euler.prototype = {
  1848. constructor: THREE.Euler,
  1849. _x: 0, _y: 0, _z: 0, _order: THREE.Euler.DefaultOrder,
  1850. get x () {
  1851. return this._x;
  1852. },
  1853. set x ( value ) {
  1854. this._x = value;
  1855. this.onChangeCallback();
  1856. },
  1857. get y () {
  1858. return this._y;
  1859. },
  1860. set y ( value ) {
  1861. this._y = value;
  1862. this.onChangeCallback();
  1863. },
  1864. get z () {
  1865. return this._z;
  1866. },
  1867. set z ( value ) {
  1868. this._z = value;
  1869. this.onChangeCallback();
  1870. },
  1871. get order () {
  1872. return this._order;
  1873. },
  1874. set order ( value ) {
  1875. this._order = value;
  1876. this.onChangeCallback();
  1877. },
  1878. set: function ( x, y, z, order ) {
  1879. this._x = x;
  1880. this._y = y;
  1881. this._z = z;
  1882. this._order = order || this._order;
  1883. this.onChangeCallback();
  1884. return this;
  1885. },
  1886. copy: function ( euler ) {
  1887. this._x = euler._x;
  1888. this._y = euler._y;
  1889. this._z = euler._z;
  1890. this._order = euler._order;
  1891. this.onChangeCallback();
  1892. return this;
  1893. },
  1894. setFromRotationMatrix: function ( m, order, update ) {
  1895. var clamp = THREE.Math.clamp;
  1896. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1897. var te = m.elements;
  1898. var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  1899. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  1900. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1901. order = order || this._order;
  1902. if ( order === 'XYZ' ) {
  1903. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  1904. if ( Math.abs( m13 ) < 0.99999 ) {
  1905. this._x = Math.atan2( - m23, m33 );
  1906. this._z = Math.atan2( - m12, m11 );
  1907. } else {
  1908. this._x = Math.atan2( m32, m22 );
  1909. this._z = 0;
  1910. }
  1911. } else if ( order === 'YXZ' ) {
  1912. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  1913. if ( Math.abs( m23 ) < 0.99999 ) {
  1914. this._y = Math.atan2( m13, m33 );
  1915. this._z = Math.atan2( m21, m22 );
  1916. } else {
  1917. this._y = Math.atan2( - m31, m11 );
  1918. this._z = 0;
  1919. }
  1920. } else if ( order === 'ZXY' ) {
  1921. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  1922. if ( Math.abs( m32 ) < 0.99999 ) {
  1923. this._y = Math.atan2( - m31, m33 );
  1924. this._z = Math.atan2( - m12, m22 );
  1925. } else {
  1926. this._y = 0;
  1927. this._z = Math.atan2( m21, m11 );
  1928. }
  1929. } else if ( order === 'ZYX' ) {
  1930. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  1931. if ( Math.abs( m31 ) < 0.99999 ) {
  1932. this._x = Math.atan2( m32, m33 );
  1933. this._z = Math.atan2( m21, m11 );
  1934. } else {
  1935. this._x = 0;
  1936. this._z = Math.atan2( - m12, m22 );
  1937. }
  1938. } else if ( order === 'YZX' ) {
  1939. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  1940. if ( Math.abs( m21 ) < 0.99999 ) {
  1941. this._x = Math.atan2( - m23, m22 );
  1942. this._y = Math.atan2( - m31, m11 );
  1943. } else {
  1944. this._x = 0;
  1945. this._y = Math.atan2( m13, m33 );
  1946. }
  1947. } else if ( order === 'XZY' ) {
  1948. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  1949. if ( Math.abs( m12 ) < 0.99999 ) {
  1950. this._x = Math.atan2( m32, m22 );
  1951. this._y = Math.atan2( m13, m11 );
  1952. } else {
  1953. this._x = Math.atan2( - m23, m33 );
  1954. this._y = 0;
  1955. }
  1956. } else {
  1957. THREE.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order )
  1958. }
  1959. this._order = order;
  1960. if ( update !== false ) this.onChangeCallback();
  1961. return this;
  1962. },
  1963. setFromQuaternion: function () {
  1964. var matrix;
  1965. return function ( q, order, update ) {
  1966. if ( matrix === undefined ) matrix = new THREE.Matrix4();
  1967. matrix.makeRotationFromQuaternion( q );
  1968. this.setFromRotationMatrix( matrix, order, update );
  1969. return this;
  1970. };
  1971. }(),
  1972. setFromVector3: function ( v, order ) {
  1973. return this.set( v.x, v.y, v.z, order || this._order );
  1974. },
  1975. reorder: function () {
  1976. // WARNING: this discards revolution information -bhouston
  1977. var q = new THREE.Quaternion();
  1978. return function ( newOrder ) {
  1979. q.setFromEuler( this );
  1980. this.setFromQuaternion( q, newOrder );
  1981. };
  1982. }(),
  1983. equals: function ( euler ) {
  1984. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  1985. },
  1986. fromArray: function ( array ) {
  1987. this._x = array[ 0 ];
  1988. this._y = array[ 1 ];
  1989. this._z = array[ 2 ];
  1990. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  1991. this.onChangeCallback();
  1992. return this;
  1993. },
  1994. toArray: function ( array, offset ) {
  1995. if ( array === undefined ) array = [];
  1996. if ( offset === undefined ) offset = 0;
  1997. array[ offset ] = this._x;
  1998. array[ offset + 1 ] = this._y;
  1999. array[ offset + 2 ] = this._z;
  2000. array[ offset + 3 ] = this._order;
  2001. return array;
  2002. },
  2003. toVector3: function ( optionalResult ) {
  2004. if ( optionalResult ) {
  2005. return optionalResult.set( this._x, this._y, this._z );
  2006. } else {
  2007. return new THREE.Vector3( this._x, this._y, this._z );
  2008. }
  2009. },
  2010. onChange: function ( callback ) {
  2011. this.onChangeCallback = callback;
  2012. return this;
  2013. },
  2014. onChangeCallback: function () {},
  2015. clone: function () {
  2016. return new THREE.Euler( this._x, this._y, this._z, this._order );
  2017. }
  2018. };
  2019. // File:src/math/Line3.js
  2020. /**
  2021. * @author bhouston / http://exocortex.com
  2022. */
  2023. THREE.Line3 = function ( start, end ) {
  2024. this.start = ( start !== undefined ) ? start : new THREE.Vector3();
  2025. this.end = ( end !== undefined ) ? end : new THREE.Vector3();
  2026. };
  2027. THREE.Line3.prototype = {
  2028. constructor: THREE.Line3,
  2029. set: function ( start, end ) {
  2030. this.start.copy( start );
  2031. this.end.copy( end );
  2032. return this;
  2033. },
  2034. copy: function ( line ) {
  2035. this.start.copy( line.start );
  2036. this.end.copy( line.end );
  2037. return this;
  2038. },
  2039. center: function ( optionalTarget ) {
  2040. var result = optionalTarget || new THREE.Vector3();
  2041. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  2042. },
  2043. delta: function ( optionalTarget ) {
  2044. var result = optionalTarget || new THREE.Vector3();
  2045. return result.subVectors( this.end, this.start );
  2046. },
  2047. distanceSq: function () {
  2048. return this.start.distanceToSquared( this.end );
  2049. },
  2050. distance: function () {
  2051. return this.start.distanceTo( this.end );
  2052. },
  2053. at: function ( t, optionalTarget ) {
  2054. var result = optionalTarget || new THREE.Vector3();
  2055. return this.delta( result ).multiplyScalar( t ).add( this.start );
  2056. },
  2057. closestPointToPointParameter: function () {
  2058. var startP = new THREE.Vector3();
  2059. var startEnd = new THREE.Vector3();
  2060. return function ( point, clampToLine ) {
  2061. startP.subVectors( point, this.start );
  2062. startEnd.subVectors( this.end, this.start );
  2063. var startEnd2 = startEnd.dot( startEnd );
  2064. var startEnd_startP = startEnd.dot( startP );
  2065. var t = startEnd_startP / startEnd2;
  2066. if ( clampToLine ) {
  2067. t = THREE.Math.clamp( t, 0, 1 );
  2068. }
  2069. return t;
  2070. };
  2071. }(),
  2072. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  2073. var t = this.closestPointToPointParameter( point, clampToLine );
  2074. var result = optionalTarget || new THREE.Vector3();
  2075. return this.delta( result ).multiplyScalar( t ).add( this.start );
  2076. },
  2077. applyMatrix4: function ( matrix ) {
  2078. this.start.applyMatrix4( matrix );
  2079. this.end.applyMatrix4( matrix );
  2080. return this;
  2081. },
  2082. equals: function ( line ) {
  2083. return line.start.equals( this.start ) && line.end.equals( this.end );
  2084. },
  2085. clone: function () {
  2086. return new THREE.Line3().copy( this );
  2087. }
  2088. };
  2089. // File:src/math/Box2.js
  2090. /**
  2091. * @author bhouston / http://exocortex.com
  2092. */
  2093. THREE.Box2 = function ( min, max ) {
  2094. this.min = ( min !== undefined ) ? min : new THREE.Vector2( Infinity, Infinity );
  2095. this.max = ( max !== undefined ) ? max : new THREE.Vector2( - Infinity, - Infinity );
  2096. };
  2097. THREE.Box2.prototype = {
  2098. constructor: THREE.Box2,
  2099. set: function ( min, max ) {
  2100. this.min.copy( min );
  2101. this.max.copy( max );
  2102. return this;
  2103. },
  2104. setFromPoints: function ( points ) {
  2105. this.makeEmpty();
  2106. for ( var i = 0, il = points.length; i < il; i ++ ) {
  2107. this.expandByPoint( points[ i ] )
  2108. }
  2109. return this;
  2110. },
  2111. setFromCenterAndSize: function () {
  2112. var v1 = new THREE.Vector2();
  2113. return function ( center, size ) {
  2114. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2115. this.min.copy( center ).sub( halfSize );
  2116. this.max.copy( center ).add( halfSize );
  2117. return this;
  2118. };
  2119. }(),
  2120. copy: function ( box ) {
  2121. this.min.copy( box.min );
  2122. this.max.copy( box.max );
  2123. return this;
  2124. },
  2125. makeEmpty: function () {
  2126. this.min.x = this.min.y = Infinity;
  2127. this.max.x = this.max.y = - Infinity;
  2128. return this;
  2129. },
  2130. empty: function () {
  2131. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2132. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  2133. },
  2134. center: function ( optionalTarget ) {
  2135. var result = optionalTarget || new THREE.Vector2();
  2136. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2137. },
  2138. size: function ( optionalTarget ) {
  2139. var result = optionalTarget || new THREE.Vector2();
  2140. return result.subVectors( this.max, this.min );
  2141. },
  2142. expandByPoint: function ( point ) {
  2143. this.min.min( point );
  2144. this.max.max( point );
  2145. return this;
  2146. },
  2147. expandByVector: function ( vector ) {
  2148. this.min.sub( vector );
  2149. this.max.add( vector );
  2150. return this;
  2151. },
  2152. expandByScalar: function ( scalar ) {
  2153. this.min.addScalar( - scalar );
  2154. this.max.addScalar( scalar );
  2155. return this;
  2156. },
  2157. containsPoint: function ( point ) {
  2158. if ( point.x < this.min.x || point.x > this.max.x ||
  2159. point.y < this.min.y || point.y > this.max.y ) {
  2160. return false;
  2161. }
  2162. return true;
  2163. },
  2164. containsBox: function ( box ) {
  2165. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2166. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  2167. return true;
  2168. }
  2169. return false;
  2170. },
  2171. getParameter: function ( point, optionalTarget ) {
  2172. // This can potentially have a divide by zero if the box
  2173. // has a size dimension of 0.
  2174. var result = optionalTarget || new THREE.Vector2();
  2175. return result.set(
  2176. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2177. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  2178. );
  2179. },
  2180. isIntersectionBox: function ( box ) {
  2181. // using 6 splitting planes to rule out intersections.
  2182. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2183. box.max.y < this.min.y || box.min.y > this.max.y ) {
  2184. return false;
  2185. }
  2186. return true;
  2187. },
  2188. clampPoint: function ( point, optionalTarget ) {
  2189. var result = optionalTarget || new THREE.Vector2();
  2190. return result.copy( point ).clamp( this.min, this.max );
  2191. },
  2192. distanceToPoint: function () {
  2193. var v1 = new THREE.Vector2();
  2194. return function ( point ) {
  2195. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2196. return clampedPoint.sub( point ).length();
  2197. };
  2198. }(),
  2199. intersect: function ( box ) {
  2200. this.min.max( box.min );
  2201. this.max.min( box.max );
  2202. return this;
  2203. },
  2204. union: function ( box ) {
  2205. this.min.min( box.min );
  2206. this.max.max( box.max );
  2207. return this;
  2208. },
  2209. translate: function ( offset ) {
  2210. this.min.add( offset );
  2211. this.max.add( offset );
  2212. return this;
  2213. },
  2214. equals: function ( box ) {
  2215. return box.min.equals( this.min ) && box.max.equals( this.max );
  2216. },
  2217. clone: function () {
  2218. return new THREE.Box2().copy( this );
  2219. }
  2220. };
  2221. // File:src/math/Box3.js
  2222. /**
  2223. * @author bhouston / http://exocortex.com
  2224. * @author WestLangley / http://github.com/WestLangley
  2225. */
  2226. THREE.Box3 = function ( min, max ) {
  2227. this.min = ( min !== undefined ) ? min : new THREE.Vector3( Infinity, Infinity, Infinity );
  2228. this.max = ( max !== undefined ) ? max : new THREE.Vector3( - Infinity, - Infinity, - Infinity );
  2229. };
  2230. THREE.Box3.prototype = {
  2231. constructor: THREE.Box3,
  2232. set: function ( min, max ) {
  2233. this.min.copy( min );
  2234. this.max.copy( max );
  2235. return this;
  2236. },
  2237. setFromPoints: function ( points ) {
  2238. this.makeEmpty();
  2239. for ( var i = 0, il = points.length; i < il; i ++ ) {
  2240. this.expandByPoint( points[ i ] )
  2241. }
  2242. return this;
  2243. },
  2244. setFromCenterAndSize: function () {
  2245. var v1 = new THREE.Vector3();
  2246. return function ( center, size ) {
  2247. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2248. this.min.copy( center ).sub( halfSize );
  2249. this.max.copy( center ).add( halfSize );
  2250. return this;
  2251. };
  2252. }(),
  2253. setFromObject: function () {
  2254. // Computes the world-axis-aligned bounding box of an object (including its children),
  2255. // accounting for both the object's, and childrens', world transforms
  2256. var v1 = new THREE.Vector3();
  2257. return function ( object ) {
  2258. var scope = this;
  2259. object.updateMatrixWorld( true );
  2260. this.makeEmpty();
  2261. object.traverse( function ( node ) {
  2262. var geometry = node.geometry;
  2263. if ( geometry !== undefined ) {
  2264. if ( geometry instanceof THREE.Geometry ) {
  2265. var vertices = geometry.vertices;
  2266. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  2267. v1.copy( vertices[ i ] );
  2268. v1.applyMatrix4( node.matrixWorld );
  2269. scope.expandByPoint( v1 );
  2270. }
  2271. } else if ( geometry instanceof THREE.BufferGeometry && geometry.attributes[ 'position' ] !== undefined ) {
  2272. var positions = geometry.attributes[ 'position' ].array;
  2273. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  2274. v1.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  2275. v1.applyMatrix4( node.matrixWorld );
  2276. scope.expandByPoint( v1 );
  2277. }
  2278. }
  2279. }
  2280. } );
  2281. return this;
  2282. };
  2283. }(),
  2284. copy: function ( box ) {
  2285. this.min.copy( box.min );
  2286. this.max.copy( box.max );
  2287. return this;
  2288. },
  2289. makeEmpty: function () {
  2290. this.min.x = this.min.y = this.min.z = Infinity;
  2291. this.max.x = this.max.y = this.max.z = - Infinity;
  2292. return this;
  2293. },
  2294. empty: function () {
  2295. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2296. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2297. },
  2298. center: function ( optionalTarget ) {
  2299. var result = optionalTarget || new THREE.Vector3();
  2300. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2301. },
  2302. size: function ( optionalTarget ) {
  2303. var result = optionalTarget || new THREE.Vector3();
  2304. return result.subVectors( this.max, this.min );
  2305. },
  2306. expandByPoint: function ( point ) {
  2307. this.min.min( point );
  2308. this.max.max( point );
  2309. return this;
  2310. },
  2311. expandByVector: function ( vector ) {
  2312. this.min.sub( vector );
  2313. this.max.add( vector );
  2314. return this;
  2315. },
  2316. expandByScalar: function ( scalar ) {
  2317. this.min.addScalar( - scalar );
  2318. this.max.addScalar( scalar );
  2319. return this;
  2320. },
  2321. containsPoint: function ( point ) {
  2322. if ( point.x < this.min.x || point.x > this.max.x ||
  2323. point.y < this.min.y || point.y > this.max.y ||
  2324. point.z < this.min.z || point.z > this.max.z ) {
  2325. return false;
  2326. }
  2327. return true;
  2328. },
  2329. containsBox: function ( box ) {
  2330. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2331. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  2332. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  2333. return true;
  2334. }
  2335. return false;
  2336. },
  2337. getParameter: function ( point, optionalTarget ) {
  2338. // This can potentially have a divide by zero if the box
  2339. // has a size dimension of 0.
  2340. var result = optionalTarget || new THREE.Vector3();
  2341. return result.set(
  2342. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2343. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2344. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2345. );
  2346. },
  2347. isIntersectionBox: function ( box ) {
  2348. // using 6 splitting planes to rule out intersections.
  2349. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2350. box.max.y < this.min.y || box.min.y > this.max.y ||
  2351. box.max.z < this.min.z || box.min.z > this.max.z ) {
  2352. return false;
  2353. }
  2354. return true;
  2355. },
  2356. clampPoint: function ( point, optionalTarget ) {
  2357. var result = optionalTarget || new THREE.Vector3();
  2358. return result.copy( point ).clamp( this.min, this.max );
  2359. },
  2360. distanceToPoint: function () {
  2361. var v1 = new THREE.Vector3();
  2362. return function ( point ) {
  2363. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2364. return clampedPoint.sub( point ).length();
  2365. };
  2366. }(),
  2367. getBoundingSphere: function () {
  2368. var v1 = new THREE.Vector3();
  2369. return function ( optionalTarget ) {
  2370. var result = optionalTarget || new THREE.Sphere();
  2371. result.center = this.center();
  2372. result.radius = this.size( v1 ).length() * 0.5;
  2373. return result;
  2374. };
  2375. }(),
  2376. intersect: function ( box ) {
  2377. this.min.max( box.min );
  2378. this.max.min( box.max );
  2379. return this;
  2380. },
  2381. union: function ( box ) {
  2382. this.min.min( box.min );
  2383. this.max.max( box.max );
  2384. return this;
  2385. },
  2386. applyMatrix4: function () {
  2387. var points = [
  2388. new THREE.Vector3(),
  2389. new THREE.Vector3(),
  2390. new THREE.Vector3(),
  2391. new THREE.Vector3(),
  2392. new THREE.Vector3(),
  2393. new THREE.Vector3(),
  2394. new THREE.Vector3(),
  2395. new THREE.Vector3()
  2396. ];
  2397. return function ( matrix ) {
  2398. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2399. points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2400. points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2401. points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2402. points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2403. points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2404. points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2405. points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2406. points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2407. this.makeEmpty();
  2408. this.setFromPoints( points );
  2409. return this;
  2410. };
  2411. }(),
  2412. translate: function ( offset ) {
  2413. this.min.add( offset );
  2414. this.max.add( offset );
  2415. return this;
  2416. },
  2417. equals: function ( box ) {
  2418. return box.min.equals( this.min ) && box.max.equals( this.max );
  2419. },
  2420. clone: function () {
  2421. return new THREE.Box3().copy( this );
  2422. }
  2423. };
  2424. // File:src/math/Matrix3.js
  2425. /**
  2426. * @author alteredq / http://alteredqualia.com/
  2427. * @author WestLangley / http://github.com/WestLangley
  2428. * @author bhouston / http://exocortex.com
  2429. */
  2430. THREE.Matrix3 = function () {
  2431. this.elements = new Float32Array( [
  2432. 1, 0, 0,
  2433. 0, 1, 0,
  2434. 0, 0, 1
  2435. ] );
  2436. if ( arguments.length > 0 ) {
  2437. THREE.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  2438. }
  2439. };
  2440. THREE.Matrix3.prototype = {
  2441. constructor: THREE.Matrix3,
  2442. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2443. var te = this.elements;
  2444. te[ 0 ] = n11; te[ 3 ] = n12; te[ 6 ] = n13;
  2445. te[ 1 ] = n21; te[ 4 ] = n22; te[ 7 ] = n23;
  2446. te[ 2 ] = n31; te[ 5 ] = n32; te[ 8 ] = n33;
  2447. return this;
  2448. },
  2449. identity: function () {
  2450. this.set(
  2451. 1, 0, 0,
  2452. 0, 1, 0,
  2453. 0, 0, 1
  2454. );
  2455. return this;
  2456. },
  2457. copy: function ( m ) {
  2458. var me = m.elements;
  2459. this.set(
  2460. me[ 0 ], me[ 3 ], me[ 6 ],
  2461. me[ 1 ], me[ 4 ], me[ 7 ],
  2462. me[ 2 ], me[ 5 ], me[ 8 ]
  2463. );
  2464. return this;
  2465. },
  2466. multiplyVector3: function ( vector ) {
  2467. THREE.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  2468. return vector.applyMatrix3( this );
  2469. },
  2470. multiplyVector3Array: function ( a ) {
  2471. THREE.warn( 'THREE.Matrix3: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  2472. return this.applyToVector3Array( a );
  2473. },
  2474. applyToVector3Array: function () {
  2475. var v1 = new THREE.Vector3();
  2476. return function ( array, offset, length ) {
  2477. if ( offset === undefined ) offset = 0;
  2478. if ( length === undefined ) length = array.length;
  2479. for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) {
  2480. v1.x = array[ j ];
  2481. v1.y = array[ j + 1 ];
  2482. v1.z = array[ j + 2 ];
  2483. v1.applyMatrix3( this );
  2484. array[ j ] = v1.x;
  2485. array[ j + 1 ] = v1.y;
  2486. array[ j + 2 ] = v1.z;
  2487. }
  2488. return array;
  2489. };
  2490. }(),
  2491. multiplyScalar: function ( s ) {
  2492. var te = this.elements;
  2493. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  2494. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  2495. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  2496. return this;
  2497. },
  2498. determinant: function () {
  2499. var te = this.elements;
  2500. var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  2501. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  2502. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  2503. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  2504. },
  2505. getInverse: function ( matrix, throwOnInvertible ) {
  2506. // input: THREE.Matrix4
  2507. // ( based on http://code.google.com/p/webgl-mjs/ )
  2508. var me = matrix.elements;
  2509. var te = this.elements;
  2510. te[ 0 ] = me[ 10 ] * me[ 5 ] - me[ 6 ] * me[ 9 ];
  2511. te[ 1 ] = - me[ 10 ] * me[ 1 ] + me[ 2 ] * me[ 9 ];
  2512. te[ 2 ] = me[ 6 ] * me[ 1 ] - me[ 2 ] * me[ 5 ];
  2513. te[ 3 ] = - me[ 10 ] * me[ 4 ] + me[ 6 ] * me[ 8 ];
  2514. te[ 4 ] = me[ 10 ] * me[ 0 ] - me[ 2 ] * me[ 8 ];
  2515. te[ 5 ] = - me[ 6 ] * me[ 0 ] + me[ 2 ] * me[ 4 ];
  2516. te[ 6 ] = me[ 9 ] * me[ 4 ] - me[ 5 ] * me[ 8 ];
  2517. te[ 7 ] = - me[ 9 ] * me[ 0 ] + me[ 1 ] * me[ 8 ];
  2518. te[ 8 ] = me[ 5 ] * me[ 0 ] - me[ 1 ] * me[ 4 ];
  2519. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ];
  2520. // no inverse
  2521. if ( det === 0 ) {
  2522. var msg = "Matrix3.getInverse(): can't invert matrix, determinant is 0";
  2523. if ( throwOnInvertible || false ) {
  2524. throw new Error( msg );
  2525. } else {
  2526. THREE.warn( msg );
  2527. }
  2528. this.identity();
  2529. return this;
  2530. }
  2531. this.multiplyScalar( 1.0 / det );
  2532. return this;
  2533. },
  2534. transpose: function () {
  2535. var tmp, m = this.elements;
  2536. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  2537. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  2538. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  2539. return this;
  2540. },
  2541. flattenToArrayOffset: function ( array, offset ) {
  2542. var te = this.elements;
  2543. array[ offset ] = te[ 0 ];
  2544. array[ offset + 1 ] = te[ 1 ];
  2545. array[ offset + 2 ] = te[ 2 ];
  2546. array[ offset + 3 ] = te[ 3 ];
  2547. array[ offset + 4 ] = te[ 4 ];
  2548. array[ offset + 5 ] = te[ 5 ];
  2549. array[ offset + 6 ] = te[ 6 ];
  2550. array[ offset + 7 ] = te[ 7 ];
  2551. array[ offset + 8 ] = te[ 8 ];
  2552. return array;
  2553. },
  2554. getNormalMatrix: function ( m ) {
  2555. // input: THREE.Matrix4
  2556. this.getInverse( m ).transpose();
  2557. return this;
  2558. },
  2559. transposeIntoArray: function ( r ) {
  2560. var m = this.elements;
  2561. r[ 0 ] = m[ 0 ];
  2562. r[ 1 ] = m[ 3 ];
  2563. r[ 2 ] = m[ 6 ];
  2564. r[ 3 ] = m[ 1 ];
  2565. r[ 4 ] = m[ 4 ];
  2566. r[ 5 ] = m[ 7 ];
  2567. r[ 6 ] = m[ 2 ];
  2568. r[ 7 ] = m[ 5 ];
  2569. r[ 8 ] = m[ 8 ];
  2570. return this;
  2571. },
  2572. fromArray: function ( array ) {
  2573. this.elements.set( array );
  2574. return this;
  2575. },
  2576. toArray: function () {
  2577. var te = this.elements;
  2578. return [
  2579. te[ 0 ], te[ 1 ], te[ 2 ],
  2580. te[ 3 ], te[ 4 ], te[ 5 ],
  2581. te[ 6 ], te[ 7 ], te[ 8 ]
  2582. ];
  2583. },
  2584. clone: function () {
  2585. return new THREE.Matrix3().fromArray( this.elements );
  2586. }
  2587. };
  2588. // File:src/math/Matrix4.js
  2589. /**
  2590. * @author mrdoob / http://mrdoob.com/
  2591. * @author supereggbert / http://www.paulbrunt.co.uk/
  2592. * @author philogb / http://blog.thejit.org/
  2593. * @author jordi_ros / http://plattsoft.com
  2594. * @author D1plo1d / http://github.com/D1plo1d
  2595. * @author alteredq / http://alteredqualia.com/
  2596. * @author mikael emtinger / http://gomo.se/
  2597. * @author timknip / http://www.floorplanner.com/
  2598. * @author bhouston / http://exocortex.com
  2599. * @author WestLangley / http://github.com/WestLangley
  2600. */
  2601. THREE.Matrix4 = function () {
  2602. this.elements = new Float32Array( [
  2603. 1, 0, 0, 0,
  2604. 0, 1, 0, 0,
  2605. 0, 0, 1, 0,
  2606. 0, 0, 0, 1
  2607. ] );
  2608. if ( arguments.length > 0 ) {
  2609. THREE.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  2610. }
  2611. };
  2612. THREE.Matrix4.prototype = {
  2613. constructor: THREE.Matrix4,
  2614. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2615. var te = this.elements;
  2616. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  2617. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  2618. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  2619. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  2620. return this;
  2621. },
  2622. identity: function () {
  2623. this.set(
  2624. 1, 0, 0, 0,
  2625. 0, 1, 0, 0,
  2626. 0, 0, 1, 0,
  2627. 0, 0, 0, 1
  2628. );
  2629. return this;
  2630. },
  2631. copy: function ( m ) {
  2632. this.elements.set( m.elements );
  2633. return this;
  2634. },
  2635. extractPosition: function ( m ) {
  2636. THREE.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  2637. return this.copyPosition( m );
  2638. },
  2639. copyPosition: function ( m ) {
  2640. var te = this.elements;
  2641. var me = m.elements;
  2642. te[ 12 ] = me[ 12 ];
  2643. te[ 13 ] = me[ 13 ];
  2644. te[ 14 ] = me[ 14 ];
  2645. return this;
  2646. },
  2647. extractBasis: function ( xAxis, yAxis, zAxis ) {
  2648. var te = this.elements;
  2649. xAxis.set( te[ 0 ], te[ 1 ], te[ 2 ] );
  2650. yAxis.set( te[ 4 ], te[ 5 ], te[ 6 ] );
  2651. zAxis.set( te[ 8 ], te[ 9 ], te[ 10 ] );
  2652. return this;
  2653. },
  2654. makeBasis: function ( xAxis, yAxis, zAxis ) {
  2655. this.set(
  2656. xAxis.x, yAxis.x, zAxis.x, 0,
  2657. xAxis.y, yAxis.y, zAxis.y, 0,
  2658. xAxis.z, yAxis.z, zAxis.z, 0,
  2659. 0, 0, 0, 1
  2660. );
  2661. return this;
  2662. },
  2663. extractRotation: function () {
  2664. var v1 = new THREE.Vector3();
  2665. return function ( m ) {
  2666. var te = this.elements;
  2667. var me = m.elements;
  2668. var scaleX = 1 / v1.set( me[ 0 ], me[ 1 ], me[ 2 ] ).length();
  2669. var scaleY = 1 / v1.set( me[ 4 ], me[ 5 ], me[ 6 ] ).length();
  2670. var scaleZ = 1 / v1.set( me[ 8 ], me[ 9 ], me[ 10 ] ).length();
  2671. te[ 0 ] = me[ 0 ] * scaleX;
  2672. te[ 1 ] = me[ 1 ] * scaleX;
  2673. te[ 2 ] = me[ 2 ] * scaleX;
  2674. te[ 4 ] = me[ 4 ] * scaleY;
  2675. te[ 5 ] = me[ 5 ] * scaleY;
  2676. te[ 6 ] = me[ 6 ] * scaleY;
  2677. te[ 8 ] = me[ 8 ] * scaleZ;
  2678. te[ 9 ] = me[ 9 ] * scaleZ;
  2679. te[ 10 ] = me[ 10 ] * scaleZ;
  2680. return this;
  2681. };
  2682. }(),
  2683. makeRotationFromEuler: function ( euler ) {
  2684. if ( euler instanceof THREE.Euler === false ) {
  2685. THREE.error( 'THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  2686. }
  2687. var te = this.elements;
  2688. var x = euler.x, y = euler.y, z = euler.z;
  2689. var a = Math.cos( x ), b = Math.sin( x );
  2690. var c = Math.cos( y ), d = Math.sin( y );
  2691. var e = Math.cos( z ), f = Math.sin( z );
  2692. if ( euler.order === 'XYZ' ) {
  2693. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2694. te[ 0 ] = c * e;
  2695. te[ 4 ] = - c * f;
  2696. te[ 8 ] = d;
  2697. te[ 1 ] = af + be * d;
  2698. te[ 5 ] = ae - bf * d;
  2699. te[ 9 ] = - b * c;
  2700. te[ 2 ] = bf - ae * d;
  2701. te[ 6 ] = be + af * d;
  2702. te[ 10 ] = a * c;
  2703. } else if ( euler.order === 'YXZ' ) {
  2704. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2705. te[ 0 ] = ce + df * b;
  2706. te[ 4 ] = de * b - cf;
  2707. te[ 8 ] = a * d;
  2708. te[ 1 ] = a * f;
  2709. te[ 5 ] = a * e;
  2710. te[ 9 ] = - b;
  2711. te[ 2 ] = cf * b - de;
  2712. te[ 6 ] = df + ce * b;
  2713. te[ 10 ] = a * c;
  2714. } else if ( euler.order === 'ZXY' ) {
  2715. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2716. te[ 0 ] = ce - df * b;
  2717. te[ 4 ] = - a * f;
  2718. te[ 8 ] = de + cf * b;
  2719. te[ 1 ] = cf + de * b;
  2720. te[ 5 ] = a * e;
  2721. te[ 9 ] = df - ce * b;
  2722. te[ 2 ] = - a * d;
  2723. te[ 6 ] = b;
  2724. te[ 10 ] = a * c;
  2725. } else if ( euler.order === 'ZYX' ) {
  2726. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2727. te[ 0 ] = c * e;
  2728. te[ 4 ] = be * d - af;
  2729. te[ 8 ] = ae * d + bf;
  2730. te[ 1 ] = c * f;
  2731. te[ 5 ] = bf * d + ae;
  2732. te[ 9 ] = af * d - be;
  2733. te[ 2 ] = - d;
  2734. te[ 6 ] = b * c;
  2735. te[ 10 ] = a * c;
  2736. } else if ( euler.order === 'YZX' ) {
  2737. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2738. te[ 0 ] = c * e;
  2739. te[ 4 ] = bd - ac * f;
  2740. te[ 8 ] = bc * f + ad;
  2741. te[ 1 ] = f;
  2742. te[ 5 ] = a * e;
  2743. te[ 9 ] = - b * e;
  2744. te[ 2 ] = - d * e;
  2745. te[ 6 ] = ad * f + bc;
  2746. te[ 10 ] = ac - bd * f;
  2747. } else if ( euler.order === 'XZY' ) {
  2748. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2749. te[ 0 ] = c * e;
  2750. te[ 4 ] = - f;
  2751. te[ 8 ] = d * e;
  2752. te[ 1 ] = ac * f + bd;
  2753. te[ 5 ] = a * e;
  2754. te[ 9 ] = ad * f - bc;
  2755. te[ 2 ] = bc * f - ad;
  2756. te[ 6 ] = b * e;
  2757. te[ 10 ] = bd * f + ac;
  2758. }
  2759. // last column
  2760. te[ 3 ] = 0;
  2761. te[ 7 ] = 0;
  2762. te[ 11 ] = 0;
  2763. // bottom row
  2764. te[ 12 ] = 0;
  2765. te[ 13 ] = 0;
  2766. te[ 14 ] = 0;
  2767. te[ 15 ] = 1;
  2768. return this;
  2769. },
  2770. setRotationFromQuaternion: function ( q ) {
  2771. THREE.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  2772. return this.makeRotationFromQuaternion( q );
  2773. },
  2774. makeRotationFromQuaternion: function ( q ) {
  2775. var te = this.elements;
  2776. var x = q.x, y = q.y, z = q.z, w = q.w;
  2777. var x2 = x + x, y2 = y + y, z2 = z + z;
  2778. var xx = x * x2, xy = x * y2, xz = x * z2;
  2779. var yy = y * y2, yz = y * z2, zz = z * z2;
  2780. var wx = w * x2, wy = w * y2, wz = w * z2;
  2781. te[ 0 ] = 1 - ( yy + zz );
  2782. te[ 4 ] = xy - wz;
  2783. te[ 8 ] = xz + wy;
  2784. te[ 1 ] = xy + wz;
  2785. te[ 5 ] = 1 - ( xx + zz );
  2786. te[ 9 ] = yz - wx;
  2787. te[ 2 ] = xz - wy;
  2788. te[ 6 ] = yz + wx;
  2789. te[ 10 ] = 1 - ( xx + yy );
  2790. // last column
  2791. te[ 3 ] = 0;
  2792. te[ 7 ] = 0;
  2793. te[ 11 ] = 0;
  2794. // bottom row
  2795. te[ 12 ] = 0;
  2796. te[ 13 ] = 0;
  2797. te[ 14 ] = 0;
  2798. te[ 15 ] = 1;
  2799. return this;
  2800. },
  2801. lookAt: function () {
  2802. var x = new THREE.Vector3();
  2803. var y = new THREE.Vector3();
  2804. var z = new THREE.Vector3();
  2805. return function ( eye, target, up ) {
  2806. var te = this.elements;
  2807. z.subVectors( eye, target ).normalize();
  2808. if ( z.length() === 0 ) {
  2809. z.z = 1;
  2810. }
  2811. x.crossVectors( up, z ).normalize();
  2812. if ( x.length() === 0 ) {
  2813. z.x += 0.0001;
  2814. x.crossVectors( up, z ).normalize();
  2815. }
  2816. y.crossVectors( z, x );
  2817. te[ 0 ] = x.x; te[ 4 ] = y.x; te[ 8 ] = z.x;
  2818. te[ 1 ] = x.y; te[ 5 ] = y.y; te[ 9 ] = z.y;
  2819. te[ 2 ] = x.z; te[ 6 ] = y.z; te[ 10 ] = z.z;
  2820. return this;
  2821. };
  2822. }(),
  2823. multiply: function ( m, n ) {
  2824. if ( n !== undefined ) {
  2825. THREE.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2826. return this.multiplyMatrices( m, n );
  2827. }
  2828. return this.multiplyMatrices( this, m );
  2829. },
  2830. multiplyMatrices: function ( a, b ) {
  2831. var ae = a.elements;
  2832. var be = b.elements;
  2833. var te = this.elements;
  2834. var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  2835. var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  2836. var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  2837. var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  2838. var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  2839. var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  2840. var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  2841. var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  2842. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2843. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2844. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2845. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2846. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2847. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2848. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2849. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2850. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2851. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2852. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2853. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2854. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2855. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2856. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2857. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2858. return this;
  2859. },
  2860. multiplyToArray: function ( a, b, r ) {
  2861. var te = this.elements;
  2862. this.multiplyMatrices( a, b );
  2863. r[ 0 ] = te[ 0 ]; r[ 1 ] = te[ 1 ]; r[ 2 ] = te[ 2 ]; r[ 3 ] = te[ 3 ];
  2864. r[ 4 ] = te[ 4 ]; r[ 5 ] = te[ 5 ]; r[ 6 ] = te[ 6 ]; r[ 7 ] = te[ 7 ];
  2865. r[ 8 ] = te[ 8 ]; r[ 9 ] = te[ 9 ]; r[ 10 ] = te[ 10 ]; r[ 11 ] = te[ 11 ];
  2866. r[ 12 ] = te[ 12 ]; r[ 13 ] = te[ 13 ]; r[ 14 ] = te[ 14 ]; r[ 15 ] = te[ 15 ];
  2867. return this;
  2868. },
  2869. multiplyScalar: function ( s ) {
  2870. var te = this.elements;
  2871. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  2872. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  2873. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  2874. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  2875. return this;
  2876. },
  2877. multiplyVector3: function ( vector ) {
  2878. THREE.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  2879. return vector.applyProjection( this );
  2880. },
  2881. multiplyVector4: function ( vector ) {
  2882. THREE.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2883. return vector.applyMatrix4( this );
  2884. },
  2885. multiplyVector3Array: function ( a ) {
  2886. THREE.warn( 'THREE.Matrix4: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  2887. return this.applyToVector3Array( a );
  2888. },
  2889. applyToVector3Array: function () {
  2890. var v1 = new THREE.Vector3();
  2891. return function ( array, offset, length ) {
  2892. if ( offset === undefined ) offset = 0;
  2893. if ( length === undefined ) length = array.length;
  2894. for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) {
  2895. v1.x = array[ j ];
  2896. v1.y = array[ j + 1 ];
  2897. v1.z = array[ j + 2 ];
  2898. v1.applyMatrix4( this );
  2899. array[ j ] = v1.x;
  2900. array[ j + 1 ] = v1.y;
  2901. array[ j + 2 ] = v1.z;
  2902. }
  2903. return array;
  2904. };
  2905. }(),
  2906. rotateAxis: function ( v ) {
  2907. THREE.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  2908. v.transformDirection( this );
  2909. },
  2910. crossVector: function ( vector ) {
  2911. THREE.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2912. return vector.applyMatrix4( this );
  2913. },
  2914. determinant: function () {
  2915. var te = this.elements;
  2916. var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  2917. var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  2918. var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  2919. var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  2920. //TODO: make this more efficient
  2921. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2922. return (
  2923. n41 * (
  2924. + n14 * n23 * n32
  2925. - n13 * n24 * n32
  2926. - n14 * n22 * n33
  2927. + n12 * n24 * n33
  2928. + n13 * n22 * n34
  2929. - n12 * n23 * n34
  2930. ) +
  2931. n42 * (
  2932. + n11 * n23 * n34
  2933. - n11 * n24 * n33
  2934. + n14 * n21 * n33
  2935. - n13 * n21 * n34
  2936. + n13 * n24 * n31
  2937. - n14 * n23 * n31
  2938. ) +
  2939. n43 * (
  2940. + n11 * n24 * n32
  2941. - n11 * n22 * n34
  2942. - n14 * n21 * n32
  2943. + n12 * n21 * n34
  2944. + n14 * n22 * n31
  2945. - n12 * n24 * n31
  2946. ) +
  2947. n44 * (
  2948. - n13 * n22 * n31
  2949. - n11 * n23 * n32
  2950. + n11 * n22 * n33
  2951. + n13 * n21 * n32
  2952. - n12 * n21 * n33
  2953. + n12 * n23 * n31
  2954. )
  2955. );
  2956. },
  2957. transpose: function () {
  2958. var te = this.elements;
  2959. var tmp;
  2960. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  2961. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  2962. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  2963. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  2964. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  2965. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  2966. return this;
  2967. },
  2968. flattenToArrayOffset: function ( array, offset ) {
  2969. var te = this.elements;
  2970. array[ offset ] = te[ 0 ];
  2971. array[ offset + 1 ] = te[ 1 ];
  2972. array[ offset + 2 ] = te[ 2 ];
  2973. array[ offset + 3 ] = te[ 3 ];
  2974. array[ offset + 4 ] = te[ 4 ];
  2975. array[ offset + 5 ] = te[ 5 ];
  2976. array[ offset + 6 ] = te[ 6 ];
  2977. array[ offset + 7 ] = te[ 7 ];
  2978. array[ offset + 8 ] = te[ 8 ];
  2979. array[ offset + 9 ] = te[ 9 ];
  2980. array[ offset + 10 ] = te[ 10 ];
  2981. array[ offset + 11 ] = te[ 11 ];
  2982. array[ offset + 12 ] = te[ 12 ];
  2983. array[ offset + 13 ] = te[ 13 ];
  2984. array[ offset + 14 ] = te[ 14 ];
  2985. array[ offset + 15 ] = te[ 15 ];
  2986. return array;
  2987. },
  2988. getPosition: function () {
  2989. var v1 = new THREE.Vector3();
  2990. return function () {
  2991. THREE.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  2992. var te = this.elements;
  2993. return v1.set( te[ 12 ], te[ 13 ], te[ 14 ] );
  2994. };
  2995. }(),
  2996. setPosition: function ( v ) {
  2997. var te = this.elements;
  2998. te[ 12 ] = v.x;
  2999. te[ 13 ] = v.y;
  3000. te[ 14 ] = v.z;
  3001. return this;
  3002. },
  3003. getInverse: function ( m, throwOnInvertible ) {
  3004. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3005. var te = this.elements;
  3006. var me = m.elements;
  3007. var n11 = me[ 0 ], n12 = me[ 4 ], n13 = me[ 8 ], n14 = me[ 12 ];
  3008. var n21 = me[ 1 ], n22 = me[ 5 ], n23 = me[ 9 ], n24 = me[ 13 ];
  3009. var n31 = me[ 2 ], n32 = me[ 6 ], n33 = me[ 10 ], n34 = me[ 14 ];
  3010. var n41 = me[ 3 ], n42 = me[ 7 ], n43 = me[ 11 ], n44 = me[ 15 ];
  3011. te[ 0 ] = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44;
  3012. te[ 4 ] = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44;
  3013. te[ 8 ] = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44;
  3014. te[ 12 ] = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3015. te[ 1 ] = n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44;
  3016. te[ 5 ] = n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44;
  3017. te[ 9 ] = n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44;
  3018. te[ 13 ] = n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34;
  3019. te[ 2 ] = n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44;
  3020. te[ 6 ] = n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44;
  3021. te[ 10 ] = n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44;
  3022. te[ 14 ] = n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34;
  3023. te[ 3 ] = n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43;
  3024. te[ 7 ] = n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43;
  3025. te[ 11 ] = n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43;
  3026. te[ 15 ] = n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33;
  3027. var det = n11 * te[ 0 ] + n21 * te[ 4 ] + n31 * te[ 8 ] + n41 * te[ 12 ];
  3028. if ( det == 0 ) {
  3029. var msg = "THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0";
  3030. if ( throwOnInvertible || false ) {
  3031. throw new Error( msg );
  3032. } else {
  3033. THREE.warn( msg );
  3034. }
  3035. this.identity();
  3036. return this;
  3037. }
  3038. this.multiplyScalar( 1 / det );
  3039. return this;
  3040. },
  3041. translate: function ( v ) {
  3042. THREE.error( 'THREE.Matrix4: .translate() has been removed.' );
  3043. },
  3044. rotateX: function ( angle ) {
  3045. THREE.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  3046. },
  3047. rotateY: function ( angle ) {
  3048. THREE.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  3049. },
  3050. rotateZ: function ( angle ) {
  3051. THREE.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  3052. },
  3053. rotateByAxis: function ( axis, angle ) {
  3054. THREE.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  3055. },
  3056. scale: function ( v ) {
  3057. var te = this.elements;
  3058. var x = v.x, y = v.y, z = v.z;
  3059. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  3060. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  3061. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  3062. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  3063. return this;
  3064. },
  3065. getMaxScaleOnAxis: function () {
  3066. var te = this.elements;
  3067. var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  3068. var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  3069. var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  3070. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  3071. },
  3072. makeTranslation: function ( x, y, z ) {
  3073. this.set(
  3074. 1, 0, 0, x,
  3075. 0, 1, 0, y,
  3076. 0, 0, 1, z,
  3077. 0, 0, 0, 1
  3078. );
  3079. return this;
  3080. },
  3081. makeRotationX: function ( theta ) {
  3082. var c = Math.cos( theta ), s = Math.sin( theta );
  3083. this.set(
  3084. 1, 0, 0, 0,
  3085. 0, c, - s, 0,
  3086. 0, s, c, 0,
  3087. 0, 0, 0, 1
  3088. );
  3089. return this;
  3090. },
  3091. makeRotationY: function ( theta ) {
  3092. var c = Math.cos( theta ), s = Math.sin( theta );
  3093. this.set(
  3094. c, 0, s, 0,
  3095. 0, 1, 0, 0,
  3096. - s, 0, c, 0,
  3097. 0, 0, 0, 1
  3098. );
  3099. return this;
  3100. },
  3101. makeRotationZ: function ( theta ) {
  3102. var c = Math.cos( theta ), s = Math.sin( theta );
  3103. this.set(
  3104. c, - s, 0, 0,
  3105. s, c, 0, 0,
  3106. 0, 0, 1, 0,
  3107. 0, 0, 0, 1
  3108. );
  3109. return this;
  3110. },
  3111. makeRotationAxis: function ( axis, angle ) {
  3112. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3113. var c = Math.cos( angle );
  3114. var s = Math.sin( angle );
  3115. var t = 1 - c;
  3116. var x = axis.x, y = axis.y, z = axis.z;
  3117. var tx = t * x, ty = t * y;
  3118. this.set(
  3119. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  3120. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3121. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3122. 0, 0, 0, 1
  3123. );
  3124. return this;
  3125. },
  3126. makeScale: function ( x, y, z ) {
  3127. this.set(
  3128. x, 0, 0, 0,
  3129. 0, y, 0, 0,
  3130. 0, 0, z, 0,
  3131. 0, 0, 0, 1
  3132. );
  3133. return this;
  3134. },
  3135. compose: function ( position, quaternion, scale ) {
  3136. this.makeRotationFromQuaternion( quaternion );
  3137. this.scale( scale );
  3138. this.setPosition( position );
  3139. return this;
  3140. },
  3141. decompose: function () {
  3142. var vector = new THREE.Vector3();
  3143. var matrix = new THREE.Matrix4();
  3144. return function ( position, quaternion, scale ) {
  3145. var te = this.elements;
  3146. var sx = vector.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  3147. var sy = vector.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  3148. var sz = vector.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  3149. // if determine is negative, we need to invert one scale
  3150. var det = this.determinant();
  3151. if ( det < 0 ) {
  3152. sx = - sx;
  3153. }
  3154. position.x = te[ 12 ];
  3155. position.y = te[ 13 ];
  3156. position.z = te[ 14 ];
  3157. // scale the rotation part
  3158. matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy()
  3159. var invSX = 1 / sx;
  3160. var invSY = 1 / sy;
  3161. var invSZ = 1 / sz;
  3162. matrix.elements[ 0 ] *= invSX;
  3163. matrix.elements[ 1 ] *= invSX;
  3164. matrix.elements[ 2 ] *= invSX;
  3165. matrix.elements[ 4 ] *= invSY;
  3166. matrix.elements[ 5 ] *= invSY;
  3167. matrix.elements[ 6 ] *= invSY;
  3168. matrix.elements[ 8 ] *= invSZ;
  3169. matrix.elements[ 9 ] *= invSZ;
  3170. matrix.elements[ 10 ] *= invSZ;
  3171. quaternion.setFromRotationMatrix( matrix );
  3172. scale.x = sx;
  3173. scale.y = sy;
  3174. scale.z = sz;
  3175. return this;
  3176. };
  3177. }(),
  3178. makeFrustum: function ( left, right, bottom, top, near, far ) {
  3179. var te = this.elements;
  3180. var x = 2 * near / ( right - left );
  3181. var y = 2 * near / ( top - bottom );
  3182. var a = ( right + left ) / ( right - left );
  3183. var b = ( top + bottom ) / ( top - bottom );
  3184. var c = - ( far + near ) / ( far - near );
  3185. var d = - 2 * far * near / ( far - near );
  3186. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  3187. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  3188. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  3189. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  3190. return this;
  3191. },
  3192. makePerspective: function ( fov, aspect, near, far ) {
  3193. var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) );
  3194. var ymin = - ymax;
  3195. var xmin = ymin * aspect;
  3196. var xmax = ymax * aspect;
  3197. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  3198. },
  3199. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  3200. var te = this.elements;
  3201. var w = right - left;
  3202. var h = top - bottom;
  3203. var p = far - near;
  3204. var x = ( right + left ) / w;
  3205. var y = ( top + bottom ) / h;
  3206. var z = ( far + near ) / p;
  3207. te[ 0 ] = 2 / w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  3208. te[ 1 ] = 0; te[ 5 ] = 2 / h; te[ 9 ] = 0; te[ 13 ] = - y;
  3209. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 / p; te[ 14 ] = - z;
  3210. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  3211. return this;
  3212. },
  3213. fromArray: function ( array ) {
  3214. this.elements.set( array );
  3215. return this;
  3216. },
  3217. toArray: function () {
  3218. var te = this.elements;
  3219. return [
  3220. te[ 0 ], te[ 1 ], te[ 2 ], te[ 3 ],
  3221. te[ 4 ], te[ 5 ], te[ 6 ], te[ 7 ],
  3222. te[ 8 ], te[ 9 ], te[ 10 ], te[ 11 ],
  3223. te[ 12 ], te[ 13 ], te[ 14 ], te[ 15 ]
  3224. ];
  3225. },
  3226. clone: function () {
  3227. return new THREE.Matrix4().fromArray( this.elements );
  3228. }
  3229. };
  3230. // File:src/math/Ray.js
  3231. /**
  3232. * @author bhouston / http://exocortex.com
  3233. */
  3234. THREE.Ray = function ( origin, direction ) {
  3235. this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3();
  3236. this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3();
  3237. };
  3238. THREE.Ray.prototype = {
  3239. constructor: THREE.Ray,
  3240. set: function ( origin, direction ) {
  3241. this.origin.copy( origin );
  3242. this.direction.copy( direction );
  3243. return this;
  3244. },
  3245. copy: function ( ray ) {
  3246. this.origin.copy( ray.origin );
  3247. this.direction.copy( ray.direction );
  3248. return this;
  3249. },
  3250. at: function ( t, optionalTarget ) {
  3251. var result = optionalTarget || new THREE.Vector3();
  3252. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  3253. },
  3254. recast: function () {
  3255. var v1 = new THREE.Vector3();
  3256. return function ( t ) {
  3257. this.origin.copy( this.at( t, v1 ) );
  3258. return this;
  3259. };
  3260. }(),
  3261. closestPointToPoint: function ( point, optionalTarget ) {
  3262. var result = optionalTarget || new THREE.Vector3();
  3263. result.subVectors( point, this.origin );
  3264. var directionDistance = result.dot( this.direction );
  3265. if ( directionDistance < 0 ) {
  3266. return result.copy( this.origin );
  3267. }
  3268. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3269. },
  3270. distanceToPoint: function () {
  3271. var v1 = new THREE.Vector3();
  3272. return function ( point ) {
  3273. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  3274. // point behind the ray
  3275. if ( directionDistance < 0 ) {
  3276. return this.origin.distanceTo( point );
  3277. }
  3278. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3279. return v1.distanceTo( point );
  3280. };
  3281. }(),
  3282. distanceSqToSegment: function () {
  3283. var segCenter = new THREE.Vector3();
  3284. var segDir = new THREE.Vector3();
  3285. var diff = new THREE.Vector3();
  3286. return function ( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3287. // from http://www.geometrictools.com/LibMathematics/Distance/Wm5DistRay3Segment3.cpp
  3288. // It returns the min distance between the ray and the segment
  3289. // defined by v0 and v1
  3290. // It can also set two optional targets :
  3291. // - The closest point on the ray
  3292. // - The closest point on the segment
  3293. segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3294. segDir.copy( v1 ).sub( v0 ).normalize();
  3295. diff.copy( this.origin ).sub( segCenter );
  3296. var segExtent = v0.distanceTo( v1 ) * 0.5;
  3297. var a01 = - this.direction.dot( segDir );
  3298. var b0 = diff.dot( this.direction );
  3299. var b1 = - diff.dot( segDir );
  3300. var c = diff.lengthSq();
  3301. var det = Math.abs( 1 - a01 * a01 );
  3302. var s0, s1, sqrDist, extDet;
  3303. if ( det > 0 ) {
  3304. // The ray and segment are not parallel.
  3305. s0 = a01 * b1 - b0;
  3306. s1 = a01 * b0 - b1;
  3307. extDet = segExtent * det;
  3308. if ( s0 >= 0 ) {
  3309. if ( s1 >= - extDet ) {
  3310. if ( s1 <= extDet ) {
  3311. // region 0
  3312. // Minimum at interior points of ray and segment.
  3313. var invDet = 1 / det;
  3314. s0 *= invDet;
  3315. s1 *= invDet;
  3316. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3317. } else {
  3318. // region 1
  3319. s1 = segExtent;
  3320. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3321. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3322. }
  3323. } else {
  3324. // region 5
  3325. s1 = - segExtent;
  3326. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3327. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3328. }
  3329. } else {
  3330. if ( s1 <= - extDet ) {
  3331. // region 4
  3332. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3333. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3334. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3335. } else if ( s1 <= extDet ) {
  3336. // region 3
  3337. s0 = 0;
  3338. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3339. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3340. } else {
  3341. // region 2
  3342. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3343. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3344. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3345. }
  3346. }
  3347. } else {
  3348. // Ray and segment are parallel.
  3349. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3350. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3351. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3352. }
  3353. if ( optionalPointOnRay ) {
  3354. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  3355. }
  3356. if ( optionalPointOnSegment ) {
  3357. optionalPointOnSegment.copy( segDir ).multiplyScalar( s1 ).add( segCenter );
  3358. }
  3359. return sqrDist;
  3360. };
  3361. }(),
  3362. isIntersectionSphere: function ( sphere ) {
  3363. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  3364. },
  3365. intersectSphere: function () {
  3366. // from http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-sphere-intersection/
  3367. var v1 = new THREE.Vector3();
  3368. return function ( sphere, optionalTarget ) {
  3369. v1.subVectors( sphere.center, this.origin );
  3370. var tca = v1.dot( this.direction );
  3371. var d2 = v1.dot( v1 ) - tca * tca;
  3372. var radius2 = sphere.radius * sphere.radius;
  3373. if ( d2 > radius2 ) return null;
  3374. var thc = Math.sqrt( radius2 - d2 );
  3375. // t0 = first intersect point - entrance on front of sphere
  3376. var t0 = tca - thc;
  3377. // t1 = second intersect point - exit point on back of sphere
  3378. var t1 = tca + thc;
  3379. // test to see if both t0 and t1 are behind the ray - if so, return null
  3380. if ( t0 < 0 && t1 < 0 ) return null;
  3381. // test to see if t0 is behind the ray:
  3382. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3383. // in order to always return an intersect point that is in front of the ray.
  3384. if ( t0 < 0 ) return this.at( t1, optionalTarget );
  3385. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3386. return this.at( t0, optionalTarget );
  3387. }
  3388. }(),
  3389. isIntersectionPlane: function ( plane ) {
  3390. // check if the ray lies on the plane first
  3391. var distToPoint = plane.distanceToPoint( this.origin );
  3392. if ( distToPoint === 0 ) {
  3393. return true;
  3394. }
  3395. var denominator = plane.normal.dot( this.direction );
  3396. if ( denominator * distToPoint < 0 ) {
  3397. return true;
  3398. }
  3399. // ray origin is behind the plane (and is pointing behind it)
  3400. return false;
  3401. },
  3402. distanceToPlane: function ( plane ) {
  3403. var denominator = plane.normal.dot( this.direction );
  3404. if ( denominator == 0 ) {
  3405. // line is coplanar, return origin
  3406. if ( plane.distanceToPoint( this.origin ) == 0 ) {
  3407. return 0;
  3408. }
  3409. // Null is preferable to undefined since undefined means.... it is undefined
  3410. return null;
  3411. }
  3412. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3413. // Return if the ray never intersects the plane
  3414. return t >= 0 ? t : null;
  3415. },
  3416. intersectPlane: function ( plane, optionalTarget ) {
  3417. var t = this.distanceToPlane( plane );
  3418. if ( t === null ) {
  3419. return null;
  3420. }
  3421. return this.at( t, optionalTarget );
  3422. },
  3423. isIntersectionBox: function () {
  3424. var v = new THREE.Vector3();
  3425. return function ( box ) {
  3426. return this.intersectBox( box, v ) !== null;
  3427. };
  3428. }(),
  3429. intersectBox: function ( box, optionalTarget ) {
  3430. // http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-box-intersection/
  3431. var tmin,tmax,tymin,tymax,tzmin,tzmax;
  3432. var invdirx = 1 / this.direction.x,
  3433. invdiry = 1 / this.direction.y,
  3434. invdirz = 1 / this.direction.z;
  3435. var origin = this.origin;
  3436. if ( invdirx >= 0 ) {
  3437. tmin = ( box.min.x - origin.x ) * invdirx;
  3438. tmax = ( box.max.x - origin.x ) * invdirx;
  3439. } else {
  3440. tmin = ( box.max.x - origin.x ) * invdirx;
  3441. tmax = ( box.min.x - origin.x ) * invdirx;
  3442. }
  3443. if ( invdiry >= 0 ) {
  3444. tymin = ( box.min.y - origin.y ) * invdiry;
  3445. tymax = ( box.max.y - origin.y ) * invdiry;
  3446. } else {
  3447. tymin = ( box.max.y - origin.y ) * invdiry;
  3448. tymax = ( box.min.y - origin.y ) * invdiry;
  3449. }
  3450. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3451. // These lines also handle the case where tmin or tmax is NaN
  3452. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3453. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  3454. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  3455. if ( invdirz >= 0 ) {
  3456. tzmin = ( box.min.z - origin.z ) * invdirz;
  3457. tzmax = ( box.max.z - origin.z ) * invdirz;
  3458. } else {
  3459. tzmin = ( box.max.z - origin.z ) * invdirz;
  3460. tzmax = ( box.min.z - origin.z ) * invdirz;
  3461. }
  3462. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3463. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3464. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3465. //return point closest to the ray (positive side)
  3466. if ( tmax < 0 ) return null;
  3467. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  3468. },
  3469. intersectTriangle: function () {
  3470. // Compute the offset origin, edges, and normal.
  3471. var diff = new THREE.Vector3();
  3472. var edge1 = new THREE.Vector3();
  3473. var edge2 = new THREE.Vector3();
  3474. var normal = new THREE.Vector3();
  3475. return function ( a, b, c, backfaceCulling, optionalTarget ) {
  3476. // from http://www.geometrictools.com/LibMathematics/Intersection/Wm5IntrRay3Triangle3.cpp
  3477. edge1.subVectors( b, a );
  3478. edge2.subVectors( c, a );
  3479. normal.crossVectors( edge1, edge2 );
  3480. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3481. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3482. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3483. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3484. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3485. var DdN = this.direction.dot( normal );
  3486. var sign;
  3487. if ( DdN > 0 ) {
  3488. if ( backfaceCulling ) return null;
  3489. sign = 1;
  3490. } else if ( DdN < 0 ) {
  3491. sign = - 1;
  3492. DdN = - DdN;
  3493. } else {
  3494. return null;
  3495. }
  3496. diff.subVectors( this.origin, a );
  3497. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  3498. // b1 < 0, no intersection
  3499. if ( DdQxE2 < 0 ) {
  3500. return null;
  3501. }
  3502. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  3503. // b2 < 0, no intersection
  3504. if ( DdE1xQ < 0 ) {
  3505. return null;
  3506. }
  3507. // b1+b2 > 1, no intersection
  3508. if ( DdQxE2 + DdE1xQ > DdN ) {
  3509. return null;
  3510. }
  3511. // Line intersects triangle, check if ray does.
  3512. var QdN = - sign * diff.dot( normal );
  3513. // t < 0, no intersection
  3514. if ( QdN < 0 ) {
  3515. return null;
  3516. }
  3517. // Ray intersects triangle.
  3518. return this.at( QdN / DdN, optionalTarget );
  3519. };
  3520. }(),
  3521. applyMatrix4: function ( matrix4 ) {
  3522. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  3523. this.origin.applyMatrix4( matrix4 );
  3524. this.direction.sub( this.origin );
  3525. this.direction.normalize();
  3526. return this;
  3527. },
  3528. equals: function ( ray ) {
  3529. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3530. },
  3531. clone: function () {
  3532. return new THREE.Ray().copy( this );
  3533. }
  3534. };
  3535. // File:src/math/Sphere.js
  3536. /**
  3537. * @author bhouston / http://exocortex.com
  3538. * @author mrdoob / http://mrdoob.com/
  3539. */
  3540. THREE.Sphere = function ( center, radius ) {
  3541. this.center = ( center !== undefined ) ? center : new THREE.Vector3();
  3542. this.radius = ( radius !== undefined ) ? radius : 0;
  3543. };
  3544. THREE.Sphere.prototype = {
  3545. constructor: THREE.Sphere,
  3546. set: function ( center, radius ) {
  3547. this.center.copy( center );
  3548. this.radius = radius;
  3549. return this;
  3550. },
  3551. setFromPoints: function () {
  3552. var box = new THREE.Box3();
  3553. return function ( points, optionalCenter ) {
  3554. var center = this.center;
  3555. if ( optionalCenter !== undefined ) {
  3556. center.copy( optionalCenter );
  3557. } else {
  3558. box.setFromPoints( points ).center( center );
  3559. }
  3560. var maxRadiusSq = 0;
  3561. for ( var i = 0, il = points.length; i < il; i ++ ) {
  3562. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3563. }
  3564. this.radius = Math.sqrt( maxRadiusSq );
  3565. return this;
  3566. };
  3567. }(),
  3568. copy: function ( sphere ) {
  3569. this.center.copy( sphere.center );
  3570. this.radius = sphere.radius;
  3571. return this;
  3572. },
  3573. empty: function () {
  3574. return ( this.radius <= 0 );
  3575. },
  3576. containsPoint: function ( point ) {
  3577. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3578. },
  3579. distanceToPoint: function ( point ) {
  3580. return ( point.distanceTo( this.center ) - this.radius );
  3581. },
  3582. intersectsSphere: function ( sphere ) {
  3583. var radiusSum = this.radius + sphere.radius;
  3584. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3585. },
  3586. clampPoint: function ( point, optionalTarget ) {
  3587. var deltaLengthSq = this.center.distanceToSquared( point );
  3588. var result = optionalTarget || new THREE.Vector3();
  3589. result.copy( point );
  3590. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3591. result.sub( this.center ).normalize();
  3592. result.multiplyScalar( this.radius ).add( this.center );
  3593. }
  3594. return result;
  3595. },
  3596. getBoundingBox: function ( optionalTarget ) {
  3597. var box = optionalTarget || new THREE.Box3();
  3598. box.set( this.center, this.center );
  3599. box.expandByScalar( this.radius );
  3600. return box;
  3601. },
  3602. applyMatrix4: function ( matrix ) {
  3603. this.center.applyMatrix4( matrix );
  3604. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3605. return this;
  3606. },
  3607. translate: function ( offset ) {
  3608. this.center.add( offset );
  3609. return this;
  3610. },
  3611. equals: function ( sphere ) {
  3612. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3613. },
  3614. clone: function () {
  3615. return new THREE.Sphere().copy( this );
  3616. }
  3617. };
  3618. // File:src/math/Frustum.js
  3619. /**
  3620. * @author mrdoob / http://mrdoob.com/
  3621. * @author alteredq / http://alteredqualia.com/
  3622. * @author bhouston / http://exocortex.com
  3623. */
  3624. THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) {
  3625. this.planes = [
  3626. ( p0 !== undefined ) ? p0 : new THREE.Plane(),
  3627. ( p1 !== undefined ) ? p1 : new THREE.Plane(),
  3628. ( p2 !== undefined ) ? p2 : new THREE.Plane(),
  3629. ( p3 !== undefined ) ? p3 : new THREE.Plane(),
  3630. ( p4 !== undefined ) ? p4 : new THREE.Plane(),
  3631. ( p5 !== undefined ) ? p5 : new THREE.Plane()
  3632. ];
  3633. };
  3634. THREE.Frustum.prototype = {
  3635. constructor: THREE.Frustum,
  3636. set: function ( p0, p1, p2, p3, p4, p5 ) {
  3637. var planes = this.planes;
  3638. planes[ 0 ].copy( p0 );
  3639. planes[ 1 ].copy( p1 );
  3640. planes[ 2 ].copy( p2 );
  3641. planes[ 3 ].copy( p3 );
  3642. planes[ 4 ].copy( p4 );
  3643. planes[ 5 ].copy( p5 );
  3644. return this;
  3645. },
  3646. copy: function ( frustum ) {
  3647. var planes = this.planes;
  3648. for ( var i = 0; i < 6; i ++ ) {
  3649. planes[ i ].copy( frustum.planes[ i ] );
  3650. }
  3651. return this;
  3652. },
  3653. setFromMatrix: function ( m ) {
  3654. var planes = this.planes;
  3655. var me = m.elements;
  3656. var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  3657. var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  3658. var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  3659. var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  3660. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  3661. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  3662. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  3663. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  3664. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  3665. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  3666. return this;
  3667. },
  3668. intersectsObject: function () {
  3669. var sphere = new THREE.Sphere();
  3670. return function ( object ) {
  3671. var geometry = object.geometry;
  3672. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  3673. sphere.copy( geometry.boundingSphere );
  3674. sphere.applyMatrix4( object.matrixWorld );
  3675. return this.intersectsSphere( sphere );
  3676. };
  3677. }(),
  3678. intersectsSphere: function ( sphere ) {
  3679. var planes = this.planes;
  3680. var center = sphere.center;
  3681. var negRadius = - sphere.radius;
  3682. for ( var i = 0; i < 6; i ++ ) {
  3683. var distance = planes[ i ].distanceToPoint( center );
  3684. if ( distance < negRadius ) {
  3685. return false;
  3686. }
  3687. }
  3688. return true;
  3689. },
  3690. intersectsBox: function () {
  3691. var p1 = new THREE.Vector3(),
  3692. p2 = new THREE.Vector3();
  3693. return function ( box ) {
  3694. var planes = this.planes;
  3695. for ( var i = 0; i < 6 ; i ++ ) {
  3696. var plane = planes[ i ];
  3697. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  3698. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  3699. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  3700. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  3701. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  3702. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  3703. var d1 = plane.distanceToPoint( p1 );
  3704. var d2 = plane.distanceToPoint( p2 );
  3705. // if both outside plane, no intersection
  3706. if ( d1 < 0 && d2 < 0 ) {
  3707. return false;
  3708. }
  3709. }
  3710. return true;
  3711. };
  3712. }(),
  3713. containsPoint: function ( point ) {
  3714. var planes = this.planes;
  3715. for ( var i = 0; i < 6; i ++ ) {
  3716. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  3717. return false;
  3718. }
  3719. }
  3720. return true;
  3721. },
  3722. clone: function () {
  3723. return new THREE.Frustum().copy( this );
  3724. }
  3725. };
  3726. // File:src/math/Plane.js
  3727. /**
  3728. * @author bhouston / http://exocortex.com
  3729. */
  3730. THREE.Plane = function ( normal, constant ) {
  3731. this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 );
  3732. this.constant = ( constant !== undefined ) ? constant : 0;
  3733. };
  3734. THREE.Plane.prototype = {
  3735. constructor: THREE.Plane,
  3736. set: function ( normal, constant ) {
  3737. this.normal.copy( normal );
  3738. this.constant = constant;
  3739. return this;
  3740. },
  3741. setComponents: function ( x, y, z, w ) {
  3742. this.normal.set( x, y, z );
  3743. this.constant = w;
  3744. return this;
  3745. },
  3746. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  3747. this.normal.copy( normal );
  3748. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  3749. return this;
  3750. },
  3751. setFromCoplanarPoints: function () {
  3752. var v1 = new THREE.Vector3();
  3753. var v2 = new THREE.Vector3();
  3754. return function ( a, b, c ) {
  3755. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  3756. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  3757. this.setFromNormalAndCoplanarPoint( normal, a );
  3758. return this;
  3759. };
  3760. }(),
  3761. copy: function ( plane ) {
  3762. this.normal.copy( plane.normal );
  3763. this.constant = plane.constant;
  3764. return this;
  3765. },
  3766. normalize: function () {
  3767. // Note: will lead to a divide by zero if the plane is invalid.
  3768. var inverseNormalLength = 1.0 / this.normal.length();
  3769. this.normal.multiplyScalar( inverseNormalLength );
  3770. this.constant *= inverseNormalLength;
  3771. return this;
  3772. },
  3773. negate: function () {
  3774. this.constant *= - 1;
  3775. this.normal.negate();
  3776. return this;
  3777. },
  3778. distanceToPoint: function ( point ) {
  3779. return this.normal.dot( point ) + this.constant;
  3780. },
  3781. distanceToSphere: function ( sphere ) {
  3782. return this.distanceToPoint( sphere.center ) - sphere.radius;
  3783. },
  3784. projectPoint: function ( point, optionalTarget ) {
  3785. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  3786. },
  3787. orthoPoint: function ( point, optionalTarget ) {
  3788. var perpendicularMagnitude = this.distanceToPoint( point );
  3789. var result = optionalTarget || new THREE.Vector3();
  3790. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  3791. },
  3792. isIntersectionLine: function ( line ) {
  3793. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  3794. var startSign = this.distanceToPoint( line.start );
  3795. var endSign = this.distanceToPoint( line.end );
  3796. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  3797. },
  3798. intersectLine: function () {
  3799. var v1 = new THREE.Vector3();
  3800. return function ( line, optionalTarget ) {
  3801. var result = optionalTarget || new THREE.Vector3();
  3802. var direction = line.delta( v1 );
  3803. var denominator = this.normal.dot( direction );
  3804. if ( denominator == 0 ) {
  3805. // line is coplanar, return origin
  3806. if ( this.distanceToPoint( line.start ) == 0 ) {
  3807. return result.copy( line.start );
  3808. }
  3809. // Unsure if this is the correct method to handle this case.
  3810. return undefined;
  3811. }
  3812. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  3813. if ( t < 0 || t > 1 ) {
  3814. return undefined;
  3815. }
  3816. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  3817. };
  3818. }(),
  3819. coplanarPoint: function ( optionalTarget ) {
  3820. var result = optionalTarget || new THREE.Vector3();
  3821. return result.copy( this.normal ).multiplyScalar( - this.constant );
  3822. },
  3823. applyMatrix4: function () {
  3824. var v1 = new THREE.Vector3();
  3825. var v2 = new THREE.Vector3();
  3826. var m1 = new THREE.Matrix3();
  3827. return function ( matrix, optionalNormalMatrix ) {
  3828. // compute new normal based on theory here:
  3829. // http://www.songho.ca/opengl/gl_normaltransform.html
  3830. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  3831. var newNormal = v1.copy( this.normal ).applyMatrix3( normalMatrix );
  3832. var newCoplanarPoint = this.coplanarPoint( v2 );
  3833. newCoplanarPoint.applyMatrix4( matrix );
  3834. this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint );
  3835. return this;
  3836. };
  3837. }(),
  3838. translate: function ( offset ) {
  3839. this.constant = this.constant - offset.dot( this.normal );
  3840. return this;
  3841. },
  3842. equals: function ( plane ) {
  3843. return plane.normal.equals( this.normal ) && ( plane.constant == this.constant );
  3844. },
  3845. clone: function () {
  3846. return new THREE.Plane().copy( this );
  3847. }
  3848. };
  3849. // File:src/math/Math.js
  3850. /**
  3851. * @author alteredq / http://alteredqualia.com/
  3852. * @author mrdoob / http://mrdoob.com/
  3853. */
  3854. THREE.Math = {
  3855. generateUUID: function () {
  3856. // http://www.broofa.com/Tools/Math.uuid.htm
  3857. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split( '' );
  3858. var uuid = new Array( 36 );
  3859. var rnd = 0, r;
  3860. return function () {
  3861. for ( var i = 0; i < 36; i ++ ) {
  3862. if ( i == 8 || i == 13 || i == 18 || i == 23 ) {
  3863. uuid[ i ] = '-';
  3864. } else if ( i == 14 ) {
  3865. uuid[ i ] = '4';
  3866. } else {
  3867. if ( rnd <= 0x02 ) rnd = 0x2000000 + ( Math.random() * 0x1000000 ) | 0;
  3868. r = rnd & 0xf;
  3869. rnd = rnd >> 4;
  3870. uuid[ i ] = chars[ ( i == 19 ) ? ( r & 0x3 ) | 0x8 : r ];
  3871. }
  3872. }
  3873. return uuid.join( '' );
  3874. };
  3875. }(),
  3876. // Clamp value to range <a, b>
  3877. clamp: function ( x, a, b ) {
  3878. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  3879. },
  3880. // Clamp value to range <a, inf)
  3881. clampBottom: function ( x, a ) {
  3882. return x < a ? a : x;
  3883. },
  3884. // Linear mapping from range <a1, a2> to range <b1, b2>
  3885. mapLinear: function ( x, a1, a2, b1, b2 ) {
  3886. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  3887. },
  3888. // http://en.wikipedia.org/wiki/Smoothstep
  3889. smoothstep: function ( x, min, max ) {
  3890. if ( x <= min ) return 0;
  3891. if ( x >= max ) return 1;
  3892. x = ( x - min ) / ( max - min );
  3893. return x * x * ( 3 - 2 * x );
  3894. },
  3895. smootherstep: function ( x, min, max ) {
  3896. if ( x <= min ) return 0;
  3897. if ( x >= max ) return 1;
  3898. x = ( x - min ) / ( max - min );
  3899. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  3900. },
  3901. // Random float from <0, 1> with 16 bits of randomness
  3902. // (standard Math.random() creates repetitive patterns when applied over larger space)
  3903. random16: function () {
  3904. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  3905. },
  3906. // Random integer from <low, high> interval
  3907. randInt: function ( low, high ) {
  3908. return Math.floor( this.randFloat( low, high ) );
  3909. },
  3910. // Random float from <low, high> interval
  3911. randFloat: function ( low, high ) {
  3912. return low + Math.random() * ( high - low );
  3913. },
  3914. // Random float from <-range/2, range/2> interval
  3915. randFloatSpread: function ( range ) {
  3916. return range * ( 0.5 - Math.random() );
  3917. },
  3918. degToRad: function () {
  3919. var degreeToRadiansFactor = Math.PI / 180;
  3920. return function ( degrees ) {
  3921. return degrees * degreeToRadiansFactor;
  3922. };
  3923. }(),
  3924. radToDeg: function () {
  3925. var radianToDegreesFactor = 180 / Math.PI;
  3926. return function ( radians ) {
  3927. return radians * radianToDegreesFactor;
  3928. };
  3929. }(),
  3930. isPowerOfTwo: function ( value ) {
  3931. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  3932. },
  3933. nextPowerOfTwo: function ( value ) {
  3934. value --;
  3935. value |= value >> 1;
  3936. value |= value >> 2;
  3937. value |= value >> 4;
  3938. value |= value >> 8;
  3939. value |= value >> 16;
  3940. value ++;
  3941. return value;
  3942. }
  3943. };
  3944. // File:src/math/Spline.js
  3945. /**
  3946. * Spline from Tween.js, slightly optimized (and trashed)
  3947. * http://sole.github.com/tween.js/examples/05_spline.html
  3948. *
  3949. * @author mrdoob / http://mrdoob.com/
  3950. * @author alteredq / http://alteredqualia.com/
  3951. */
  3952. THREE.Spline = function ( points ) {
  3953. this.points = points;
  3954. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3955. point, intPoint, weight, w2, w3,
  3956. pa, pb, pc, pd;
  3957. this.initFromArray = function ( a ) {
  3958. this.points = [];
  3959. for ( var i = 0; i < a.length; i ++ ) {
  3960. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3961. }
  3962. };
  3963. this.getPoint = function ( k ) {
  3964. point = ( this.points.length - 1 ) * k;
  3965. intPoint = Math.floor( point );
  3966. weight = point - intPoint;
  3967. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3968. c[ 1 ] = intPoint;
  3969. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3970. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3971. pa = this.points[ c[ 0 ] ];
  3972. pb = this.points[ c[ 1 ] ];
  3973. pc = this.points[ c[ 2 ] ];
  3974. pd = this.points[ c[ 3 ] ];
  3975. w2 = weight * weight;
  3976. w3 = weight * w2;
  3977. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3978. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3979. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3980. return v3;
  3981. };
  3982. this.getControlPointsArray = function () {
  3983. var i, p, l = this.points.length,
  3984. coords = [];
  3985. for ( i = 0; i < l; i ++ ) {
  3986. p = this.points[ i ];
  3987. coords[ i ] = [ p.x, p.y, p.z ];
  3988. }
  3989. return coords;
  3990. };
  3991. // approximate length by summing linear segments
  3992. this.getLength = function ( nSubDivisions ) {
  3993. var i, index, nSamples, position,
  3994. point = 0, intPoint = 0, oldIntPoint = 0,
  3995. oldPosition = new THREE.Vector3(),
  3996. tmpVec = new THREE.Vector3(),
  3997. chunkLengths = [],
  3998. totalLength = 0;
  3999. // first point has 0 length
  4000. chunkLengths[ 0 ] = 0;
  4001. if ( ! nSubDivisions ) nSubDivisions = 100;
  4002. nSamples = this.points.length * nSubDivisions;
  4003. oldPosition.copy( this.points[ 0 ] );
  4004. for ( i = 1; i < nSamples; i ++ ) {
  4005. index = i / nSamples;
  4006. position = this.getPoint( index );
  4007. tmpVec.copy( position );
  4008. totalLength += tmpVec.distanceTo( oldPosition );
  4009. oldPosition.copy( position );
  4010. point = ( this.points.length - 1 ) * index;
  4011. intPoint = Math.floor( point );
  4012. if ( intPoint != oldIntPoint ) {
  4013. chunkLengths[ intPoint ] = totalLength;
  4014. oldIntPoint = intPoint;
  4015. }
  4016. }
  4017. // last point ends with total length
  4018. chunkLengths[ chunkLengths.length ] = totalLength;
  4019. return { chunks: chunkLengths, total: totalLength };
  4020. };
  4021. this.reparametrizeByArcLength = function ( samplingCoef ) {
  4022. var i, j,
  4023. index, indexCurrent, indexNext,
  4024. realDistance,
  4025. sampling, position,
  4026. newpoints = [],
  4027. tmpVec = new THREE.Vector3(),
  4028. sl = this.getLength();
  4029. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  4030. for ( i = 1; i < this.points.length; i ++ ) {
  4031. //tmpVec.copy( this.points[ i - 1 ] );
  4032. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  4033. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  4034. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  4035. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  4036. indexNext = i / ( this.points.length - 1 );
  4037. for ( j = 1; j < sampling - 1; j ++ ) {
  4038. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  4039. position = this.getPoint( index );
  4040. newpoints.push( tmpVec.copy( position ).clone() );
  4041. }
  4042. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  4043. }
  4044. this.points = newpoints;
  4045. };
  4046. // Catmull-Rom
  4047. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  4048. var v0 = ( p2 - p0 ) * 0.5,
  4049. v1 = ( p3 - p1 ) * 0.5;
  4050. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  4051. };
  4052. };
  4053. // File:src/math/Triangle.js
  4054. /**
  4055. * @author bhouston / http://exocortex.com
  4056. * @author mrdoob / http://mrdoob.com/
  4057. */
  4058. THREE.Triangle = function ( a, b, c ) {
  4059. this.a = ( a !== undefined ) ? a : new THREE.Vector3();
  4060. this.b = ( b !== undefined ) ? b : new THREE.Vector3();
  4061. this.c = ( c !== undefined ) ? c : new THREE.Vector3();
  4062. };
  4063. THREE.Triangle.normal = function () {
  4064. var v0 = new THREE.Vector3();
  4065. return function ( a, b, c, optionalTarget ) {
  4066. var result = optionalTarget || new THREE.Vector3();
  4067. result.subVectors( c, b );
  4068. v0.subVectors( a, b );
  4069. result.cross( v0 );
  4070. var resultLengthSq = result.lengthSq();
  4071. if ( resultLengthSq > 0 ) {
  4072. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  4073. }
  4074. return result.set( 0, 0, 0 );
  4075. };
  4076. }();
  4077. // static/instance method to calculate barycoordinates
  4078. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4079. THREE.Triangle.barycoordFromPoint = function () {
  4080. var v0 = new THREE.Vector3();
  4081. var v1 = new THREE.Vector3();
  4082. var v2 = new THREE.Vector3();
  4083. return function ( point, a, b, c, optionalTarget ) {
  4084. v0.subVectors( c, a );
  4085. v1.subVectors( b, a );
  4086. v2.subVectors( point, a );
  4087. var dot00 = v0.dot( v0 );
  4088. var dot01 = v0.dot( v1 );
  4089. var dot02 = v0.dot( v2 );
  4090. var dot11 = v1.dot( v1 );
  4091. var dot12 = v1.dot( v2 );
  4092. var denom = ( dot00 * dot11 - dot01 * dot01 );
  4093. var result = optionalTarget || new THREE.Vector3();
  4094. // colinear or singular triangle
  4095. if ( denom == 0 ) {
  4096. // arbitrary location outside of triangle?
  4097. // not sure if this is the best idea, maybe should be returning undefined
  4098. return result.set( - 2, - 1, - 1 );
  4099. }
  4100. var invDenom = 1 / denom;
  4101. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  4102. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  4103. // barycoordinates must always sum to 1
  4104. return result.set( 1 - u - v, v, u );
  4105. };
  4106. }();
  4107. THREE.Triangle.containsPoint = function () {
  4108. var v1 = new THREE.Vector3();
  4109. return function ( point, a, b, c ) {
  4110. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 );
  4111. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  4112. };
  4113. }();
  4114. THREE.Triangle.prototype = {
  4115. constructor: THREE.Triangle,
  4116. set: function ( a, b, c ) {
  4117. this.a.copy( a );
  4118. this.b.copy( b );
  4119. this.c.copy( c );
  4120. return this;
  4121. },
  4122. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  4123. this.a.copy( points[ i0 ] );
  4124. this.b.copy( points[ i1 ] );
  4125. this.c.copy( points[ i2 ] );
  4126. return this;
  4127. },
  4128. copy: function ( triangle ) {
  4129. this.a.copy( triangle.a );
  4130. this.b.copy( triangle.b );
  4131. this.c.copy( triangle.c );
  4132. return this;
  4133. },
  4134. area: function () {
  4135. var v0 = new THREE.Vector3();
  4136. var v1 = new THREE.Vector3();
  4137. return function () {
  4138. v0.subVectors( this.c, this.b );
  4139. v1.subVectors( this.a, this.b );
  4140. return v0.cross( v1 ).length() * 0.5;
  4141. };
  4142. }(),
  4143. midpoint: function ( optionalTarget ) {
  4144. var result = optionalTarget || new THREE.Vector3();
  4145. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  4146. },
  4147. normal: function ( optionalTarget ) {
  4148. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  4149. },
  4150. plane: function ( optionalTarget ) {
  4151. var result = optionalTarget || new THREE.Plane();
  4152. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  4153. },
  4154. barycoordFromPoint: function ( point, optionalTarget ) {
  4155. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  4156. },
  4157. containsPoint: function ( point ) {
  4158. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  4159. },
  4160. equals: function ( triangle ) {
  4161. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  4162. },
  4163. clone: function () {
  4164. return new THREE.Triangle().copy( this );
  4165. }
  4166. };
  4167. // File:src/core/Clock.js
  4168. /**
  4169. * @author alteredq / http://alteredqualia.com/
  4170. */
  4171. THREE.Clock = function ( autoStart ) {
  4172. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  4173. this.startTime = 0;
  4174. this.oldTime = 0;
  4175. this.elapsedTime = 0;
  4176. this.running = false;
  4177. };
  4178. THREE.Clock.prototype = {
  4179. constructor: THREE.Clock,
  4180. start: function () {
  4181. this.startTime = self.performance !== undefined && self.performance.now !== undefined
  4182. ? self.performance.now()
  4183. : Date.now();
  4184. this.oldTime = this.startTime;
  4185. this.running = true;
  4186. },
  4187. stop: function () {
  4188. this.getElapsedTime();
  4189. this.running = false;
  4190. },
  4191. getElapsedTime: function () {
  4192. this.getDelta();
  4193. return this.elapsedTime;
  4194. },
  4195. getDelta: function () {
  4196. var diff = 0;
  4197. if ( this.autoStart && ! this.running ) {
  4198. this.start();
  4199. }
  4200. if ( this.running ) {
  4201. var newTime = self.performance !== undefined && self.performance.now !== undefined
  4202. ? self.performance.now()
  4203. : Date.now();
  4204. diff = 0.001 * ( newTime - this.oldTime );
  4205. this.oldTime = newTime;
  4206. this.elapsedTime += diff;
  4207. }
  4208. return diff;
  4209. }
  4210. };
  4211. // File:src/core/EventDispatcher.js
  4212. /**
  4213. * https://github.com/mrdoob/eventdispatcher.js/
  4214. */
  4215. THREE.EventDispatcher = function () {}
  4216. THREE.EventDispatcher.prototype = {
  4217. constructor: THREE.EventDispatcher,
  4218. apply: function ( object ) {
  4219. object.addEventListener = THREE.EventDispatcher.prototype.addEventListener;
  4220. object.hasEventListener = THREE.EventDispatcher.prototype.hasEventListener;
  4221. object.removeEventListener = THREE.EventDispatcher.prototype.removeEventListener;
  4222. object.dispatchEvent = THREE.EventDispatcher.prototype.dispatchEvent;
  4223. },
  4224. addEventListener: function ( type, listener ) {
  4225. if ( this._listeners === undefined ) this._listeners = {};
  4226. var listeners = this._listeners;
  4227. if ( listeners[ type ] === undefined ) {
  4228. listeners[ type ] = [];
  4229. }
  4230. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  4231. listeners[ type ].push( listener );
  4232. }
  4233. },
  4234. hasEventListener: function ( type, listener ) {
  4235. if ( this._listeners === undefined ) return false;
  4236. var listeners = this._listeners;
  4237. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  4238. return true;
  4239. }
  4240. return false;
  4241. },
  4242. removeEventListener: function ( type, listener ) {
  4243. if ( this._listeners === undefined ) return;
  4244. var listeners = this._listeners;
  4245. var listenerArray = listeners[ type ];
  4246. if ( listenerArray !== undefined ) {
  4247. var index = listenerArray.indexOf( listener );
  4248. if ( index !== - 1 ) {
  4249. listenerArray.splice( index, 1 );
  4250. }
  4251. }
  4252. },
  4253. dispatchEvent: function ( event ) {
  4254. if ( this._listeners === undefined ) return;
  4255. var listeners = this._listeners;
  4256. var listenerArray = listeners[ event.type ];
  4257. if ( listenerArray !== undefined ) {
  4258. event.target = this;
  4259. var array = [];
  4260. var length = listenerArray.length;
  4261. for ( var i = 0; i < length; i ++ ) {
  4262. array[ i ] = listenerArray[ i ];
  4263. }
  4264. for ( var i = 0; i < length; i ++ ) {
  4265. array[ i ].call( this, event );
  4266. }
  4267. }
  4268. }
  4269. };
  4270. // File:src/core/Raycaster.js
  4271. /**
  4272. * @author mrdoob / http://mrdoob.com/
  4273. * @author bhouston / http://exocortex.com/
  4274. * @author stephomi / http://stephaneginier.com/
  4275. */
  4276. ( function ( THREE ) {
  4277. THREE.Raycaster = function ( origin, direction, near, far ) {
  4278. this.ray = new THREE.Ray( origin, direction );
  4279. // direction is assumed to be normalized (for accurate distance calculations)
  4280. this.near = near || 0;
  4281. this.far = far || Infinity;
  4282. this.params = {
  4283. Sprite: {},
  4284. Mesh: {},
  4285. PointCloud: { threshold: 1 },
  4286. LOD: {},
  4287. Line: {}
  4288. };
  4289. };
  4290. var descSort = function ( a, b ) {
  4291. return a.distance - b.distance;
  4292. };
  4293. var intersectObject = function ( object, raycaster, intersects, recursive ) {
  4294. object.raycast( raycaster, intersects );
  4295. if ( recursive === true ) {
  4296. var children = object.children;
  4297. for ( var i = 0, l = children.length; i < l; i ++ ) {
  4298. intersectObject( children[ i ], raycaster, intersects, true );
  4299. }
  4300. }
  4301. };
  4302. //
  4303. THREE.Raycaster.prototype = {
  4304. constructor: THREE.Raycaster,
  4305. precision: 0.0001,
  4306. linePrecision: 1,
  4307. set: function ( origin, direction ) {
  4308. // direction is assumed to be normalized (for accurate distance calculations)
  4309. this.ray.set( origin, direction );
  4310. },
  4311. setFromCamera: function ( coords, camera ) {
  4312. // camera is assumed _not_ to be a child of a transformed object
  4313. if ( camera instanceof THREE.PerspectiveCamera ) {
  4314. this.ray.origin.copy( camera.position );
  4315. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( camera.position ).normalize();
  4316. } else if ( camera instanceof THREE.OrthographicCamera ) {
  4317. this.ray.origin.set( coords.x, coords.y, - 1 ).unproject( camera );
  4318. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  4319. } else {
  4320. THREE.error( 'THREE.Raycaster: Unsupported camera type.' );
  4321. }
  4322. },
  4323. intersectObject: function ( object, recursive ) {
  4324. var intersects = [];
  4325. intersectObject( object, this, intersects, recursive );
  4326. intersects.sort( descSort );
  4327. return intersects;
  4328. },
  4329. intersectObjects: function ( objects, recursive ) {
  4330. var intersects = [];
  4331. if ( objects instanceof Array === false ) {
  4332. THREE.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
  4333. return intersects;
  4334. }
  4335. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  4336. intersectObject( objects[ i ], this, intersects, recursive );
  4337. }
  4338. intersects.sort( descSort );
  4339. return intersects;
  4340. }
  4341. };
  4342. }( THREE ) );
  4343. // File:src/core/Object3D.js
  4344. /**
  4345. * @author mrdoob / http://mrdoob.com/
  4346. * @author mikael emtinger / http://gomo.se/
  4347. * @author alteredq / http://alteredqualia.com/
  4348. * @author WestLangley / http://github.com/WestLangley
  4349. */
  4350. THREE.Object3D = function () {
  4351. Object.defineProperty( this, 'id', { value: THREE.Object3DIdCount ++ } );
  4352. this.uuid = THREE.Math.generateUUID();
  4353. this.name = '';
  4354. this.type = 'Object3D';
  4355. this.parent = undefined;
  4356. this.children = [];
  4357. this.up = THREE.Object3D.DefaultUp.clone();
  4358. var position = new THREE.Vector3();
  4359. var rotation = new THREE.Euler();
  4360. var quaternion = new THREE.Quaternion();
  4361. var scale = new THREE.Vector3( 1, 1, 1 );
  4362. var onRotationChange = function () {
  4363. quaternion.setFromEuler( rotation, false );
  4364. };
  4365. var onQuaternionChange = function () {
  4366. rotation.setFromQuaternion( quaternion, undefined, false );
  4367. };
  4368. rotation.onChange( onRotationChange );
  4369. quaternion.onChange( onQuaternionChange );
  4370. Object.defineProperties( this, {
  4371. position: {
  4372. enumerable: true,
  4373. value: position
  4374. },
  4375. rotation: {
  4376. enumerable: true,
  4377. value: rotation
  4378. },
  4379. quaternion: {
  4380. enumerable: true,
  4381. value: quaternion
  4382. },
  4383. scale: {
  4384. enumerable: true,
  4385. value: scale
  4386. }
  4387. } );
  4388. this.rotationAutoUpdate = true;
  4389. this.matrix = new THREE.Matrix4();
  4390. this.matrixWorld = new THREE.Matrix4();
  4391. this.matrixAutoUpdate = true;
  4392. this.matrixWorldNeedsUpdate = false;
  4393. this.visible = true;
  4394. this.castShadow = false;
  4395. this.receiveShadow = false;
  4396. this.frustumCulled = true;
  4397. this.renderOrder = 0;
  4398. this.userData = {};
  4399. };
  4400. THREE.Object3D.DefaultUp = new THREE.Vector3( 0, 1, 0 );
  4401. THREE.Object3D.prototype = {
  4402. constructor: THREE.Object3D,
  4403. get eulerOrder () {
  4404. THREE.warn( 'THREE.Object3D: .eulerOrder has been moved to .rotation.order.' );
  4405. return this.rotation.order;
  4406. },
  4407. set eulerOrder ( value ) {
  4408. THREE.warn( 'THREE.Object3D: .eulerOrder has been moved to .rotation.order.' );
  4409. this.rotation.order = value;
  4410. },
  4411. get useQuaternion () {
  4412. THREE.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  4413. },
  4414. set useQuaternion ( value ) {
  4415. THREE.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  4416. },
  4417. applyMatrix: function ( matrix ) {
  4418. this.matrix.multiplyMatrices( matrix, this.matrix );
  4419. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4420. },
  4421. setRotationFromAxisAngle: function ( axis, angle ) {
  4422. // assumes axis is normalized
  4423. this.quaternion.setFromAxisAngle( axis, angle );
  4424. },
  4425. setRotationFromEuler: function ( euler ) {
  4426. this.quaternion.setFromEuler( euler, true );
  4427. },
  4428. setRotationFromMatrix: function ( m ) {
  4429. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4430. this.quaternion.setFromRotationMatrix( m );
  4431. },
  4432. setRotationFromQuaternion: function ( q ) {
  4433. // assumes q is normalized
  4434. this.quaternion.copy( q );
  4435. },
  4436. rotateOnAxis: function () {
  4437. // rotate object on axis in object space
  4438. // axis is assumed to be normalized
  4439. var q1 = new THREE.Quaternion();
  4440. return function ( axis, angle ) {
  4441. q1.setFromAxisAngle( axis, angle );
  4442. this.quaternion.multiply( q1 );
  4443. return this;
  4444. }
  4445. }(),
  4446. rotateX: function () {
  4447. var v1 = new THREE.Vector3( 1, 0, 0 );
  4448. return function ( angle ) {
  4449. return this.rotateOnAxis( v1, angle );
  4450. };
  4451. }(),
  4452. rotateY: function () {
  4453. var v1 = new THREE.Vector3( 0, 1, 0 );
  4454. return function ( angle ) {
  4455. return this.rotateOnAxis( v1, angle );
  4456. };
  4457. }(),
  4458. rotateZ: function () {
  4459. var v1 = new THREE.Vector3( 0, 0, 1 );
  4460. return function ( angle ) {
  4461. return this.rotateOnAxis( v1, angle );
  4462. };
  4463. }(),
  4464. translateOnAxis: function () {
  4465. // translate object by distance along axis in object space
  4466. // axis is assumed to be normalized
  4467. var v1 = new THREE.Vector3();
  4468. return function ( axis, distance ) {
  4469. v1.copy( axis ).applyQuaternion( this.quaternion );
  4470. this.position.add( v1.multiplyScalar( distance ) );
  4471. return this;
  4472. }
  4473. }(),
  4474. translate: function ( distance, axis ) {
  4475. THREE.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  4476. return this.translateOnAxis( axis, distance );
  4477. },
  4478. translateX: function () {
  4479. var v1 = new THREE.Vector3( 1, 0, 0 );
  4480. return function ( distance ) {
  4481. return this.translateOnAxis( v1, distance );
  4482. };
  4483. }(),
  4484. translateY: function () {
  4485. var v1 = new THREE.Vector3( 0, 1, 0 );
  4486. return function ( distance ) {
  4487. return this.translateOnAxis( v1, distance );
  4488. };
  4489. }(),
  4490. translateZ: function () {
  4491. var v1 = new THREE.Vector3( 0, 0, 1 );
  4492. return function ( distance ) {
  4493. return this.translateOnAxis( v1, distance );
  4494. };
  4495. }(),
  4496. localToWorld: function ( vector ) {
  4497. return vector.applyMatrix4( this.matrixWorld );
  4498. },
  4499. worldToLocal: function () {
  4500. var m1 = new THREE.Matrix4();
  4501. return function ( vector ) {
  4502. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  4503. };
  4504. }(),
  4505. lookAt: function () {
  4506. // This routine does not support objects with rotated and/or translated parent(s)
  4507. var m1 = new THREE.Matrix4();
  4508. return function ( vector ) {
  4509. m1.lookAt( vector, this.position, this.up );
  4510. this.quaternion.setFromRotationMatrix( m1 );
  4511. };
  4512. }(),
  4513. add: function ( object ) {
  4514. if ( arguments.length > 1 ) {
  4515. for ( var i = 0; i < arguments.length; i ++ ) {
  4516. this.add( arguments[ i ] );
  4517. }
  4518. return this;
  4519. };
  4520. if ( object === this ) {
  4521. THREE.error( "THREE.Object3D.add: object can't be added as a child of itself.", object );
  4522. return this;
  4523. }
  4524. if ( object instanceof THREE.Object3D ) {
  4525. if ( object.parent !== undefined ) {
  4526. object.parent.remove( object );
  4527. }
  4528. object.parent = this;
  4529. object.dispatchEvent( { type: 'added' } );
  4530. this.children.push( object );
  4531. } else {
  4532. THREE.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object );
  4533. }
  4534. return this;
  4535. },
  4536. remove: function ( object ) {
  4537. if ( arguments.length > 1 ) {
  4538. for ( var i = 0; i < arguments.length; i ++ ) {
  4539. this.remove( arguments[ i ] );
  4540. }
  4541. };
  4542. var index = this.children.indexOf( object );
  4543. if ( index !== - 1 ) {
  4544. object.parent = undefined;
  4545. object.dispatchEvent( { type: 'removed' } );
  4546. this.children.splice( index, 1 );
  4547. }
  4548. },
  4549. getChildByName: function ( name ) {
  4550. THREE.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  4551. return this.getObjectByName( name );
  4552. },
  4553. getObjectById: function ( id ) {
  4554. return this.getObjectByProperty( 'id', id );
  4555. },
  4556. getObjectByName: function ( name ) {
  4557. return this.getObjectByProperty( 'name', name );
  4558. },
  4559. getObjectByProperty: function ( name, value ) {
  4560. if ( this[ name ] === value ) return this;
  4561. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4562. var child = this.children[ i ];
  4563. var object = child.getObjectByProperty( name, value );
  4564. if ( object !== undefined ) {
  4565. return object;
  4566. }
  4567. }
  4568. return undefined;
  4569. },
  4570. getWorldPosition: function ( optionalTarget ) {
  4571. var result = optionalTarget || new THREE.Vector3();
  4572. this.updateMatrixWorld( true );
  4573. return result.setFromMatrixPosition( this.matrixWorld );
  4574. },
  4575. getWorldQuaternion: function () {
  4576. var position = new THREE.Vector3();
  4577. var scale = new THREE.Vector3();
  4578. return function ( optionalTarget ) {
  4579. var result = optionalTarget || new THREE.Quaternion();
  4580. this.updateMatrixWorld( true );
  4581. this.matrixWorld.decompose( position, result, scale );
  4582. return result;
  4583. }
  4584. }(),
  4585. getWorldRotation: function () {
  4586. var quaternion = new THREE.Quaternion();
  4587. return function ( optionalTarget ) {
  4588. var result = optionalTarget || new THREE.Euler();
  4589. this.getWorldQuaternion( quaternion );
  4590. return result.setFromQuaternion( quaternion, this.rotation.order, false );
  4591. }
  4592. }(),
  4593. getWorldScale: function () {
  4594. var position = new THREE.Vector3();
  4595. var quaternion = new THREE.Quaternion();
  4596. return function ( optionalTarget ) {
  4597. var result = optionalTarget || new THREE.Vector3();
  4598. this.updateMatrixWorld( true );
  4599. this.matrixWorld.decompose( position, quaternion, result );
  4600. return result;
  4601. }
  4602. }(),
  4603. getWorldDirection: function () {
  4604. var quaternion = new THREE.Quaternion();
  4605. return function ( optionalTarget ) {
  4606. var result = optionalTarget || new THREE.Vector3();
  4607. this.getWorldQuaternion( quaternion );
  4608. return result.set( 0, 0, 1 ).applyQuaternion( quaternion );
  4609. }
  4610. }(),
  4611. raycast: function () {},
  4612. traverse: function ( callback ) {
  4613. callback( this );
  4614. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4615. this.children[ i ].traverse( callback );
  4616. }
  4617. },
  4618. traverseVisible: function ( callback ) {
  4619. if ( this.visible === false ) return;
  4620. callback( this );
  4621. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4622. this.children[ i ].traverseVisible( callback );
  4623. }
  4624. },
  4625. traverseAncestors: function ( callback ) {
  4626. if ( this.parent ) {
  4627. callback( this.parent );
  4628. this.parent.traverseAncestors( callback );
  4629. }
  4630. },
  4631. updateMatrix: function () {
  4632. this.matrix.compose( this.position, this.quaternion, this.scale );
  4633. this.matrixWorldNeedsUpdate = true;
  4634. },
  4635. updateMatrixWorld: function ( force ) {
  4636. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  4637. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  4638. if ( this.parent === undefined ) {
  4639. this.matrixWorld.copy( this.matrix );
  4640. } else {
  4641. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4642. }
  4643. this.matrixWorldNeedsUpdate = false;
  4644. force = true;
  4645. }
  4646. // update children
  4647. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4648. this.children[ i ].updateMatrixWorld( force );
  4649. }
  4650. },
  4651. toJSON: function () {
  4652. var output = {
  4653. metadata: {
  4654. version: 4.3,
  4655. type: 'Object',
  4656. generator: 'ObjectExporter'
  4657. }
  4658. };
  4659. //
  4660. var geometries = {};
  4661. var parseGeometry = function ( geometry ) {
  4662. if ( output.geometries === undefined ) {
  4663. output.geometries = [];
  4664. }
  4665. if ( geometries[ geometry.uuid ] === undefined ) {
  4666. var json = geometry.toJSON();
  4667. delete json.metadata;
  4668. geometries[ geometry.uuid ] = json;
  4669. output.geometries.push( json );
  4670. }
  4671. return geometry.uuid;
  4672. };
  4673. //
  4674. var materials = {};
  4675. var parseMaterial = function ( material ) {
  4676. if ( output.materials === undefined ) {
  4677. output.materials = [];
  4678. }
  4679. if ( materials[ material.uuid ] === undefined ) {
  4680. var json = material.toJSON();
  4681. delete json.metadata;
  4682. materials[ material.uuid ] = json;
  4683. output.materials.push( json );
  4684. }
  4685. return material.uuid;
  4686. };
  4687. //
  4688. var parseObject = function ( object ) {
  4689. var data = {};
  4690. data.uuid = object.uuid;
  4691. data.type = object.type;
  4692. if ( object.name !== '' ) data.name = object.name;
  4693. if ( JSON.stringify( object.userData ) !== '{}' ) data.userData = object.userData;
  4694. if ( object.visible !== true ) data.visible = object.visible;
  4695. if ( object instanceof THREE.PerspectiveCamera ) {
  4696. data.fov = object.fov;
  4697. data.aspect = object.aspect;
  4698. data.near = object.near;
  4699. data.far = object.far;
  4700. } else if ( object instanceof THREE.OrthographicCamera ) {
  4701. data.left = object.left;
  4702. data.right = object.right;
  4703. data.top = object.top;
  4704. data.bottom = object.bottom;
  4705. data.near = object.near;
  4706. data.far = object.far;
  4707. } else if ( object instanceof THREE.AmbientLight ) {
  4708. data.color = object.color.getHex();
  4709. } else if ( object instanceof THREE.DirectionalLight ) {
  4710. data.color = object.color.getHex();
  4711. data.intensity = object.intensity;
  4712. } else if ( object instanceof THREE.PointLight ) {
  4713. data.color = object.color.getHex();
  4714. data.intensity = object.intensity;
  4715. data.distance = object.distance;
  4716. data.decay = object.decay;
  4717. } else if ( object instanceof THREE.SpotLight ) {
  4718. data.color = object.color.getHex();
  4719. data.intensity = object.intensity;
  4720. data.distance = object.distance;
  4721. data.angle = object.angle;
  4722. data.exponent = object.exponent;
  4723. data.decay = object.decay;
  4724. } else if ( object instanceof THREE.HemisphereLight ) {
  4725. data.color = object.color.getHex();
  4726. data.groundColor = object.groundColor.getHex();
  4727. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.PointCloud ) {
  4728. data.geometry = parseGeometry( object.geometry );
  4729. data.material = parseMaterial( object.material );
  4730. if ( object instanceof THREE.Line ) data.mode = object.mode;
  4731. } else if ( object instanceof THREE.Sprite ) {
  4732. data.material = parseMaterial( object.material );
  4733. }
  4734. data.matrix = object.matrix.toArray();
  4735. if ( object.children.length > 0 ) {
  4736. data.children = [];
  4737. for ( var i = 0; i < object.children.length; i ++ ) {
  4738. data.children.push( parseObject( object.children[ i ] ) );
  4739. }
  4740. }
  4741. return data;
  4742. }
  4743. output.object = parseObject( this );
  4744. return output;
  4745. },
  4746. clone: function ( object, recursive ) {
  4747. if ( object === undefined ) object = new THREE.Object3D();
  4748. if ( recursive === undefined ) recursive = true;
  4749. object.name = this.name;
  4750. object.up.copy( this.up );
  4751. object.position.copy( this.position );
  4752. object.quaternion.copy( this.quaternion );
  4753. object.scale.copy( this.scale );
  4754. object.rotationAutoUpdate = this.rotationAutoUpdate;
  4755. object.matrix.copy( this.matrix );
  4756. object.matrixWorld.copy( this.matrixWorld );
  4757. object.matrixAutoUpdate = this.matrixAutoUpdate;
  4758. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  4759. object.visible = this.visible;
  4760. object.castShadow = this.castShadow;
  4761. object.receiveShadow = this.receiveShadow;
  4762. object.frustumCulled = this.frustumCulled;
  4763. object.userData = JSON.parse( JSON.stringify( this.userData ) );
  4764. if ( recursive === true ) {
  4765. for ( var i = 0; i < this.children.length; i ++ ) {
  4766. var child = this.children[ i ];
  4767. object.add( child.clone() );
  4768. }
  4769. }
  4770. return object;
  4771. }
  4772. };
  4773. THREE.EventDispatcher.prototype.apply( THREE.Object3D.prototype );
  4774. THREE.Object3DIdCount = 0;
  4775. // File:src/core/Face3.js
  4776. /**
  4777. * @author mrdoob / http://mrdoob.com/
  4778. * @author alteredq / http://alteredqualia.com/
  4779. */
  4780. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  4781. this.a = a;
  4782. this.b = b;
  4783. this.c = c;
  4784. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4785. this.vertexNormals = normal instanceof Array ? normal : [];
  4786. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4787. this.vertexColors = color instanceof Array ? color : [];
  4788. this.vertexTangents = [];
  4789. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  4790. };
  4791. THREE.Face3.prototype = {
  4792. constructor: THREE.Face3,
  4793. clone: function () {
  4794. var face = new THREE.Face3( this.a, this.b, this.c );
  4795. face.normal.copy( this.normal );
  4796. face.color.copy( this.color );
  4797. face.materialIndex = this.materialIndex;
  4798. for ( var i = 0, il = this.vertexNormals.length; i < il; i ++ ) {
  4799. face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  4800. }
  4801. for ( var i = 0, il = this.vertexColors.length; i < il; i ++ ) {
  4802. face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  4803. }
  4804. for ( var i = 0, il = this.vertexTangents.length; i < il; i ++ ) {
  4805. face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  4806. }
  4807. return face;
  4808. }
  4809. };
  4810. // File:src/core/Face4.js
  4811. /**
  4812. * @author mrdoob / http://mrdoob.com/
  4813. */
  4814. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  4815. THREE.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' )
  4816. return new THREE.Face3( a, b, c, normal, color, materialIndex );
  4817. };
  4818. // File:src/core/BufferAttribute.js
  4819. /**
  4820. * @author mrdoob / http://mrdoob.com/
  4821. */
  4822. THREE.BufferAttribute = function ( array, itemSize ) {
  4823. this.array = array;
  4824. this.itemSize = itemSize;
  4825. this.needsUpdate = false;
  4826. };
  4827. THREE.BufferAttribute.prototype = {
  4828. constructor: THREE.BufferAttribute,
  4829. get length () {
  4830. return this.array.length;
  4831. },
  4832. copyAt: function ( index1, attribute, index2 ) {
  4833. index1 *= this.itemSize;
  4834. index2 *= attribute.itemSize;
  4835. for ( var i = 0, l = this.itemSize; i < l; i ++ ) {
  4836. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  4837. }
  4838. return this;
  4839. },
  4840. set: function ( value, offset ) {
  4841. if ( offset === undefined ) offset = 0;
  4842. this.array.set( value, offset );
  4843. return this;
  4844. },
  4845. setX: function ( index, x ) {
  4846. this.array[ index * this.itemSize ] = x;
  4847. return this;
  4848. },
  4849. setY: function ( index, y ) {
  4850. this.array[ index * this.itemSize + 1 ] = y;
  4851. return this;
  4852. },
  4853. setZ: function ( index, z ) {
  4854. this.array[ index * this.itemSize + 2 ] = z;
  4855. return this;
  4856. },
  4857. setXY: function ( index, x, y ) {
  4858. index *= this.itemSize;
  4859. this.array[ index ] = x;
  4860. this.array[ index + 1 ] = y;
  4861. return this;
  4862. },
  4863. setXYZ: function ( index, x, y, z ) {
  4864. index *= this.itemSize;
  4865. this.array[ index ] = x;
  4866. this.array[ index + 1 ] = y;
  4867. this.array[ index + 2 ] = z;
  4868. return this;
  4869. },
  4870. setXYZW: function ( index, x, y, z, w ) {
  4871. index *= this.itemSize;
  4872. this.array[ index ] = x;
  4873. this.array[ index + 1 ] = y;
  4874. this.array[ index + 2 ] = z;
  4875. this.array[ index + 3 ] = w;
  4876. return this;
  4877. },
  4878. clone: function () {
  4879. return new THREE.BufferAttribute( new this.array.constructor( this.array ), this.itemSize );
  4880. }
  4881. };
  4882. //
  4883. THREE.Int8Attribute = function ( data, itemSize ) {
  4884. THREE.warn( 'THREE.Int8Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  4885. return new THREE.BufferAttribute( data, itemSize );
  4886. };
  4887. THREE.Uint8Attribute = function ( data, itemSize ) {
  4888. THREE.warn( 'THREE.Uint8Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  4889. return new THREE.BufferAttribute( data, itemSize );
  4890. };
  4891. THREE.Uint8ClampedAttribute = function ( data, itemSize ) {
  4892. THREE.warn( 'THREE.Uint8ClampedAttribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  4893. return new THREE.BufferAttribute( data, itemSize );
  4894. };
  4895. THREE.Int16Attribute = function ( data, itemSize ) {
  4896. THREE.warn( 'THREE.Int16Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  4897. return new THREE.BufferAttribute( data, itemSize );
  4898. };
  4899. THREE.Uint16Attribute = function ( data, itemSize ) {
  4900. THREE.warn( 'THREE.Uint16Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  4901. return new THREE.BufferAttribute( data, itemSize );
  4902. };
  4903. THREE.Int32Attribute = function ( data, itemSize ) {
  4904. THREE.warn( 'THREE.Int32Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  4905. return new THREE.BufferAttribute( data, itemSize );
  4906. };
  4907. THREE.Uint32Attribute = function ( data, itemSize ) {
  4908. THREE.warn( 'THREE.Uint32Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  4909. return new THREE.BufferAttribute( data, itemSize );
  4910. };
  4911. THREE.Float32Attribute = function ( data, itemSize ) {
  4912. THREE.warn( 'THREE.Float32Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  4913. return new THREE.BufferAttribute( data, itemSize );
  4914. };
  4915. THREE.Float64Attribute = function ( data, itemSize ) {
  4916. THREE.warn( 'THREE.Float64Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  4917. return new THREE.BufferAttribute( data, itemSize );
  4918. };
  4919. // File:src/core/DynamicBufferAttribute.js
  4920. /**
  4921. * @author benaadams / https://twitter.com/ben_a_adams
  4922. * @author mrdoob / http://mrdoob.com/
  4923. */
  4924. THREE.DynamicBufferAttribute = function ( array, itemSize ) {
  4925. THREE.BufferAttribute.call( this, array, itemSize );
  4926. this.updateRange = { offset: 0, count: -1 };
  4927. };
  4928. THREE.DynamicBufferAttribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  4929. THREE.DynamicBufferAttribute.prototype.constructor = THREE.DynamicBufferAttribute;
  4930. THREE.DynamicBufferAttribute.prototype.clone = function () {
  4931. return new THREE.DynamicBufferAttribute( new this.array.constructor( this.array ), this.itemSize );
  4932. };
  4933. // File:src/core/BufferGeometry.js
  4934. /**
  4935. * @author alteredq / http://alteredqualia.com/
  4936. * @author mrdoob / http://mrdoob.com/
  4937. */
  4938. THREE.BufferGeometry = function () {
  4939. Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } );
  4940. this.uuid = THREE.Math.generateUUID();
  4941. this.name = '';
  4942. this.type = 'BufferGeometry';
  4943. this.attributes = {};
  4944. this.attributesKeys = [];
  4945. this.drawcalls = [];
  4946. this.offsets = this.drawcalls; // backwards compatibility
  4947. this.boundingBox = null;
  4948. this.boundingSphere = null;
  4949. };
  4950. THREE.BufferGeometry.prototype = {
  4951. constructor: THREE.BufferGeometry,
  4952. addAttribute: function ( name, attribute ) {
  4953. if ( attribute instanceof THREE.BufferAttribute === false ) {
  4954. THREE.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  4955. this.attributes[ name ] = { array: arguments[ 1 ], itemSize: arguments[ 2 ] };
  4956. return;
  4957. }
  4958. this.attributes[ name ] = attribute;
  4959. this.attributesKeys = Object.keys( this.attributes );
  4960. },
  4961. getAttribute: function ( name ) {
  4962. return this.attributes[ name ];
  4963. },
  4964. addDrawCall: function ( start, count, indexOffset ) {
  4965. this.drawcalls.push( {
  4966. start: start,
  4967. count: count,
  4968. index: indexOffset !== undefined ? indexOffset : 0
  4969. } );
  4970. },
  4971. applyMatrix: function ( matrix ) {
  4972. var position = this.attributes.position;
  4973. if ( position !== undefined ) {
  4974. matrix.applyToVector3Array( position.array );
  4975. position.needsUpdate = true;
  4976. }
  4977. var normal = this.attributes.normal;
  4978. if ( normal !== undefined ) {
  4979. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  4980. normalMatrix.applyToVector3Array( normal.array );
  4981. normal.needsUpdate = true;
  4982. }
  4983. if ( this.boundingBox !== null ) {
  4984. this.computeBoundingBox();
  4985. }
  4986. if ( this.boundingSphere !== null ) {
  4987. this.computeBoundingSphere();
  4988. }
  4989. },
  4990. center: function () {
  4991. this.computeBoundingBox();
  4992. var offset = this.boundingBox.center().negate();
  4993. this.applyMatrix( new THREE.Matrix4().setPosition( offset ) );
  4994. return offset;
  4995. },
  4996. fromGeometry: function ( geometry, settings ) {
  4997. settings = settings || { 'vertexColors': THREE.NoColors };
  4998. var vertices = geometry.vertices;
  4999. var faces = geometry.faces;
  5000. var faceVertexUvs = geometry.faceVertexUvs;
  5001. var vertexColors = settings.vertexColors;
  5002. var hasFaceVertexUv = faceVertexUvs[ 0 ].length > 0;
  5003. var hasFaceVertexNormals = faces[ 0 ].vertexNormals.length == 3;
  5004. var positions = new Float32Array( faces.length * 3 * 3 );
  5005. this.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
  5006. var normals = new Float32Array( faces.length * 3 * 3 );
  5007. this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
  5008. if ( vertexColors !== THREE.NoColors ) {
  5009. var colors = new Float32Array( faces.length * 3 * 3 );
  5010. this.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) );
  5011. }
  5012. if ( hasFaceVertexUv === true ) {
  5013. var uvs = new Float32Array( faces.length * 3 * 2 );
  5014. this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) );
  5015. }
  5016. for ( var i = 0, i2 = 0, i3 = 0; i < faces.length; i ++, i2 += 6, i3 += 9 ) {
  5017. var face = faces[ i ];
  5018. var a = vertices[ face.a ];
  5019. var b = vertices[ face.b ];
  5020. var c = vertices[ face.c ];
  5021. positions[ i3 ] = a.x;
  5022. positions[ i3 + 1 ] = a.y;
  5023. positions[ i3 + 2 ] = a.z;
  5024. positions[ i3 + 3 ] = b.x;
  5025. positions[ i3 + 4 ] = b.y;
  5026. positions[ i3 + 5 ] = b.z;
  5027. positions[ i3 + 6 ] = c.x;
  5028. positions[ i3 + 7 ] = c.y;
  5029. positions[ i3 + 8 ] = c.z;
  5030. if ( hasFaceVertexNormals === true ) {
  5031. var na = face.vertexNormals[ 0 ];
  5032. var nb = face.vertexNormals[ 1 ];
  5033. var nc = face.vertexNormals[ 2 ];
  5034. normals[ i3 ] = na.x;
  5035. normals[ i3 + 1 ] = na.y;
  5036. normals[ i3 + 2 ] = na.z;
  5037. normals[ i3 + 3 ] = nb.x;
  5038. normals[ i3 + 4 ] = nb.y;
  5039. normals[ i3 + 5 ] = nb.z;
  5040. normals[ i3 + 6 ] = nc.x;
  5041. normals[ i3 + 7 ] = nc.y;
  5042. normals[ i3 + 8 ] = nc.z;
  5043. } else {
  5044. var n = face.normal;
  5045. normals[ i3 ] = n.x;
  5046. normals[ i3 + 1 ] = n.y;
  5047. normals[ i3 + 2 ] = n.z;
  5048. normals[ i3 + 3 ] = n.x;
  5049. normals[ i3 + 4 ] = n.y;
  5050. normals[ i3 + 5 ] = n.z;
  5051. normals[ i3 + 6 ] = n.x;
  5052. normals[ i3 + 7 ] = n.y;
  5053. normals[ i3 + 8 ] = n.z;
  5054. }
  5055. if ( vertexColors === THREE.FaceColors ) {
  5056. var fc = face.color;
  5057. colors[ i3 ] = fc.r;
  5058. colors[ i3 + 1 ] = fc.g;
  5059. colors[ i3 + 2 ] = fc.b;
  5060. colors[ i3 + 3 ] = fc.r;
  5061. colors[ i3 + 4 ] = fc.g;
  5062. colors[ i3 + 5 ] = fc.b;
  5063. colors[ i3 + 6 ] = fc.r;
  5064. colors[ i3 + 7 ] = fc.g;
  5065. colors[ i3 + 8 ] = fc.b;
  5066. } else if ( vertexColors === THREE.VertexColors ) {
  5067. var vca = face.vertexColors[ 0 ];
  5068. var vcb = face.vertexColors[ 1 ];
  5069. var vcc = face.vertexColors[ 2 ];
  5070. colors[ i3 ] = vca.r;
  5071. colors[ i3 + 1 ] = vca.g;
  5072. colors[ i3 + 2 ] = vca.b;
  5073. colors[ i3 + 3 ] = vcb.r;
  5074. colors[ i3 + 4 ] = vcb.g;
  5075. colors[ i3 + 5 ] = vcb.b;
  5076. colors[ i3 + 6 ] = vcc.r;
  5077. colors[ i3 + 7 ] = vcc.g;
  5078. colors[ i3 + 8 ] = vcc.b;
  5079. }
  5080. if ( hasFaceVertexUv === true ) {
  5081. var uva = faceVertexUvs[ 0 ][ i ][ 0 ];
  5082. var uvb = faceVertexUvs[ 0 ][ i ][ 1 ];
  5083. var uvc = faceVertexUvs[ 0 ][ i ][ 2 ];
  5084. uvs[ i2 ] = uva.x;
  5085. uvs[ i2 + 1 ] = uva.y;
  5086. uvs[ i2 + 2 ] = uvb.x;
  5087. uvs[ i2 + 3 ] = uvb.y;
  5088. uvs[ i2 + 4 ] = uvc.x;
  5089. uvs[ i2 + 5 ] = uvc.y;
  5090. }
  5091. }
  5092. this.computeBoundingSphere()
  5093. return this;
  5094. },
  5095. computeBoundingBox: function () {
  5096. var vector = new THREE.Vector3();
  5097. return function () {
  5098. if ( this.boundingBox === null ) {
  5099. this.boundingBox = new THREE.Box3();
  5100. }
  5101. var positions = this.attributes.position.array;
  5102. if ( positions ) {
  5103. var bb = this.boundingBox;
  5104. bb.makeEmpty();
  5105. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5106. vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5107. bb.expandByPoint( vector );
  5108. }
  5109. }
  5110. if ( positions === undefined || positions.length === 0 ) {
  5111. this.boundingBox.min.set( 0, 0, 0 );
  5112. this.boundingBox.max.set( 0, 0, 0 );
  5113. }
  5114. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  5115. THREE.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.' );
  5116. }
  5117. }
  5118. }(),
  5119. computeBoundingSphere: function () {
  5120. var box = new THREE.Box3();
  5121. var vector = new THREE.Vector3();
  5122. return function () {
  5123. if ( this.boundingSphere === null ) {
  5124. this.boundingSphere = new THREE.Sphere();
  5125. }
  5126. var positions = this.attributes.position.array;
  5127. if ( positions ) {
  5128. box.makeEmpty();
  5129. var center = this.boundingSphere.center;
  5130. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5131. vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5132. box.expandByPoint( vector );
  5133. }
  5134. box.center( center );
  5135. // hoping to find a boundingSphere with a radius smaller than the
  5136. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  5137. var maxRadiusSq = 0;
  5138. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5139. vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5140. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  5141. }
  5142. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  5143. if ( isNaN( this.boundingSphere.radius ) ) {
  5144. THREE.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.' );
  5145. }
  5146. }
  5147. }
  5148. }(),
  5149. computeFaceNormals: function () {
  5150. // backwards compatibility
  5151. },
  5152. computeVertexNormals: function () {
  5153. var attributes = this.attributes;
  5154. if ( attributes.position ) {
  5155. var positions = attributes.position.array;
  5156. if ( attributes.normal === undefined ) {
  5157. this.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( positions.length ), 3 ) );
  5158. } else {
  5159. // reset existing normals to zero
  5160. var normals = attributes.normal.array;
  5161. for ( var i = 0, il = normals.length; i < il; i ++ ) {
  5162. normals[ i ] = 0;
  5163. }
  5164. }
  5165. var normals = attributes.normal.array;
  5166. var vA, vB, vC,
  5167. pA = new THREE.Vector3(),
  5168. pB = new THREE.Vector3(),
  5169. pC = new THREE.Vector3(),
  5170. cb = new THREE.Vector3(),
  5171. ab = new THREE.Vector3();
  5172. // indexed elements
  5173. if ( attributes.index ) {
  5174. var indices = attributes.index.array;
  5175. var offsets = ( this.offsets.length > 0 ? this.offsets : [ { start: 0, count: indices.length, index: 0 } ] );
  5176. for ( var j = 0, jl = offsets.length; j < jl; ++ j ) {
  5177. var start = offsets[ j ].start;
  5178. var count = offsets[ j ].count;
  5179. var index = offsets[ j ].index;
  5180. for ( var i = start, il = start + count; i < il; i += 3 ) {
  5181. vA = ( index + indices[ i ] ) * 3;
  5182. vB = ( index + indices[ i + 1 ] ) * 3;
  5183. vC = ( index + indices[ i + 2 ] ) * 3;
  5184. pA.fromArray( positions, vA );
  5185. pB.fromArray( positions, vB );
  5186. pC.fromArray( positions, vC );
  5187. cb.subVectors( pC, pB );
  5188. ab.subVectors( pA, pB );
  5189. cb.cross( ab );
  5190. normals[ vA ] += cb.x;
  5191. normals[ vA + 1 ] += cb.y;
  5192. normals[ vA + 2 ] += cb.z;
  5193. normals[ vB ] += cb.x;
  5194. normals[ vB + 1 ] += cb.y;
  5195. normals[ vB + 2 ] += cb.z;
  5196. normals[ vC ] += cb.x;
  5197. normals[ vC + 1 ] += cb.y;
  5198. normals[ vC + 2 ] += cb.z;
  5199. }
  5200. }
  5201. } else {
  5202. // non-indexed elements (unconnected triangle soup)
  5203. for ( var i = 0, il = positions.length; i < il; i += 9 ) {
  5204. pA.fromArray( positions, i );
  5205. pB.fromArray( positions, i + 3 );
  5206. pC.fromArray( positions, i + 6 );
  5207. cb.subVectors( pC, pB );
  5208. ab.subVectors( pA, pB );
  5209. cb.cross( ab );
  5210. normals[ i ] = cb.x;
  5211. normals[ i + 1 ] = cb.y;
  5212. normals[ i + 2 ] = cb.z;
  5213. normals[ i + 3 ] = cb.x;
  5214. normals[ i + 4 ] = cb.y;
  5215. normals[ i + 5 ] = cb.z;
  5216. normals[ i + 6 ] = cb.x;
  5217. normals[ i + 7 ] = cb.y;
  5218. normals[ i + 8 ] = cb.z;
  5219. }
  5220. }
  5221. this.normalizeNormals();
  5222. attributes.normal.needsUpdate = true;
  5223. }
  5224. },
  5225. computeTangents: function () {
  5226. // based on http://www.terathon.com/code/tangent.html
  5227. // (per vertex tangents)
  5228. if ( this.attributes.index === undefined ||
  5229. this.attributes.position === undefined ||
  5230. this.attributes.normal === undefined ||
  5231. this.attributes.uv === undefined ) {
  5232. THREE.warn( 'THREE.BufferGeometry: Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()' );
  5233. return;
  5234. }
  5235. var indices = this.attributes.index.array;
  5236. var positions = this.attributes.position.array;
  5237. var normals = this.attributes.normal.array;
  5238. var uvs = this.attributes.uv.array;
  5239. var nVertices = positions.length / 3;
  5240. if ( this.attributes.tangent === undefined ) {
  5241. this.addAttribute( 'tangent', new THREE.BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) );
  5242. }
  5243. var tangents = this.attributes.tangent.array;
  5244. var tan1 = [], tan2 = [];
  5245. for ( var k = 0; k < nVertices; k ++ ) {
  5246. tan1[ k ] = new THREE.Vector3();
  5247. tan2[ k ] = new THREE.Vector3();
  5248. }
  5249. var vA = new THREE.Vector3(),
  5250. vB = new THREE.Vector3(),
  5251. vC = new THREE.Vector3(),
  5252. uvA = new THREE.Vector2(),
  5253. uvB = new THREE.Vector2(),
  5254. uvC = new THREE.Vector2(),
  5255. x1, x2, y1, y2, z1, z2,
  5256. s1, s2, t1, t2, r;
  5257. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  5258. function handleTriangle( a, b, c ) {
  5259. vA.fromArray( positions, a * 3 );
  5260. vB.fromArray( positions, b * 3 );
  5261. vC.fromArray( positions, c * 3 );
  5262. uvA.fromArray( uvs, a * 2 );
  5263. uvB.fromArray( uvs, b * 2 );
  5264. uvC.fromArray( uvs, c * 2 );
  5265. x1 = vB.x - vA.x;
  5266. x2 = vC.x - vA.x;
  5267. y1 = vB.y - vA.y;
  5268. y2 = vC.y - vA.y;
  5269. z1 = vB.z - vA.z;
  5270. z2 = vC.z - vA.z;
  5271. s1 = uvB.x - uvA.x;
  5272. s2 = uvC.x - uvA.x;
  5273. t1 = uvB.y - uvA.y;
  5274. t2 = uvC.y - uvA.y;
  5275. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5276. sdir.set(
  5277. ( t2 * x1 - t1 * x2 ) * r,
  5278. ( t2 * y1 - t1 * y2 ) * r,
  5279. ( t2 * z1 - t1 * z2 ) * r
  5280. );
  5281. tdir.set(
  5282. ( s1 * x2 - s2 * x1 ) * r,
  5283. ( s1 * y2 - s2 * y1 ) * r,
  5284. ( s1 * z2 - s2 * z1 ) * r
  5285. );
  5286. tan1[ a ].add( sdir );
  5287. tan1[ b ].add( sdir );
  5288. tan1[ c ].add( sdir );
  5289. tan2[ a ].add( tdir );
  5290. tan2[ b ].add( tdir );
  5291. tan2[ c ].add( tdir );
  5292. }
  5293. var i, il;
  5294. var j, jl;
  5295. var iA, iB, iC;
  5296. if ( this.drawcalls.length === 0 ) {
  5297. this.addDrawCall( 0, indices.length, 0 );
  5298. }
  5299. var drawcalls = this.drawcalls;
  5300. for ( j = 0, jl = drawcalls.length; j < jl; ++ j ) {
  5301. var start = drawcalls[ j ].start;
  5302. var count = drawcalls[ j ].count;
  5303. var index = drawcalls[ j ].index;
  5304. for ( i = start, il = start + count; i < il; i += 3 ) {
  5305. iA = index + indices[ i ];
  5306. iB = index + indices[ i + 1 ];
  5307. iC = index + indices[ i + 2 ];
  5308. handleTriangle( iA, iB, iC );
  5309. }
  5310. }
  5311. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  5312. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  5313. var w, t, test;
  5314. function handleVertex( v ) {
  5315. n.fromArray( normals, v * 3 );
  5316. n2.copy( n );
  5317. t = tan1[ v ];
  5318. // Gram-Schmidt orthogonalize
  5319. tmp.copy( t );
  5320. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5321. // Calculate handedness
  5322. tmp2.crossVectors( n2, t );
  5323. test = tmp2.dot( tan2[ v ] );
  5324. w = ( test < 0.0 ) ? - 1.0 : 1.0;
  5325. tangents[ v * 4 ] = tmp.x;
  5326. tangents[ v * 4 + 1 ] = tmp.y;
  5327. tangents[ v * 4 + 2 ] = tmp.z;
  5328. tangents[ v * 4 + 3 ] = w;
  5329. }
  5330. for ( j = 0, jl = drawcalls.length; j < jl; ++ j ) {
  5331. var start = drawcalls[ j ].start;
  5332. var count = drawcalls[ j ].count;
  5333. var index = drawcalls[ j ].index;
  5334. for ( i = start, il = start + count; i < il; i += 3 ) {
  5335. iA = index + indices[ i ];
  5336. iB = index + indices[ i + 1 ];
  5337. iC = index + indices[ i + 2 ];
  5338. handleVertex( iA );
  5339. handleVertex( iB );
  5340. handleVertex( iC );
  5341. }
  5342. }
  5343. },
  5344. /*
  5345. computeOffsets
  5346. Compute the draw offset for large models by chunking the index buffer into chunks of 65k addressable vertices.
  5347. This method will effectively rewrite the index buffer and remap all attributes to match the new indices.
  5348. WARNING: This method will also expand the vertex count to prevent sprawled triangles across draw offsets.
  5349. indexBufferSize - Defaults to 65535, but allows for larger or smaller chunks.
  5350. */
  5351. computeOffsets: function ( indexBufferSize ) {
  5352. var size = indexBufferSize;
  5353. if ( indexBufferSize === undefined )
  5354. size = 65535; //WebGL limits type of index buffer values to 16-bit.
  5355. //var s = Date.now();
  5356. var indices = this.attributes.index.array;
  5357. var vertices = this.attributes.position.array;
  5358. //var verticesCount = ( vertices.length / 3 );
  5359. var facesCount = ( indices.length / 3 );
  5360. /*
  5361. console.log("Computing buffers in offsets of "+size+" -> indices:"+indices.length+" vertices:"+vertices.length);
  5362. console.log("Faces to process: "+(indices.length/3));
  5363. console.log("Reordering "+verticesCount+" vertices.");
  5364. */
  5365. var sortedIndices = new Uint16Array( indices.length ); //16-bit buffers
  5366. var indexPtr = 0;
  5367. var vertexPtr = 0;
  5368. var offsets = [ { start:0, count:0, index:0 } ];
  5369. var offset = offsets[ 0 ];
  5370. var duplicatedVertices = 0;
  5371. var newVerticeMaps = 0;
  5372. var faceVertices = new Int32Array( 6 );
  5373. var vertexMap = new Int32Array( vertices.length );
  5374. var revVertexMap = new Int32Array( vertices.length );
  5375. for ( var j = 0; j < vertices.length; j ++ ) { vertexMap[ j ] = - 1; revVertexMap[ j ] = - 1; }
  5376. /*
  5377. Traverse every face and reorder vertices in the proper offsets of 65k.
  5378. We can have more than 65k entries in the index buffer per offset, but only reference 65k values.
  5379. */
  5380. for ( var findex = 0; findex < facesCount; findex ++ ) {
  5381. newVerticeMaps = 0;
  5382. for ( var vo = 0; vo < 3; vo ++ ) {
  5383. var vid = indices[ findex * 3 + vo ];
  5384. if ( vertexMap[ vid ] == - 1 ) {
  5385. //Unmapped vertice
  5386. faceVertices[ vo * 2 ] = vid;
  5387. faceVertices[ vo * 2 + 1 ] = - 1;
  5388. newVerticeMaps ++;
  5389. } else if ( vertexMap[ vid ] < offset.index ) {
  5390. //Reused vertices from previous block (duplicate)
  5391. faceVertices[ vo * 2 ] = vid;
  5392. faceVertices[ vo * 2 + 1 ] = - 1;
  5393. duplicatedVertices ++;
  5394. } else {
  5395. //Reused vertice in the current block
  5396. faceVertices[ vo * 2 ] = vid;
  5397. faceVertices[ vo * 2 + 1 ] = vertexMap[ vid ];
  5398. }
  5399. }
  5400. var faceMax = vertexPtr + newVerticeMaps;
  5401. if ( faceMax > ( offset.index + size ) ) {
  5402. var new_offset = { start:indexPtr, count:0, index:vertexPtr };
  5403. offsets.push( new_offset );
  5404. offset = new_offset;
  5405. //Re-evaluate reused vertices in light of new offset.
  5406. for ( var v = 0; v < 6; v += 2 ) {
  5407. var new_vid = faceVertices[ v + 1 ];
  5408. if ( new_vid > - 1 && new_vid < offset.index )
  5409. faceVertices[ v + 1 ] = - 1;
  5410. }
  5411. }
  5412. //Reindex the face.
  5413. for ( var v = 0; v < 6; v += 2 ) {
  5414. var vid = faceVertices[ v ];
  5415. var new_vid = faceVertices[ v + 1 ];
  5416. if ( new_vid === - 1 )
  5417. new_vid = vertexPtr ++;
  5418. vertexMap[ vid ] = new_vid;
  5419. revVertexMap[ new_vid ] = vid;
  5420. sortedIndices[ indexPtr ++ ] = new_vid - offset.index; //XXX overflows at 16bit
  5421. offset.count ++;
  5422. }
  5423. }
  5424. /* Move all attribute values to map to the new computed indices , also expand the vertice stack to match our new vertexPtr. */
  5425. this.reorderBuffers( sortedIndices, revVertexMap, vertexPtr );
  5426. this.offsets = offsets;
  5427. /*
  5428. var orderTime = Date.now();
  5429. console.log("Reorder time: "+(orderTime-s)+"ms");
  5430. console.log("Duplicated "+duplicatedVertices+" vertices.");
  5431. console.log("Compute Buffers time: "+(Date.now()-s)+"ms");
  5432. console.log("Draw offsets: "+offsets.length);
  5433. */
  5434. return offsets;
  5435. },
  5436. merge: function ( geometry, offset ) {
  5437. if ( geometry instanceof THREE.BufferGeometry === false ) {
  5438. THREE.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  5439. return;
  5440. }
  5441. if ( offset === undefined ) offset = 0;
  5442. var attributes = this.attributes;
  5443. for ( var key in attributes ) {
  5444. if ( geometry.attributes[ key ] === undefined ) continue;
  5445. var attribute1 = attributes[ key ];
  5446. var attributeArray1 = attribute1.array;
  5447. var attribute2 = geometry.attributes[ key ];
  5448. var attributeArray2 = attribute2.array;
  5449. var attributeSize = attribute2.itemSize;
  5450. for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) {
  5451. attributeArray1[ j ] = attributeArray2[ i ];
  5452. }
  5453. }
  5454. return this;
  5455. },
  5456. normalizeNormals: function () {
  5457. var normals = this.attributes.normal.array;
  5458. var x, y, z, n;
  5459. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  5460. x = normals[ i ];
  5461. y = normals[ i + 1 ];
  5462. z = normals[ i + 2 ];
  5463. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  5464. normals[ i ] *= n;
  5465. normals[ i + 1 ] *= n;
  5466. normals[ i + 2 ] *= n;
  5467. }
  5468. },
  5469. /*
  5470. reoderBuffers:
  5471. Reorder attributes based on a new indexBuffer and indexMap.
  5472. indexBuffer - Uint16Array of the new ordered indices.
  5473. indexMap - Int32Array where the position is the new vertex ID and the value the old vertex ID for each vertex.
  5474. vertexCount - Amount of total vertices considered in this reordering (in case you want to grow the vertice stack).
  5475. */
  5476. reorderBuffers: function ( indexBuffer, indexMap, vertexCount ) {
  5477. /* Create a copy of all attributes for reordering. */
  5478. var sortedAttributes = {};
  5479. for ( var attr in this.attributes ) {
  5480. if ( attr == 'index' )
  5481. continue;
  5482. var sourceArray = this.attributes[ attr ].array;
  5483. sortedAttributes[ attr ] = new sourceArray.constructor( this.attributes[ attr ].itemSize * vertexCount );
  5484. }
  5485. /* Move attribute positions based on the new index map */
  5486. for ( var new_vid = 0; new_vid < vertexCount; new_vid ++ ) {
  5487. var vid = indexMap[ new_vid ];
  5488. for ( var attr in this.attributes ) {
  5489. if ( attr == 'index' )
  5490. continue;
  5491. var attrArray = this.attributes[ attr ].array;
  5492. var attrSize = this.attributes[ attr ].itemSize;
  5493. var sortedAttr = sortedAttributes[ attr ];
  5494. for ( var k = 0; k < attrSize; k ++ )
  5495. sortedAttr[ new_vid * attrSize + k ] = attrArray[ vid * attrSize + k ];
  5496. }
  5497. }
  5498. /* Carry the new sorted buffers locally */
  5499. this.attributes[ 'index' ].array = indexBuffer;
  5500. for ( var attr in this.attributes ) {
  5501. if ( attr == 'index' )
  5502. continue;
  5503. this.attributes[ attr ].array = sortedAttributes[ attr ];
  5504. this.attributes[ attr ].numItems = this.attributes[ attr ].itemSize * vertexCount;
  5505. }
  5506. },
  5507. toJSON: function () {
  5508. var output = {
  5509. metadata: {
  5510. version: 4.0,
  5511. type: 'BufferGeometry',
  5512. generator: 'BufferGeometryExporter'
  5513. },
  5514. uuid: this.uuid,
  5515. type: this.type,
  5516. data: {
  5517. attributes: {}
  5518. }
  5519. };
  5520. var attributes = this.attributes;
  5521. var offsets = this.offsets;
  5522. var boundingSphere = this.boundingSphere;
  5523. for ( var key in attributes ) {
  5524. var attribute = attributes[ key ];
  5525. var array = Array.prototype.slice.call( attribute.array );
  5526. output.data.attributes[ key ] = {
  5527. itemSize: attribute.itemSize,
  5528. type: attribute.array.constructor.name,
  5529. array: array
  5530. }
  5531. }
  5532. if ( offsets.length > 0 ) {
  5533. output.data.offsets = JSON.parse( JSON.stringify( offsets ) );
  5534. }
  5535. if ( boundingSphere !== null ) {
  5536. output.data.boundingSphere = {
  5537. center: boundingSphere.center.toArray(),
  5538. radius: boundingSphere.radius
  5539. }
  5540. }
  5541. return output;
  5542. },
  5543. clone: function () {
  5544. var geometry = new THREE.BufferGeometry();
  5545. for ( var attr in this.attributes ) {
  5546. var sourceAttr = this.attributes[ attr ];
  5547. geometry.addAttribute( attr, sourceAttr.clone() );
  5548. }
  5549. for ( var i = 0, il = this.offsets.length; i < il; i ++ ) {
  5550. var offset = this.offsets[ i ];
  5551. geometry.offsets.push( {
  5552. start: offset.start,
  5553. index: offset.index,
  5554. count: offset.count
  5555. } );
  5556. }
  5557. return geometry;
  5558. },
  5559. dispose: function () {
  5560. this.dispatchEvent( { type: 'dispose' } );
  5561. }
  5562. };
  5563. THREE.EventDispatcher.prototype.apply( THREE.BufferGeometry.prototype );
  5564. // File:src/core/Geometry.js
  5565. /**
  5566. * @author mrdoob / http://mrdoob.com/
  5567. * @author kile / http://kile.stravaganza.org/
  5568. * @author alteredq / http://alteredqualia.com/
  5569. * @author mikael emtinger / http://gomo.se/
  5570. * @author zz85 / http://www.lab4games.net/zz85/blog
  5571. * @author bhouston / http://exocortex.com
  5572. */
  5573. THREE.Geometry = function () {
  5574. Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } );
  5575. this.uuid = THREE.Math.generateUUID();
  5576. this.name = '';
  5577. this.type = 'Geometry';
  5578. this.vertices = [];
  5579. this.colors = []; // one-to-one vertex colors, used in Points and Line
  5580. this.faces = [];
  5581. this.faceVertexUvs = [ [] ];
  5582. this.morphTargets = [];
  5583. this.morphColors = [];
  5584. this.morphNormals = [];
  5585. this.skinWeights = [];
  5586. this.skinIndices = [];
  5587. this.lineDistances = [];
  5588. this.boundingBox = null;
  5589. this.boundingSphere = null;
  5590. this.hasTangents = false;
  5591. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  5592. // update flags
  5593. this.verticesNeedUpdate = false;
  5594. this.elementsNeedUpdate = false;
  5595. this.uvsNeedUpdate = false;
  5596. this.normalsNeedUpdate = false;
  5597. this.tangentsNeedUpdate = false;
  5598. this.colorsNeedUpdate = false;
  5599. this.lineDistancesNeedUpdate = false;
  5600. this.groupsNeedUpdate = false;
  5601. };
  5602. THREE.Geometry.prototype = {
  5603. constructor: THREE.Geometry,
  5604. applyMatrix: function ( matrix ) {
  5605. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5606. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  5607. var vertex = this.vertices[ i ];
  5608. vertex.applyMatrix4( matrix );
  5609. }
  5610. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  5611. var face = this.faces[ i ];
  5612. face.normal.applyMatrix3( normalMatrix ).normalize();
  5613. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  5614. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  5615. }
  5616. }
  5617. if ( this.boundingBox !== null ) {
  5618. this.computeBoundingBox();
  5619. }
  5620. if ( this.boundingSphere !== null ) {
  5621. this.computeBoundingSphere();
  5622. }
  5623. this.verticesNeedUpdate = true;
  5624. this.normalsNeedUpdate = true;
  5625. },
  5626. fromBufferGeometry: function ( geometry ) {
  5627. var scope = this;
  5628. var attributes = geometry.attributes;
  5629. var vertices = attributes.position.array;
  5630. var indices = attributes.index !== undefined ? attributes.index.array : undefined;
  5631. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  5632. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  5633. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  5634. var tempNormals = [];
  5635. var tempUVs = [];
  5636. for ( var i = 0, j = 0; i < vertices.length; i += 3, j += 2 ) {
  5637. scope.vertices.push( new THREE.Vector3( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] ) );
  5638. if ( normals !== undefined ) {
  5639. tempNormals.push( new THREE.Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) );
  5640. }
  5641. if ( colors !== undefined ) {
  5642. scope.colors.push( new THREE.Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) );
  5643. }
  5644. if ( uvs !== undefined ) {
  5645. tempUVs.push( new THREE.Vector2( uvs[ j ], uvs[ j + 1 ] ) );
  5646. }
  5647. }
  5648. var addFace = function ( a, b, c ) {
  5649. var vertexNormals = normals !== undefined ? [ tempNormals[ a ].clone(), tempNormals[ b ].clone(), tempNormals[ c ].clone() ] : [];
  5650. var vertexColors = colors !== undefined ? [ scope.colors[ a ].clone(), scope.colors[ b ].clone(), scope.colors[ c ].clone() ] : [];
  5651. scope.faces.push( new THREE.Face3( a, b, c, vertexNormals, vertexColors ) );
  5652. if ( uvs !== undefined ) {
  5653. scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] );
  5654. }
  5655. };
  5656. if ( indices !== undefined ) {
  5657. for ( var i = 0; i < indices.length; i += 3 ) {
  5658. addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  5659. }
  5660. } else {
  5661. for ( var i = 0; i < vertices.length / 3; i += 3 ) {
  5662. addFace( i, i + 1, i + 2 );
  5663. }
  5664. }
  5665. this.computeFaceNormals();
  5666. if ( geometry.boundingBox !== null ) {
  5667. this.boundingBox = geometry.boundingBox.clone();
  5668. }
  5669. if ( geometry.boundingSphere !== null ) {
  5670. this.boundingSphere = geometry.boundingSphere.clone();
  5671. }
  5672. return this;
  5673. },
  5674. center: function () {
  5675. this.computeBoundingBox();
  5676. var offset = this.boundingBox.center().negate();
  5677. this.applyMatrix( new THREE.Matrix4().setPosition( offset ) );
  5678. return offset;
  5679. },
  5680. computeFaceNormals: function () {
  5681. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  5682. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5683. var face = this.faces[ f ];
  5684. var vA = this.vertices[ face.a ];
  5685. var vB = this.vertices[ face.b ];
  5686. var vC = this.vertices[ face.c ];
  5687. cb.subVectors( vC, vB );
  5688. ab.subVectors( vA, vB );
  5689. cb.cross( ab );
  5690. cb.normalize();
  5691. face.normal.copy( cb );
  5692. }
  5693. },
  5694. computeVertexNormals: function ( areaWeighted ) {
  5695. var v, vl, f, fl, face, vertices;
  5696. vertices = new Array( this.vertices.length );
  5697. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5698. vertices[ v ] = new THREE.Vector3();
  5699. }
  5700. if ( areaWeighted ) {
  5701. // vertex normals weighted by triangle areas
  5702. // http://www.iquilezles.org/www/articles/normals/normals.htm
  5703. var vA, vB, vC;
  5704. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  5705. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5706. face = this.faces[ f ];
  5707. vA = this.vertices[ face.a ];
  5708. vB = this.vertices[ face.b ];
  5709. vC = this.vertices[ face.c ];
  5710. cb.subVectors( vC, vB );
  5711. ab.subVectors( vA, vB );
  5712. cb.cross( ab );
  5713. vertices[ face.a ].add( cb );
  5714. vertices[ face.b ].add( cb );
  5715. vertices[ face.c ].add( cb );
  5716. }
  5717. } else {
  5718. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5719. face = this.faces[ f ];
  5720. vertices[ face.a ].add( face.normal );
  5721. vertices[ face.b ].add( face.normal );
  5722. vertices[ face.c ].add( face.normal );
  5723. }
  5724. }
  5725. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5726. vertices[ v ].normalize();
  5727. }
  5728. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5729. face = this.faces[ f ];
  5730. face.vertexNormals[ 0 ] = vertices[ face.a ].clone();
  5731. face.vertexNormals[ 1 ] = vertices[ face.b ].clone();
  5732. face.vertexNormals[ 2 ] = vertices[ face.c ].clone();
  5733. }
  5734. },
  5735. computeMorphNormals: function () {
  5736. var i, il, f, fl, face;
  5737. // save original normals
  5738. // - create temp variables on first access
  5739. // otherwise just copy (for faster repeated calls)
  5740. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5741. face = this.faces[ f ];
  5742. if ( ! face.__originalFaceNormal ) {
  5743. face.__originalFaceNormal = face.normal.clone();
  5744. } else {
  5745. face.__originalFaceNormal.copy( face.normal );
  5746. }
  5747. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  5748. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  5749. if ( ! face.__originalVertexNormals[ i ] ) {
  5750. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  5751. } else {
  5752. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  5753. }
  5754. }
  5755. }
  5756. // use temp geometry to compute face and vertex normals for each morph
  5757. var tmpGeo = new THREE.Geometry();
  5758. tmpGeo.faces = this.faces;
  5759. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  5760. // create on first access
  5761. if ( ! this.morphNormals[ i ] ) {
  5762. this.morphNormals[ i ] = {};
  5763. this.morphNormals[ i ].faceNormals = [];
  5764. this.morphNormals[ i ].vertexNormals = [];
  5765. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  5766. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  5767. var faceNormal, vertexNormals;
  5768. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5769. faceNormal = new THREE.Vector3();
  5770. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  5771. dstNormalsFace.push( faceNormal );
  5772. dstNormalsVertex.push( vertexNormals );
  5773. }
  5774. }
  5775. var morphNormals = this.morphNormals[ i ];
  5776. // set vertices to morph target
  5777. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  5778. // compute morph normals
  5779. tmpGeo.computeFaceNormals();
  5780. tmpGeo.computeVertexNormals();
  5781. // store morph normals
  5782. var faceNormal, vertexNormals;
  5783. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5784. face = this.faces[ f ];
  5785. faceNormal = morphNormals.faceNormals[ f ];
  5786. vertexNormals = morphNormals.vertexNormals[ f ];
  5787. faceNormal.copy( face.normal );
  5788. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  5789. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  5790. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  5791. }
  5792. }
  5793. // restore original normals
  5794. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5795. face = this.faces[ f ];
  5796. face.normal = face.__originalFaceNormal;
  5797. face.vertexNormals = face.__originalVertexNormals;
  5798. }
  5799. },
  5800. computeTangents: function () {
  5801. // based on http://www.terathon.com/code/tangent.html
  5802. // tangents go to vertices
  5803. var f, fl, v, vl, i, vertexIndex,
  5804. face, uv, vA, vB, vC, uvA, uvB, uvC,
  5805. x1, x2, y1, y2, z1, z2,
  5806. s1, s2, t1, t2, r, t, test,
  5807. tan1 = [], tan2 = [],
  5808. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  5809. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  5810. n = new THREE.Vector3(), w;
  5811. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5812. tan1[ v ] = new THREE.Vector3();
  5813. tan2[ v ] = new THREE.Vector3();
  5814. }
  5815. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  5816. vA = context.vertices[ a ];
  5817. vB = context.vertices[ b ];
  5818. vC = context.vertices[ c ];
  5819. uvA = uv[ ua ];
  5820. uvB = uv[ ub ];
  5821. uvC = uv[ uc ];
  5822. x1 = vB.x - vA.x;
  5823. x2 = vC.x - vA.x;
  5824. y1 = vB.y - vA.y;
  5825. y2 = vC.y - vA.y;
  5826. z1 = vB.z - vA.z;
  5827. z2 = vC.z - vA.z;
  5828. s1 = uvB.x - uvA.x;
  5829. s2 = uvC.x - uvA.x;
  5830. t1 = uvB.y - uvA.y;
  5831. t2 = uvC.y - uvA.y;
  5832. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5833. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  5834. ( t2 * y1 - t1 * y2 ) * r,
  5835. ( t2 * z1 - t1 * z2 ) * r );
  5836. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  5837. ( s1 * y2 - s2 * y1 ) * r,
  5838. ( s1 * z2 - s2 * z1 ) * r );
  5839. tan1[ a ].add( sdir );
  5840. tan1[ b ].add( sdir );
  5841. tan1[ c ].add( sdir );
  5842. tan2[ a ].add( tdir );
  5843. tan2[ b ].add( tdir );
  5844. tan2[ c ].add( tdir );
  5845. }
  5846. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5847. face = this.faces[ f ];
  5848. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  5849. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  5850. }
  5851. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  5852. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5853. face = this.faces[ f ];
  5854. for ( i = 0; i < Math.min( face.vertexNormals.length, 3 ); i ++ ) {
  5855. n.copy( face.vertexNormals[ i ] );
  5856. vertexIndex = face[ faceIndex[ i ] ];
  5857. t = tan1[ vertexIndex ];
  5858. // Gram-Schmidt orthogonalize
  5859. tmp.copy( t );
  5860. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5861. // Calculate handedness
  5862. tmp2.crossVectors( face.vertexNormals[ i ], t );
  5863. test = tmp2.dot( tan2[ vertexIndex ] );
  5864. w = ( test < 0.0 ) ? - 1.0 : 1.0;
  5865. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  5866. }
  5867. }
  5868. this.hasTangents = true;
  5869. },
  5870. computeLineDistances: function () {
  5871. var d = 0;
  5872. var vertices = this.vertices;
  5873. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  5874. if ( i > 0 ) {
  5875. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  5876. }
  5877. this.lineDistances[ i ] = d;
  5878. }
  5879. },
  5880. computeBoundingBox: function () {
  5881. if ( this.boundingBox === null ) {
  5882. this.boundingBox = new THREE.Box3();
  5883. }
  5884. this.boundingBox.setFromPoints( this.vertices );
  5885. },
  5886. computeBoundingSphere: function () {
  5887. if ( this.boundingSphere === null ) {
  5888. this.boundingSphere = new THREE.Sphere();
  5889. }
  5890. this.boundingSphere.setFromPoints( this.vertices );
  5891. },
  5892. merge: function ( geometry, matrix, materialIndexOffset ) {
  5893. if ( geometry instanceof THREE.Geometry === false ) {
  5894. THREE.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  5895. return;
  5896. }
  5897. var normalMatrix,
  5898. vertexOffset = this.vertices.length,
  5899. vertices1 = this.vertices,
  5900. vertices2 = geometry.vertices,
  5901. faces1 = this.faces,
  5902. faces2 = geometry.faces,
  5903. uvs1 = this.faceVertexUvs[ 0 ],
  5904. uvs2 = geometry.faceVertexUvs[ 0 ];
  5905. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  5906. if ( matrix !== undefined ) {
  5907. normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5908. }
  5909. // vertices
  5910. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  5911. var vertex = vertices2[ i ];
  5912. var vertexCopy = vertex.clone();
  5913. if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
  5914. vertices1.push( vertexCopy );
  5915. }
  5916. // faces
  5917. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  5918. var face = faces2[ i ], faceCopy, normal, color,
  5919. faceVertexNormals = face.vertexNormals,
  5920. faceVertexColors = face.vertexColors;
  5921. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  5922. faceCopy.normal.copy( face.normal );
  5923. if ( normalMatrix !== undefined ) {
  5924. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  5925. }
  5926. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  5927. normal = faceVertexNormals[ j ].clone();
  5928. if ( normalMatrix !== undefined ) {
  5929. normal.applyMatrix3( normalMatrix ).normalize();
  5930. }
  5931. faceCopy.vertexNormals.push( normal );
  5932. }
  5933. faceCopy.color.copy( face.color );
  5934. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  5935. color = faceVertexColors[ j ];
  5936. faceCopy.vertexColors.push( color.clone() );
  5937. }
  5938. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  5939. faces1.push( faceCopy );
  5940. }
  5941. // uvs
  5942. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  5943. var uv = uvs2[ i ], uvCopy = [];
  5944. if ( uv === undefined ) {
  5945. continue;
  5946. }
  5947. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  5948. uvCopy.push( uv[ j ].clone() );
  5949. }
  5950. uvs1.push( uvCopy );
  5951. }
  5952. },
  5953. mergeMesh: function ( mesh ) {
  5954. if ( mesh instanceof THREE.Mesh === false ) {
  5955. THREE.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
  5956. return;
  5957. }
  5958. mesh.matrixAutoUpdate && mesh.updateMatrix();
  5959. this.merge( mesh.geometry, mesh.matrix );
  5960. },
  5961. /*
  5962. * Checks for duplicate vertices with hashmap.
  5963. * Duplicated vertices are removed
  5964. * and faces' vertices are updated.
  5965. */
  5966. mergeVertices: function () {
  5967. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  5968. var unique = [], changes = [];
  5969. var v, key;
  5970. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  5971. var precision = Math.pow( 10, precisionPoints );
  5972. var i, il, face;
  5973. var indices, j, jl;
  5974. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  5975. v = this.vertices[ i ];
  5976. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  5977. if ( verticesMap[ key ] === undefined ) {
  5978. verticesMap[ key ] = i;
  5979. unique.push( this.vertices[ i ] );
  5980. changes[ i ] = unique.length - 1;
  5981. } else {
  5982. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  5983. changes[ i ] = changes[ verticesMap[ key ] ];
  5984. }
  5985. };
  5986. // if faces are completely degenerate after merging vertices, we
  5987. // have to remove them from the geometry.
  5988. var faceIndicesToRemove = [];
  5989. for ( i = 0, il = this.faces.length; i < il; i ++ ) {
  5990. face = this.faces[ i ];
  5991. face.a = changes[ face.a ];
  5992. face.b = changes[ face.b ];
  5993. face.c = changes[ face.c ];
  5994. indices = [ face.a, face.b, face.c ];
  5995. var dupIndex = - 1;
  5996. // if any duplicate vertices are found in a Face3
  5997. // we have to remove the face as nothing can be saved
  5998. for ( var n = 0; n < 3; n ++ ) {
  5999. if ( indices[ n ] == indices[ ( n + 1 ) % 3 ] ) {
  6000. dupIndex = n;
  6001. faceIndicesToRemove.push( i );
  6002. break;
  6003. }
  6004. }
  6005. }
  6006. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  6007. var idx = faceIndicesToRemove[ i ];
  6008. this.faces.splice( idx, 1 );
  6009. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  6010. this.faceVertexUvs[ j ].splice( idx, 1 );
  6011. }
  6012. }
  6013. // Use unique set of vertices
  6014. var diff = this.vertices.length - unique.length;
  6015. this.vertices = unique;
  6016. return diff;
  6017. },
  6018. toJSON: function () {
  6019. var output = {
  6020. metadata: {
  6021. version: 4.0,
  6022. type: 'BufferGeometry',
  6023. generator: 'BufferGeometryExporter'
  6024. },
  6025. uuid: this.uuid,
  6026. type: this.type
  6027. };
  6028. if ( this.name !== "" ) output.name = this.name;
  6029. if ( this.parameters !== undefined ) {
  6030. var parameters = this.parameters;
  6031. for ( var key in parameters ) {
  6032. if ( parameters[ key ] !== undefined ) output[ key ] = parameters[ key ];
  6033. }
  6034. return output;
  6035. }
  6036. var vertices = [];
  6037. for ( var i = 0; i < this.vertices.length; i ++ ) {
  6038. var vertex = this.vertices[ i ];
  6039. vertices.push( vertex.x, vertex.y, vertex.z );
  6040. }
  6041. var faces = [];
  6042. var normals = [];
  6043. var normalsHash = {};
  6044. var colors = [];
  6045. var colorsHash = {};
  6046. var uvs = [];
  6047. var uvsHash = {};
  6048. for ( var i = 0; i < this.faces.length; i ++ ) {
  6049. var face = this.faces[ i ];
  6050. var hasMaterial = false; // face.materialIndex !== undefined;
  6051. var hasFaceUv = false; // deprecated
  6052. var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined;
  6053. var hasFaceNormal = face.normal.length() > 0;
  6054. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  6055. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  6056. var hasFaceVertexColor = face.vertexColors.length > 0;
  6057. var faceType = 0;
  6058. faceType = setBit( faceType, 0, 0 );
  6059. faceType = setBit( faceType, 1, hasMaterial );
  6060. faceType = setBit( faceType, 2, hasFaceUv );
  6061. faceType = setBit( faceType, 3, hasFaceVertexUv );
  6062. faceType = setBit( faceType, 4, hasFaceNormal );
  6063. faceType = setBit( faceType, 5, hasFaceVertexNormal );
  6064. faceType = setBit( faceType, 6, hasFaceColor );
  6065. faceType = setBit( faceType, 7, hasFaceVertexColor );
  6066. faces.push( faceType );
  6067. faces.push( face.a, face.b, face.c );
  6068. /*
  6069. if ( hasMaterial ) {
  6070. faces.push( face.materialIndex );
  6071. }
  6072. */
  6073. if ( hasFaceVertexUv ) {
  6074. var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ];
  6075. faces.push(
  6076. getUvIndex( faceVertexUvs[ 0 ] ),
  6077. getUvIndex( faceVertexUvs[ 1 ] ),
  6078. getUvIndex( faceVertexUvs[ 2 ] )
  6079. );
  6080. }
  6081. if ( hasFaceNormal ) {
  6082. faces.push( getNormalIndex( face.normal ) );
  6083. }
  6084. if ( hasFaceVertexNormal ) {
  6085. var vertexNormals = face.vertexNormals;
  6086. faces.push(
  6087. getNormalIndex( vertexNormals[ 0 ] ),
  6088. getNormalIndex( vertexNormals[ 1 ] ),
  6089. getNormalIndex( vertexNormals[ 2 ] )
  6090. );
  6091. }
  6092. if ( hasFaceColor ) {
  6093. faces.push( getColorIndex( face.color ) );
  6094. }
  6095. if ( hasFaceVertexColor ) {
  6096. var vertexColors = face.vertexColors;
  6097. faces.push(
  6098. getColorIndex( vertexColors[ 0 ] ),
  6099. getColorIndex( vertexColors[ 1 ] ),
  6100. getColorIndex( vertexColors[ 2 ] )
  6101. );
  6102. }
  6103. }
  6104. function setBit( value, position, enabled ) {
  6105. return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position) );
  6106. }
  6107. function getNormalIndex( normal ) {
  6108. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  6109. if ( normalsHash[ hash ] !== undefined ) {
  6110. return normalsHash[ hash ];
  6111. }
  6112. normalsHash[ hash ] = normals.length / 3;
  6113. normals.push( normal.x, normal.y, normal.z );
  6114. return normalsHash[ hash ];
  6115. }
  6116. function getColorIndex( color ) {
  6117. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  6118. if ( colorsHash[ hash ] !== undefined ) {
  6119. return colorsHash[ hash ];
  6120. }
  6121. colorsHash[ hash ] = colors.length;
  6122. colors.push( color.getHex() );
  6123. return colorsHash[ hash ];
  6124. }
  6125. function getUvIndex( uv ) {
  6126. var hash = uv.x.toString() + uv.y.toString();
  6127. if ( uvsHash[ hash ] !== undefined ) {
  6128. return uvsHash[ hash ];
  6129. }
  6130. uvsHash[ hash ] = uvs.length / 2;
  6131. uvs.push( uv.x, uv.y );
  6132. return uvsHash[ hash ];
  6133. }
  6134. output.data = {};
  6135. output.data.vertices = vertices;
  6136. output.data.normals = normals;
  6137. if ( colors.length > 0 ) output.data.colors = colors;
  6138. if ( uvs.length > 0 ) output.data.uvs = [ uvs ]; // temporal backward compatibility
  6139. output.data.faces = faces;
  6140. //
  6141. return output;
  6142. },
  6143. clone: function () {
  6144. var geometry = new THREE.Geometry();
  6145. var vertices = this.vertices;
  6146. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  6147. geometry.vertices.push( vertices[ i ].clone() );
  6148. }
  6149. var faces = this.faces;
  6150. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  6151. geometry.faces.push( faces[ i ].clone() );
  6152. }
  6153. for ( var i = 0, il = this.faceVertexUvs.length; i < il; i ++ ) {
  6154. var faceVertexUvs = this.faceVertexUvs[ i ];
  6155. if ( geometry.faceVertexUvs[ i ] === undefined ) {
  6156. geometry.faceVertexUvs[ i ] = [];
  6157. }
  6158. for ( var j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {
  6159. var uvs = faceVertexUvs[ j ], uvsCopy = [];
  6160. for ( var k = 0, kl = uvs.length; k < kl; k ++ ) {
  6161. var uv = uvs[ k ];
  6162. uvsCopy.push( uv.clone() );
  6163. }
  6164. geometry.faceVertexUvs[ i ].push( uvsCopy );
  6165. }
  6166. }
  6167. return geometry;
  6168. },
  6169. dispose: function () {
  6170. this.dispatchEvent( { type: 'dispose' } );
  6171. }
  6172. };
  6173. THREE.EventDispatcher.prototype.apply( THREE.Geometry.prototype );
  6174. THREE.GeometryIdCount = 0;
  6175. // File:src/cameras/Camera.js
  6176. /**
  6177. * @author mrdoob / http://mrdoob.com/
  6178. * @author mikael emtinger / http://gomo.se/
  6179. * @author WestLangley / http://github.com/WestLangley
  6180. */
  6181. THREE.Camera = function () {
  6182. THREE.Object3D.call( this );
  6183. this.type = 'Camera';
  6184. this.matrixWorldInverse = new THREE.Matrix4();
  6185. this.projectionMatrix = new THREE.Matrix4();
  6186. };
  6187. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  6188. THREE.Camera.prototype.constructor = THREE.Camera;
  6189. THREE.Camera.prototype.getWorldDirection = function () {
  6190. var quaternion = new THREE.Quaternion();
  6191. return function ( optionalTarget ) {
  6192. var result = optionalTarget || new THREE.Vector3();
  6193. this.getWorldQuaternion( quaternion );
  6194. return result.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  6195. }
  6196. }();
  6197. THREE.Camera.prototype.lookAt = function () {
  6198. // This routine does not support cameras with rotated and/or translated parent(s)
  6199. var m1 = new THREE.Matrix4();
  6200. return function ( vector ) {
  6201. m1.lookAt( this.position, vector, this.up );
  6202. this.quaternion.setFromRotationMatrix( m1 );
  6203. };
  6204. }();
  6205. THREE.Camera.prototype.clone = function ( camera ) {
  6206. if ( camera === undefined ) camera = new THREE.Camera();
  6207. THREE.Object3D.prototype.clone.call( this, camera );
  6208. camera.matrixWorldInverse.copy( this.matrixWorldInverse );
  6209. camera.projectionMatrix.copy( this.projectionMatrix );
  6210. return camera;
  6211. };
  6212. // File:src/cameras/CubeCamera.js
  6213. /**
  6214. * Camera for rendering cube maps
  6215. * - renders scene into axis-aligned cube
  6216. *
  6217. * @author alteredq / http://alteredqualia.com/
  6218. */
  6219. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  6220. THREE.Object3D.call( this );
  6221. this.type = 'CubeCamera';
  6222. var fov = 90, aspect = 1;
  6223. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  6224. cameraPX.up.set( 0, - 1, 0 );
  6225. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  6226. this.add( cameraPX );
  6227. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  6228. cameraNX.up.set( 0, - 1, 0 );
  6229. cameraNX.lookAt( new THREE.Vector3( - 1, 0, 0 ) );
  6230. this.add( cameraNX );
  6231. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  6232. cameraPY.up.set( 0, 0, 1 );
  6233. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  6234. this.add( cameraPY );
  6235. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  6236. cameraNY.up.set( 0, 0, - 1 );
  6237. cameraNY.lookAt( new THREE.Vector3( 0, - 1, 0 ) );
  6238. this.add( cameraNY );
  6239. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  6240. cameraPZ.up.set( 0, - 1, 0 );
  6241. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  6242. this.add( cameraPZ );
  6243. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  6244. cameraNZ.up.set( 0, - 1, 0 );
  6245. cameraNZ.lookAt( new THREE.Vector3( 0, 0, - 1 ) );
  6246. this.add( cameraNZ );
  6247. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  6248. this.updateCubeMap = function ( renderer, scene ) {
  6249. var renderTarget = this.renderTarget;
  6250. var generateMipmaps = renderTarget.generateMipmaps;
  6251. renderTarget.generateMipmaps = false;
  6252. renderTarget.activeCubeFace = 0;
  6253. renderer.render( scene, cameraPX, renderTarget );
  6254. renderTarget.activeCubeFace = 1;
  6255. renderer.render( scene, cameraNX, renderTarget );
  6256. renderTarget.activeCubeFace = 2;
  6257. renderer.render( scene, cameraPY, renderTarget );
  6258. renderTarget.activeCubeFace = 3;
  6259. renderer.render( scene, cameraNY, renderTarget );
  6260. renderTarget.activeCubeFace = 4;
  6261. renderer.render( scene, cameraPZ, renderTarget );
  6262. renderTarget.generateMipmaps = generateMipmaps;
  6263. renderTarget.activeCubeFace = 5;
  6264. renderer.render( scene, cameraNZ, renderTarget );
  6265. };
  6266. };
  6267. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  6268. THREE.CubeCamera.prototype.constructor = THREE.CubeCamera;
  6269. // File:src/cameras/OrthographicCamera.js
  6270. /**
  6271. * @author alteredq / http://alteredqualia.com/
  6272. */
  6273. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  6274. THREE.Camera.call( this );
  6275. this.type = 'OrthographicCamera';
  6276. this.zoom = 1;
  6277. this.left = left;
  6278. this.right = right;
  6279. this.top = top;
  6280. this.bottom = bottom;
  6281. this.near = ( near !== undefined ) ? near : 0.1;
  6282. this.far = ( far !== undefined ) ? far : 2000;
  6283. this.updateProjectionMatrix();
  6284. };
  6285. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  6286. THREE.OrthographicCamera.prototype.constructor = THREE.OrthographicCamera;
  6287. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  6288. var dx = ( this.right - this.left ) / ( 2 * this.zoom );
  6289. var dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  6290. var cx = ( this.right + this.left ) / 2;
  6291. var cy = ( this.top + this.bottom ) / 2;
  6292. this.projectionMatrix.makeOrthographic( cx - dx, cx + dx, cy + dy, cy - dy, this.near, this.far );
  6293. };
  6294. THREE.OrthographicCamera.prototype.clone = function () {
  6295. var camera = new THREE.OrthographicCamera();
  6296. THREE.Camera.prototype.clone.call( this, camera );
  6297. camera.zoom = this.zoom;
  6298. camera.left = this.left;
  6299. camera.right = this.right;
  6300. camera.top = this.top;
  6301. camera.bottom = this.bottom;
  6302. camera.near = this.near;
  6303. camera.far = this.far;
  6304. camera.projectionMatrix.copy( this.projectionMatrix );
  6305. return camera;
  6306. };
  6307. // File:src/cameras/PerspectiveCamera.js
  6308. /**
  6309. * @author mrdoob / http://mrdoob.com/
  6310. * @author greggman / http://games.greggman.com/
  6311. * @author zz85 / http://www.lab4games.net/zz85/blog
  6312. */
  6313. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  6314. THREE.Camera.call( this );
  6315. this.type = 'PerspectiveCamera';
  6316. this.zoom = 1;
  6317. this.fov = fov !== undefined ? fov : 50;
  6318. this.aspect = aspect !== undefined ? aspect : 1;
  6319. this.near = near !== undefined ? near : 0.1;
  6320. this.far = far !== undefined ? far : 2000;
  6321. this.updateProjectionMatrix();
  6322. };
  6323. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  6324. THREE.PerspectiveCamera.prototype.constructor = THREE.PerspectiveCamera;
  6325. /**
  6326. * Uses Focal Length (in mm) to estimate and set FOV
  6327. * 35mm (fullframe) camera is used if frame size is not specified;
  6328. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  6329. */
  6330. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  6331. if ( frameHeight === undefined ) frameHeight = 24;
  6332. this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  6333. this.updateProjectionMatrix();
  6334. }
  6335. /**
  6336. * Sets an offset in a larger frustum. This is useful for multi-window or
  6337. * multi-monitor/multi-machine setups.
  6338. *
  6339. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  6340. * the monitors are in grid like this
  6341. *
  6342. * +---+---+---+
  6343. * | A | B | C |
  6344. * +---+---+---+
  6345. * | D | E | F |
  6346. * +---+---+---+
  6347. *
  6348. * then for each monitor you would call it like this
  6349. *
  6350. * var w = 1920;
  6351. * var h = 1080;
  6352. * var fullWidth = w * 3;
  6353. * var fullHeight = h * 2;
  6354. *
  6355. * --A--
  6356. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  6357. * --B--
  6358. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  6359. * --C--
  6360. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  6361. * --D--
  6362. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  6363. * --E--
  6364. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  6365. * --F--
  6366. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  6367. *
  6368. * Note there is no reason monitors have to be the same size or in a grid.
  6369. */
  6370. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  6371. this.fullWidth = fullWidth;
  6372. this.fullHeight = fullHeight;
  6373. this.x = x;
  6374. this.y = y;
  6375. this.width = width;
  6376. this.height = height;
  6377. this.updateProjectionMatrix();
  6378. };
  6379. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  6380. var fov = THREE.Math.radToDeg( 2 * Math.atan( Math.tan( THREE.Math.degToRad( this.fov ) * 0.5 ) / this.zoom ) );
  6381. if ( this.fullWidth ) {
  6382. var aspect = this.fullWidth / this.fullHeight;
  6383. var top = Math.tan( THREE.Math.degToRad( fov * 0.5 ) ) * this.near;
  6384. var bottom = - top;
  6385. var left = aspect * bottom;
  6386. var right = aspect * top;
  6387. var width = Math.abs( right - left );
  6388. var height = Math.abs( top - bottom );
  6389. this.projectionMatrix.makeFrustum(
  6390. left + this.x * width / this.fullWidth,
  6391. left + ( this.x + this.width ) * width / this.fullWidth,
  6392. top - ( this.y + this.height ) * height / this.fullHeight,
  6393. top - this.y * height / this.fullHeight,
  6394. this.near,
  6395. this.far
  6396. );
  6397. } else {
  6398. this.projectionMatrix.makePerspective( fov, this.aspect, this.near, this.far );
  6399. }
  6400. };
  6401. THREE.PerspectiveCamera.prototype.clone = function () {
  6402. var camera = new THREE.PerspectiveCamera();
  6403. THREE.Camera.prototype.clone.call( this, camera );
  6404. camera.zoom = this.zoom;
  6405. camera.fov = this.fov;
  6406. camera.aspect = this.aspect;
  6407. camera.near = this.near;
  6408. camera.far = this.far;
  6409. camera.projectionMatrix.copy( this.projectionMatrix );
  6410. return camera;
  6411. };
  6412. // File:src/lights/Light.js
  6413. /**
  6414. * @author mrdoob / http://mrdoob.com/
  6415. * @author alteredq / http://alteredqualia.com/
  6416. */
  6417. THREE.Light = function ( color ) {
  6418. THREE.Object3D.call( this );
  6419. this.type = 'Light';
  6420. this.color = new THREE.Color( color );
  6421. };
  6422. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  6423. THREE.Light.prototype.constructor = THREE.Light;
  6424. THREE.Light.prototype.clone = function ( light ) {
  6425. if ( light === undefined ) light = new THREE.Light();
  6426. THREE.Object3D.prototype.clone.call( this, light );
  6427. light.color.copy( this.color );
  6428. return light;
  6429. };
  6430. // File:src/lights/AmbientLight.js
  6431. /**
  6432. * @author mrdoob / http://mrdoob.com/
  6433. */
  6434. THREE.AmbientLight = function ( color ) {
  6435. THREE.Light.call( this, color );
  6436. this.type = 'AmbientLight';
  6437. };
  6438. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  6439. THREE.AmbientLight.prototype.constructor = THREE.AmbientLight;
  6440. THREE.AmbientLight.prototype.clone = function () {
  6441. var light = new THREE.AmbientLight();
  6442. THREE.Light.prototype.clone.call( this, light );
  6443. return light;
  6444. };
  6445. // File:src/lights/AreaLight.js
  6446. /**
  6447. * @author MPanknin / http://www.redplant.de/
  6448. * @author alteredq / http://alteredqualia.com/
  6449. */
  6450. THREE.AreaLight = function ( color, intensity ) {
  6451. THREE.Light.call( this, color );
  6452. this.type = 'AreaLight';
  6453. this.normal = new THREE.Vector3( 0, - 1, 0 );
  6454. this.right = new THREE.Vector3( 1, 0, 0 );
  6455. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6456. this.width = 1.0;
  6457. this.height = 1.0;
  6458. this.constantAttenuation = 1.5;
  6459. this.linearAttenuation = 0.5;
  6460. this.quadraticAttenuation = 0.1;
  6461. };
  6462. THREE.AreaLight.prototype = Object.create( THREE.Light.prototype );
  6463. THREE.AreaLight.prototype.constructor = THREE.AreaLight;
  6464. // File:src/lights/DirectionalLight.js
  6465. /**
  6466. * @author mrdoob / http://mrdoob.com/
  6467. * @author alteredq / http://alteredqualia.com/
  6468. */
  6469. THREE.DirectionalLight = function ( color, intensity ) {
  6470. THREE.Light.call( this, color );
  6471. this.type = 'DirectionalLight';
  6472. this.position.set( 0, 1, 0 );
  6473. this.target = new THREE.Object3D();
  6474. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6475. this.castShadow = false;
  6476. this.onlyShadow = false;
  6477. //
  6478. this.shadowCameraNear = 50;
  6479. this.shadowCameraFar = 5000;
  6480. this.shadowCameraLeft = - 500;
  6481. this.shadowCameraRight = 500;
  6482. this.shadowCameraTop = 500;
  6483. this.shadowCameraBottom = - 500;
  6484. this.shadowCameraVisible = false;
  6485. this.shadowBias = 0;
  6486. this.shadowDarkness = 0.5;
  6487. this.shadowMapWidth = 512;
  6488. this.shadowMapHeight = 512;
  6489. //
  6490. this.shadowCascade = false;
  6491. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, - 1000 );
  6492. this.shadowCascadeCount = 2;
  6493. this.shadowCascadeBias = [ 0, 0, 0 ];
  6494. this.shadowCascadeWidth = [ 512, 512, 512 ];
  6495. this.shadowCascadeHeight = [ 512, 512, 512 ];
  6496. this.shadowCascadeNearZ = [ - 1.000, 0.990, 0.998 ];
  6497. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  6498. this.shadowCascadeArray = [];
  6499. //
  6500. this.shadowMap = null;
  6501. this.shadowMapSize = null;
  6502. this.shadowCamera = null;
  6503. this.shadowMatrix = null;
  6504. };
  6505. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  6506. THREE.DirectionalLight.prototype.constructor = THREE.DirectionalLight;
  6507. THREE.DirectionalLight.prototype.clone = function () {
  6508. var light = new THREE.DirectionalLight();
  6509. THREE.Light.prototype.clone.call( this, light );
  6510. light.target = this.target.clone();
  6511. light.intensity = this.intensity;
  6512. light.castShadow = this.castShadow;
  6513. light.onlyShadow = this.onlyShadow;
  6514. //
  6515. light.shadowCameraNear = this.shadowCameraNear;
  6516. light.shadowCameraFar = this.shadowCameraFar;
  6517. light.shadowCameraLeft = this.shadowCameraLeft;
  6518. light.shadowCameraRight = this.shadowCameraRight;
  6519. light.shadowCameraTop = this.shadowCameraTop;
  6520. light.shadowCameraBottom = this.shadowCameraBottom;
  6521. light.shadowCameraVisible = this.shadowCameraVisible;
  6522. light.shadowBias = this.shadowBias;
  6523. light.shadowDarkness = this.shadowDarkness;
  6524. light.shadowMapWidth = this.shadowMapWidth;
  6525. light.shadowMapHeight = this.shadowMapHeight;
  6526. //
  6527. light.shadowCascade = this.shadowCascade;
  6528. light.shadowCascadeOffset.copy( this.shadowCascadeOffset );
  6529. light.shadowCascadeCount = this.shadowCascadeCount;
  6530. light.shadowCascadeBias = this.shadowCascadeBias.slice( 0 );
  6531. light.shadowCascadeWidth = this.shadowCascadeWidth.slice( 0 );
  6532. light.shadowCascadeHeight = this.shadowCascadeHeight.slice( 0 );
  6533. light.shadowCascadeNearZ = this.shadowCascadeNearZ.slice( 0 );
  6534. light.shadowCascadeFarZ = this.shadowCascadeFarZ.slice( 0 );
  6535. return light;
  6536. };
  6537. // File:src/lights/HemisphereLight.js
  6538. /**
  6539. * @author alteredq / http://alteredqualia.com/
  6540. */
  6541. THREE.HemisphereLight = function ( skyColor, groundColor, intensity ) {
  6542. THREE.Light.call( this, skyColor );
  6543. this.type = 'HemisphereLight';
  6544. this.position.set( 0, 100, 0 );
  6545. this.groundColor = new THREE.Color( groundColor );
  6546. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6547. };
  6548. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  6549. THREE.HemisphereLight.prototype.constructor = THREE.HemisphereLight;
  6550. THREE.HemisphereLight.prototype.clone = function () {
  6551. var light = new THREE.HemisphereLight();
  6552. THREE.Light.prototype.clone.call( this, light );
  6553. light.groundColor.copy( this.groundColor );
  6554. light.intensity = this.intensity;
  6555. return light;
  6556. };
  6557. // File:src/lights/PointLight.js
  6558. /**
  6559. * @author mrdoob / http://mrdoob.com/
  6560. */
  6561. THREE.PointLight = function ( color, intensity, distance, decay ) {
  6562. THREE.Light.call( this, color );
  6563. this.type = 'PointLight';
  6564. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6565. this.distance = ( distance !== undefined ) ? distance : 0;
  6566. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  6567. };
  6568. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  6569. THREE.PointLight.prototype.constructor = THREE.PointLight;
  6570. THREE.PointLight.prototype.clone = function () {
  6571. var light = new THREE.PointLight();
  6572. THREE.Light.prototype.clone.call( this, light );
  6573. light.intensity = this.intensity;
  6574. light.distance = this.distance;
  6575. light.decay = this.decay;
  6576. return light;
  6577. };
  6578. // File:src/lights/SpotLight.js
  6579. /**
  6580. * @author alteredq / http://alteredqualia.com/
  6581. */
  6582. THREE.SpotLight = function ( color, intensity, distance, angle, exponent, decay ) {
  6583. THREE.Light.call( this, color );
  6584. this.type = 'SpotLight';
  6585. this.position.set( 0, 1, 0 );
  6586. this.target = new THREE.Object3D();
  6587. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6588. this.distance = ( distance !== undefined ) ? distance : 0;
  6589. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  6590. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  6591. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  6592. this.castShadow = false;
  6593. this.onlyShadow = false;
  6594. //
  6595. this.shadowCameraNear = 50;
  6596. this.shadowCameraFar = 5000;
  6597. this.shadowCameraFov = 50;
  6598. this.shadowCameraVisible = false;
  6599. this.shadowBias = 0;
  6600. this.shadowDarkness = 0.5;
  6601. this.shadowMapWidth = 512;
  6602. this.shadowMapHeight = 512;
  6603. //
  6604. this.shadowMap = null;
  6605. this.shadowMapSize = null;
  6606. this.shadowCamera = null;
  6607. this.shadowMatrix = null;
  6608. };
  6609. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  6610. THREE.SpotLight.prototype.constructor = THREE.SpotLight;
  6611. THREE.SpotLight.prototype.clone = function () {
  6612. var light = new THREE.SpotLight();
  6613. THREE.Light.prototype.clone.call( this, light );
  6614. light.target = this.target.clone();
  6615. light.intensity = this.intensity;
  6616. light.distance = this.distance;
  6617. light.angle = this.angle;
  6618. light.exponent = this.exponent;
  6619. light.decay = this.decay;
  6620. light.castShadow = this.castShadow;
  6621. light.onlyShadow = this.onlyShadow;
  6622. //
  6623. light.shadowCameraNear = this.shadowCameraNear;
  6624. light.shadowCameraFar = this.shadowCameraFar;
  6625. light.shadowCameraFov = this.shadowCameraFov;
  6626. light.shadowCameraVisible = this.shadowCameraVisible;
  6627. light.shadowBias = this.shadowBias;
  6628. light.shadowDarkness = this.shadowDarkness;
  6629. light.shadowMapWidth = this.shadowMapWidth;
  6630. light.shadowMapHeight = this.shadowMapHeight;
  6631. return light;
  6632. };
  6633. // File:src/loaders/Cache.js
  6634. /**
  6635. * @author mrdoob / http://mrdoob.com/
  6636. */
  6637. THREE.Cache = {
  6638. files: {},
  6639. add: function ( key, file ) {
  6640. // console.log( 'THREE.Cache', 'Adding key:', key );
  6641. this.files[ key ] = file;
  6642. },
  6643. get: function ( key ) {
  6644. // console.log( 'THREE.Cache', 'Checking key:', key );
  6645. return this.files[ key ];
  6646. },
  6647. remove: function ( key ) {
  6648. delete this.files[ key ];
  6649. },
  6650. clear: function () {
  6651. this.files = {}
  6652. }
  6653. };
  6654. // File:src/loaders/Loader.js
  6655. /**
  6656. * @author alteredq / http://alteredqualia.com/
  6657. */
  6658. THREE.Loader = function ( showStatus ) {
  6659. this.showStatus = showStatus;
  6660. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  6661. this.imageLoader = new THREE.ImageLoader();
  6662. this.onLoadStart = function () {};
  6663. this.onLoadProgress = function () {};
  6664. this.onLoadComplete = function () {};
  6665. };
  6666. THREE.Loader.prototype = {
  6667. constructor: THREE.Loader,
  6668. crossOrigin: undefined,
  6669. addStatusElement: function () {
  6670. var e = document.createElement( 'div' );
  6671. e.style.position = 'absolute';
  6672. e.style.right = '0px';
  6673. e.style.top = '0px';
  6674. e.style.fontSize = '0.8em';
  6675. e.style.textAlign = 'left';
  6676. e.style.background = 'rgba(0,0,0,0.25)';
  6677. e.style.color = '#fff';
  6678. e.style.width = '120px';
  6679. e.style.padding = '0.5em 0.5em 0.5em 0.5em';
  6680. e.style.zIndex = 1000;
  6681. e.innerHTML = 'Loading ...';
  6682. return e;
  6683. },
  6684. updateProgress: function ( progress ) {
  6685. var message = 'Loaded ';
  6686. if ( progress.total ) {
  6687. message += ( 100 * progress.loaded / progress.total ).toFixed( 0 ) + '%';
  6688. } else {
  6689. message += ( progress.loaded / 1024 ).toFixed( 2 ) + ' KB';
  6690. }
  6691. this.statusDomElement.innerHTML = message;
  6692. },
  6693. extractUrlBase: function ( url ) {
  6694. var parts = url.split( '/' );
  6695. if ( parts.length === 1 ) return './';
  6696. parts.pop();
  6697. return parts.join( '/' ) + '/';
  6698. },
  6699. initMaterials: function ( materials, texturePath ) {
  6700. var array = [];
  6701. for ( var i = 0; i < materials.length; ++ i ) {
  6702. array[ i ] = this.createMaterial( materials[ i ], texturePath );
  6703. }
  6704. return array;
  6705. },
  6706. needsTangents: function ( materials ) {
  6707. for ( var i = 0, il = materials.length; i < il; i ++ ) {
  6708. var m = materials[ i ];
  6709. if ( m instanceof THREE.ShaderMaterial ) return true;
  6710. }
  6711. return false;
  6712. },
  6713. createMaterial: function ( m, texturePath ) {
  6714. var scope = this;
  6715. function nearest_pow2( n ) {
  6716. var l = Math.log( n ) / Math.LN2;
  6717. return Math.pow( 2, Math.round( l ) );
  6718. }
  6719. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  6720. var fullPath = texturePath + sourceFile;
  6721. var texture;
  6722. var loader = THREE.Loader.Handlers.get( fullPath );
  6723. if ( loader !== null ) {
  6724. texture = loader.load( fullPath );
  6725. } else {
  6726. texture = new THREE.Texture();
  6727. loader = scope.imageLoader;
  6728. loader.crossOrigin = scope.crossOrigin;
  6729. loader.load( fullPath, function ( image ) {
  6730. if ( THREE.Math.isPowerOfTwo( image.width ) === false ||
  6731. THREE.Math.isPowerOfTwo( image.height ) === false ) {
  6732. var width = nearest_pow2( image.width );
  6733. var height = nearest_pow2( image.height );
  6734. var canvas = document.createElement( 'canvas' );
  6735. canvas.width = width;
  6736. canvas.height = height;
  6737. var context = canvas.getContext( '2d' );
  6738. context.drawImage( image, 0, 0, width, height );
  6739. texture.image = canvas;
  6740. } else {
  6741. texture.image = image;
  6742. }
  6743. texture.needsUpdate = true;
  6744. } );
  6745. }
  6746. texture.sourceFile = sourceFile;
  6747. if ( repeat ) {
  6748. texture.repeat.set( repeat[ 0 ], repeat[ 1 ] );
  6749. if ( repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  6750. if ( repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  6751. }
  6752. if ( offset ) {
  6753. texture.offset.set( offset[ 0 ], offset[ 1 ] );
  6754. }
  6755. if ( wrap ) {
  6756. var wrapMap = {
  6757. 'repeat': THREE.RepeatWrapping,
  6758. 'mirror': THREE.MirroredRepeatWrapping
  6759. }
  6760. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ wrap[ 0 ] ];
  6761. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ wrap[ 1 ] ];
  6762. }
  6763. if ( anisotropy ) {
  6764. texture.anisotropy = anisotropy;
  6765. }
  6766. where[ name ] = texture;
  6767. }
  6768. function rgb2hex( rgb ) {
  6769. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  6770. }
  6771. // defaults
  6772. var mtype = 'MeshLambertMaterial';
  6773. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  6774. // parameters from model file
  6775. if ( m.shading ) {
  6776. var shading = m.shading.toLowerCase();
  6777. if ( shading === 'phong' ) mtype = 'MeshPhongMaterial';
  6778. else if ( shading === 'basic' ) mtype = 'MeshBasicMaterial';
  6779. }
  6780. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  6781. mpars.blending = THREE[ m.blending ];
  6782. }
  6783. if ( m.transparent !== undefined ) {
  6784. mpars.transparent = m.transparent;
  6785. }
  6786. if ( m.opacity !== undefined && m.opacity < 1.0 ) {
  6787. mpars.transparent = true;
  6788. }
  6789. if ( m.depthTest !== undefined ) {
  6790. mpars.depthTest = m.depthTest;
  6791. }
  6792. if ( m.depthWrite !== undefined ) {
  6793. mpars.depthWrite = m.depthWrite;
  6794. }
  6795. if ( m.visible !== undefined ) {
  6796. mpars.visible = m.visible;
  6797. }
  6798. if ( m.flipSided !== undefined ) {
  6799. mpars.side = THREE.BackSide;
  6800. }
  6801. if ( m.doubleSided !== undefined ) {
  6802. mpars.side = THREE.DoubleSide;
  6803. }
  6804. if ( m.wireframe !== undefined ) {
  6805. mpars.wireframe = m.wireframe;
  6806. }
  6807. if ( m.vertexColors !== undefined ) {
  6808. if ( m.vertexColors === 'face' ) {
  6809. mpars.vertexColors = THREE.FaceColors;
  6810. } else if ( m.vertexColors ) {
  6811. mpars.vertexColors = THREE.VertexColors;
  6812. }
  6813. }
  6814. // colors
  6815. if ( m.colorDiffuse ) {
  6816. mpars.color = rgb2hex( m.colorDiffuse );
  6817. } else if ( m.DbgColor ) {
  6818. mpars.color = m.DbgColor;
  6819. }
  6820. if ( m.colorSpecular ) {
  6821. mpars.specular = rgb2hex( m.colorSpecular );
  6822. }
  6823. if ( m.colorEmissive ) {
  6824. mpars.emissive = rgb2hex( m.colorEmissive );
  6825. }
  6826. // modifiers
  6827. if ( m.transparency !== undefined ) {
  6828. console.warn( 'THREE.Loader: transparency has been renamed to opacity' );
  6829. m.opacity = m.transparency;
  6830. }
  6831. if ( m.opacity !== undefined ) {
  6832. mpars.opacity = m.opacity;
  6833. }
  6834. if ( m.specularCoef ) {
  6835. mpars.shininess = m.specularCoef;
  6836. }
  6837. // textures
  6838. if ( m.mapDiffuse && texturePath ) {
  6839. create_texture( mpars, 'map', m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  6840. }
  6841. if ( m.mapLight && texturePath ) {
  6842. create_texture( mpars, 'lightMap', m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  6843. }
  6844. if ( m.mapBump && texturePath ) {
  6845. create_texture( mpars, 'bumpMap', m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  6846. }
  6847. if ( m.mapNormal && texturePath ) {
  6848. create_texture( mpars, 'normalMap', m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  6849. }
  6850. if ( m.mapSpecular && texturePath ) {
  6851. create_texture( mpars, 'specularMap', m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  6852. }
  6853. if ( m.mapAlpha && texturePath ) {
  6854. create_texture( mpars, 'alphaMap', m.mapAlpha, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy );
  6855. }
  6856. //
  6857. if ( m.mapBumpScale ) {
  6858. mpars.bumpScale = m.mapBumpScale;
  6859. }
  6860. if ( m.mapNormalFactor ) {
  6861. mpars.normalScale = new THREE.Vector2( m.mapNormalFactor, m.mapNormalFactor );
  6862. }
  6863. var material = new THREE[ mtype ]( mpars );
  6864. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  6865. return material;
  6866. }
  6867. };
  6868. THREE.Loader.Handlers = {
  6869. handlers: [],
  6870. add: function ( regex, loader ) {
  6871. this.handlers.push( regex, loader );
  6872. },
  6873. get: function ( file ) {
  6874. for ( var i = 0, l = this.handlers.length; i < l; i += 2 ) {
  6875. var regex = this.handlers[ i ];
  6876. var loader = this.handlers[ i + 1 ];
  6877. if ( regex.test( file ) ) {
  6878. return loader;
  6879. }
  6880. }
  6881. return null;
  6882. }
  6883. };
  6884. // File:src/loaders/XHRLoader.js
  6885. /**
  6886. * @author mrdoob / http://mrdoob.com/
  6887. */
  6888. THREE.XHRLoader = function ( manager ) {
  6889. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6890. };
  6891. THREE.XHRLoader.prototype = {
  6892. constructor: THREE.XHRLoader,
  6893. load: function ( url, onLoad, onProgress, onError ) {
  6894. var scope = this;
  6895. var cached = THREE.Cache.get( url );
  6896. if ( cached !== undefined ) {
  6897. if ( onLoad ) onLoad( cached );
  6898. return;
  6899. }
  6900. var request = new XMLHttpRequest();
  6901. request.open( 'GET', url, true );
  6902. request.addEventListener( 'load', function ( event ) {
  6903. THREE.Cache.add( url, this.response );
  6904. if ( onLoad ) onLoad( this.response );
  6905. scope.manager.itemEnd( url );
  6906. }, false );
  6907. if ( onProgress !== undefined ) {
  6908. request.addEventListener( 'progress', function ( event ) {
  6909. onProgress( event );
  6910. }, false );
  6911. }
  6912. if ( onError !== undefined ) {
  6913. request.addEventListener( 'error', function ( event ) {
  6914. onError( event );
  6915. }, false );
  6916. }
  6917. if ( this.crossOrigin !== undefined ) request.crossOrigin = this.crossOrigin;
  6918. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  6919. request.send( null );
  6920. scope.manager.itemStart( url );
  6921. },
  6922. setResponseType: function ( value ) {
  6923. this.responseType = value;
  6924. },
  6925. setCrossOrigin: function ( value ) {
  6926. this.crossOrigin = value;
  6927. }
  6928. };
  6929. // File:src/loaders/ImageLoader.js
  6930. /**
  6931. * @author mrdoob / http://mrdoob.com/
  6932. */
  6933. THREE.ImageLoader = function ( manager ) {
  6934. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6935. };
  6936. THREE.ImageLoader.prototype = {
  6937. constructor: THREE.ImageLoader,
  6938. load: function ( url, onLoad, onProgress, onError ) {
  6939. var scope = this;
  6940. var cached = THREE.Cache.get( url );
  6941. if ( cached !== undefined ) {
  6942. onLoad( cached );
  6943. return;
  6944. }
  6945. var image = document.createElement( 'img' );
  6946. image.addEventListener( 'load', function ( event ) {
  6947. THREE.Cache.add( url, this );
  6948. if ( onLoad ) onLoad( this );
  6949. scope.manager.itemEnd( url );
  6950. }, false );
  6951. if ( onProgress !== undefined ) {
  6952. image.addEventListener( 'progress', function ( event ) {
  6953. onProgress( event );
  6954. }, false );
  6955. }
  6956. if ( onError !== undefined ) {
  6957. image.addEventListener( 'error', function ( event ) {
  6958. onError( event );
  6959. }, false );
  6960. }
  6961. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  6962. image.src = url;
  6963. scope.manager.itemStart( url );
  6964. return image;
  6965. },
  6966. setCrossOrigin: function ( value ) {
  6967. this.crossOrigin = value;
  6968. }
  6969. }
  6970. // File:src/loaders/JSONLoader.js
  6971. /**
  6972. * @author mrdoob / http://mrdoob.com/
  6973. * @author alteredq / http://alteredqualia.com/
  6974. */
  6975. THREE.JSONLoader = function ( showStatus ) {
  6976. THREE.Loader.call( this, showStatus );
  6977. this.withCredentials = false;
  6978. };
  6979. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  6980. THREE.JSONLoader.prototype.constructor = THREE.JSONLoader;
  6981. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  6982. // todo: unify load API to for easier SceneLoader use
  6983. texturePath = texturePath && ( typeof texturePath === 'string' ) ? texturePath : this.extractUrlBase( url );
  6984. this.onLoadStart();
  6985. this.loadAjaxJSON( this, url, callback, texturePath );
  6986. };
  6987. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  6988. var xhr = new XMLHttpRequest();
  6989. var length = 0;
  6990. xhr.onreadystatechange = function () {
  6991. if ( xhr.readyState === xhr.DONE ) {
  6992. if ( xhr.status === 200 || xhr.status === 0 ) {
  6993. if ( xhr.responseText ) {
  6994. var json = JSON.parse( xhr.responseText );
  6995. if ( json.metadata !== undefined && json.metadata.version >= 4 ) {
  6996. console.error( 'THREE.JSONLoader: "' + url + '" should be loaded with THREE.ObjectLoader instead.' );
  6997. return;
  6998. }
  6999. if ( json.metadata !== undefined && json.metadata.type === 'scene' ) {
  7000. THREE.error( 'THREE.JSONLoader: "' + url + '" seems to be a Scene. Use THREE.SceneLoader instead.' );
  7001. return;
  7002. }
  7003. var result = context.parse( json, texturePath );
  7004. callback( result.geometry, result.materials );
  7005. } else {
  7006. THREE.error( 'THREE.JSONLoader: "' + url + '" seems to be unreachable or the file is empty.' );
  7007. }
  7008. // in context of more complex asset initialization
  7009. // do not block on single failed file
  7010. // maybe should go even one more level up
  7011. context.onLoadComplete();
  7012. } else {
  7013. THREE.error( 'THREE.JSONLoader: Couldn\'t load "' + url + '" (' + xhr.status + ')' );
  7014. }
  7015. } else if ( xhr.readyState === xhr.LOADING ) {
  7016. if ( callbackProgress ) {
  7017. if ( length === 0 ) {
  7018. length = xhr.getResponseHeader( 'Content-Length' );
  7019. }
  7020. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  7021. }
  7022. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  7023. if ( callbackProgress !== undefined ) {
  7024. length = xhr.getResponseHeader( 'Content-Length' );
  7025. }
  7026. }
  7027. };
  7028. xhr.open( 'GET', url, true );
  7029. xhr.withCredentials = this.withCredentials;
  7030. xhr.send( null );
  7031. };
  7032. THREE.JSONLoader.prototype.parse = function ( json, texturePath ) {
  7033. var geometry = new THREE.Geometry(),
  7034. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  7035. parseModel( scale );
  7036. parseSkin();
  7037. parseMorphing( scale );
  7038. geometry.computeFaceNormals();
  7039. geometry.computeBoundingSphere();
  7040. function parseModel( scale ) {
  7041. function isBitSet( value, position ) {
  7042. return value & ( 1 << position );
  7043. }
  7044. var i, j, fi,
  7045. offset, zLength,
  7046. colorIndex, normalIndex, uvIndex, materialIndex,
  7047. type,
  7048. isQuad,
  7049. hasMaterial,
  7050. hasFaceVertexUv,
  7051. hasFaceNormal, hasFaceVertexNormal,
  7052. hasFaceColor, hasFaceVertexColor,
  7053. vertex, face, faceA, faceB, hex, normal,
  7054. uvLayer, uv, u, v,
  7055. faces = json.faces,
  7056. vertices = json.vertices,
  7057. normals = json.normals,
  7058. colors = json.colors,
  7059. nUvLayers = 0;
  7060. if ( json.uvs !== undefined ) {
  7061. // disregard empty arrays
  7062. for ( i = 0; i < json.uvs.length; i ++ ) {
  7063. if ( json.uvs[ i ].length ) nUvLayers ++;
  7064. }
  7065. for ( i = 0; i < nUvLayers; i ++ ) {
  7066. geometry.faceVertexUvs[ i ] = [];
  7067. }
  7068. }
  7069. offset = 0;
  7070. zLength = vertices.length;
  7071. while ( offset < zLength ) {
  7072. vertex = new THREE.Vector3();
  7073. vertex.x = vertices[ offset ++ ] * scale;
  7074. vertex.y = vertices[ offset ++ ] * scale;
  7075. vertex.z = vertices[ offset ++ ] * scale;
  7076. geometry.vertices.push( vertex );
  7077. }
  7078. offset = 0;
  7079. zLength = faces.length;
  7080. while ( offset < zLength ) {
  7081. type = faces[ offset ++ ];
  7082. isQuad = isBitSet( type, 0 );
  7083. hasMaterial = isBitSet( type, 1 );
  7084. hasFaceVertexUv = isBitSet( type, 3 );
  7085. hasFaceNormal = isBitSet( type, 4 );
  7086. hasFaceVertexNormal = isBitSet( type, 5 );
  7087. hasFaceColor = isBitSet( type, 6 );
  7088. hasFaceVertexColor = isBitSet( type, 7 );
  7089. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  7090. if ( isQuad ) {
  7091. faceA = new THREE.Face3();
  7092. faceA.a = faces[ offset ];
  7093. faceA.b = faces[ offset + 1 ];
  7094. faceA.c = faces[ offset + 3 ];
  7095. faceB = new THREE.Face3();
  7096. faceB.a = faces[ offset + 1 ];
  7097. faceB.b = faces[ offset + 2 ];
  7098. faceB.c = faces[ offset + 3 ];
  7099. offset += 4;
  7100. if ( hasMaterial ) {
  7101. materialIndex = faces[ offset ++ ];
  7102. faceA.materialIndex = materialIndex;
  7103. faceB.materialIndex = materialIndex;
  7104. }
  7105. // to get face <=> uv index correspondence
  7106. fi = geometry.faces.length;
  7107. if ( hasFaceVertexUv ) {
  7108. for ( i = 0; i < nUvLayers; i ++ ) {
  7109. uvLayer = json.uvs[ i ];
  7110. geometry.faceVertexUvs[ i ][ fi ] = [];
  7111. geometry.faceVertexUvs[ i ][ fi + 1 ] = []
  7112. for ( j = 0; j < 4; j ++ ) {
  7113. uvIndex = faces[ offset ++ ];
  7114. u = uvLayer[ uvIndex * 2 ];
  7115. v = uvLayer[ uvIndex * 2 + 1 ];
  7116. uv = new THREE.Vector2( u, v );
  7117. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  7118. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  7119. }
  7120. }
  7121. }
  7122. if ( hasFaceNormal ) {
  7123. normalIndex = faces[ offset ++ ] * 3;
  7124. faceA.normal.set(
  7125. normals[ normalIndex ++ ],
  7126. normals[ normalIndex ++ ],
  7127. normals[ normalIndex ]
  7128. );
  7129. faceB.normal.copy( faceA.normal );
  7130. }
  7131. if ( hasFaceVertexNormal ) {
  7132. for ( i = 0; i < 4; i ++ ) {
  7133. normalIndex = faces[ offset ++ ] * 3;
  7134. normal = new THREE.Vector3(
  7135. normals[ normalIndex ++ ],
  7136. normals[ normalIndex ++ ],
  7137. normals[ normalIndex ]
  7138. );
  7139. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  7140. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  7141. }
  7142. }
  7143. if ( hasFaceColor ) {
  7144. colorIndex = faces[ offset ++ ];
  7145. hex = colors[ colorIndex ];
  7146. faceA.color.setHex( hex );
  7147. faceB.color.setHex( hex );
  7148. }
  7149. if ( hasFaceVertexColor ) {
  7150. for ( i = 0; i < 4; i ++ ) {
  7151. colorIndex = faces[ offset ++ ];
  7152. hex = colors[ colorIndex ];
  7153. if ( i !== 2 ) faceA.vertexColors.push( new THREE.Color( hex ) );
  7154. if ( i !== 0 ) faceB.vertexColors.push( new THREE.Color( hex ) );
  7155. }
  7156. }
  7157. geometry.faces.push( faceA );
  7158. geometry.faces.push( faceB );
  7159. } else {
  7160. face = new THREE.Face3();
  7161. face.a = faces[ offset ++ ];
  7162. face.b = faces[ offset ++ ];
  7163. face.c = faces[ offset ++ ];
  7164. if ( hasMaterial ) {
  7165. materialIndex = faces[ offset ++ ];
  7166. face.materialIndex = materialIndex;
  7167. }
  7168. // to get face <=> uv index correspondence
  7169. fi = geometry.faces.length;
  7170. if ( hasFaceVertexUv ) {
  7171. for ( i = 0; i < nUvLayers; i ++ ) {
  7172. uvLayer = json.uvs[ i ];
  7173. geometry.faceVertexUvs[ i ][ fi ] = [];
  7174. for ( j = 0; j < 3; j ++ ) {
  7175. uvIndex = faces[ offset ++ ];
  7176. u = uvLayer[ uvIndex * 2 ];
  7177. v = uvLayer[ uvIndex * 2 + 1 ];
  7178. uv = new THREE.Vector2( u, v );
  7179. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  7180. }
  7181. }
  7182. }
  7183. if ( hasFaceNormal ) {
  7184. normalIndex = faces[ offset ++ ] * 3;
  7185. face.normal.set(
  7186. normals[ normalIndex ++ ],
  7187. normals[ normalIndex ++ ],
  7188. normals[ normalIndex ]
  7189. );
  7190. }
  7191. if ( hasFaceVertexNormal ) {
  7192. for ( i = 0; i < 3; i ++ ) {
  7193. normalIndex = faces[ offset ++ ] * 3;
  7194. normal = new THREE.Vector3(
  7195. normals[ normalIndex ++ ],
  7196. normals[ normalIndex ++ ],
  7197. normals[ normalIndex ]
  7198. );
  7199. face.vertexNormals.push( normal );
  7200. }
  7201. }
  7202. if ( hasFaceColor ) {
  7203. colorIndex = faces[ offset ++ ];
  7204. face.color.setHex( colors[ colorIndex ] );
  7205. }
  7206. if ( hasFaceVertexColor ) {
  7207. for ( i = 0; i < 3; i ++ ) {
  7208. colorIndex = faces[ offset ++ ];
  7209. face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) );
  7210. }
  7211. }
  7212. geometry.faces.push( face );
  7213. }
  7214. }
  7215. };
  7216. function parseSkin() {
  7217. var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2;
  7218. if ( json.skinWeights ) {
  7219. for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {
  7220. var x = json.skinWeights[ i ];
  7221. var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
  7222. var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
  7223. var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;
  7224. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  7225. }
  7226. }
  7227. if ( json.skinIndices ) {
  7228. for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {
  7229. var a = json.skinIndices[ i ];
  7230. var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
  7231. var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
  7232. var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;
  7233. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  7234. }
  7235. }
  7236. geometry.bones = json.bones;
  7237. if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {
  7238. THREE.warn( 'THREE.JSONLoader: When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
  7239. geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );
  7240. }
  7241. // could change this to json.animations[0] or remove completely
  7242. geometry.animation = json.animation;
  7243. geometry.animations = json.animations;
  7244. };
  7245. function parseMorphing( scale ) {
  7246. if ( json.morphTargets !== undefined ) {
  7247. var i, l, v, vl, dstVertices, srcVertices;
  7248. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  7249. geometry.morphTargets[ i ] = {};
  7250. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  7251. geometry.morphTargets[ i ].vertices = [];
  7252. dstVertices = geometry.morphTargets[ i ].vertices;
  7253. srcVertices = json.morphTargets [ i ].vertices;
  7254. for ( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  7255. var vertex = new THREE.Vector3();
  7256. vertex.x = srcVertices[ v ] * scale;
  7257. vertex.y = srcVertices[ v + 1 ] * scale;
  7258. vertex.z = srcVertices[ v + 2 ] * scale;
  7259. dstVertices.push( vertex );
  7260. }
  7261. }
  7262. }
  7263. if ( json.morphColors !== undefined ) {
  7264. var i, l, c, cl, dstColors, srcColors, color;
  7265. for ( i = 0, l = json.morphColors.length; i < l; i ++ ) {
  7266. geometry.morphColors[ i ] = {};
  7267. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  7268. geometry.morphColors[ i ].colors = [];
  7269. dstColors = geometry.morphColors[ i ].colors;
  7270. srcColors = json.morphColors [ i ].colors;
  7271. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  7272. color = new THREE.Color( 0xffaa00 );
  7273. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  7274. dstColors.push( color );
  7275. }
  7276. }
  7277. }
  7278. };
  7279. if ( json.materials === undefined || json.materials.length === 0 ) {
  7280. return { geometry: geometry };
  7281. } else {
  7282. var materials = this.initMaterials( json.materials, texturePath );
  7283. if ( this.needsTangents( materials ) ) {
  7284. geometry.computeTangents();
  7285. }
  7286. return { geometry: geometry, materials: materials };
  7287. }
  7288. };
  7289. // File:src/loaders/LoadingManager.js
  7290. /**
  7291. * @author mrdoob / http://mrdoob.com/
  7292. */
  7293. THREE.LoadingManager = function ( onLoad, onProgress, onError ) {
  7294. var scope = this;
  7295. var loaded = 0, total = 0;
  7296. this.onLoad = onLoad;
  7297. this.onProgress = onProgress;
  7298. this.onError = onError;
  7299. this.itemStart = function ( url ) {
  7300. total ++;
  7301. };
  7302. this.itemEnd = function ( url ) {
  7303. loaded ++;
  7304. if ( scope.onProgress !== undefined ) {
  7305. scope.onProgress( url, loaded, total );
  7306. }
  7307. if ( loaded === total && scope.onLoad !== undefined ) {
  7308. scope.onLoad();
  7309. }
  7310. };
  7311. };
  7312. THREE.DefaultLoadingManager = new THREE.LoadingManager();
  7313. // File:src/loaders/BufferGeometryLoader.js
  7314. /**
  7315. * @author mrdoob / http://mrdoob.com/
  7316. */
  7317. THREE.BufferGeometryLoader = function ( manager ) {
  7318. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7319. };
  7320. THREE.BufferGeometryLoader.prototype = {
  7321. constructor: THREE.BufferGeometryLoader,
  7322. load: function ( url, onLoad, onProgress, onError ) {
  7323. var scope = this;
  7324. var loader = new THREE.XHRLoader( scope.manager );
  7325. loader.setCrossOrigin( this.crossOrigin );
  7326. loader.load( url, function ( text ) {
  7327. onLoad( scope.parse( JSON.parse( text ) ) );
  7328. }, onProgress, onError );
  7329. },
  7330. setCrossOrigin: function ( value ) {
  7331. this.crossOrigin = value;
  7332. },
  7333. parse: function ( json ) {
  7334. var geometry = new THREE.BufferGeometry();
  7335. var attributes = json.data.attributes;
  7336. for ( var key in attributes ) {
  7337. var attribute = attributes[ key ];
  7338. var typedArray = new self[ attribute.type ]( attribute.array );
  7339. geometry.addAttribute( key, new THREE.BufferAttribute( typedArray, attribute.itemSize ) );
  7340. }
  7341. var offsets = json.data.offsets;
  7342. if ( offsets !== undefined ) {
  7343. geometry.offsets = JSON.parse( JSON.stringify( offsets ) );
  7344. }
  7345. var boundingSphere = json.data.boundingSphere;
  7346. if ( boundingSphere !== undefined ) {
  7347. var center = new THREE.Vector3();
  7348. if ( boundingSphere.center !== undefined ) {
  7349. center.fromArray( boundingSphere.center );
  7350. }
  7351. geometry.boundingSphere = new THREE.Sphere( center, boundingSphere.radius );
  7352. }
  7353. return geometry;
  7354. }
  7355. };
  7356. // File:src/loaders/MaterialLoader.js
  7357. /**
  7358. * @author mrdoob / http://mrdoob.com/
  7359. */
  7360. THREE.MaterialLoader = function ( manager ) {
  7361. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7362. };
  7363. THREE.MaterialLoader.prototype = {
  7364. constructor: THREE.MaterialLoader,
  7365. load: function ( url, onLoad, onProgress, onError ) {
  7366. var scope = this;
  7367. var loader = new THREE.XHRLoader( scope.manager );
  7368. loader.setCrossOrigin( this.crossOrigin );
  7369. loader.load( url, function ( text ) {
  7370. onLoad( scope.parse( JSON.parse( text ) ) );
  7371. }, onProgress, onError );
  7372. },
  7373. setCrossOrigin: function ( value ) {
  7374. this.crossOrigin = value;
  7375. },
  7376. parse: function ( json ) {
  7377. var material = new THREE[ json.type ];
  7378. if ( json.color !== undefined ) material.color.setHex( json.color );
  7379. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  7380. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  7381. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  7382. if ( json.uniforms !== undefined ) material.uniforms = json.uniforms;
  7383. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  7384. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  7385. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  7386. if ( json.shading !== undefined ) material.shading = json.shading;
  7387. if ( json.blending !== undefined ) material.blending = json.blending;
  7388. if ( json.side !== undefined ) material.side = json.side;
  7389. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  7390. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  7391. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  7392. // for PointCloudMaterial
  7393. if ( json.size !== undefined ) material.size = json.size;
  7394. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  7395. if ( json.materials !== undefined ) {
  7396. for ( var i = 0, l = json.materials.length; i < l; i ++ ) {
  7397. material.materials.push( this.parse( json.materials[ i ] ) );
  7398. }
  7399. }
  7400. return material;
  7401. }
  7402. };
  7403. // File:src/loaders/ObjectLoader.js
  7404. /**
  7405. * @author mrdoob / http://mrdoob.com/
  7406. */
  7407. THREE.ObjectLoader = function ( manager ) {
  7408. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7409. this.texturePath = '';
  7410. };
  7411. THREE.ObjectLoader.prototype = {
  7412. constructor: THREE.ObjectLoader,
  7413. load: function ( url, onLoad, onProgress, onError ) {
  7414. if ( this.texturePath === '' ) {
  7415. this.texturePath = url.substring( 0, url.lastIndexOf( '/' ) + 1 );
  7416. }
  7417. var scope = this;
  7418. var loader = new THREE.XHRLoader( scope.manager );
  7419. loader.setCrossOrigin( this.crossOrigin );
  7420. loader.load( url, function ( text ) {
  7421. scope.parse( JSON.parse( text ), onLoad );
  7422. }, onProgress, onError );
  7423. },
  7424. setTexturePath: function ( value ) {
  7425. this.texturePath = value;
  7426. },
  7427. setCrossOrigin: function ( value ) {
  7428. this.crossOrigin = value;
  7429. },
  7430. parse: function ( json, onLoad ) {
  7431. var geometries = this.parseGeometries( json.geometries );
  7432. var images = this.parseImages( json.images, function () {
  7433. if ( onLoad !== undefined ) onLoad( object );
  7434. } );
  7435. var textures = this.parseTextures( json.textures, images );
  7436. var materials = this.parseMaterials( json.materials, textures );
  7437. var object = this.parseObject( json.object, geometries, materials );
  7438. if ( json.images === undefined || json.images.length === 0 ) {
  7439. if ( onLoad !== undefined ) onLoad( object );
  7440. }
  7441. return object;
  7442. },
  7443. parseGeometries: function ( json ) {
  7444. var geometries = {};
  7445. if ( json !== undefined ) {
  7446. var geometryLoader = new THREE.JSONLoader();
  7447. var bufferGeometryLoader = new THREE.BufferGeometryLoader();
  7448. for ( var i = 0, l = json.length; i < l; i ++ ) {
  7449. var geometry;
  7450. var data = json[ i ];
  7451. switch ( data.type ) {
  7452. case 'PlaneGeometry':
  7453. case 'PlaneBufferGeometry':
  7454. geometry = new THREE[ data.type ](
  7455. data.width,
  7456. data.height,
  7457. data.widthSegments,
  7458. data.heightSegments
  7459. );
  7460. break;
  7461. case 'BoxGeometry':
  7462. case 'CubeGeometry': // backwards compatible
  7463. geometry = new THREE.BoxGeometry(
  7464. data.width,
  7465. data.height,
  7466. data.depth,
  7467. data.widthSegments,
  7468. data.heightSegments,
  7469. data.depthSegments
  7470. );
  7471. break;
  7472. case 'CircleGeometry':
  7473. geometry = new THREE.CircleGeometry(
  7474. data.radius,
  7475. data.segments
  7476. );
  7477. break;
  7478. case 'CylinderGeometry':
  7479. geometry = new THREE.CylinderGeometry(
  7480. data.radiusTop,
  7481. data.radiusBottom,
  7482. data.height,
  7483. data.radialSegments,
  7484. data.heightSegments,
  7485. data.openEnded
  7486. );
  7487. break;
  7488. case 'SphereGeometry':
  7489. geometry = new THREE.SphereGeometry(
  7490. data.radius,
  7491. data.widthSegments,
  7492. data.heightSegments,
  7493. data.phiStart,
  7494. data.phiLength,
  7495. data.thetaStart,
  7496. data.thetaLength
  7497. );
  7498. break;
  7499. case 'IcosahedronGeometry':
  7500. geometry = new THREE.IcosahedronGeometry(
  7501. data.radius,
  7502. data.detail
  7503. );
  7504. break;
  7505. case 'TorusGeometry':
  7506. geometry = new THREE.TorusGeometry(
  7507. data.radius,
  7508. data.tube,
  7509. data.radialSegments,
  7510. data.tubularSegments,
  7511. data.arc
  7512. );
  7513. break;
  7514. case 'TorusKnotGeometry':
  7515. geometry = new THREE.TorusKnotGeometry(
  7516. data.radius,
  7517. data.tube,
  7518. data.radialSegments,
  7519. data.tubularSegments,
  7520. data.p,
  7521. data.q,
  7522. data.heightScale
  7523. );
  7524. break;
  7525. case 'BufferGeometry':
  7526. geometry = bufferGeometryLoader.parse( data );
  7527. break;
  7528. case 'Geometry':
  7529. geometry = geometryLoader.parse( data.data ).geometry;
  7530. break;
  7531. }
  7532. geometry.uuid = data.uuid;
  7533. if ( data.name !== undefined ) geometry.name = data.name;
  7534. geometries[ data.uuid ] = geometry;
  7535. }
  7536. }
  7537. return geometries;
  7538. },
  7539. parseMaterials: function ( json, textures ) {
  7540. var materials = {};
  7541. if ( json !== undefined ) {
  7542. var getTexture = function ( name ) {
  7543. if ( textures[ name ] === undefined ) {
  7544. THREE.warn( 'THREE.ObjectLoader: Undefined texture', name );
  7545. }
  7546. return textures[ name ];
  7547. };
  7548. var loader = new THREE.MaterialLoader();
  7549. for ( var i = 0, l = json.length; i < l; i ++ ) {
  7550. var data = json[ i ];
  7551. var material = loader.parse( data );
  7552. material.uuid = data.uuid;
  7553. if ( data.name !== undefined ) material.name = data.name;
  7554. if ( data.map !== undefined ) {
  7555. material.map = getTexture( data.map );
  7556. }
  7557. if ( data.bumpMap !== undefined ) {
  7558. material.bumpMap = getTexture( data.bumpMap );
  7559. if ( data.bumpScale ) {
  7560. material.bumpScale = new THREE.Vector2( data.bumpScale, data.bumpScale );
  7561. }
  7562. }
  7563. if ( data.alphaMap !== undefined ) {
  7564. material.alphaMap = getTexture( data.alphaMap );
  7565. }
  7566. if ( data.envMap !== undefined ) {
  7567. material.envMap = getTexture( data.envMap );
  7568. }
  7569. if ( data.normalMap !== undefined ) {
  7570. material.normalMap = getTexture( data.normalMap );
  7571. if ( data.normalScale ) {
  7572. material.normalScale = new THREE.Vector2( data.normalScale, data.normalScale );
  7573. }
  7574. }
  7575. if ( data.lightMap !== undefined ) {
  7576. material.lightMap = getTexture( data.lightMap );
  7577. }
  7578. if ( data.specularMap !== undefined ) {
  7579. material.specularMap = getTexture( data.specularMap );
  7580. }
  7581. materials[ data.uuid ] = material;
  7582. }
  7583. }
  7584. return materials;
  7585. },
  7586. parseImages: function ( json, onLoad ) {
  7587. var scope = this;
  7588. var images = {};
  7589. if ( json !== undefined && json.length > 0 ) {
  7590. var manager = new THREE.LoadingManager( onLoad );
  7591. var loader = new THREE.ImageLoader( manager );
  7592. loader.setCrossOrigin( this.crossOrigin );
  7593. var loadImage = function ( url ) {
  7594. scope.manager.itemStart( url );
  7595. return loader.load( url, function () {
  7596. scope.manager.itemEnd( url );
  7597. } );
  7598. };
  7599. for ( var i = 0, l = json.length; i < l; i ++ ) {
  7600. var image = json[ i ];
  7601. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.texturePath + image.url;
  7602. images[ image.uuid ] = loadImage( path );
  7603. }
  7604. }
  7605. return images;
  7606. },
  7607. parseTextures: function ( json, images ) {
  7608. var textures = {};
  7609. if ( json !== undefined ) {
  7610. for ( var i = 0, l = json.length; i < l; i ++ ) {
  7611. var data = json[ i ];
  7612. if ( data.image === undefined ) {
  7613. THREE.warn( 'THREE.ObjectLoader: No "image" speficied for', data.uuid );
  7614. }
  7615. if ( images[ data.image ] === undefined ) {
  7616. THREE.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  7617. }
  7618. var texture = new THREE.Texture( images[ data.image ] );
  7619. texture.needsUpdate = true;
  7620. texture.uuid = data.uuid;
  7621. if ( data.name !== undefined ) texture.name = data.name;
  7622. if ( data.repeat !== undefined ) texture.repeat = new THREE.Vector2( data.repeat[ 0 ], data.repeat[ 1 ] );
  7623. if ( data.minFilter !== undefined ) texture.minFilter = THREE[ data.minFilter ];
  7624. if ( data.magFilter !== undefined ) texture.magFilter = THREE[ data.magFilter ];
  7625. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  7626. if ( data.wrap instanceof Array ) {
  7627. texture.wrapS = THREE[ data.wrap[ 0 ] ];
  7628. texture.wrapT = THREE[ data.wrap[ 1 ] ];
  7629. }
  7630. textures[ data.uuid ] = texture;
  7631. }
  7632. }
  7633. return textures;
  7634. },
  7635. parseObject: function () {
  7636. var matrix = new THREE.Matrix4();
  7637. return function ( data, geometries, materials ) {
  7638. var object;
  7639. var getGeometry = function ( name ) {
  7640. if ( geometries[ name ] === undefined ) {
  7641. THREE.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  7642. }
  7643. return geometries[ name ];
  7644. };
  7645. var getMaterial = function ( name ) {
  7646. if ( materials[ name ] === undefined ) {
  7647. THREE.warn( 'THREE.ObjectLoader: Undefined material', name );
  7648. }
  7649. return materials[ name ];
  7650. };
  7651. switch ( data.type ) {
  7652. case 'Scene':
  7653. object = new THREE.Scene();
  7654. break;
  7655. case 'PerspectiveCamera':
  7656. object = new THREE.PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  7657. break;
  7658. case 'OrthographicCamera':
  7659. object = new THREE.OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  7660. break;
  7661. case 'AmbientLight':
  7662. object = new THREE.AmbientLight( data.color );
  7663. break;
  7664. case 'DirectionalLight':
  7665. object = new THREE.DirectionalLight( data.color, data.intensity );
  7666. break;
  7667. case 'PointLight':
  7668. object = new THREE.PointLight( data.color, data.intensity, data.distance, data.decay );
  7669. break;
  7670. case 'SpotLight':
  7671. object = new THREE.SpotLight( data.color, data.intensity, data.distance, data.angle, data.exponent, data.decay );
  7672. break;
  7673. case 'HemisphereLight':
  7674. object = new THREE.HemisphereLight( data.color, data.groundColor, data.intensity );
  7675. break;
  7676. case 'Mesh':
  7677. object = new THREE.Mesh( getGeometry( data.geometry ), getMaterial( data.material ) );
  7678. break;
  7679. case 'Line':
  7680. object = new THREE.Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode );
  7681. break;
  7682. case 'PointCloud':
  7683. object = new THREE.PointCloud( getGeometry( data.geometry ), getMaterial( data.material ) );
  7684. break;
  7685. case 'Sprite':
  7686. object = new THREE.Sprite( getMaterial( data.material ) );
  7687. break;
  7688. case 'Group':
  7689. object = new THREE.Group();
  7690. break;
  7691. default:
  7692. object = new THREE.Object3D();
  7693. }
  7694. object.uuid = data.uuid;
  7695. if ( data.name !== undefined ) object.name = data.name;
  7696. if ( data.matrix !== undefined ) {
  7697. matrix.fromArray( data.matrix );
  7698. matrix.decompose( object.position, object.quaternion, object.scale );
  7699. } else {
  7700. if ( data.position !== undefined ) object.position.fromArray( data.position );
  7701. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  7702. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  7703. }
  7704. if ( data.visible !== undefined ) object.visible = data.visible;
  7705. if ( data.userData !== undefined ) object.userData = data.userData;
  7706. if ( data.children !== undefined ) {
  7707. for ( var child in data.children ) {
  7708. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  7709. }
  7710. }
  7711. return object;
  7712. }
  7713. }()
  7714. };
  7715. // File:src/loaders/TextureLoader.js
  7716. /**
  7717. * @author mrdoob / http://mrdoob.com/
  7718. */
  7719. THREE.TextureLoader = function ( manager ) {
  7720. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7721. };
  7722. THREE.TextureLoader.prototype = {
  7723. constructor: THREE.TextureLoader,
  7724. load: function ( url, onLoad, onProgress, onError ) {
  7725. var scope = this;
  7726. var loader = new THREE.ImageLoader( scope.manager );
  7727. loader.setCrossOrigin( this.crossOrigin );
  7728. loader.load( url, function ( image ) {
  7729. var texture = new THREE.Texture( image );
  7730. texture.needsUpdate = true;
  7731. if ( onLoad !== undefined ) {
  7732. onLoad( texture );
  7733. }
  7734. }, onProgress, onError );
  7735. },
  7736. setCrossOrigin: function ( value ) {
  7737. this.crossOrigin = value;
  7738. }
  7739. };
  7740. // File:src/loaders/BinaryTextureLoader.js
  7741. /**
  7742. * @author Nikos M. / https://github.com/foo123/
  7743. *
  7744. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  7745. */
  7746. THREE.DataTextureLoader = THREE.BinaryTextureLoader = function () {
  7747. // override in sub classes
  7748. this._parser = null;
  7749. };
  7750. THREE.BinaryTextureLoader.prototype = {
  7751. constructor: THREE.BinaryTextureLoader,
  7752. load: function ( url, onLoad, onProgress, onError ) {
  7753. var scope = this;
  7754. var texture = new THREE.DataTexture( );
  7755. var loader = new THREE.XHRLoader();
  7756. loader.setResponseType( 'arraybuffer' );
  7757. loader.load( url, function ( buffer ) {
  7758. var texData = scope._parser( buffer );
  7759. if ( !texData ) return;
  7760. if ( undefined !== texData.image ) {
  7761. texture.image = texData.image;
  7762. } else if ( undefined !== texData.data ) {
  7763. texture.image.width = texData.width;
  7764. texture.image.height = texData.height;
  7765. texture.image.data = texData.data;
  7766. }
  7767. texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : THREE.ClampToEdgeWrapping;
  7768. texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : THREE.ClampToEdgeWrapping;
  7769. texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : THREE.LinearFilter;
  7770. texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : THREE.LinearMipMapLinearFilter;
  7771. texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1;
  7772. if ( undefined !== texData.format ) {
  7773. texture.format = texData.format;
  7774. }
  7775. if ( undefined !== texData.type ) {
  7776. texture.type = texData.type;
  7777. }
  7778. if ( undefined !== texData.mipmaps ) {
  7779. texture.mipmaps = texData.mipmaps;
  7780. }
  7781. if ( 1 === texData.mipmapCount ) {
  7782. texture.minFilter = THREE.LinearFilter;
  7783. }
  7784. texture.needsUpdate = true;
  7785. if ( onLoad ) onLoad( texture, texData );
  7786. }, onProgress, onError );
  7787. return texture;
  7788. }
  7789. };
  7790. // File:src/loaders/CompressedTextureLoader.js
  7791. /**
  7792. * @author mrdoob / http://mrdoob.com/
  7793. *
  7794. * Abstract Base class to block based textures loader (dds, pvr, ...)
  7795. */
  7796. THREE.CompressedTextureLoader = function () {
  7797. // override in sub classes
  7798. this._parser = null;
  7799. };
  7800. THREE.CompressedTextureLoader.prototype = {
  7801. constructor: THREE.CompressedTextureLoader,
  7802. load: function ( url, onLoad, onError ) {
  7803. var scope = this;
  7804. var images = [];
  7805. var texture = new THREE.CompressedTexture();
  7806. texture.image = images;
  7807. var loader = new THREE.XHRLoader();
  7808. loader.setResponseType( 'arraybuffer' );
  7809. if ( url instanceof Array ) {
  7810. var loaded = 0;
  7811. var loadTexture = function ( i ) {
  7812. loader.load( url[ i ], function ( buffer ) {
  7813. var texDatas = scope._parser( buffer, true );
  7814. images[ i ] = {
  7815. width: texDatas.width,
  7816. height: texDatas.height,
  7817. format: texDatas.format,
  7818. mipmaps: texDatas.mipmaps
  7819. };
  7820. loaded += 1;
  7821. if ( loaded === 6 ) {
  7822. if (texDatas.mipmapCount == 1)
  7823. texture.minFilter = THREE.LinearFilter;
  7824. texture.format = texDatas.format;
  7825. texture.needsUpdate = true;
  7826. if ( onLoad ) onLoad( texture );
  7827. }
  7828. } );
  7829. };
  7830. for ( var i = 0, il = url.length; i < il; ++ i ) {
  7831. loadTexture( i );
  7832. }
  7833. } else {
  7834. // compressed cubemap texture stored in a single DDS file
  7835. loader.load( url, function ( buffer ) {
  7836. var texDatas = scope._parser( buffer, true );
  7837. if ( texDatas.isCubemap ) {
  7838. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  7839. for ( var f = 0; f < faces; f ++ ) {
  7840. images[ f ] = { mipmaps : [] };
  7841. for ( var i = 0; i < texDatas.mipmapCount; i ++ ) {
  7842. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  7843. images[ f ].format = texDatas.format;
  7844. images[ f ].width = texDatas.width;
  7845. images[ f ].height = texDatas.height;
  7846. }
  7847. }
  7848. } else {
  7849. texture.image.width = texDatas.width;
  7850. texture.image.height = texDatas.height;
  7851. texture.mipmaps = texDatas.mipmaps;
  7852. }
  7853. if ( texDatas.mipmapCount === 1 ) {
  7854. texture.minFilter = THREE.LinearFilter;
  7855. }
  7856. texture.format = texDatas.format;
  7857. texture.needsUpdate = true;
  7858. if ( onLoad ) onLoad( texture );
  7859. } );
  7860. }
  7861. return texture;
  7862. }
  7863. };
  7864. // File:src/materials/Material.js
  7865. /**
  7866. * @author mrdoob / http://mrdoob.com/
  7867. * @author alteredq / http://alteredqualia.com/
  7868. */
  7869. THREE.Material = function () {
  7870. Object.defineProperty( this, 'id', { value: THREE.MaterialIdCount ++ } );
  7871. this.uuid = THREE.Math.generateUUID();
  7872. this.name = '';
  7873. this.type = 'Material';
  7874. this.side = THREE.FrontSide;
  7875. this.opacity = 1;
  7876. this.transparent = false;
  7877. this.blending = THREE.NormalBlending;
  7878. this.blendSrc = THREE.SrcAlphaFactor;
  7879. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  7880. this.blendEquation = THREE.AddEquation;
  7881. this.blendSrcAlpha = null;
  7882. this.blendDstAlpha = null;
  7883. this.blendEquationAlpha = null;
  7884. this.depthTest = true;
  7885. this.depthWrite = true;
  7886. this.colorWrite = true;
  7887. this.polygonOffset = false;
  7888. this.polygonOffsetFactor = 0;
  7889. this.polygonOffsetUnits = 0;
  7890. this.alphaTest = 0;
  7891. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  7892. this.visible = true;
  7893. this._needsUpdate = true;
  7894. };
  7895. THREE.Material.prototype = {
  7896. constructor: THREE.Material,
  7897. get needsUpdate () {
  7898. return this._needsUpdate;
  7899. },
  7900. set needsUpdate ( value ) {
  7901. if ( value === true ) this.update();
  7902. this._needsUpdate = value;
  7903. },
  7904. setValues: function ( values ) {
  7905. if ( values === undefined ) return;
  7906. for ( var key in values ) {
  7907. var newValue = values[ key ];
  7908. if ( newValue === undefined ) {
  7909. THREE.warn( "THREE.Material: '" + key + "' parameter is undefined." );
  7910. continue;
  7911. }
  7912. if ( key in this ) {
  7913. var currentValue = this[ key ];
  7914. if ( currentValue instanceof THREE.Color ) {
  7915. currentValue.set( newValue );
  7916. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  7917. currentValue.copy( newValue );
  7918. } else if ( key == 'overdraw' ) {
  7919. // ensure overdraw is backwards-compatable with legacy boolean type
  7920. this[ key ] = Number( newValue );
  7921. } else {
  7922. this[ key ] = newValue;
  7923. }
  7924. }
  7925. }
  7926. },
  7927. toJSON: function () {
  7928. var output = {
  7929. metadata: {
  7930. version: 4.2,
  7931. type: 'material',
  7932. generator: 'MaterialExporter'
  7933. },
  7934. uuid: this.uuid,
  7935. type: this.type
  7936. };
  7937. if ( this.name !== "" ) output.name = this.name;
  7938. if ( this instanceof THREE.MeshBasicMaterial ) {
  7939. output.color = this.color.getHex();
  7940. if ( this.vertexColors !== THREE.NoColors ) output.vertexColors = this.vertexColors;
  7941. if ( this.blending !== THREE.NormalBlending ) output.blending = this.blending;
  7942. if ( this.side !== THREE.FrontSide ) output.side = this.side;
  7943. } else if ( this instanceof THREE.MeshLambertMaterial ) {
  7944. output.color = this.color.getHex();
  7945. output.emissive = this.emissive.getHex();
  7946. if ( this.vertexColors !== THREE.NoColors ) output.vertexColors = this.vertexColors;
  7947. if ( this.shading !== THREE.SmoothShading ) output.shading = this.shading;
  7948. if ( this.blending !== THREE.NormalBlending ) output.blending = this.blending;
  7949. if ( this.side !== THREE.FrontSide ) output.side = this.side;
  7950. } else if ( this instanceof THREE.MeshPhongMaterial ) {
  7951. output.color = this.color.getHex();
  7952. output.emissive = this.emissive.getHex();
  7953. output.specular = this.specular.getHex();
  7954. output.shininess = this.shininess;
  7955. if ( this.vertexColors !== THREE.NoColors ) output.vertexColors = this.vertexColors;
  7956. if ( this.shading !== THREE.SmoothShading ) output.shading = this.shading;
  7957. if ( this.blending !== THREE.NormalBlending ) output.blending = this.blending;
  7958. if ( this.side !== THREE.FrontSide ) output.side = this.side;
  7959. } else if ( this instanceof THREE.MeshNormalMaterial ) {
  7960. if ( this.blending !== THREE.NormalBlending ) output.blending = this.blending;
  7961. if ( this.side !== THREE.FrontSide ) output.side = this.side;
  7962. } else if ( this instanceof THREE.MeshDepthMaterial ) {
  7963. if ( this.blending !== THREE.NormalBlending ) output.blending = this.blending;
  7964. if ( this.side !== THREE.FrontSide ) output.side = this.side;
  7965. } else if ( this instanceof THREE.PointCloudMaterial ) {
  7966. output.size = this.size;
  7967. output.sizeAttenuation = this.sizeAttenuation;
  7968. output.color = this.color.getHex();
  7969. if ( this.vertexColors !== THREE.NoColors ) output.vertexColors = this.vertexColors;
  7970. if ( this.blending !== THREE.NormalBlending ) output.blending = this.blending;
  7971. } else if ( this instanceof THREE.ShaderMaterial ) {
  7972. output.uniforms = this.uniforms;
  7973. output.vertexShader = this.vertexShader;
  7974. output.fragmentShader = this.fragmentShader;
  7975. } else if ( this instanceof THREE.SpriteMaterial ) {
  7976. output.color = this.color.getHex();
  7977. }
  7978. if ( this.opacity < 1 ) output.opacity = this.opacity;
  7979. if ( this.transparent !== false ) output.transparent = this.transparent;
  7980. if ( this.wireframe !== false ) output.wireframe = this.wireframe;
  7981. return output;
  7982. },
  7983. clone: function ( material ) {
  7984. if ( material === undefined ) material = new THREE.Material();
  7985. material.name = this.name;
  7986. material.side = this.side;
  7987. material.opacity = this.opacity;
  7988. material.transparent = this.transparent;
  7989. material.blending = this.blending;
  7990. material.blendSrc = this.blendSrc;
  7991. material.blendDst = this.blendDst;
  7992. material.blendEquation = this.blendEquation;
  7993. material.blendSrcAlpha = this.blendSrcAlpha;
  7994. material.blendDstAlpha = this.blendDstAlpha;
  7995. material.blendEquationAlpha = this.blendEquationAlpha;
  7996. material.depthTest = this.depthTest;
  7997. material.depthWrite = this.depthWrite;
  7998. material.polygonOffset = this.polygonOffset;
  7999. material.polygonOffsetFactor = this.polygonOffsetFactor;
  8000. material.polygonOffsetUnits = this.polygonOffsetUnits;
  8001. material.alphaTest = this.alphaTest;
  8002. material.overdraw = this.overdraw;
  8003. material.visible = this.visible;
  8004. return material;
  8005. },
  8006. update: function () {
  8007. this.dispatchEvent( { type: 'update' } );
  8008. },
  8009. dispose: function () {
  8010. this.dispatchEvent( { type: 'dispose' } );
  8011. }
  8012. };
  8013. THREE.EventDispatcher.prototype.apply( THREE.Material.prototype );
  8014. THREE.MaterialIdCount = 0;
  8015. // File:src/materials/LineBasicMaterial.js
  8016. /**
  8017. * @author mrdoob / http://mrdoob.com/
  8018. * @author alteredq / http://alteredqualia.com/
  8019. *
  8020. * parameters = {
  8021. * color: <hex>,
  8022. * opacity: <float>,
  8023. *
  8024. * blending: THREE.NormalBlending,
  8025. * depthTest: <bool>,
  8026. * depthWrite: <bool>,
  8027. *
  8028. * linewidth: <float>,
  8029. * linecap: "round",
  8030. * linejoin: "round",
  8031. *
  8032. * vertexColors: <bool>
  8033. *
  8034. * fog: <bool>
  8035. * }
  8036. */
  8037. THREE.LineBasicMaterial = function ( parameters ) {
  8038. THREE.Material.call( this );
  8039. this.type = 'LineBasicMaterial';
  8040. this.color = new THREE.Color( 0xffffff );
  8041. this.linewidth = 1;
  8042. this.linecap = 'round';
  8043. this.linejoin = 'round';
  8044. this.vertexColors = THREE.NoColors;
  8045. this.fog = true;
  8046. this.setValues( parameters );
  8047. };
  8048. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  8049. THREE.LineBasicMaterial.prototype.constructor = THREE.LineBasicMaterial;
  8050. THREE.LineBasicMaterial.prototype.clone = function () {
  8051. var material = new THREE.LineBasicMaterial();
  8052. THREE.Material.prototype.clone.call( this, material );
  8053. material.color.copy( this.color );
  8054. material.linewidth = this.linewidth;
  8055. material.linecap = this.linecap;
  8056. material.linejoin = this.linejoin;
  8057. material.vertexColors = this.vertexColors;
  8058. material.fog = this.fog;
  8059. return material;
  8060. };
  8061. // File:src/materials/LineDashedMaterial.js
  8062. /**
  8063. * @author alteredq / http://alteredqualia.com/
  8064. *
  8065. * parameters = {
  8066. * color: <hex>,
  8067. * opacity: <float>,
  8068. *
  8069. * blending: THREE.NormalBlending,
  8070. * depthTest: <bool>,
  8071. * depthWrite: <bool>,
  8072. *
  8073. * linewidth: <float>,
  8074. *
  8075. * scale: <float>,
  8076. * dashSize: <float>,
  8077. * gapSize: <float>,
  8078. *
  8079. * vertexColors: <bool>
  8080. *
  8081. * fog: <bool>
  8082. * }
  8083. */
  8084. THREE.LineDashedMaterial = function ( parameters ) {
  8085. THREE.Material.call( this );
  8086. this.type = 'LineDashedMaterial';
  8087. this.color = new THREE.Color( 0xffffff );
  8088. this.linewidth = 1;
  8089. this.scale = 1;
  8090. this.dashSize = 3;
  8091. this.gapSize = 1;
  8092. this.vertexColors = false;
  8093. this.fog = true;
  8094. this.setValues( parameters );
  8095. };
  8096. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  8097. THREE.LineDashedMaterial.prototype.constructor = THREE.LineDashedMaterial;
  8098. THREE.LineDashedMaterial.prototype.clone = function () {
  8099. var material = new THREE.LineDashedMaterial();
  8100. THREE.Material.prototype.clone.call( this, material );
  8101. material.color.copy( this.color );
  8102. material.linewidth = this.linewidth;
  8103. material.scale = this.scale;
  8104. material.dashSize = this.dashSize;
  8105. material.gapSize = this.gapSize;
  8106. material.vertexColors = this.vertexColors;
  8107. material.fog = this.fog;
  8108. return material;
  8109. };
  8110. // File:src/materials/MeshBasicMaterial.js
  8111. /**
  8112. * @author mrdoob / http://mrdoob.com/
  8113. * @author alteredq / http://alteredqualia.com/
  8114. *
  8115. * parameters = {
  8116. * color: <hex>,
  8117. * opacity: <float>,
  8118. * map: new THREE.Texture( <Image> ),
  8119. *
  8120. * lightMap: new THREE.Texture( <Image> ),
  8121. *
  8122. * specularMap: new THREE.Texture( <Image> ),
  8123. *
  8124. * alphaMap: new THREE.Texture( <Image> ),
  8125. *
  8126. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8127. * combine: THREE.Multiply,
  8128. * reflectivity: <float>,
  8129. * refractionRatio: <float>,
  8130. *
  8131. * shading: THREE.SmoothShading,
  8132. * blending: THREE.NormalBlending,
  8133. * depthTest: <bool>,
  8134. * depthWrite: <bool>,
  8135. *
  8136. * wireframe: <boolean>,
  8137. * wireframeLinewidth: <float>,
  8138. *
  8139. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8140. *
  8141. * skinning: <bool>,
  8142. * morphTargets: <bool>,
  8143. *
  8144. * fog: <bool>
  8145. * }
  8146. */
  8147. THREE.MeshBasicMaterial = function ( parameters ) {
  8148. THREE.Material.call( this );
  8149. this.type = 'MeshBasicMaterial';
  8150. this.color = new THREE.Color( 0xffffff ); // emissive
  8151. this.map = null;
  8152. this.lightMap = null;
  8153. this.specularMap = null;
  8154. this.alphaMap = null;
  8155. this.envMap = null;
  8156. this.combine = THREE.MultiplyOperation;
  8157. this.reflectivity = 1;
  8158. this.refractionRatio = 0.98;
  8159. this.fog = true;
  8160. this.shading = THREE.SmoothShading;
  8161. this.wireframe = false;
  8162. this.wireframeLinewidth = 1;
  8163. this.wireframeLinecap = 'round';
  8164. this.wireframeLinejoin = 'round';
  8165. this.vertexColors = THREE.NoColors;
  8166. this.skinning = false;
  8167. this.morphTargets = false;
  8168. this.setValues( parameters );
  8169. };
  8170. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  8171. THREE.MeshBasicMaterial.prototype.constructor = THREE.MeshBasicMaterial;
  8172. THREE.MeshBasicMaterial.prototype.clone = function () {
  8173. var material = new THREE.MeshBasicMaterial();
  8174. THREE.Material.prototype.clone.call( this, material );
  8175. material.color.copy( this.color );
  8176. material.map = this.map;
  8177. material.lightMap = this.lightMap;
  8178. material.specularMap = this.specularMap;
  8179. material.alphaMap = this.alphaMap;
  8180. material.envMap = this.envMap;
  8181. material.combine = this.combine;
  8182. material.reflectivity = this.reflectivity;
  8183. material.refractionRatio = this.refractionRatio;
  8184. material.fog = this.fog;
  8185. material.shading = this.shading;
  8186. material.wireframe = this.wireframe;
  8187. material.wireframeLinewidth = this.wireframeLinewidth;
  8188. material.wireframeLinecap = this.wireframeLinecap;
  8189. material.wireframeLinejoin = this.wireframeLinejoin;
  8190. material.vertexColors = this.vertexColors;
  8191. material.skinning = this.skinning;
  8192. material.morphTargets = this.morphTargets;
  8193. return material;
  8194. };
  8195. // File:src/materials/MeshLambertMaterial.js
  8196. /**
  8197. * @author mrdoob / http://mrdoob.com/
  8198. * @author alteredq / http://alteredqualia.com/
  8199. *
  8200. * parameters = {
  8201. * color: <hex>,
  8202. * emissive: <hex>,
  8203. * opacity: <float>,
  8204. *
  8205. * map: new THREE.Texture( <Image> ),
  8206. *
  8207. * lightMap: new THREE.Texture( <Image> ),
  8208. *
  8209. * specularMap: new THREE.Texture( <Image> ),
  8210. *
  8211. * alphaMap: new THREE.Texture( <Image> ),
  8212. *
  8213. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8214. * combine: THREE.Multiply,
  8215. * reflectivity: <float>,
  8216. * refractionRatio: <float>,
  8217. *
  8218. * shading: THREE.SmoothShading,
  8219. * blending: THREE.NormalBlending,
  8220. * depthTest: <bool>,
  8221. * depthWrite: <bool>,
  8222. *
  8223. * wireframe: <boolean>,
  8224. * wireframeLinewidth: <float>,
  8225. *
  8226. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8227. *
  8228. * skinning: <bool>,
  8229. * morphTargets: <bool>,
  8230. * morphNormals: <bool>,
  8231. *
  8232. * fog: <bool>
  8233. * }
  8234. */
  8235. THREE.MeshLambertMaterial = function ( parameters ) {
  8236. THREE.Material.call( this );
  8237. this.type = 'MeshLambertMaterial';
  8238. this.color = new THREE.Color( 0xffffff ); // diffuse
  8239. this.emissive = new THREE.Color( 0x000000 );
  8240. this.wrapAround = false;
  8241. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  8242. this.map = null;
  8243. this.lightMap = null;
  8244. this.specularMap = null;
  8245. this.alphaMap = null;
  8246. this.envMap = null;
  8247. this.combine = THREE.MultiplyOperation;
  8248. this.reflectivity = 1;
  8249. this.refractionRatio = 0.98;
  8250. this.fog = true;
  8251. this.shading = THREE.SmoothShading;
  8252. this.wireframe = false;
  8253. this.wireframeLinewidth = 1;
  8254. this.wireframeLinecap = 'round';
  8255. this.wireframeLinejoin = 'round';
  8256. this.vertexColors = THREE.NoColors;
  8257. this.skinning = false;
  8258. this.morphTargets = false;
  8259. this.morphNormals = false;
  8260. this.setValues( parameters );
  8261. };
  8262. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  8263. THREE.MeshLambertMaterial.prototype.constructor = THREE.MeshLambertMaterial;
  8264. THREE.MeshLambertMaterial.prototype.clone = function () {
  8265. var material = new THREE.MeshLambertMaterial();
  8266. THREE.Material.prototype.clone.call( this, material );
  8267. material.color.copy( this.color );
  8268. material.emissive.copy( this.emissive );
  8269. material.wrapAround = this.wrapAround;
  8270. material.wrapRGB.copy( this.wrapRGB );
  8271. material.map = this.map;
  8272. material.lightMap = this.lightMap;
  8273. material.specularMap = this.specularMap;
  8274. material.alphaMap = this.alphaMap;
  8275. material.envMap = this.envMap;
  8276. material.combine = this.combine;
  8277. material.reflectivity = this.reflectivity;
  8278. material.refractionRatio = this.refractionRatio;
  8279. material.fog = this.fog;
  8280. material.shading = this.shading;
  8281. material.wireframe = this.wireframe;
  8282. material.wireframeLinewidth = this.wireframeLinewidth;
  8283. material.wireframeLinecap = this.wireframeLinecap;
  8284. material.wireframeLinejoin = this.wireframeLinejoin;
  8285. material.vertexColors = this.vertexColors;
  8286. material.skinning = this.skinning;
  8287. material.morphTargets = this.morphTargets;
  8288. material.morphNormals = this.morphNormals;
  8289. return material;
  8290. };
  8291. // File:src/materials/MeshPhongMaterial.js
  8292. /**
  8293. * @author mrdoob / http://mrdoob.com/
  8294. * @author alteredq / http://alteredqualia.com/
  8295. *
  8296. * parameters = {
  8297. * color: <hex>,
  8298. * emissive: <hex>,
  8299. * specular: <hex>,
  8300. * shininess: <float>,
  8301. * opacity: <float>,
  8302. *
  8303. * map: new THREE.Texture( <Image> ),
  8304. *
  8305. * lightMap: new THREE.Texture( <Image> ),
  8306. *
  8307. * bumpMap: new THREE.Texture( <Image> ),
  8308. * bumpScale: <float>,
  8309. *
  8310. * normalMap: new THREE.Texture( <Image> ),
  8311. * normalScale: <Vector2>,
  8312. *
  8313. * specularMap: new THREE.Texture( <Image> ),
  8314. *
  8315. * alphaMap: new THREE.Texture( <Image> ),
  8316. *
  8317. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8318. * combine: THREE.Multiply,
  8319. * reflectivity: <float>,
  8320. * refractionRatio: <float>,
  8321. *
  8322. * shading: THREE.SmoothShading,
  8323. * blending: THREE.NormalBlending,
  8324. * depthTest: <bool>,
  8325. * depthWrite: <bool>,
  8326. *
  8327. * wireframe: <boolean>,
  8328. * wireframeLinewidth: <float>,
  8329. *
  8330. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8331. *
  8332. * skinning: <bool>,
  8333. * morphTargets: <bool>,
  8334. * morphNormals: <bool>,
  8335. *
  8336. * fog: <bool>
  8337. * }
  8338. */
  8339. THREE.MeshPhongMaterial = function ( parameters ) {
  8340. THREE.Material.call( this );
  8341. this.type = 'MeshPhongMaterial';
  8342. this.color = new THREE.Color( 0xffffff ); // diffuse
  8343. this.emissive = new THREE.Color( 0x000000 );
  8344. this.specular = new THREE.Color( 0x111111 );
  8345. this.shininess = 30;
  8346. this.metal = false;
  8347. this.wrapAround = false;
  8348. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  8349. this.map = null;
  8350. this.lightMap = null;
  8351. this.bumpMap = null;
  8352. this.bumpScale = 1;
  8353. this.normalMap = null;
  8354. this.normalScale = new THREE.Vector2( 1, 1 );
  8355. this.specularMap = null;
  8356. this.alphaMap = null;
  8357. this.envMap = null;
  8358. this.combine = THREE.MultiplyOperation;
  8359. this.reflectivity = 1;
  8360. this.refractionRatio = 0.98;
  8361. this.fog = true;
  8362. this.shading = THREE.SmoothShading;
  8363. this.wireframe = false;
  8364. this.wireframeLinewidth = 1;
  8365. this.wireframeLinecap = 'round';
  8366. this.wireframeLinejoin = 'round';
  8367. this.vertexColors = THREE.NoColors;
  8368. this.skinning = false;
  8369. this.morphTargets = false;
  8370. this.morphNormals = false;
  8371. this.setValues( parameters );
  8372. };
  8373. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  8374. THREE.MeshPhongMaterial.prototype.constructor = THREE.MeshPhongMaterial;
  8375. THREE.MeshPhongMaterial.prototype.clone = function () {
  8376. var material = new THREE.MeshPhongMaterial();
  8377. THREE.Material.prototype.clone.call( this, material );
  8378. material.color.copy( this.color );
  8379. material.emissive.copy( this.emissive );
  8380. material.specular.copy( this.specular );
  8381. material.shininess = this.shininess;
  8382. material.metal = this.metal;
  8383. material.wrapAround = this.wrapAround;
  8384. material.wrapRGB.copy( this.wrapRGB );
  8385. material.map = this.map;
  8386. material.lightMap = this.lightMap;
  8387. material.bumpMap = this.bumpMap;
  8388. material.bumpScale = this.bumpScale;
  8389. material.normalMap = this.normalMap;
  8390. material.normalScale.copy( this.normalScale );
  8391. material.specularMap = this.specularMap;
  8392. material.alphaMap = this.alphaMap;
  8393. material.envMap = this.envMap;
  8394. material.combine = this.combine;
  8395. material.reflectivity = this.reflectivity;
  8396. material.refractionRatio = this.refractionRatio;
  8397. material.fog = this.fog;
  8398. material.shading = this.shading;
  8399. material.wireframe = this.wireframe;
  8400. material.wireframeLinewidth = this.wireframeLinewidth;
  8401. material.wireframeLinecap = this.wireframeLinecap;
  8402. material.wireframeLinejoin = this.wireframeLinejoin;
  8403. material.vertexColors = this.vertexColors;
  8404. material.skinning = this.skinning;
  8405. material.morphTargets = this.morphTargets;
  8406. material.morphNormals = this.morphNormals;
  8407. return material;
  8408. };
  8409. // File:src/materials/MeshDepthMaterial.js
  8410. /**
  8411. * @author mrdoob / http://mrdoob.com/
  8412. * @author alteredq / http://alteredqualia.com/
  8413. *
  8414. * parameters = {
  8415. * opacity: <float>,
  8416. *
  8417. * blending: THREE.NormalBlending,
  8418. * depthTest: <bool>,
  8419. * depthWrite: <bool>,
  8420. *
  8421. * wireframe: <boolean>,
  8422. * wireframeLinewidth: <float>
  8423. * }
  8424. */
  8425. THREE.MeshDepthMaterial = function ( parameters ) {
  8426. THREE.Material.call( this );
  8427. this.type = 'MeshDepthMaterial';
  8428. this.morphTargets = false;
  8429. this.wireframe = false;
  8430. this.wireframeLinewidth = 1;
  8431. this.setValues( parameters );
  8432. };
  8433. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  8434. THREE.MeshDepthMaterial.prototype.constructor = THREE.MeshDepthMaterial;
  8435. THREE.MeshDepthMaterial.prototype.clone = function () {
  8436. var material = new THREE.MeshDepthMaterial();
  8437. THREE.Material.prototype.clone.call( this, material );
  8438. material.wireframe = this.wireframe;
  8439. material.wireframeLinewidth = this.wireframeLinewidth;
  8440. return material;
  8441. };
  8442. // File:src/materials/MeshNormalMaterial.js
  8443. /**
  8444. * @author mrdoob / http://mrdoob.com/
  8445. *
  8446. * parameters = {
  8447. * opacity: <float>,
  8448. *
  8449. * shading: THREE.FlatShading,
  8450. * blending: THREE.NormalBlending,
  8451. * depthTest: <bool>,
  8452. * depthWrite: <bool>,
  8453. *
  8454. * wireframe: <boolean>,
  8455. * wireframeLinewidth: <float>
  8456. * }
  8457. */
  8458. THREE.MeshNormalMaterial = function ( parameters ) {
  8459. THREE.Material.call( this, parameters );
  8460. this.type = 'MeshNormalMaterial';
  8461. this.wireframe = false;
  8462. this.wireframeLinewidth = 1;
  8463. this.morphTargets = false;
  8464. this.setValues( parameters );
  8465. };
  8466. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  8467. THREE.MeshNormalMaterial.prototype.constructor = THREE.MeshNormalMaterial;
  8468. THREE.MeshNormalMaterial.prototype.clone = function () {
  8469. var material = new THREE.MeshNormalMaterial();
  8470. THREE.Material.prototype.clone.call( this, material );
  8471. material.wireframe = this.wireframe;
  8472. material.wireframeLinewidth = this.wireframeLinewidth;
  8473. return material;
  8474. };
  8475. // File:src/materials/MeshFaceMaterial.js
  8476. /**
  8477. * @author mrdoob / http://mrdoob.com/
  8478. */
  8479. THREE.MeshFaceMaterial = function ( materials ) {
  8480. this.uuid = THREE.Math.generateUUID();
  8481. this.type = 'MeshFaceMaterial';
  8482. this.materials = materials instanceof Array ? materials : [];
  8483. };
  8484. THREE.MeshFaceMaterial.prototype = {
  8485. constructor: THREE.MeshFaceMaterial,
  8486. toJSON: function () {
  8487. var output = {
  8488. metadata: {
  8489. version: 4.2,
  8490. type: 'material',
  8491. generator: 'MaterialExporter'
  8492. },
  8493. uuid: this.uuid,
  8494. type: this.type,
  8495. materials: []
  8496. };
  8497. for ( var i = 0, l = this.materials.length; i < l; i ++ ) {
  8498. output.materials.push( this.materials[ i ].toJSON() );
  8499. }
  8500. return output;
  8501. },
  8502. clone: function () {
  8503. var material = new THREE.MeshFaceMaterial();
  8504. for ( var i = 0; i < this.materials.length; i ++ ) {
  8505. material.materials.push( this.materials[ i ].clone() );
  8506. }
  8507. return material;
  8508. }
  8509. };
  8510. // File:src/materials/PointCloudMaterial.js
  8511. /**
  8512. * @author mrdoob / http://mrdoob.com/
  8513. * @author alteredq / http://alteredqualia.com/
  8514. *
  8515. * parameters = {
  8516. * color: <hex>,
  8517. * opacity: <float>,
  8518. * map: new THREE.Texture( <Image> ),
  8519. *
  8520. * size: <float>,
  8521. * sizeAttenuation: <bool>,
  8522. *
  8523. * blending: THREE.NormalBlending,
  8524. * depthTest: <bool>,
  8525. * depthWrite: <bool>,
  8526. *
  8527. * vertexColors: <bool>,
  8528. *
  8529. * fog: <bool>
  8530. * }
  8531. */
  8532. THREE.PointCloudMaterial = function ( parameters ) {
  8533. THREE.Material.call( this );
  8534. this.type = 'PointCloudMaterial';
  8535. this.color = new THREE.Color( 0xffffff );
  8536. this.map = null;
  8537. this.size = 1;
  8538. this.sizeAttenuation = true;
  8539. this.vertexColors = THREE.NoColors;
  8540. this.fog = true;
  8541. this.setValues( parameters );
  8542. };
  8543. THREE.PointCloudMaterial.prototype = Object.create( THREE.Material.prototype );
  8544. THREE.PointCloudMaterial.prototype.constructor = THREE.PointCloudMaterial;
  8545. THREE.PointCloudMaterial.prototype.clone = function () {
  8546. var material = new THREE.PointCloudMaterial();
  8547. THREE.Material.prototype.clone.call( this, material );
  8548. material.color.copy( this.color );
  8549. material.map = this.map;
  8550. material.size = this.size;
  8551. material.sizeAttenuation = this.sizeAttenuation;
  8552. material.vertexColors = this.vertexColors;
  8553. material.fog = this.fog;
  8554. return material;
  8555. };
  8556. // backwards compatibility
  8557. THREE.ParticleBasicMaterial = function ( parameters ) {
  8558. THREE.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointCloudMaterial.' );
  8559. return new THREE.PointCloudMaterial( parameters );
  8560. };
  8561. THREE.ParticleSystemMaterial = function ( parameters ) {
  8562. THREE.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointCloudMaterial.' );
  8563. return new THREE.PointCloudMaterial( parameters );
  8564. };
  8565. // File:src/materials/ShaderMaterial.js
  8566. /**
  8567. * @author alteredq / http://alteredqualia.com/
  8568. *
  8569. * parameters = {
  8570. * defines: { "label" : "value" },
  8571. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  8572. *
  8573. * fragmentShader: <string>,
  8574. * vertexShader: <string>,
  8575. *
  8576. * shading: THREE.SmoothShading,
  8577. * blending: THREE.NormalBlending,
  8578. * depthTest: <bool>,
  8579. * depthWrite: <bool>,
  8580. *
  8581. * wireframe: <boolean>,
  8582. * wireframeLinewidth: <float>,
  8583. *
  8584. * lights: <bool>,
  8585. *
  8586. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8587. *
  8588. * skinning: <bool>,
  8589. * morphTargets: <bool>,
  8590. * morphNormals: <bool>,
  8591. *
  8592. * fog: <bool>
  8593. * }
  8594. */
  8595. THREE.ShaderMaterial = function ( parameters ) {
  8596. THREE.Material.call( this );
  8597. this.type = 'ShaderMaterial';
  8598. this.defines = {};
  8599. this.uniforms = {};
  8600. this.attributes = null;
  8601. this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}';
  8602. this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}';
  8603. this.shading = THREE.SmoothShading;
  8604. this.linewidth = 1;
  8605. this.wireframe = false;
  8606. this.wireframeLinewidth = 1;
  8607. this.fog = false; // set to use scene fog
  8608. this.lights = false; // set to use scene lights
  8609. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  8610. this.skinning = false; // set to use skinning attribute streams
  8611. this.morphTargets = false; // set to use morph targets
  8612. this.morphNormals = false; // set to use morph normals
  8613. // When rendered geometry doesn't include these attributes but the material does,
  8614. // use these default values in WebGL. This avoids errors when buffer data is missing.
  8615. this.defaultAttributeValues = {
  8616. 'color': [ 1, 1, 1 ],
  8617. 'uv': [ 0, 0 ],
  8618. 'uv2': [ 0, 0 ]
  8619. };
  8620. this.index0AttributeName = undefined;
  8621. this.setValues( parameters );
  8622. };
  8623. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  8624. THREE.ShaderMaterial.prototype.constructor = THREE.ShaderMaterial;
  8625. THREE.ShaderMaterial.prototype.clone = function () {
  8626. var material = new THREE.ShaderMaterial();
  8627. THREE.Material.prototype.clone.call( this, material );
  8628. material.fragmentShader = this.fragmentShader;
  8629. material.vertexShader = this.vertexShader;
  8630. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  8631. material.attributes = this.attributes;
  8632. material.defines = this.defines;
  8633. material.shading = this.shading;
  8634. material.wireframe = this.wireframe;
  8635. material.wireframeLinewidth = this.wireframeLinewidth;
  8636. material.fog = this.fog;
  8637. material.lights = this.lights;
  8638. material.vertexColors = this.vertexColors;
  8639. material.skinning = this.skinning;
  8640. material.morphTargets = this.morphTargets;
  8641. material.morphNormals = this.morphNormals;
  8642. return material;
  8643. };
  8644. // File:src/materials/RawShaderMaterial.js
  8645. /**
  8646. * @author mrdoob / http://mrdoob.com/
  8647. */
  8648. THREE.RawShaderMaterial = function ( parameters ) {
  8649. THREE.ShaderMaterial.call( this, parameters );
  8650. this.type = 'RawShaderMaterial';
  8651. };
  8652. THREE.RawShaderMaterial.prototype = Object.create( THREE.ShaderMaterial.prototype );
  8653. THREE.RawShaderMaterial.prototype.constructor = THREE.RawShaderMaterial;
  8654. THREE.RawShaderMaterial.prototype.clone = function () {
  8655. var material = new THREE.RawShaderMaterial();
  8656. THREE.ShaderMaterial.prototype.clone.call( this, material );
  8657. return material;
  8658. };
  8659. // File:src/materials/SpriteMaterial.js
  8660. /**
  8661. * @author alteredq / http://alteredqualia.com/
  8662. *
  8663. * parameters = {
  8664. * color: <hex>,
  8665. * opacity: <float>,
  8666. * map: new THREE.Texture( <Image> ),
  8667. *
  8668. * blending: THREE.NormalBlending,
  8669. * depthTest: <bool>,
  8670. * depthWrite: <bool>,
  8671. *
  8672. * uvOffset: new THREE.Vector2(),
  8673. * uvScale: new THREE.Vector2(),
  8674. *
  8675. * fog: <bool>
  8676. * }
  8677. */
  8678. THREE.SpriteMaterial = function ( parameters ) {
  8679. THREE.Material.call( this );
  8680. this.type = 'SpriteMaterial';
  8681. this.color = new THREE.Color( 0xffffff );
  8682. this.map = null;
  8683. this.rotation = 0;
  8684. this.fog = false;
  8685. // set parameters
  8686. this.setValues( parameters );
  8687. };
  8688. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  8689. THREE.SpriteMaterial.prototype.constructor = THREE.SpriteMaterial;
  8690. THREE.SpriteMaterial.prototype.clone = function () {
  8691. var material = new THREE.SpriteMaterial();
  8692. THREE.Material.prototype.clone.call( this, material );
  8693. material.color.copy( this.color );
  8694. material.map = this.map;
  8695. material.rotation = this.rotation;
  8696. material.fog = this.fog;
  8697. return material;
  8698. };
  8699. // File:src/textures/Texture.js
  8700. /**
  8701. * @author mrdoob / http://mrdoob.com/
  8702. * @author alteredq / http://alteredqualia.com/
  8703. * @author szimek / https://github.com/szimek/
  8704. */
  8705. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  8706. Object.defineProperty( this, 'id', { value: THREE.TextureIdCount ++ } );
  8707. this.uuid = THREE.Math.generateUUID();
  8708. this.name = '';
  8709. this.image = image !== undefined ? image : THREE.Texture.DEFAULT_IMAGE;
  8710. this.mipmaps = [];
  8711. this.mapping = mapping !== undefined ? mapping : THREE.Texture.DEFAULT_MAPPING;
  8712. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  8713. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  8714. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  8715. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  8716. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  8717. this.format = format !== undefined ? format : THREE.RGBAFormat;
  8718. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  8719. this.offset = new THREE.Vector2( 0, 0 );
  8720. this.repeat = new THREE.Vector2( 1, 1 );
  8721. this.generateMipmaps = true;
  8722. this.premultiplyAlpha = false;
  8723. this.flipY = true;
  8724. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  8725. this._needsUpdate = false;
  8726. this.onUpdate = null;
  8727. };
  8728. THREE.Texture.DEFAULT_IMAGE = undefined;
  8729. THREE.Texture.DEFAULT_MAPPING = THREE.UVMapping;
  8730. THREE.Texture.prototype = {
  8731. constructor: THREE.Texture,
  8732. get needsUpdate () {
  8733. return this._needsUpdate;
  8734. },
  8735. set needsUpdate ( value ) {
  8736. if ( value === true ) this.update();
  8737. this._needsUpdate = value;
  8738. },
  8739. clone: function ( texture ) {
  8740. if ( texture === undefined ) texture = new THREE.Texture();
  8741. texture.image = this.image;
  8742. texture.mipmaps = this.mipmaps.slice( 0 );
  8743. texture.mapping = this.mapping;
  8744. texture.wrapS = this.wrapS;
  8745. texture.wrapT = this.wrapT;
  8746. texture.magFilter = this.magFilter;
  8747. texture.minFilter = this.minFilter;
  8748. texture.anisotropy = this.anisotropy;
  8749. texture.format = this.format;
  8750. texture.type = this.type;
  8751. texture.offset.copy( this.offset );
  8752. texture.repeat.copy( this.repeat );
  8753. texture.generateMipmaps = this.generateMipmaps;
  8754. texture.premultiplyAlpha = this.premultiplyAlpha;
  8755. texture.flipY = this.flipY;
  8756. texture.unpackAlignment = this.unpackAlignment;
  8757. return texture;
  8758. },
  8759. update: function () {
  8760. this.dispatchEvent( { type: 'update' } );
  8761. },
  8762. dispose: function () {
  8763. this.dispatchEvent( { type: 'dispose' } );
  8764. }
  8765. };
  8766. THREE.EventDispatcher.prototype.apply( THREE.Texture.prototype );
  8767. THREE.TextureIdCount = 0;
  8768. // File:src/textures/CubeTexture.js
  8769. /**
  8770. * @author mrdoob / http://mrdoob.com/
  8771. */
  8772. THREE.CubeTexture = function ( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  8773. mapping = mapping !== undefined ? mapping : THREE.CubeReflectionMapping;
  8774. THREE.Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8775. this.images = images;
  8776. };
  8777. THREE.CubeTexture.prototype = Object.create( THREE.Texture.prototype );
  8778. THREE.CubeTexture.prototype.constructor = THREE.CubeTexture;
  8779. THREE.CubeTexture.clone = function ( texture ) {
  8780. if ( texture === undefined ) texture = new THREE.CubeTexture();
  8781. THREE.Texture.prototype.clone.call( this, texture );
  8782. texture.images = this.images;
  8783. return texture;
  8784. };
  8785. // File:src/textures/CompressedTexture.js
  8786. /**
  8787. * @author alteredq / http://alteredqualia.com/
  8788. */
  8789. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  8790. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8791. this.image = { width: width, height: height };
  8792. this.mipmaps = mipmaps;
  8793. // no flipping for cube textures
  8794. // (also flipping doesn't work for compressed textures )
  8795. this.flipY = false;
  8796. // can't generate mipmaps for compressed textures
  8797. // mips must be embedded in DDS files
  8798. this.generateMipmaps = false;
  8799. };
  8800. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  8801. THREE.CompressedTexture.prototype.constructor = THREE.CompressedTexture;
  8802. THREE.CompressedTexture.prototype.clone = function () {
  8803. var texture = new THREE.CompressedTexture();
  8804. THREE.Texture.prototype.clone.call( this, texture );
  8805. return texture;
  8806. };
  8807. // File:src/textures/DataTexture.js
  8808. /**
  8809. * @author alteredq / http://alteredqualia.com/
  8810. */
  8811. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  8812. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8813. this.image = { data: data, width: width, height: height };
  8814. };
  8815. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  8816. THREE.DataTexture.prototype.constructor = THREE.DataTexture;
  8817. THREE.DataTexture.prototype.clone = function () {
  8818. var texture = new THREE.DataTexture();
  8819. THREE.Texture.prototype.clone.call( this, texture );
  8820. return texture;
  8821. };
  8822. // File:src/textures/VideoTexture.js
  8823. /**
  8824. * @author mrdoob / http://mrdoob.com/
  8825. */
  8826. THREE.VideoTexture = function ( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  8827. THREE.Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8828. this.generateMipmaps = false;
  8829. var scope = this;
  8830. var update = function () {
  8831. requestAnimationFrame( update );
  8832. if ( video.readyState === video.HAVE_ENOUGH_DATA ) {
  8833. scope.needsUpdate = true;
  8834. }
  8835. };
  8836. update();
  8837. };
  8838. THREE.VideoTexture.prototype = Object.create( THREE.Texture.prototype );
  8839. THREE.VideoTexture.prototype.constructor = THREE.VideoTexture;
  8840. // File:src/objects/Group.js
  8841. /**
  8842. * @author mrdoob / http://mrdoob.com/
  8843. */
  8844. THREE.Group = function () {
  8845. THREE.Object3D.call( this );
  8846. this.type = 'Group';
  8847. };
  8848. THREE.Group.prototype = Object.create( THREE.Object3D.prototype );
  8849. THREE.Group.prototype.constructor = THREE.Group;
  8850. // File:src/objects/PointCloud.js
  8851. /**
  8852. * @author alteredq / http://alteredqualia.com/
  8853. */
  8854. THREE.PointCloud = function ( geometry, material ) {
  8855. THREE.Object3D.call( this );
  8856. this.type = 'PointCloud';
  8857. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  8858. this.material = material !== undefined ? material : new THREE.PointCloudMaterial( { color: Math.random() * 0xffffff } );
  8859. };
  8860. THREE.PointCloud.prototype = Object.create( THREE.Object3D.prototype );
  8861. THREE.PointCloud.prototype.constructor = THREE.PointCloud;
  8862. THREE.PointCloud.prototype.raycast = ( function () {
  8863. var inverseMatrix = new THREE.Matrix4();
  8864. var ray = new THREE.Ray();
  8865. return function ( raycaster, intersects ) {
  8866. var object = this;
  8867. var geometry = object.geometry;
  8868. var threshold = raycaster.params.PointCloud.threshold;
  8869. inverseMatrix.getInverse( this.matrixWorld );
  8870. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  8871. if ( geometry.boundingBox !== null ) {
  8872. if ( ray.isIntersectionBox( geometry.boundingBox ) === false ) {
  8873. return;
  8874. }
  8875. }
  8876. var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  8877. var position = new THREE.Vector3();
  8878. var testPoint = function ( point, index ) {
  8879. var rayPointDistance = ray.distanceToPoint( point );
  8880. if ( rayPointDistance < localThreshold ) {
  8881. var intersectPoint = ray.closestPointToPoint( point );
  8882. intersectPoint.applyMatrix4( object.matrixWorld );
  8883. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  8884. intersects.push( {
  8885. distance: distance,
  8886. distanceToRay: rayPointDistance,
  8887. point: intersectPoint.clone(),
  8888. index: index,
  8889. face: null,
  8890. object: object
  8891. } );
  8892. }
  8893. };
  8894. if ( geometry instanceof THREE.BufferGeometry ) {
  8895. var attributes = geometry.attributes;
  8896. var positions = attributes.position.array;
  8897. if ( attributes.index !== undefined ) {
  8898. var indices = attributes.index.array;
  8899. var offsets = geometry.offsets;
  8900. if ( offsets.length === 0 ) {
  8901. var offset = {
  8902. start: 0,
  8903. count: indices.length,
  8904. index: 0
  8905. };
  8906. offsets = [ offset ];
  8907. }
  8908. for ( var oi = 0, ol = offsets.length; oi < ol; ++ oi ) {
  8909. var start = offsets[ oi ].start;
  8910. var count = offsets[ oi ].count;
  8911. var index = offsets[ oi ].index;
  8912. for ( var i = start, il = start + count; i < il; i ++ ) {
  8913. var a = index + indices[ i ];
  8914. position.fromArray( positions, a * 3 );
  8915. testPoint( position, a );
  8916. }
  8917. }
  8918. } else {
  8919. var pointCount = positions.length / 3;
  8920. for ( var i = 0; i < pointCount; i ++ ) {
  8921. position.set(
  8922. positions[ 3 * i ],
  8923. positions[ 3 * i + 1 ],
  8924. positions[ 3 * i + 2 ]
  8925. );
  8926. testPoint( position, i );
  8927. }
  8928. }
  8929. } else {
  8930. var vertices = this.geometry.vertices;
  8931. for ( var i = 0; i < vertices.length; i ++ ) {
  8932. testPoint( vertices[ i ], i );
  8933. }
  8934. }
  8935. };
  8936. }() );
  8937. THREE.PointCloud.prototype.clone = function ( object ) {
  8938. if ( object === undefined ) object = new THREE.PointCloud( this.geometry, this.material );
  8939. THREE.Object3D.prototype.clone.call( this, object );
  8940. return object;
  8941. };
  8942. // Backwards compatibility
  8943. THREE.ParticleSystem = function ( geometry, material ) {
  8944. THREE.warn( 'THREE.ParticleSystem has been renamed to THREE.PointCloud.' );
  8945. return new THREE.PointCloud( geometry, material );
  8946. };
  8947. // File:src/objects/Line.js
  8948. /**
  8949. * @author mrdoob / http://mrdoob.com/
  8950. */
  8951. THREE.Line = function ( geometry, material, mode ) {
  8952. THREE.Object3D.call( this );
  8953. this.type = 'Line';
  8954. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  8955. this.material = material !== undefined ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  8956. this.mode = mode !== undefined ? mode : THREE.LineStrip;
  8957. };
  8958. THREE.LineStrip = 0;
  8959. THREE.LinePieces = 1;
  8960. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  8961. THREE.Line.prototype.constructor = THREE.Line;
  8962. THREE.Line.prototype.raycast = ( function () {
  8963. var inverseMatrix = new THREE.Matrix4();
  8964. var ray = new THREE.Ray();
  8965. var sphere = new THREE.Sphere();
  8966. return function ( raycaster, intersects ) {
  8967. var precision = raycaster.linePrecision;
  8968. var precisionSq = precision * precision;
  8969. var geometry = this.geometry;
  8970. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  8971. // Checking boundingSphere distance to ray
  8972. sphere.copy( geometry.boundingSphere );
  8973. sphere.applyMatrix4( this.matrixWorld );
  8974. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  8975. return;
  8976. }
  8977. inverseMatrix.getInverse( this.matrixWorld );
  8978. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  8979. var vStart = new THREE.Vector3();
  8980. var vEnd = new THREE.Vector3();
  8981. var interSegment = new THREE.Vector3();
  8982. var interRay = new THREE.Vector3();
  8983. var step = this.mode === THREE.LineStrip ? 1 : 2;
  8984. if ( geometry instanceof THREE.BufferGeometry ) {
  8985. var attributes = geometry.attributes;
  8986. if ( attributes.index !== undefined ) {
  8987. var indices = attributes.index.array;
  8988. var positions = attributes.position.array;
  8989. var offsets = geometry.offsets;
  8990. if ( offsets.length === 0 ) {
  8991. offsets = [ { start: 0, count: indices.length, index: 0 } ];
  8992. }
  8993. for ( var oi = 0; oi < offsets.length; oi ++) {
  8994. var start = offsets[ oi ].start;
  8995. var count = offsets[ oi ].count;
  8996. var index = offsets[ oi ].index;
  8997. for ( var i = start; i < start + count - 1; i += step ) {
  8998. var a = index + indices[ i ];
  8999. var b = index + indices[ i + 1 ];
  9000. vStart.fromArray( positions, a * 3 );
  9001. vEnd.fromArray( positions, b * 3 );
  9002. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  9003. if ( distSq > precisionSq ) continue;
  9004. var distance = ray.origin.distanceTo( interRay );
  9005. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  9006. intersects.push( {
  9007. distance: distance,
  9008. // What do we want? intersection point on the ray or on the segment??
  9009. // point: raycaster.ray.at( distance ),
  9010. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  9011. index: i,
  9012. offsetIndex: oi,
  9013. face: null,
  9014. faceIndex: null,
  9015. object: this
  9016. } );
  9017. }
  9018. }
  9019. } else {
  9020. var positions = attributes.position.array;
  9021. for ( var i = 0; i < positions.length / 3 - 1; i += step ) {
  9022. vStart.fromArray( positions, 3 * i );
  9023. vEnd.fromArray( positions, 3 * i + 3 );
  9024. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  9025. if ( distSq > precisionSq ) continue;
  9026. var distance = ray.origin.distanceTo( interRay );
  9027. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  9028. intersects.push( {
  9029. distance: distance,
  9030. // What do we want? intersection point on the ray or on the segment??
  9031. // point: raycaster.ray.at( distance ),
  9032. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  9033. index: i,
  9034. face: null,
  9035. faceIndex: null,
  9036. object: this
  9037. } );
  9038. }
  9039. }
  9040. } else if ( geometry instanceof THREE.Geometry ) {
  9041. var vertices = geometry.vertices;
  9042. var nbVertices = vertices.length;
  9043. for ( var i = 0; i < nbVertices - 1; i += step ) {
  9044. var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  9045. if ( distSq > precisionSq ) continue;
  9046. var distance = ray.origin.distanceTo( interRay );
  9047. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  9048. intersects.push( {
  9049. distance: distance,
  9050. // What do we want? intersection point on the ray or on the segment??
  9051. // point: raycaster.ray.at( distance ),
  9052. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  9053. index: i,
  9054. face: null,
  9055. faceIndex: null,
  9056. object: this
  9057. } );
  9058. }
  9059. }
  9060. };
  9061. }() );
  9062. THREE.Line.prototype.clone = function ( object ) {
  9063. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.mode );
  9064. THREE.Object3D.prototype.clone.call( this, object );
  9065. return object;
  9066. };
  9067. // File:src/objects/Mesh.js
  9068. /**
  9069. * @author mrdoob / http://mrdoob.com/
  9070. * @author alteredq / http://alteredqualia.com/
  9071. * @author mikael emtinger / http://gomo.se/
  9072. * @author jonobr1 / http://jonobr1.com/
  9073. */
  9074. THREE.Mesh = function ( geometry, material ) {
  9075. THREE.Object3D.call( this );
  9076. this.type = 'Mesh';
  9077. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  9078. this.material = material !== undefined ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  9079. this.updateMorphTargets();
  9080. };
  9081. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  9082. THREE.Mesh.prototype.constructor = THREE.Mesh;
  9083. THREE.Mesh.prototype.updateMorphTargets = function () {
  9084. if ( this.geometry.morphTargets !== undefined && this.geometry.morphTargets.length > 0 ) {
  9085. this.morphTargetBase = - 1;
  9086. this.morphTargetForcedOrder = [];
  9087. this.morphTargetInfluences = [];
  9088. this.morphTargetDictionary = {};
  9089. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  9090. this.morphTargetInfluences.push( 0 );
  9091. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  9092. }
  9093. }
  9094. };
  9095. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  9096. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  9097. return this.morphTargetDictionary[ name ];
  9098. }
  9099. THREE.warn( 'THREE.Mesh.getMorphTargetIndexByName: morph target ' + name + ' does not exist. Returning 0.' );
  9100. return 0;
  9101. };
  9102. THREE.Mesh.prototype.raycast = ( function () {
  9103. var inverseMatrix = new THREE.Matrix4();
  9104. var ray = new THREE.Ray();
  9105. var sphere = new THREE.Sphere();
  9106. var vA = new THREE.Vector3();
  9107. var vB = new THREE.Vector3();
  9108. var vC = new THREE.Vector3();
  9109. return function ( raycaster, intersects ) {
  9110. var geometry = this.geometry;
  9111. // Checking boundingSphere distance to ray
  9112. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9113. sphere.copy( geometry.boundingSphere );
  9114. sphere.applyMatrix4( this.matrixWorld );
  9115. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  9116. return;
  9117. }
  9118. // Check boundingBox before continuing
  9119. inverseMatrix.getInverse( this.matrixWorld );
  9120. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  9121. if ( geometry.boundingBox !== null ) {
  9122. if ( ray.isIntersectionBox( geometry.boundingBox ) === false ) {
  9123. return;
  9124. }
  9125. }
  9126. if ( geometry instanceof THREE.BufferGeometry ) {
  9127. var material = this.material;
  9128. if ( material === undefined ) return;
  9129. var attributes = geometry.attributes;
  9130. var a, b, c;
  9131. var precision = raycaster.precision;
  9132. if ( attributes.index !== undefined ) {
  9133. var indices = attributes.index.array;
  9134. var positions = attributes.position.array;
  9135. var offsets = geometry.offsets;
  9136. if ( offsets.length === 0 ) {
  9137. offsets = [ { start: 0, count: indices.length, index: 0 } ];
  9138. }
  9139. for ( var oi = 0, ol = offsets.length; oi < ol; ++ oi ) {
  9140. var start = offsets[ oi ].start;
  9141. var count = offsets[ oi ].count;
  9142. var index = offsets[ oi ].index;
  9143. for ( var i = start, il = start + count; i < il; i += 3 ) {
  9144. a = index + indices[ i ];
  9145. b = index + indices[ i + 1 ];
  9146. c = index + indices[ i + 2 ];
  9147. vA.fromArray( positions, a * 3 );
  9148. vB.fromArray( positions, b * 3 );
  9149. vC.fromArray( positions, c * 3 );
  9150. if ( material.side === THREE.BackSide ) {
  9151. var intersectionPoint = ray.intersectTriangle( vC, vB, vA, true );
  9152. } else {
  9153. var intersectionPoint = ray.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );
  9154. }
  9155. if ( intersectionPoint === null ) continue;
  9156. intersectionPoint.applyMatrix4( this.matrixWorld );
  9157. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  9158. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  9159. intersects.push( {
  9160. distance: distance,
  9161. point: intersectionPoint,
  9162. face: new THREE.Face3( a, b, c, THREE.Triangle.normal( vA, vB, vC ) ),
  9163. faceIndex: null,
  9164. object: this
  9165. } );
  9166. }
  9167. }
  9168. } else {
  9169. var positions = attributes.position.array;
  9170. for ( var i = 0, j = 0, il = positions.length; i < il; i += 3, j += 9 ) {
  9171. a = i;
  9172. b = i + 1;
  9173. c = i + 2;
  9174. vA.fromArray( positions, j );
  9175. vB.fromArray( positions, j + 3 );
  9176. vC.fromArray( positions, j + 6 );
  9177. if ( material.side === THREE.BackSide ) {
  9178. var intersectionPoint = ray.intersectTriangle( vC, vB, vA, true );
  9179. } else {
  9180. var intersectionPoint = ray.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );
  9181. }
  9182. if ( intersectionPoint === null ) continue;
  9183. intersectionPoint.applyMatrix4( this.matrixWorld );
  9184. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  9185. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  9186. intersects.push( {
  9187. distance: distance,
  9188. point: intersectionPoint,
  9189. face: new THREE.Face3( a, b, c, THREE.Triangle.normal( vA, vB, vC ) ),
  9190. faceIndex: null,
  9191. object: this
  9192. } );
  9193. }
  9194. }
  9195. } else if ( geometry instanceof THREE.Geometry ) {
  9196. var isFaceMaterial = this.material instanceof THREE.MeshFaceMaterial;
  9197. var objectMaterials = isFaceMaterial === true ? this.material.materials : null;
  9198. var a, b, c;
  9199. var precision = raycaster.precision;
  9200. var vertices = geometry.vertices;
  9201. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  9202. var face = geometry.faces[ f ];
  9203. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : this.material;
  9204. if ( material === undefined ) continue;
  9205. a = vertices[ face.a ];
  9206. b = vertices[ face.b ];
  9207. c = vertices[ face.c ];
  9208. if ( material.morphTargets === true ) {
  9209. var morphTargets = geometry.morphTargets;
  9210. var morphInfluences = this.morphTargetInfluences;
  9211. vA.set( 0, 0, 0 );
  9212. vB.set( 0, 0, 0 );
  9213. vC.set( 0, 0, 0 );
  9214. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  9215. var influence = morphInfluences[ t ];
  9216. if ( influence === 0 ) continue;
  9217. var targets = morphTargets[ t ].vertices;
  9218. vA.x += ( targets[ face.a ].x - a.x ) * influence;
  9219. vA.y += ( targets[ face.a ].y - a.y ) * influence;
  9220. vA.z += ( targets[ face.a ].z - a.z ) * influence;
  9221. vB.x += ( targets[ face.b ].x - b.x ) * influence;
  9222. vB.y += ( targets[ face.b ].y - b.y ) * influence;
  9223. vB.z += ( targets[ face.b ].z - b.z ) * influence;
  9224. vC.x += ( targets[ face.c ].x - c.x ) * influence;
  9225. vC.y += ( targets[ face.c ].y - c.y ) * influence;
  9226. vC.z += ( targets[ face.c ].z - c.z ) * influence;
  9227. }
  9228. vA.add( a );
  9229. vB.add( b );
  9230. vC.add( c );
  9231. a = vA;
  9232. b = vB;
  9233. c = vC;
  9234. }
  9235. if ( material.side === THREE.BackSide ) {
  9236. var intersectionPoint = ray.intersectTriangle( c, b, a, true );
  9237. } else {
  9238. var intersectionPoint = ray.intersectTriangle( a, b, c, material.side !== THREE.DoubleSide );
  9239. }
  9240. if ( intersectionPoint === null ) continue;
  9241. intersectionPoint.applyMatrix4( this.matrixWorld );
  9242. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  9243. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  9244. intersects.push( {
  9245. distance: distance,
  9246. point: intersectionPoint,
  9247. face: face,
  9248. faceIndex: f,
  9249. object: this
  9250. } );
  9251. }
  9252. }
  9253. };
  9254. }() );
  9255. THREE.Mesh.prototype.clone = function ( object, recursive ) {
  9256. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  9257. THREE.Object3D.prototype.clone.call( this, object, recursive );
  9258. return object;
  9259. };
  9260. // File:src/objects/Bone.js
  9261. /**
  9262. * @author mikael emtinger / http://gomo.se/
  9263. * @author alteredq / http://alteredqualia.com/
  9264. * @author ikerr / http://verold.com
  9265. */
  9266. THREE.Bone = function ( skin ) {
  9267. THREE.Object3D.call( this );
  9268. this.type = 'Bone';
  9269. this.skin = skin;
  9270. };
  9271. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  9272. THREE.Bone.prototype.constructor = THREE.Bone;
  9273. // File:src/objects/Skeleton.js
  9274. /**
  9275. * @author mikael emtinger / http://gomo.se/
  9276. * @author alteredq / http://alteredqualia.com/
  9277. * @author michael guerrero / http://realitymeltdown.com
  9278. * @author ikerr / http://verold.com
  9279. */
  9280. THREE.Skeleton = function ( bones, boneInverses, useVertexTexture ) {
  9281. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  9282. this.identityMatrix = new THREE.Matrix4();
  9283. // copy the bone array
  9284. bones = bones || [];
  9285. this.bones = bones.slice( 0 );
  9286. // create a bone texture or an array of floats
  9287. if ( this.useVertexTexture ) {
  9288. // layout (1 matrix = 4 pixels)
  9289. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  9290. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  9291. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  9292. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  9293. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  9294. var size;
  9295. if ( this.bones.length > 256 )
  9296. size = 64;
  9297. else if ( this.bones.length > 64 )
  9298. size = 32;
  9299. else if ( this.bones.length > 16 )
  9300. size = 16;
  9301. else
  9302. size = 8;
  9303. this.boneTextureWidth = size;
  9304. this.boneTextureHeight = size;
  9305. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  9306. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  9307. this.boneTexture.minFilter = THREE.NearestFilter;
  9308. this.boneTexture.magFilter = THREE.NearestFilter;
  9309. this.boneTexture.generateMipmaps = false;
  9310. this.boneTexture.flipY = false;
  9311. } else {
  9312. this.boneMatrices = new Float32Array( 16 * this.bones.length );
  9313. }
  9314. // use the supplied bone inverses or calculate the inverses
  9315. if ( boneInverses === undefined ) {
  9316. this.calculateInverses();
  9317. } else {
  9318. if ( this.bones.length === boneInverses.length ) {
  9319. this.boneInverses = boneInverses.slice( 0 );
  9320. } else {
  9321. THREE.warn( 'THREE.Skeleton bonInverses is the wrong length.' );
  9322. this.boneInverses = [];
  9323. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  9324. this.boneInverses.push( new THREE.Matrix4() );
  9325. }
  9326. }
  9327. }
  9328. };
  9329. THREE.Skeleton.prototype.calculateInverses = function () {
  9330. this.boneInverses = [];
  9331. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  9332. var inverse = new THREE.Matrix4();
  9333. if ( this.bones[ b ] ) {
  9334. inverse.getInverse( this.bones[ b ].matrixWorld );
  9335. }
  9336. this.boneInverses.push( inverse );
  9337. }
  9338. };
  9339. THREE.Skeleton.prototype.pose = function () {
  9340. var bone;
  9341. // recover the bind-time world matrices
  9342. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  9343. bone = this.bones[ b ];
  9344. if ( bone ) {
  9345. bone.matrixWorld.getInverse( this.boneInverses[ b ] );
  9346. }
  9347. }
  9348. // compute the local matrices, positions, rotations and scales
  9349. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  9350. bone = this.bones[ b ];
  9351. if ( bone ) {
  9352. if ( bone.parent ) {
  9353. bone.matrix.getInverse( bone.parent.matrixWorld );
  9354. bone.matrix.multiply( bone.matrixWorld );
  9355. } else {
  9356. bone.matrix.copy( bone.matrixWorld );
  9357. }
  9358. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  9359. }
  9360. }
  9361. };
  9362. THREE.Skeleton.prototype.update = ( function () {
  9363. var offsetMatrix = new THREE.Matrix4();
  9364. return function () {
  9365. // flatten bone matrices to array
  9366. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  9367. // compute the offset between the current and the original transform
  9368. var matrix = this.bones[ b ] ? this.bones[ b ].matrixWorld : this.identityMatrix;
  9369. offsetMatrix.multiplyMatrices( matrix, this.boneInverses[ b ] );
  9370. offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  9371. }
  9372. if ( this.useVertexTexture ) {
  9373. this.boneTexture.needsUpdate = true;
  9374. }
  9375. };
  9376. } )();
  9377. // File:src/objects/SkinnedMesh.js
  9378. /**
  9379. * @author mikael emtinger / http://gomo.se/
  9380. * @author alteredq / http://alteredqualia.com/
  9381. * @author ikerr / http://verold.com
  9382. */
  9383. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  9384. THREE.Mesh.call( this, geometry, material );
  9385. this.type = 'SkinnedMesh';
  9386. this.bindMode = "attached";
  9387. this.bindMatrix = new THREE.Matrix4();
  9388. this.bindMatrixInverse = new THREE.Matrix4();
  9389. // init bones
  9390. // TODO: remove bone creation as there is no reason (other than
  9391. // convenience) for THREE.SkinnedMesh to do this.
  9392. var bones = [];
  9393. if ( this.geometry && this.geometry.bones !== undefined ) {
  9394. var bone, gbone, p, q, s;
  9395. for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {
  9396. gbone = this.geometry.bones[ b ];
  9397. p = gbone.pos;
  9398. q = gbone.rotq;
  9399. s = gbone.scl;
  9400. bone = new THREE.Bone( this );
  9401. bones.push( bone );
  9402. bone.name = gbone.name;
  9403. bone.position.set( p[ 0 ], p[ 1 ], p[ 2 ] );
  9404. bone.quaternion.set( q[ 0 ], q[ 1 ], q[ 2 ], q[ 3 ] );
  9405. if ( s !== undefined ) {
  9406. bone.scale.set( s[ 0 ], s[ 1 ], s[ 2 ] );
  9407. } else {
  9408. bone.scale.set( 1, 1, 1 );
  9409. }
  9410. }
  9411. for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {
  9412. gbone = this.geometry.bones[ b ];
  9413. if ( gbone.parent !== - 1 ) {
  9414. bones[ gbone.parent ].add( bones[ b ] );
  9415. } else {
  9416. this.add( bones[ b ] );
  9417. }
  9418. }
  9419. }
  9420. this.normalizeSkinWeights();
  9421. this.updateMatrixWorld( true );
  9422. this.bind( new THREE.Skeleton( bones, undefined, useVertexTexture ) );
  9423. };
  9424. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  9425. THREE.SkinnedMesh.prototype.constructor = THREE.SkinnedMesh;
  9426. THREE.SkinnedMesh.prototype.bind = function( skeleton, bindMatrix ) {
  9427. this.skeleton = skeleton;
  9428. if ( bindMatrix === undefined ) {
  9429. this.updateMatrixWorld( true );
  9430. bindMatrix = this.matrixWorld;
  9431. }
  9432. this.bindMatrix.copy( bindMatrix );
  9433. this.bindMatrixInverse.getInverse( bindMatrix );
  9434. };
  9435. THREE.SkinnedMesh.prototype.pose = function () {
  9436. this.skeleton.pose();
  9437. };
  9438. THREE.SkinnedMesh.prototype.normalizeSkinWeights = function () {
  9439. if ( this.geometry instanceof THREE.Geometry ) {
  9440. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  9441. var sw = this.geometry.skinWeights[ i ];
  9442. var scale = 1.0 / sw.lengthManhattan();
  9443. if ( scale !== Infinity ) {
  9444. sw.multiplyScalar( scale );
  9445. } else {
  9446. sw.set( 1 ); // this will be normalized by the shader anyway
  9447. }
  9448. }
  9449. } else {
  9450. // skinning weights assumed to be normalized for THREE.BufferGeometry
  9451. }
  9452. };
  9453. THREE.SkinnedMesh.prototype.updateMatrixWorld = function( force ) {
  9454. THREE.Mesh.prototype.updateMatrixWorld.call( this, true );
  9455. if ( this.bindMode === "attached" ) {
  9456. this.bindMatrixInverse.getInverse( this.matrixWorld );
  9457. } else if ( this.bindMode === "detached" ) {
  9458. this.bindMatrixInverse.getInverse( this.bindMatrix );
  9459. } else {
  9460. THREE.warn( 'THREE.SkinnedMesh unreckognized bindMode: ' + this.bindMode );
  9461. }
  9462. };
  9463. THREE.SkinnedMesh.prototype.clone = function( object ) {
  9464. if ( object === undefined ) {
  9465. object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  9466. }
  9467. THREE.Mesh.prototype.clone.call( this, object );
  9468. return object;
  9469. };
  9470. // File:src/objects/MorphAnimMesh.js
  9471. /**
  9472. * @author alteredq / http://alteredqualia.com/
  9473. */
  9474. THREE.MorphAnimMesh = function ( geometry, material ) {
  9475. THREE.Mesh.call( this, geometry, material );
  9476. this.type = 'MorphAnimMesh';
  9477. // API
  9478. this.duration = 1000; // milliseconds
  9479. this.mirroredLoop = false;
  9480. this.time = 0;
  9481. // internals
  9482. this.lastKeyframe = 0;
  9483. this.currentKeyframe = 0;
  9484. this.direction = 1;
  9485. this.directionBackwards = false;
  9486. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  9487. };
  9488. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  9489. THREE.MorphAnimMesh.prototype.constructor = THREE.MorphAnimMesh;
  9490. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  9491. this.startKeyframe = start;
  9492. this.endKeyframe = end;
  9493. this.length = this.endKeyframe - this.startKeyframe + 1;
  9494. };
  9495. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  9496. this.direction = 1;
  9497. this.directionBackwards = false;
  9498. };
  9499. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  9500. this.direction = - 1;
  9501. this.directionBackwards = true;
  9502. };
  9503. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  9504. var geometry = this.geometry;
  9505. if ( ! geometry.animations ) geometry.animations = {};
  9506. var firstAnimation, animations = geometry.animations;
  9507. var pattern = /([a-z]+)_?(\d+)/;
  9508. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  9509. var morph = geometry.morphTargets[ i ];
  9510. var parts = morph.name.match( pattern );
  9511. if ( parts && parts.length > 1 ) {
  9512. var label = parts[ 1 ];
  9513. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: - Infinity };
  9514. var animation = animations[ label ];
  9515. if ( i < animation.start ) animation.start = i;
  9516. if ( i > animation.end ) animation.end = i;
  9517. if ( ! firstAnimation ) firstAnimation = label;
  9518. }
  9519. }
  9520. geometry.firstAnimation = firstAnimation;
  9521. };
  9522. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  9523. if ( ! this.geometry.animations ) this.geometry.animations = {};
  9524. this.geometry.animations[ label ] = { start: start, end: end };
  9525. };
  9526. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  9527. var animation = this.geometry.animations[ label ];
  9528. if ( animation ) {
  9529. this.setFrameRange( animation.start, animation.end );
  9530. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  9531. this.time = 0;
  9532. } else {
  9533. THREE.warn( 'THREE.MorphAnimMesh: animation[' + label + '] undefined in .playAnimation()' );
  9534. }
  9535. };
  9536. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  9537. var frameTime = this.duration / this.length;
  9538. this.time += this.direction * delta;
  9539. if ( this.mirroredLoop ) {
  9540. if ( this.time > this.duration || this.time < 0 ) {
  9541. this.direction *= - 1;
  9542. if ( this.time > this.duration ) {
  9543. this.time = this.duration;
  9544. this.directionBackwards = true;
  9545. }
  9546. if ( this.time < 0 ) {
  9547. this.time = 0;
  9548. this.directionBackwards = false;
  9549. }
  9550. }
  9551. } else {
  9552. this.time = this.time % this.duration;
  9553. if ( this.time < 0 ) this.time += this.duration;
  9554. }
  9555. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  9556. if ( keyframe !== this.currentKeyframe ) {
  9557. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  9558. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  9559. this.morphTargetInfluences[ keyframe ] = 0;
  9560. this.lastKeyframe = this.currentKeyframe;
  9561. this.currentKeyframe = keyframe;
  9562. }
  9563. var mix = ( this.time % frameTime ) / frameTime;
  9564. if ( this.directionBackwards ) {
  9565. mix = 1 - mix;
  9566. }
  9567. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  9568. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  9569. };
  9570. THREE.MorphAnimMesh.prototype.interpolateTargets = function ( a, b, t ) {
  9571. var influences = this.morphTargetInfluences;
  9572. for ( var i = 0, l = influences.length; i < l; i ++ ) {
  9573. influences[ i ] = 0;
  9574. }
  9575. if ( a > -1 ) influences[ a ] = 1 - t;
  9576. if ( b > -1 ) influences[ b ] = t;
  9577. };
  9578. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  9579. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  9580. object.duration = this.duration;
  9581. object.mirroredLoop = this.mirroredLoop;
  9582. object.time = this.time;
  9583. object.lastKeyframe = this.lastKeyframe;
  9584. object.currentKeyframe = this.currentKeyframe;
  9585. object.direction = this.direction;
  9586. object.directionBackwards = this.directionBackwards;
  9587. THREE.Mesh.prototype.clone.call( this, object );
  9588. return object;
  9589. };
  9590. // File:src/objects/LOD.js
  9591. /**
  9592. * @author mikael emtinger / http://gomo.se/
  9593. * @author alteredq / http://alteredqualia.com/
  9594. * @author mrdoob / http://mrdoob.com/
  9595. */
  9596. THREE.LOD = function () {
  9597. THREE.Object3D.call( this );
  9598. this.objects = [];
  9599. };
  9600. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  9601. THREE.LOD.prototype.constructor = THREE.LOD;
  9602. THREE.LOD.prototype.addLevel = function ( object, distance ) {
  9603. if ( distance === undefined ) distance = 0;
  9604. distance = Math.abs( distance );
  9605. for ( var l = 0; l < this.objects.length; l ++ ) {
  9606. if ( distance < this.objects[ l ].distance ) {
  9607. break;
  9608. }
  9609. }
  9610. this.objects.splice( l, 0, { distance: distance, object: object } );
  9611. this.add( object );
  9612. };
  9613. THREE.LOD.prototype.getObjectForDistance = function ( distance ) {
  9614. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  9615. if ( distance < this.objects[ i ].distance ) {
  9616. break;
  9617. }
  9618. }
  9619. return this.objects[ i - 1 ].object;
  9620. };
  9621. THREE.LOD.prototype.raycast = ( function () {
  9622. var matrixPosition = new THREE.Vector3();
  9623. return function ( raycaster, intersects ) {
  9624. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  9625. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  9626. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  9627. };
  9628. }() );
  9629. THREE.LOD.prototype.update = function () {
  9630. var v1 = new THREE.Vector3();
  9631. var v2 = new THREE.Vector3();
  9632. return function ( camera ) {
  9633. if ( this.objects.length > 1 ) {
  9634. v1.setFromMatrixPosition( camera.matrixWorld );
  9635. v2.setFromMatrixPosition( this.matrixWorld );
  9636. var distance = v1.distanceTo( v2 );
  9637. this.objects[ 0 ].object.visible = true;
  9638. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  9639. if ( distance >= this.objects[ i ].distance ) {
  9640. this.objects[ i - 1 ].object.visible = false;
  9641. this.objects[ i ].object.visible = true;
  9642. } else {
  9643. break;
  9644. }
  9645. }
  9646. for ( ; i < l; i ++ ) {
  9647. this.objects[ i ].object.visible = false;
  9648. }
  9649. }
  9650. };
  9651. }();
  9652. THREE.LOD.prototype.clone = function ( object ) {
  9653. if ( object === undefined ) object = new THREE.LOD();
  9654. THREE.Object3D.prototype.clone.call( this, object );
  9655. for ( var i = 0, l = this.objects.length; i < l; i ++ ) {
  9656. var x = this.objects[ i ].object.clone();
  9657. x.visible = i === 0;
  9658. object.addLevel( x, this.objects[ i ].distance );
  9659. }
  9660. return object;
  9661. };
  9662. // File:src/objects/Sprite.js
  9663. /**
  9664. * @author mikael emtinger / http://gomo.se/
  9665. * @author alteredq / http://alteredqualia.com/
  9666. */
  9667. THREE.Sprite = ( function () {
  9668. var indices = new Uint16Array( [ 0, 1, 2, 0, 2, 3 ] );
  9669. var vertices = new Float32Array( [ - 0.5, - 0.5, 0, 0.5, - 0.5, 0, 0.5, 0.5, 0, - 0.5, 0.5, 0 ] );
  9670. var uvs = new Float32Array( [ 0, 0, 1, 0, 1, 1, 0, 1 ] );
  9671. var geometry = new THREE.BufferGeometry();
  9672. geometry.addAttribute( 'index', new THREE.BufferAttribute( indices, 1 ) );
  9673. geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  9674. geometry.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) );
  9675. return function ( material ) {
  9676. THREE.Object3D.call( this );
  9677. this.type = 'Sprite';
  9678. this.geometry = geometry;
  9679. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  9680. };
  9681. } )();
  9682. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  9683. THREE.Sprite.prototype.constructor = THREE.Sprite;
  9684. THREE.Sprite.prototype.raycast = ( function () {
  9685. var matrixPosition = new THREE.Vector3();
  9686. return function ( raycaster, intersects ) {
  9687. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  9688. var distance = raycaster.ray.distanceToPoint( matrixPosition );
  9689. if ( distance > this.scale.x ) {
  9690. return;
  9691. }
  9692. intersects.push( {
  9693. distance: distance,
  9694. point: this.position,
  9695. face: null,
  9696. object: this
  9697. } );
  9698. };
  9699. }() );
  9700. THREE.Sprite.prototype.clone = function ( object ) {
  9701. if ( object === undefined ) object = new THREE.Sprite( this.material );
  9702. THREE.Object3D.prototype.clone.call( this, object );
  9703. return object;
  9704. };
  9705. // Backwards compatibility
  9706. THREE.Particle = THREE.Sprite;
  9707. // File:src/objects/LensFlare.js
  9708. /**
  9709. * @author mikael emtinger / http://gomo.se/
  9710. * @author alteredq / http://alteredqualia.com/
  9711. */
  9712. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  9713. THREE.Object3D.call( this );
  9714. this.lensFlares = [];
  9715. this.positionScreen = new THREE.Vector3();
  9716. this.customUpdateCallback = undefined;
  9717. if ( texture !== undefined ) {
  9718. this.add( texture, size, distance, blending, color );
  9719. }
  9720. };
  9721. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  9722. THREE.LensFlare.prototype.constructor = THREE.LensFlare;
  9723. /*
  9724. * Add: adds another flare
  9725. */
  9726. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  9727. if ( size === undefined ) size = - 1;
  9728. if ( distance === undefined ) distance = 0;
  9729. if ( opacity === undefined ) opacity = 1;
  9730. if ( color === undefined ) color = new THREE.Color( 0xffffff );
  9731. if ( blending === undefined ) blending = THREE.NormalBlending;
  9732. distance = Math.min( distance, Math.max( 0, distance ) );
  9733. this.lensFlares.push( {
  9734. texture: texture, // THREE.Texture
  9735. size: size, // size in pixels (-1 = use texture.width)
  9736. distance: distance, // distance (0-1) from light source (0=at light source)
  9737. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  9738. scale: 1, // scale
  9739. rotation: 1, // rotation
  9740. opacity: opacity, // opacity
  9741. color: color, // color
  9742. blending: blending // blending
  9743. } );
  9744. };
  9745. /*
  9746. * Update lens flares update positions on all flares based on the screen position
  9747. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  9748. */
  9749. THREE.LensFlare.prototype.updateLensFlares = function () {
  9750. var f, fl = this.lensFlares.length;
  9751. var flare;
  9752. var vecX = - this.positionScreen.x * 2;
  9753. var vecY = - this.positionScreen.y * 2;
  9754. for ( f = 0; f < fl; f ++ ) {
  9755. flare = this.lensFlares[ f ];
  9756. flare.x = this.positionScreen.x + vecX * flare.distance;
  9757. flare.y = this.positionScreen.y + vecY * flare.distance;
  9758. flare.wantedRotation = flare.x * Math.PI * 0.25;
  9759. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  9760. }
  9761. };
  9762. // File:src/scenes/Scene.js
  9763. /**
  9764. * @author mrdoob / http://mrdoob.com/
  9765. */
  9766. THREE.Scene = function () {
  9767. THREE.Object3D.call( this );
  9768. this.type = 'Scene';
  9769. this.fog = null;
  9770. this.overrideMaterial = null;
  9771. this.autoUpdate = true; // checked by the renderer
  9772. };
  9773. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  9774. THREE.Scene.prototype.constructor = THREE.Scene;
  9775. THREE.Scene.prototype.clone = function ( object ) {
  9776. if ( object === undefined ) object = new THREE.Scene();
  9777. THREE.Object3D.prototype.clone.call( this, object );
  9778. if ( this.fog !== null ) object.fog = this.fog.clone();
  9779. if ( this.overrideMaterial !== null ) object.overrideMaterial = this.overrideMaterial.clone();
  9780. object.autoUpdate = this.autoUpdate;
  9781. object.matrixAutoUpdate = this.matrixAutoUpdate;
  9782. return object;
  9783. };
  9784. // File:src/scenes/Fog.js
  9785. /**
  9786. * @author mrdoob / http://mrdoob.com/
  9787. * @author alteredq / http://alteredqualia.com/
  9788. */
  9789. THREE.Fog = function ( color, near, far ) {
  9790. this.name = '';
  9791. this.color = new THREE.Color( color );
  9792. this.near = ( near !== undefined ) ? near : 1;
  9793. this.far = ( far !== undefined ) ? far : 1000;
  9794. };
  9795. THREE.Fog.prototype.clone = function () {
  9796. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  9797. };
  9798. // File:src/scenes/FogExp2.js
  9799. /**
  9800. * @author mrdoob / http://mrdoob.com/
  9801. * @author alteredq / http://alteredqualia.com/
  9802. */
  9803. THREE.FogExp2 = function ( color, density ) {
  9804. this.name = '';
  9805. this.color = new THREE.Color( color );
  9806. this.density = ( density !== undefined ) ? density : 0.00025;
  9807. };
  9808. THREE.FogExp2.prototype.clone = function () {
  9809. return new THREE.FogExp2( this.color.getHex(), this.density );
  9810. };
  9811. // File:src/renderers/shaders/ShaderChunk.js
  9812. THREE.ShaderChunk = {};
  9813. // File:src/renderers/shaders/ShaderChunk/common.glsl
  9814. 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\nfloat square( in float a ) { return a*a; }\nvec2 square( in vec2 a ) { return vec2( a.x*a.x, a.y*a.y ); }\nvec3 square( in vec3 a ) { return vec3( a.x*a.x, a.y*a.y, a.z*a.z ); }\nvec4 square( in vec4 a ) { return vec4( a.x*a.x, a.y*a.y, a.z*a.z, a.w*a.w ); }\nfloat saturate( in float a ) { return clamp( a, 0.0, 1.0 ); }\nvec2 saturate( in vec2 a ) { return clamp( a, 0.0, 1.0 ); }\nvec3 saturate( in vec3 a ) { return clamp( a, 0.0, 1.0 ); }\nvec4 saturate( in vec4 a ) { return clamp( a, 0.0, 1.0 ); }\nfloat average( in float a ) { return a; }\nfloat average( in vec2 a ) { return ( a.x + a.y) * 0.5; }\nfloat average( in vec3 a ) { return ( a.x + a.y + a.z) / 3.0; }\nfloat average( in vec4 a ) { return ( a.x + a.y + a.z + a.w) * 0.25; }\nfloat whiteCompliment( in float a ) { return saturate( 1.0 - a ); }\nvec2 whiteCompliment( in vec2 a ) { return saturate( vec2(1.0) - a ); }\nvec3 whiteCompliment( in vec3 a ) { return saturate( vec3(1.0) - a ); }\nvec4 whiteCompliment( in vec4 a ) { return saturate( vec4(1.0) - a ); }\nvec3 transformDirection( in vec3 normal, in mat4 matrix ) {\n return normalize( ( matrix * vec4( normal, 0.0 ) ).xyz );\n}\n// http://en.wikibooks.org/wiki/GLSL_Programming/Applying_Matrix_Transformations\nvec3 inverseTransformDirection( in vec3 normal, in mat4 matrix ) {\n return normalize( ( vec4( normal, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal) {\n float distance = dot( planeNormal, point-pointOnPlane );\n return point - distance * planeNormal;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n return sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n return pointOnLine + lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) );\n}\nfloat calcLightAttenuation( float lightDistance, float cutoffDistance, float decayExponent ) {\n if ( decayExponent > 0.0 ) {\n return pow( saturate( 1.0 - lightDistance / cutoffDistance ), decayExponent );\n }\n return 1.0;\n}\n\nvec3 inputToLinear( in vec3 a ) {\n#ifdef GAMMA_INPUT\n return pow( a, vec3( float( GAMMA_FACTOR ) ) );\n#else\n return a;\n#endif\n}\nvec3 linearToOutput( in vec3 a ) {\n#ifdef GAMMA_OUTPUT\n return pow( a, vec3( 1.0 / float( GAMMA_FACTOR ) ) );\n#else\n return a;\n#endif\n}\n";
  9815. // File:src/renderers/shaders/ShaderChunk/alphatest_fragment.glsl
  9816. THREE.ShaderChunk[ 'alphatest_fragment'] = "#ifdef ALPHATEST\n\n if ( diffuseColor.a < ALPHATEST ) discard;\n\n#endif\n";
  9817. // File:src/renderers/shaders/ShaderChunk/lights_lambert_vertex.glsl
  9818. THREE.ShaderChunk[ 'lights_lambert_vertex'] = "vLightFront = vec3( 0.0 );\n\n#ifdef DOUBLE_SIDED\n\n vLightBack = vec3( 0.0 );\n\n#endif\n\ntransformedNormal = normalize( transformedNormal );\n\n#if MAX_DIR_LIGHTS > 0\n\nfor( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {\n\n vec3 dirVector = transformDirection( directionalLightDirection[ i ], viewMatrix );\n\n float dotProduct = dot( transformedNormal, dirVector );\n vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );\n\n #ifdef DOUBLE_SIDED\n\n vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );\n\n #ifdef WRAP_AROUND\n\n vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );\n\n #endif\n\n #endif\n\n #ifdef WRAP_AROUND\n\n vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );\n directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );\n\n #ifdef DOUBLE_SIDED\n\n directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );\n\n #endif\n\n #endif\n\n vLightFront += directionalLightColor[ i ] * directionalLightWeighting;\n\n #ifdef DOUBLE_SIDED\n\n vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;\n\n #endif\n\n}\n\n#endif\n\n#if MAX_POINT_LIGHTS > 0\n\n for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {\n\n vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );\n vec3 lVector = lPosition.xyz - mvPosition.xyz;\n\n float attenuation = calcLightAttenuation( length( lVector ), pointLightDistance[ i ], pointLightDecay[ i ] );\n\n lVector = normalize( lVector );\n float dotProduct = dot( transformedNormal, lVector );\n\n vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );\n\n #ifdef DOUBLE_SIDED\n\n vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );\n\n #ifdef WRAP_AROUND\n\n vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );\n\n #endif\n\n #endif\n\n #ifdef WRAP_AROUND\n\n vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );\n pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );\n\n #ifdef DOUBLE_SIDED\n\n pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );\n\n #endif\n\n #endif\n\n vLightFront += pointLightColor[ i ] * pointLightWeighting * attenuation;\n\n #ifdef DOUBLE_SIDED\n\n vLightBack += pointLightColor[ i ] * pointLightWeightingBack * attenuation;\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 vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );\n vec3 lVector = lPosition.xyz - mvPosition.xyz;\n\n float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );\n\n if ( spotEffect > spotLightAngleCos[ i ] ) {\n\n spotEffect = max( pow( max( spotEffect, 0.0 ), spotLightExponent[ i ] ), 0.0 );\n\n float attenuation = calcLightAttenuation( length( lVector ), spotLightDistance[ i ], spotLightDecay[ i ] );\n\n lVector = normalize( lVector );\n\n float dotProduct = dot( transformedNormal, lVector );\n vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );\n\n #ifdef DOUBLE_SIDED\n\n vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );\n\n #ifdef WRAP_AROUND\n\n vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );\n\n #endif\n\n #endif\n\n #ifdef WRAP_AROUND\n\n vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );\n spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );\n\n #ifdef DOUBLE_SIDED\n\n spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );\n\n #endif\n\n #endif\n\n vLightFront += spotLightColor[ i ] * spotLightWeighting * attenuation * spotEffect;\n\n #ifdef DOUBLE_SIDED\n\n vLightBack += spotLightColor[ i ] * spotLightWeightingBack * attenuation * spotEffect;\n\n #endif\n\n }\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 lVector = transformDirection( hemisphereLightDirection[ i ], viewMatrix );\n\n float dotProduct = dot( transformedNormal, lVector );\n\n float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;\n float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;\n\n vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );\n\n #ifdef DOUBLE_SIDED\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";
  9819. // File:src/renderers/shaders/ShaderChunk/map_particle_pars_fragment.glsl
  9820. THREE.ShaderChunk[ 'map_particle_pars_fragment'] = "#ifdef USE_MAP\n\n uniform vec4 offsetRepeat;\n uniform sampler2D map;\n\n#endif\n";
  9821. // File:src/renderers/shaders/ShaderChunk/default_vertex.glsl
  9822. 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";
  9823. // File:src/renderers/shaders/ShaderChunk/map_pars_fragment.glsl
  9824. THREE.ShaderChunk[ 'map_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\n\n#ifdef USE_MAP\n\n uniform sampler2D map;\n\n#endif";
  9825. // File:src/renderers/shaders/ShaderChunk/skinnormal_vertex.glsl
  9826. 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";
  9827. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_pars_vertex.glsl
  9828. 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";
  9829. // File:src/renderers/shaders/ShaderChunk/lightmap_pars_vertex.glsl
  9830. THREE.ShaderChunk[ 'lightmap_pars_vertex'] = "#ifdef USE_LIGHTMAP\n\n varying vec2 vUv2;\n\n#endif";
  9831. // File:src/renderers/shaders/ShaderChunk/lights_phong_fragment.glsl
  9832. 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\nvec3 viewPosition = normalize( vViewPosition );\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 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 vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );\n vec3 lVector = lPosition.xyz + vViewPosition.xyz;\n\n float attenuation = calcLightAttenuation( length( lVector ), pointLightDistance[ i ], pointLightDecay[ i ] );\n\n lVector = normalize( lVector );\n\n // diffuse\n\n float dotProduct = dot( normal, lVector );\n\n #ifdef WRAP_AROUND\n\n float pointDiffuseWeightFull = max( dotProduct, 0.0 );\n float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );\n\n vec3 pointDiffuseWeight = mix( vec3( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );\n\n #else\n\n float pointDiffuseWeight = max( dotProduct, 0.0 );\n\n #endif\n\n totalDiffuseLight += pointLightColor[ i ] * pointDiffuseWeight * attenuation;\n\n // specular\n\n vec3 pointHalfVector = normalize( lVector + viewPosition );\n float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );\n float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );\n\n float specularNormalization = ( shininess + 2.0 ) / 8.0;\n\n vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, pointHalfVector ), 0.0 ), 5.0 );\n totalSpecularLight += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * attenuation * specularNormalization;\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 vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );\n vec3 lVector = lPosition.xyz + vViewPosition.xyz;\n\n float attenuation = calcLightAttenuation( length( lVector ), spotLightDistance[ i ], spotLightDecay[ i ] );\n\n lVector = normalize( lVector );\n\n float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );\n\n if ( spotEffect > spotLightAngleCos[ i ] ) {\n\n spotEffect = max( pow( max( spotEffect, 0.0 ), spotLightExponent[ i ] ), 0.0 );\n\n // diffuse\n\n float dotProduct = dot( normal, lVector );\n\n #ifdef WRAP_AROUND\n\n float spotDiffuseWeightFull = max( dotProduct, 0.0 );\n float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );\n\n vec3 spotDiffuseWeight = mix( vec3( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );\n\n #else\n\n float spotDiffuseWeight = max( dotProduct, 0.0 );\n\n #endif\n\n totalDiffuseLight += spotLightColor[ i ] * spotDiffuseWeight * attenuation * spotEffect;\n\n // specular\n\n vec3 spotHalfVector = normalize( lVector + viewPosition );\n float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );\n float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );\n\n float specularNormalization = ( shininess + 2.0 ) / 8.0;\n\n vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, spotHalfVector ), 0.0 ), 5.0 );\n totalSpecularLight += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * attenuation * specularNormalization * spotEffect;\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 dirVector = transformDirection( directionalLightDirection[ i ], viewMatrix );\n\n // diffuse\n\n float dotProduct = dot( normal, dirVector );\n\n #ifdef WRAP_AROUND\n\n float dirDiffuseWeightFull = max( dotProduct, 0.0 );\n float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );\n\n vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );\n\n #else\n\n float dirDiffuseWeight = max( dotProduct, 0.0 );\n\n #endif\n\n totalDiffuseLight += directionalLightColor[ i ] * dirDiffuseWeight;\n\n // specular\n\n vec3 dirHalfVector = normalize( dirVector + viewPosition );\n float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );\n float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );\n\n /*\n // fresnel term from skin shader\n const float F0 = 0.128;\n\n float base = 1.0 - dot( viewPosition, dirHalfVector );\n float exponential = pow( base, 5.0 );\n\n float fresnel = exponential + F0 * ( 1.0 - exponential );\n */\n\n /*\n // fresnel term from fresnel shader\n const float mFresnelBias = 0.08;\n const float mFresnelScale = 0.3;\n const float mFresnelPower = 5.0;\n\n float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );\n */\n\n float specularNormalization = ( shininess + 2.0 ) / 8.0;\n\n // dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;\n\n vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( dirVector, dirHalfVector ), 0.0 ), 5.0 );\n totalSpecularLight += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;\n\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 lVector = transformDirection( hemisphereLightDirection[ i ], viewMatrix );\n\n // diffuse\n\n float dotProduct = dot( normal, lVector );\n float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;\n\n vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );\n\n totalDiffuseLight += hemiColor;\n\n // specular (sky light)\n\n vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );\n float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;\n float hemiSpecularWeightSky = specularStrength * max( pow( max( hemiDotNormalHalfSky, 0.0 ), shininess ), 0.0 );\n\n // specular (ground light)\n\n vec3 lVectorGround = -lVector;\n\n vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );\n float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;\n float hemiSpecularWeightGround = specularStrength * max( pow( max( hemiDotNormalHalfGround, 0.0 ), shininess ), 0.0 );\n\n float dotProductGround = dot( normal, lVectorGround );\n\n float specularNormalization = ( shininess + 2.0 ) / 8.0;\n\n vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, hemiHalfVectorSky ), 0.0 ), 5.0 );\n vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 0.0 ), 5.0 );\n totalSpecularLight += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );\n\n }\n\n#endif\n\n#ifdef METAL\n\n outgoingLight += diffuseColor.rgb * ( totalDiffuseLight + ambientLightColor ) * specular + totalSpecularLight + emissive;\n\n#else\n\n outgoingLight += diffuseColor.rgb * ( totalDiffuseLight + ambientLightColor ) + totalSpecularLight + emissive;\n\n#endif\n";
  9833. // File:src/renderers/shaders/ShaderChunk/fog_pars_fragment.glsl
  9834. 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";
  9835. // File:src/renderers/shaders/ShaderChunk/morphnormal_vertex.glsl
  9836. 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";
  9837. // File:src/renderers/shaders/ShaderChunk/envmap_pars_fragment.glsl
  9838. 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";
  9839. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_fragment.glsl
  9840. THREE.ShaderChunk[ 'logdepthbuf_fragment'] = "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n\n gl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n\n#endif";
  9841. // File:src/renderers/shaders/ShaderChunk/normalmap_pars_fragment.glsl
  9842. 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";
  9843. // File:src/renderers/shaders/ShaderChunk/lights_phong_pars_vertex.glsl
  9844. 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";
  9845. // File:src/renderers/shaders/ShaderChunk/lightmap_pars_fragment.glsl
  9846. THREE.ShaderChunk[ 'lightmap_pars_fragment'] = "#ifdef USE_LIGHTMAP\n\n varying vec2 vUv2;\n uniform sampler2D lightMap;\n\n#endif";
  9847. // File:src/renderers/shaders/ShaderChunk/shadowmap_vertex.glsl
  9848. 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";
  9849. // File:src/renderers/shaders/ShaderChunk/lights_phong_vertex.glsl
  9850. THREE.ShaderChunk[ 'lights_phong_vertex'] = "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP ) || defined( USE_ENVMAP )\n\n vWorldPosition = worldPosition.xyz;\n\n#endif";
  9851. // File:src/renderers/shaders/ShaderChunk/map_fragment.glsl
  9852. 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";
  9853. // File:src/renderers/shaders/ShaderChunk/lightmap_vertex.glsl
  9854. THREE.ShaderChunk[ 'lightmap_vertex'] = "#ifdef USE_LIGHTMAP\n\n vUv2 = uv2;\n\n#endif";
  9855. // File:src/renderers/shaders/ShaderChunk/map_particle_fragment.glsl
  9856. 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";
  9857. // File:src/renderers/shaders/ShaderChunk/color_pars_fragment.glsl
  9858. THREE.ShaderChunk[ 'color_pars_fragment'] = "#ifdef USE_COLOR\n\n varying vec3 vColor;\n\n#endif\n";
  9859. // File:src/renderers/shaders/ShaderChunk/color_vertex.glsl
  9860. THREE.ShaderChunk[ 'color_vertex'] = "#ifdef USE_COLOR\n\n vColor.xyz = inputToLinear( color.xyz );\n\n#endif";
  9861. // File:src/renderers/shaders/ShaderChunk/skinning_vertex.glsl
  9862. 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";
  9863. // File:src/renderers/shaders/ShaderChunk/envmap_pars_vertex.glsl
  9864. 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";
  9865. // File:src/renderers/shaders/ShaderChunk/linear_to_gamma_fragment.glsl
  9866. THREE.ShaderChunk[ 'linear_to_gamma_fragment'] = "\n outgoingLight = linearToOutput( outgoingLight );\n";
  9867. // File:src/renderers/shaders/ShaderChunk/color_pars_vertex.glsl
  9868. THREE.ShaderChunk[ 'color_pars_vertex'] = "#ifdef USE_COLOR\n\n varying vec3 vColor;\n\n#endif";
  9869. // File:src/renderers/shaders/ShaderChunk/lights_lambert_pars_vertex.glsl
  9870. 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\n#ifdef WRAP_AROUND\n\n uniform vec3 wrapRGB;\n\n#endif\n";
  9871. // File:src/renderers/shaders/ShaderChunk/map_pars_vertex.glsl
  9872. THREE.ShaderChunk[ 'map_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";
  9873. // File:src/renderers/shaders/ShaderChunk/envmap_fragment.glsl
  9874. 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 = ( -1.0 + 2.0 * float( gl_FrontFacing ) );\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";
  9875. // File:src/renderers/shaders/ShaderChunk/specularmap_pars_fragment.glsl
  9876. THREE.ShaderChunk[ 'specularmap_pars_fragment'] = "#ifdef USE_SPECULARMAP\n\n uniform sampler2D specularMap;\n\n#endif";
  9877. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_vertex.glsl
  9878. 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";
  9879. // File:src/renderers/shaders/ShaderChunk/morphtarget_pars_vertex.glsl
  9880. 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";
  9881. // File:src/renderers/shaders/ShaderChunk/specularmap_fragment.glsl
  9882. 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";
  9883. // File:src/renderers/shaders/ShaderChunk/fog_fragment.glsl
  9884. 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 = exp2( - square( fogDensity ) * square( depth ) * LOG2 );\n fogFactor = whiteCompliment( fogFactor );\n\n #else\n\n float fogFactor = smoothstep( fogNear, fogFar, depth );\n\n #endif\n \n outgoingLight = mix( outgoingLight, fogColor, fogFactor );\n\n#endif";
  9885. // File:src/renderers/shaders/ShaderChunk/bumpmap_pars_fragment.glsl
  9886. 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";
  9887. // File:src/renderers/shaders/ShaderChunk/defaultnormal_vertex.glsl
  9888. 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";
  9889. // File:src/renderers/shaders/ShaderChunk/lights_phong_pars_fragment.glsl
  9890. 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\n#ifdef WRAP_AROUND\n\n uniform vec3 wrapRGB;\n\n#endif\n\nvarying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n\n varying vec3 vNormal;\n\n#endif\n";
  9891. // File:src/renderers/shaders/ShaderChunk/skinbase_vertex.glsl
  9892. 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";
  9893. // File:src/renderers/shaders/ShaderChunk/map_vertex.glsl
  9894. THREE.ShaderChunk[ 'map_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";
  9895. // File:src/renderers/shaders/ShaderChunk/lightmap_fragment.glsl
  9896. THREE.ShaderChunk[ 'lightmap_fragment'] = "#ifdef USE_LIGHTMAP\n\n outgoingLight *= diffuseColor.xyz * texture2D( lightMap, vUv2 ).xyz;\n\n#endif";
  9897. // File:src/renderers/shaders/ShaderChunk/shadowmap_pars_vertex.glsl
  9898. THREE.ShaderChunk[ 'shadowmap_pars_vertex'] = "#ifdef USE_SHADOWMAP\n\n varying vec4 vShadowCoord[ MAX_SHADOWS ];\n uniform mat4 shadowMatrix[ MAX_SHADOWS ];\n\n#endif";
  9899. // File:src/renderers/shaders/ShaderChunk/color_fragment.glsl
  9900. THREE.ShaderChunk[ 'color_fragment'] = "#ifdef USE_COLOR\n\n diffuseColor.rgb *= vColor;\n\n#endif";
  9901. // File:src/renderers/shaders/ShaderChunk/morphtarget_vertex.glsl
  9902. 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";
  9903. // File:src/renderers/shaders/ShaderChunk/envmap_vertex.glsl
  9904. 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";
  9905. // File:src/renderers/shaders/ShaderChunk/shadowmap_fragment.glsl
  9906. 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";
  9907. // File:src/renderers/shaders/ShaderChunk/worldpos_vertex.glsl
  9908. 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";
  9909. // File:src/renderers/shaders/ShaderChunk/shadowmap_pars_fragment.glsl
  9910. 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";
  9911. // File:src/renderers/shaders/ShaderChunk/skinning_pars_vertex.glsl
  9912. 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";
  9913. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_pars_fragment.glsl
  9914. 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";
  9915. // File:src/renderers/shaders/ShaderChunk/alphamap_fragment.glsl
  9916. THREE.ShaderChunk[ 'alphamap_fragment'] = "#ifdef USE_ALPHAMAP\n\n diffuseColor.a *= texture2D( alphaMap, vUv ).g;\n\n#endif\n";
  9917. // File:src/renderers/shaders/ShaderChunk/alphamap_pars_fragment.glsl
  9918. THREE.ShaderChunk[ 'alphamap_pars_fragment'] = "#ifdef USE_ALPHAMAP\n\n uniform sampler2D alphaMap;\n\n#endif\n";
  9919. // File:src/renderers/shaders/UniformsUtils.js
  9920. /**
  9921. * Uniform Utilities
  9922. */
  9923. THREE.UniformsUtils = {
  9924. merge: function ( uniforms ) {
  9925. var merged = {};
  9926. for ( var u = 0; u < uniforms.length; u ++ ) {
  9927. var tmp = this.clone( uniforms[ u ] );
  9928. for ( var p in tmp ) {
  9929. merged[ p ] = tmp[ p ];
  9930. }
  9931. }
  9932. return merged;
  9933. },
  9934. clone: function ( uniforms_src ) {
  9935. var uniforms_dst = {};
  9936. for ( var u in uniforms_src ) {
  9937. uniforms_dst[ u ] = {};
  9938. for ( var p in uniforms_src[ u ] ) {
  9939. var parameter_src = uniforms_src[ u ][ p ];
  9940. if ( parameter_src instanceof THREE.Color ||
  9941. parameter_src instanceof THREE.Vector2 ||
  9942. parameter_src instanceof THREE.Vector3 ||
  9943. parameter_src instanceof THREE.Vector4 ||
  9944. parameter_src instanceof THREE.Matrix4 ||
  9945. parameter_src instanceof THREE.Texture ) {
  9946. uniforms_dst[ u ][ p ] = parameter_src.clone();
  9947. } else if ( parameter_src instanceof Array ) {
  9948. uniforms_dst[ u ][ p ] = parameter_src.slice();
  9949. } else {
  9950. uniforms_dst[ u ][ p ] = parameter_src;
  9951. }
  9952. }
  9953. }
  9954. return uniforms_dst;
  9955. }
  9956. };
  9957. // File:src/renderers/shaders/UniformsLib.js
  9958. /**
  9959. * Uniforms library for shared webgl shaders
  9960. */
  9961. THREE.UniformsLib = {
  9962. common: {
  9963. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  9964. "opacity" : { type: "f", value: 1.0 },
  9965. "map" : { type: "t", value: null },
  9966. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  9967. "lightMap" : { type: "t", value: null },
  9968. "specularMap" : { type: "t", value: null },
  9969. "alphaMap" : { type: "t", value: null },
  9970. "envMap" : { type: "t", value: null },
  9971. "flipEnvMap" : { type: "f", value: - 1 },
  9972. "reflectivity" : { type: "f", value: 1.0 },
  9973. "refractionRatio" : { type: "f", value: 0.98 },
  9974. "morphTargetInfluences" : { type: "f", value: 0 }
  9975. },
  9976. bump: {
  9977. "bumpMap" : { type: "t", value: null },
  9978. "bumpScale" : { type: "f", value: 1 }
  9979. },
  9980. normalmap: {
  9981. "normalMap" : { type: "t", value: null },
  9982. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  9983. },
  9984. fog : {
  9985. "fogDensity" : { type: "f", value: 0.00025 },
  9986. "fogNear" : { type: "f", value: 1 },
  9987. "fogFar" : { type: "f", value: 2000 },
  9988. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  9989. },
  9990. lights: {
  9991. "ambientLightColor" : { type: "fv", value: [] },
  9992. "directionalLightDirection" : { type: "fv", value: [] },
  9993. "directionalLightColor" : { type: "fv", value: [] },
  9994. "hemisphereLightDirection" : { type: "fv", value: [] },
  9995. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  9996. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  9997. "pointLightColor" : { type: "fv", value: [] },
  9998. "pointLightPosition" : { type: "fv", value: [] },
  9999. "pointLightDistance" : { type: "fv1", value: [] },
  10000. "pointLightDecay" : { type: "fv1", value: [] },
  10001. "spotLightColor" : { type: "fv", value: [] },
  10002. "spotLightPosition" : { type: "fv", value: [] },
  10003. "spotLightDirection" : { type: "fv", value: [] },
  10004. "spotLightDistance" : { type: "fv1", value: [] },
  10005. "spotLightAngleCos" : { type: "fv1", value: [] },
  10006. "spotLightExponent" : { type: "fv1", value: [] },
  10007. "spotLightDecay" : { type: "fv1", value: [] }
  10008. },
  10009. particle: {
  10010. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10011. "opacity" : { type: "f", value: 1.0 },
  10012. "size" : { type: "f", value: 1.0 },
  10013. "scale" : { type: "f", value: 1.0 },
  10014. "map" : { type: "t", value: null },
  10015. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  10016. "fogDensity" : { type: "f", value: 0.00025 },
  10017. "fogNear" : { type: "f", value: 1 },
  10018. "fogFar" : { type: "f", value: 2000 },
  10019. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10020. },
  10021. shadowmap: {
  10022. "shadowMap": { type: "tv", value: [] },
  10023. "shadowMapSize": { type: "v2v", value: [] },
  10024. "shadowBias" : { type: "fv1", value: [] },
  10025. "shadowDarkness": { type: "fv1", value: [] },
  10026. "shadowMatrix" : { type: "m4v", value: [] }
  10027. }
  10028. };
  10029. // File:src/renderers/shaders/ShaderLib.js
  10030. /**
  10031. * Webgl Shader Library for three.js
  10032. *
  10033. * @author alteredq / http://alteredqualia.com/
  10034. * @author mrdoob / http://mrdoob.com/
  10035. * @author mikael emtinger / http://gomo.se/
  10036. */
  10037. THREE.ShaderLib = {
  10038. 'basic': {
  10039. uniforms: THREE.UniformsUtils.merge( [
  10040. THREE.UniformsLib[ "common" ],
  10041. THREE.UniformsLib[ "fog" ],
  10042. THREE.UniformsLib[ "shadowmap" ]
  10043. ] ),
  10044. vertexShader: [
  10045. THREE.ShaderChunk[ "common" ],
  10046. THREE.ShaderChunk[ "map_pars_vertex" ],
  10047. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10048. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10049. THREE.ShaderChunk[ "color_pars_vertex" ],
  10050. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10051. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10052. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10053. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  10054. "void main() {",
  10055. THREE.ShaderChunk[ "map_vertex" ],
  10056. THREE.ShaderChunk[ "lightmap_vertex" ],
  10057. THREE.ShaderChunk[ "color_vertex" ],
  10058. THREE.ShaderChunk[ "skinbase_vertex" ],
  10059. " #ifdef USE_ENVMAP",
  10060. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10061. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10062. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10063. " #endif",
  10064. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10065. THREE.ShaderChunk[ "skinning_vertex" ],
  10066. THREE.ShaderChunk[ "default_vertex" ],
  10067. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  10068. THREE.ShaderChunk[ "worldpos_vertex" ],
  10069. THREE.ShaderChunk[ "envmap_vertex" ],
  10070. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10071. "}"
  10072. ].join("\n"),
  10073. fragmentShader: [
  10074. "uniform vec3 diffuse;",
  10075. "uniform float opacity;",
  10076. THREE.ShaderChunk[ "common" ],
  10077. THREE.ShaderChunk[ "color_pars_fragment" ],
  10078. THREE.ShaderChunk[ "map_pars_fragment" ],
  10079. THREE.ShaderChunk[ "alphamap_pars_fragment" ],
  10080. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10081. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10082. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10083. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10084. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10085. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  10086. "void main() {",
  10087. " vec3 outgoingLight = vec3( 0.0 );", // outgoing light does not have an alpha, the surface does
  10088. " vec4 diffuseColor = vec4( diffuse, opacity );",
  10089. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  10090. THREE.ShaderChunk[ "map_fragment" ],
  10091. THREE.ShaderChunk[ "color_fragment" ],
  10092. THREE.ShaderChunk[ "alphamap_fragment" ],
  10093. THREE.ShaderChunk[ "alphatest_fragment" ],
  10094. THREE.ShaderChunk[ "specularmap_fragment" ],
  10095. " outgoingLight = diffuseColor.rgb;", // simple shader
  10096. THREE.ShaderChunk[ "lightmap_fragment" ], // TODO: Light map on an otherwise unlit surface doesn't make sense.
  10097. THREE.ShaderChunk[ "envmap_fragment" ],
  10098. THREE.ShaderChunk[ "shadowmap_fragment" ], // TODO: Shadows on an otherwise unlit surface doesn't make sense.
  10099. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10100. THREE.ShaderChunk[ "fog_fragment" ],
  10101. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );", // TODO, this should be pre-multiplied to allow for bright highlights on very transparent objects
  10102. "}"
  10103. ].join("\n")
  10104. },
  10105. 'lambert': {
  10106. uniforms: THREE.UniformsUtils.merge( [
  10107. THREE.UniformsLib[ "common" ],
  10108. THREE.UniformsLib[ "fog" ],
  10109. THREE.UniformsLib[ "lights" ],
  10110. THREE.UniformsLib[ "shadowmap" ],
  10111. {
  10112. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10113. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10114. }
  10115. ] ),
  10116. vertexShader: [
  10117. "#define LAMBERT",
  10118. "varying vec3 vLightFront;",
  10119. "#ifdef DOUBLE_SIDED",
  10120. " varying vec3 vLightBack;",
  10121. "#endif",
  10122. THREE.ShaderChunk[ "common" ],
  10123. THREE.ShaderChunk[ "map_pars_vertex" ],
  10124. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10125. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10126. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  10127. THREE.ShaderChunk[ "color_pars_vertex" ],
  10128. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10129. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10130. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10131. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  10132. "void main() {",
  10133. THREE.ShaderChunk[ "map_vertex" ],
  10134. THREE.ShaderChunk[ "lightmap_vertex" ],
  10135. THREE.ShaderChunk[ "color_vertex" ],
  10136. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10137. THREE.ShaderChunk[ "skinbase_vertex" ],
  10138. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10139. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10140. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10141. THREE.ShaderChunk[ "skinning_vertex" ],
  10142. THREE.ShaderChunk[ "default_vertex" ],
  10143. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  10144. THREE.ShaderChunk[ "worldpos_vertex" ],
  10145. THREE.ShaderChunk[ "envmap_vertex" ],
  10146. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  10147. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10148. "}"
  10149. ].join("\n"),
  10150. fragmentShader: [
  10151. "uniform vec3 diffuse;",
  10152. "uniform vec3 emissive;",
  10153. "uniform float opacity;",
  10154. "varying vec3 vLightFront;",
  10155. "#ifdef DOUBLE_SIDED",
  10156. " varying vec3 vLightBack;",
  10157. "#endif",
  10158. THREE.ShaderChunk[ "common" ],
  10159. THREE.ShaderChunk[ "color_pars_fragment" ],
  10160. THREE.ShaderChunk[ "map_pars_fragment" ],
  10161. THREE.ShaderChunk[ "alphamap_pars_fragment" ],
  10162. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10163. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10164. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10165. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10166. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10167. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  10168. "void main() {",
  10169. " vec3 outgoingLight = vec3( 0.0 );", // outgoing light does not have an alpha, the surface does
  10170. " vec4 diffuseColor = vec4( diffuse, opacity );",
  10171. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  10172. THREE.ShaderChunk[ "map_fragment" ],
  10173. THREE.ShaderChunk[ "color_fragment" ],
  10174. THREE.ShaderChunk[ "alphamap_fragment" ],
  10175. THREE.ShaderChunk[ "alphatest_fragment" ],
  10176. THREE.ShaderChunk[ "specularmap_fragment" ],
  10177. " #ifdef DOUBLE_SIDED",
  10178. //"float isFront = float( gl_FrontFacing );",
  10179. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  10180. " if ( gl_FrontFacing )",
  10181. " outgoingLight += diffuseColor.rgb * vLightFront + emissive;",
  10182. " else",
  10183. " outgoingLight += diffuseColor.rgb * vLightBack + emissive;",
  10184. " #else",
  10185. " outgoingLight += diffuseColor.rgb * vLightFront + emissive;",
  10186. " #endif",
  10187. THREE.ShaderChunk[ "lightmap_fragment" ],
  10188. THREE.ShaderChunk[ "envmap_fragment" ],
  10189. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10190. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10191. THREE.ShaderChunk[ "fog_fragment" ],
  10192. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );", // TODO, this should be pre-multiplied to allow for bright highlights on very transparent objects
  10193. "}"
  10194. ].join("\n")
  10195. },
  10196. 'phong': {
  10197. uniforms: THREE.UniformsUtils.merge( [
  10198. THREE.UniformsLib[ "common" ],
  10199. THREE.UniformsLib[ "bump" ],
  10200. THREE.UniformsLib[ "normalmap" ],
  10201. THREE.UniformsLib[ "fog" ],
  10202. THREE.UniformsLib[ "lights" ],
  10203. THREE.UniformsLib[ "shadowmap" ],
  10204. {
  10205. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10206. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  10207. "shininess": { type: "f", value: 30 },
  10208. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10209. }
  10210. ] ),
  10211. vertexShader: [
  10212. "#define PHONG",
  10213. "varying vec3 vViewPosition;",
  10214. "#ifndef FLAT_SHADED",
  10215. " varying vec3 vNormal;",
  10216. "#endif",
  10217. THREE.ShaderChunk[ "common" ],
  10218. THREE.ShaderChunk[ "map_pars_vertex" ],
  10219. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10220. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10221. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  10222. THREE.ShaderChunk[ "color_pars_vertex" ],
  10223. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10224. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10225. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10226. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  10227. "void main() {",
  10228. THREE.ShaderChunk[ "map_vertex" ],
  10229. THREE.ShaderChunk[ "lightmap_vertex" ],
  10230. THREE.ShaderChunk[ "color_vertex" ],
  10231. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10232. THREE.ShaderChunk[ "skinbase_vertex" ],
  10233. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10234. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10235. "#ifndef FLAT_SHADED", // Normal computed with derivatives when FLAT_SHADED
  10236. " vNormal = normalize( transformedNormal );",
  10237. "#endif",
  10238. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10239. THREE.ShaderChunk[ "skinning_vertex" ],
  10240. THREE.ShaderChunk[ "default_vertex" ],
  10241. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  10242. " vViewPosition = -mvPosition.xyz;",
  10243. THREE.ShaderChunk[ "worldpos_vertex" ],
  10244. THREE.ShaderChunk[ "envmap_vertex" ],
  10245. THREE.ShaderChunk[ "lights_phong_vertex" ],
  10246. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10247. "}"
  10248. ].join("\n"),
  10249. fragmentShader: [
  10250. "#define PHONG",
  10251. "uniform vec3 diffuse;",
  10252. "uniform vec3 emissive;",
  10253. "uniform vec3 specular;",
  10254. "uniform float shininess;",
  10255. "uniform float opacity;",
  10256. THREE.ShaderChunk[ "common" ],
  10257. THREE.ShaderChunk[ "color_pars_fragment" ],
  10258. THREE.ShaderChunk[ "map_pars_fragment" ],
  10259. THREE.ShaderChunk[ "alphamap_pars_fragment" ],
  10260. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10261. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10262. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10263. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  10264. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10265. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  10266. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  10267. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10268. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  10269. "void main() {",
  10270. " vec3 outgoingLight = vec3( 0.0 );", // outgoing light does not have an alpha, the surface does
  10271. " vec4 diffuseColor = vec4( diffuse, opacity );",
  10272. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  10273. THREE.ShaderChunk[ "map_fragment" ],
  10274. THREE.ShaderChunk[ "color_fragment" ],
  10275. THREE.ShaderChunk[ "alphamap_fragment" ],
  10276. THREE.ShaderChunk[ "alphatest_fragment" ],
  10277. THREE.ShaderChunk[ "specularmap_fragment" ],
  10278. THREE.ShaderChunk[ "lights_phong_fragment" ],
  10279. THREE.ShaderChunk[ "lightmap_fragment" ],
  10280. THREE.ShaderChunk[ "envmap_fragment" ],
  10281. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10282. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10283. THREE.ShaderChunk[ "fog_fragment" ],
  10284. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );", // TODO, this should be pre-multiplied to allow for bright highlights on very transparent objects
  10285. "}"
  10286. ].join("\n")
  10287. },
  10288. 'particle_basic': {
  10289. uniforms: THREE.UniformsUtils.merge( [
  10290. THREE.UniformsLib[ "particle" ],
  10291. THREE.UniformsLib[ "shadowmap" ]
  10292. ] ),
  10293. vertexShader: [
  10294. "uniform float size;",
  10295. "uniform float scale;",
  10296. THREE.ShaderChunk[ "common" ],
  10297. THREE.ShaderChunk[ "color_pars_vertex" ],
  10298. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10299. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  10300. "void main() {",
  10301. THREE.ShaderChunk[ "color_vertex" ],
  10302. " vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10303. " #ifdef USE_SIZEATTENUATION",
  10304. " gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  10305. " #else",
  10306. " gl_PointSize = size;",
  10307. " #endif",
  10308. " gl_Position = projectionMatrix * mvPosition;",
  10309. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  10310. THREE.ShaderChunk[ "worldpos_vertex" ],
  10311. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10312. "}"
  10313. ].join("\n"),
  10314. fragmentShader: [
  10315. "uniform vec3 psColor;",
  10316. "uniform float opacity;",
  10317. THREE.ShaderChunk[ "common" ],
  10318. THREE.ShaderChunk[ "color_pars_fragment" ],
  10319. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  10320. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10321. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10322. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  10323. "void main() {",
  10324. " vec3 outgoingLight = vec3( 0.0 );", // outgoing light does not have an alpha, the surface does
  10325. " vec4 diffuseColor = vec4( psColor, opacity );",
  10326. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  10327. THREE.ShaderChunk[ "map_particle_fragment" ],
  10328. THREE.ShaderChunk[ "color_fragment" ],
  10329. THREE.ShaderChunk[ "alphatest_fragment" ],
  10330. " outgoingLight = diffuseColor.rgb;", // simple shader
  10331. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10332. THREE.ShaderChunk[ "fog_fragment" ],
  10333. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );", // TODO, this should be pre-multiplied to allow for bright highlights on very transparent objects
  10334. "}"
  10335. ].join("\n")
  10336. },
  10337. 'dashed': {
  10338. uniforms: THREE.UniformsUtils.merge( [
  10339. THREE.UniformsLib[ "common" ],
  10340. THREE.UniformsLib[ "fog" ],
  10341. {
  10342. "scale" : { type: "f", value: 1 },
  10343. "dashSize" : { type: "f", value: 1 },
  10344. "totalSize": { type: "f", value: 2 }
  10345. }
  10346. ] ),
  10347. vertexShader: [
  10348. "uniform float scale;",
  10349. "attribute float lineDistance;",
  10350. "varying float vLineDistance;",
  10351. THREE.ShaderChunk[ "common" ],
  10352. THREE.ShaderChunk[ "color_pars_vertex" ],
  10353. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  10354. "void main() {",
  10355. THREE.ShaderChunk[ "color_vertex" ],
  10356. " vLineDistance = scale * lineDistance;",
  10357. " vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10358. " gl_Position = projectionMatrix * mvPosition;",
  10359. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  10360. "}"
  10361. ].join("\n"),
  10362. fragmentShader: [
  10363. "uniform vec3 diffuse;",
  10364. "uniform float opacity;",
  10365. "uniform float dashSize;",
  10366. "uniform float totalSize;",
  10367. "varying float vLineDistance;",
  10368. THREE.ShaderChunk[ "common" ],
  10369. THREE.ShaderChunk[ "color_pars_fragment" ],
  10370. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10371. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  10372. "void main() {",
  10373. " if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  10374. " discard;",
  10375. " }",
  10376. " vec3 outgoingLight = vec3( 0.0 );", // outgoing light does not have an alpha, the surface does
  10377. " vec4 diffuseColor = vec4( diffuse, opacity );",
  10378. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  10379. THREE.ShaderChunk[ "color_fragment" ],
  10380. " outgoingLight = diffuseColor.rgb;", // simple shader
  10381. THREE.ShaderChunk[ "fog_fragment" ],
  10382. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );", // TODO, this should be pre-multiplied to allow for bright highlights on very transparent objects
  10383. "}"
  10384. ].join("\n")
  10385. },
  10386. 'depth': {
  10387. uniforms: {
  10388. "mNear": { type: "f", value: 1.0 },
  10389. "mFar" : { type: "f", value: 2000.0 },
  10390. "opacity" : { type: "f", value: 1.0 }
  10391. },
  10392. vertexShader: [
  10393. THREE.ShaderChunk[ "common" ],
  10394. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10395. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  10396. "void main() {",
  10397. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10398. THREE.ShaderChunk[ "default_vertex" ],
  10399. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  10400. "}"
  10401. ].join("\n"),
  10402. fragmentShader: [
  10403. "uniform float mNear;",
  10404. "uniform float mFar;",
  10405. "uniform float opacity;",
  10406. THREE.ShaderChunk[ "common" ],
  10407. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  10408. "void main() {",
  10409. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  10410. " #ifdef USE_LOGDEPTHBUF_EXT",
  10411. " float depth = gl_FragDepthEXT / gl_FragCoord.w;",
  10412. " #else",
  10413. " float depth = gl_FragCoord.z / gl_FragCoord.w;",
  10414. " #endif",
  10415. " float color = 1.0 - smoothstep( mNear, mFar, depth );",
  10416. " gl_FragColor = vec4( vec3( color ), opacity );", // TODO, this should be pre-multiplied to allow for bright highlights on very transparent objects
  10417. "}"
  10418. ].join("\n")
  10419. },
  10420. 'normal': {
  10421. uniforms: {
  10422. "opacity" : { type: "f", value: 1.0 }
  10423. },
  10424. vertexShader: [
  10425. "varying vec3 vNormal;",
  10426. THREE.ShaderChunk[ "common" ],
  10427. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10428. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  10429. "void main() {",
  10430. " vNormal = normalize( normalMatrix * normal );",
  10431. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10432. THREE.ShaderChunk[ "default_vertex" ],
  10433. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  10434. "}"
  10435. ].join("\n"),
  10436. fragmentShader: [
  10437. "uniform float opacity;",
  10438. "varying vec3 vNormal;",
  10439. THREE.ShaderChunk[ "common" ],
  10440. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  10441. "void main() {",
  10442. " gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  10443. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  10444. "}"
  10445. ].join("\n")
  10446. },
  10447. /* -------------------------------------------------------------------------
  10448. // Cube map shader
  10449. ------------------------------------------------------------------------- */
  10450. 'cube': {
  10451. uniforms: { "tCube": { type: "t", value: null },
  10452. "tFlip": { type: "f", value: - 1 } },
  10453. vertexShader: [
  10454. "varying vec3 vWorldPosition;",
  10455. THREE.ShaderChunk[ "common" ],
  10456. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  10457. "void main() {",
  10458. " vWorldPosition = transformDirection( position, modelMatrix );",
  10459. " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  10460. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  10461. "}"
  10462. ].join("\n"),
  10463. fragmentShader: [
  10464. "uniform samplerCube tCube;",
  10465. "uniform float tFlip;",
  10466. "varying vec3 vWorldPosition;",
  10467. THREE.ShaderChunk[ "common" ],
  10468. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  10469. "void main() {",
  10470. " gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  10471. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  10472. "}"
  10473. ].join("\n")
  10474. },
  10475. /* -------------------------------------------------------------------------
  10476. // Cube map shader
  10477. ------------------------------------------------------------------------- */
  10478. 'equirect': {
  10479. uniforms: { "tEquirect": { type: "t", value: null },
  10480. "tFlip": { type: "f", value: - 1 } },
  10481. vertexShader: [
  10482. "varying vec3 vWorldPosition;",
  10483. THREE.ShaderChunk[ "common" ],
  10484. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  10485. "void main() {",
  10486. " vWorldPosition = transformDirection( position, modelMatrix );",
  10487. " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  10488. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  10489. "}"
  10490. ].join("\n"),
  10491. fragmentShader: [
  10492. "uniform sampler2D tEquirect;",
  10493. "uniform float tFlip;",
  10494. "varying vec3 vWorldPosition;",
  10495. THREE.ShaderChunk[ "common" ],
  10496. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  10497. "void main() {",
  10498. // " gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  10499. "vec3 direction = normalize( vWorldPosition );",
  10500. "vec2 sampleUV;",
  10501. "sampleUV.y = saturate( tFlip * direction.y * -0.5 + 0.5 );",
  10502. "sampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;",
  10503. "gl_FragColor = texture2D( tEquirect, sampleUV );",
  10504. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  10505. "}"
  10506. ].join("\n")
  10507. },
  10508. /* Depth encoding into RGBA texture
  10509. *
  10510. * based on SpiderGL shadow map example
  10511. * http://spidergl.org/example.php?id=6
  10512. *
  10513. * originally from
  10514. * http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  10515. *
  10516. * see also
  10517. * http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  10518. */
  10519. 'depthRGBA': {
  10520. uniforms: {},
  10521. vertexShader: [
  10522. THREE.ShaderChunk[ "common" ],
  10523. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10524. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10525. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  10526. "void main() {",
  10527. THREE.ShaderChunk[ "skinbase_vertex" ],
  10528. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10529. THREE.ShaderChunk[ "skinning_vertex" ],
  10530. THREE.ShaderChunk[ "default_vertex" ],
  10531. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  10532. "}"
  10533. ].join("\n"),
  10534. fragmentShader: [
  10535. THREE.ShaderChunk[ "common" ],
  10536. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  10537. "vec4 pack_depth( const in float depth ) {",
  10538. " const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  10539. " const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  10540. " vec4 res = mod( depth * bit_shift * vec4( 255 ), vec4( 256 ) ) / vec4( 255 );", // " vec4 res = fract( depth * bit_shift );",
  10541. " res -= res.xxyz * bit_mask;",
  10542. " return res;",
  10543. "}",
  10544. "void main() {",
  10545. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  10546. " #ifdef USE_LOGDEPTHBUF_EXT",
  10547. " gl_FragData[ 0 ] = pack_depth( gl_FragDepthEXT );",
  10548. " #else",
  10549. " gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  10550. " #endif",
  10551. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  10552. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  10553. //"gl_FragData[ 0 ] = pack_depth( z );",
  10554. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  10555. "}"
  10556. ].join("\n")
  10557. }
  10558. };
  10559. // File:src/renderers/WebGLRenderer.js
  10560. /**
  10561. * @author supereggbert / http://www.paulbrunt.co.uk/
  10562. * @author mrdoob / http://mrdoob.com/
  10563. * @author alteredq / http://alteredqualia.com/
  10564. * @author szimek / https://github.com/szimek/
  10565. */
  10566. THREE.WebGLRenderer = function ( parameters ) {
  10567. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  10568. parameters = parameters || {};
  10569. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  10570. _context = parameters.context !== undefined ? parameters.context : null,
  10571. pixelRatio = 1,
  10572. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  10573. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  10574. _depth = parameters.depth !== undefined ? parameters.depth : true,
  10575. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  10576. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  10577. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  10578. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  10579. _logarithmicDepthBuffer = parameters.logarithmicDepthBuffer !== undefined ? parameters.logarithmicDepthBuffer : false,
  10580. _clearColor = new THREE.Color( 0x000000 ),
  10581. _clearAlpha = 0;
  10582. var lights = [];
  10583. var _webglObjects = {};
  10584. var _webglObjectsImmediate = [];
  10585. var opaqueObjects = [];
  10586. var transparentObjects = [];
  10587. var sprites = [];
  10588. var lensFlares = [];
  10589. // public properties
  10590. this.domElement = _canvas;
  10591. this.context = null;
  10592. // clearing
  10593. this.autoClear = true;
  10594. this.autoClearColor = true;
  10595. this.autoClearDepth = true;
  10596. this.autoClearStencil = true;
  10597. // scene graph
  10598. this.sortObjects = true;
  10599. // physically based shading
  10600. this.gammaFactor = 2.0; // for backwards compatibility
  10601. this.gammaInput = false;
  10602. this.gammaOutput = false;
  10603. // shadow map
  10604. this.shadowMapEnabled = false;
  10605. this.shadowMapType = THREE.PCFShadowMap;
  10606. this.shadowMapCullFace = THREE.CullFaceFront;
  10607. this.shadowMapDebug = false;
  10608. this.shadowMapCascade = false;
  10609. // morphs
  10610. this.maxMorphTargets = 8;
  10611. this.maxMorphNormals = 4;
  10612. // flags
  10613. this.autoScaleCubemaps = true;
  10614. // info
  10615. this.info = {
  10616. memory: {
  10617. programs: 0,
  10618. geometries: 0,
  10619. textures: 0
  10620. },
  10621. render: {
  10622. calls: 0,
  10623. vertices: 0,
  10624. faces: 0,
  10625. points: 0
  10626. }
  10627. };
  10628. // internal properties
  10629. var _this = this,
  10630. _programs = [],
  10631. // internal state cache
  10632. _currentProgram = null,
  10633. _currentFramebuffer = null,
  10634. _currentMaterialId = - 1,
  10635. _currentGeometryProgram = '',
  10636. _currentCamera = null,
  10637. _usedTextureUnits = 0,
  10638. _viewportX = 0,
  10639. _viewportY = 0,
  10640. _viewportWidth = _canvas.width,
  10641. _viewportHeight = _canvas.height,
  10642. _currentWidth = 0,
  10643. _currentHeight = 0,
  10644. // frustum
  10645. _frustum = new THREE.Frustum(),
  10646. // camera matrices cache
  10647. _projScreenMatrix = new THREE.Matrix4(),
  10648. _vector3 = new THREE.Vector3(),
  10649. // light arrays cache
  10650. _direction = new THREE.Vector3(),
  10651. _lightsNeedUpdate = true,
  10652. _lights = {
  10653. ambient: [ 0, 0, 0 ],
  10654. directional: { length: 0, colors:[], positions: [] },
  10655. point: { length: 0, colors: [], positions: [], distances: [], decays: [] },
  10656. spot: { length: 0, colors: [], positions: [], distances: [], directions: [], anglesCos: [], exponents: [], decays: [] },
  10657. hemi: { length: 0, skyColors: [], groundColors: [], positions: [] }
  10658. };
  10659. // initialize
  10660. var _gl;
  10661. try {
  10662. var attributes = {
  10663. alpha: _alpha,
  10664. depth: _depth,
  10665. stencil: _stencil,
  10666. antialias: _antialias,
  10667. premultipliedAlpha: _premultipliedAlpha,
  10668. preserveDrawingBuffer: _preserveDrawingBuffer
  10669. };
  10670. _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  10671. if ( _gl === null ) {
  10672. if ( _canvas.getContext( 'webgl') !== null ) {
  10673. throw 'Error creating WebGL context with your selected attributes.';
  10674. } else {
  10675. throw 'Error creating WebGL context.';
  10676. }
  10677. }
  10678. _canvas.addEventListener( 'webglcontextlost', function ( event ) {
  10679. event.preventDefault();
  10680. resetGLState();
  10681. setDefaultGLState();
  10682. _webglObjects = {};
  10683. }, false);
  10684. } catch ( error ) {
  10685. THREE.error( 'THREE.WebGLRenderer: ' + error );
  10686. }
  10687. var state = new THREE.WebGLState( _gl, paramThreeToGL );
  10688. if ( _gl.getShaderPrecisionFormat === undefined ) {
  10689. _gl.getShaderPrecisionFormat = function () {
  10690. return {
  10691. 'rangeMin': 1,
  10692. 'rangeMax': 1,
  10693. 'precision': 1
  10694. };
  10695. }
  10696. }
  10697. var extensions = new THREE.WebGLExtensions( _gl );
  10698. extensions.get( 'OES_texture_float' );
  10699. extensions.get( 'OES_texture_float_linear' );
  10700. extensions.get( 'OES_texture_half_float' );
  10701. extensions.get( 'OES_texture_half_float_linear' );
  10702. extensions.get( 'OES_standard_derivatives' );
  10703. if ( _logarithmicDepthBuffer ) {
  10704. extensions.get( 'EXT_frag_depth' );
  10705. }
  10706. //
  10707. var glClearColor = function ( r, g, b, a ) {
  10708. if ( _premultipliedAlpha === true ) {
  10709. r *= a; g *= a; b *= a;
  10710. }
  10711. _gl.clearColor( r, g, b, a );
  10712. };
  10713. var setDefaultGLState = function () {
  10714. _gl.clearColor( 0, 0, 0, 1 );
  10715. _gl.clearDepth( 1 );
  10716. _gl.clearStencil( 0 );
  10717. _gl.enable( _gl.DEPTH_TEST );
  10718. _gl.depthFunc( _gl.LEQUAL );
  10719. _gl.frontFace( _gl.CCW );
  10720. _gl.cullFace( _gl.BACK );
  10721. _gl.enable( _gl.CULL_FACE );
  10722. _gl.enable( _gl.BLEND );
  10723. _gl.blendEquation( _gl.FUNC_ADD );
  10724. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  10725. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  10726. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  10727. };
  10728. var resetGLState = function () {
  10729. _currentProgram = null;
  10730. _currentCamera = null;
  10731. _currentGeometryProgram = '';
  10732. _currentMaterialId = - 1;
  10733. _lightsNeedUpdate = true;
  10734. state.reset();
  10735. };
  10736. setDefaultGLState();
  10737. this.context = _gl;
  10738. this.state = state;
  10739. // GPU capabilities
  10740. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  10741. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  10742. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  10743. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  10744. var _supportsVertexTextures = _maxVertexTextures > 0;
  10745. var _supportsBoneTextures = _supportsVertexTextures && extensions.get( 'OES_texture_float' );
  10746. //
  10747. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  10748. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  10749. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  10750. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  10751. var getCompressedTextureFormats = ( function () {
  10752. var array;
  10753. return function () {
  10754. if ( array !== undefined ) {
  10755. return array;
  10756. }
  10757. array = [];
  10758. if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) || extensions.get( 'WEBGL_compressed_texture_s3tc' ) ) {
  10759. var formats = _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS );
  10760. for ( var i = 0; i < formats.length; i ++ ) {
  10761. array.push( formats[ i ] );
  10762. }
  10763. }
  10764. return array;
  10765. };
  10766. } )();
  10767. // clamp precision to maximum available
  10768. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  10769. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  10770. if ( _precision === 'highp' && ! highpAvailable ) {
  10771. if ( mediumpAvailable ) {
  10772. _precision = 'mediump';
  10773. THREE.warn( 'THREE.WebGLRenderer: highp not supported, using mediump.' );
  10774. } else {
  10775. _precision = 'lowp';
  10776. THREE.warn( 'THREE.WebGLRenderer: highp and mediump not supported, using lowp.' );
  10777. }
  10778. }
  10779. if ( _precision === 'mediump' && ! mediumpAvailable ) {
  10780. _precision = 'lowp';
  10781. THREE.warn( 'THREE.WebGLRenderer: mediump not supported, using lowp.' );
  10782. }
  10783. // Plugins
  10784. var shadowMapPlugin = new THREE.ShadowMapPlugin( this, lights, _webglObjects, _webglObjectsImmediate );
  10785. var spritePlugin = new THREE.SpritePlugin( this, sprites );
  10786. var lensFlarePlugin = new THREE.LensFlarePlugin( this, lensFlares );
  10787. // API
  10788. this.getContext = function () {
  10789. return _gl;
  10790. };
  10791. this.forceContextLoss = function () {
  10792. extensions.get( 'WEBGL_lose_context' ).loseContext();
  10793. };
  10794. this.supportsVertexTextures = function () {
  10795. return _supportsVertexTextures;
  10796. };
  10797. this.supportsFloatTextures = function () {
  10798. return extensions.get( 'OES_texture_float' );
  10799. };
  10800. this.supportsHalfFloatTextures = function () {
  10801. return extensions.get( 'OES_texture_half_float' );
  10802. };
  10803. this.supportsStandardDerivatives = function () {
  10804. return extensions.get( 'OES_standard_derivatives' );
  10805. };
  10806. this.supportsCompressedTextureS3TC = function () {
  10807. return extensions.get( 'WEBGL_compressed_texture_s3tc' );
  10808. };
  10809. this.supportsCompressedTexturePVRTC = function () {
  10810. return extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  10811. };
  10812. this.supportsBlendMinMax = function () {
  10813. return extensions.get( 'EXT_blend_minmax' );
  10814. };
  10815. this.getMaxAnisotropy = ( function () {
  10816. var value;
  10817. return function () {
  10818. if ( value !== undefined ) {
  10819. return value;
  10820. }
  10821. var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  10822. value = extension !== null ? _gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  10823. return value;
  10824. }
  10825. } )();
  10826. this.getPrecision = function () {
  10827. return _precision;
  10828. };
  10829. this.getPixelRatio = function () {
  10830. return pixelRatio;
  10831. };
  10832. this.setPixelRatio = function ( value ) {
  10833. pixelRatio = value;
  10834. };
  10835. this.setSize = function ( width, height, updateStyle ) {
  10836. _canvas.width = width * pixelRatio;
  10837. _canvas.height = height * pixelRatio;
  10838. if ( updateStyle !== false ) {
  10839. _canvas.style.width = width + 'px';
  10840. _canvas.style.height = height + 'px';
  10841. }
  10842. this.setViewport( 0, 0, width, height );
  10843. };
  10844. this.setViewport = function ( x, y, width, height ) {
  10845. _viewportX = x * pixelRatio;
  10846. _viewportY = y * pixelRatio;
  10847. _viewportWidth = width * pixelRatio;
  10848. _viewportHeight = height * pixelRatio;
  10849. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  10850. };
  10851. this.setScissor = function ( x, y, width, height ) {
  10852. _gl.scissor(
  10853. x * pixelRatio,
  10854. y * pixelRatio,
  10855. width * pixelRatio,
  10856. height * pixelRatio
  10857. );
  10858. };
  10859. this.enableScissorTest = function ( enable ) {
  10860. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  10861. };
  10862. // Clearing
  10863. this.getClearColor = function () {
  10864. return _clearColor;
  10865. };
  10866. this.setClearColor = function ( color, alpha ) {
  10867. _clearColor.set( color );
  10868. _clearAlpha = alpha !== undefined ? alpha : 1;
  10869. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  10870. };
  10871. this.getClearAlpha = function () {
  10872. return _clearAlpha;
  10873. };
  10874. this.setClearAlpha = function ( alpha ) {
  10875. _clearAlpha = alpha;
  10876. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  10877. };
  10878. this.clear = function ( color, depth, stencil ) {
  10879. var bits = 0;
  10880. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  10881. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  10882. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  10883. _gl.clear( bits );
  10884. };
  10885. this.clearColor = function () {
  10886. _gl.clear( _gl.COLOR_BUFFER_BIT );
  10887. };
  10888. this.clearDepth = function () {
  10889. _gl.clear( _gl.DEPTH_BUFFER_BIT );
  10890. };
  10891. this.clearStencil = function () {
  10892. _gl.clear( _gl.STENCIL_BUFFER_BIT );
  10893. };
  10894. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  10895. this.setRenderTarget( renderTarget );
  10896. this.clear( color, depth, stencil );
  10897. };
  10898. // Reset
  10899. this.resetGLState = resetGLState;
  10900. // Buffer allocation
  10901. function createParticleBuffers ( geometry ) {
  10902. geometry.__webglVertexBuffer = _gl.createBuffer();
  10903. geometry.__webglColorBuffer = _gl.createBuffer();
  10904. _this.info.memory.geometries ++;
  10905. };
  10906. function createLineBuffers ( geometry ) {
  10907. geometry.__webglVertexBuffer = _gl.createBuffer();
  10908. geometry.__webglColorBuffer = _gl.createBuffer();
  10909. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  10910. _this.info.memory.geometries ++;
  10911. };
  10912. function createMeshBuffers ( geometryGroup ) {
  10913. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  10914. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  10915. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  10916. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  10917. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  10918. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  10919. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  10920. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  10921. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  10922. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  10923. var numMorphTargets = geometryGroup.numMorphTargets;
  10924. if ( numMorphTargets ) {
  10925. geometryGroup.__webglMorphTargetsBuffers = [];
  10926. for ( var m = 0, ml = numMorphTargets; m < ml; m ++ ) {
  10927. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  10928. }
  10929. }
  10930. var numMorphNormals = geometryGroup.numMorphNormals;
  10931. if ( numMorphNormals ) {
  10932. geometryGroup.__webglMorphNormalsBuffers = [];
  10933. for ( var m = 0, ml = numMorphNormals; m < ml; m ++ ) {
  10934. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  10935. }
  10936. }
  10937. _this.info.memory.geometries ++;
  10938. };
  10939. // Events
  10940. var onObjectRemoved = function ( event ) {
  10941. var object = event.target;
  10942. object.traverse( function ( child ) {
  10943. child.removeEventListener( 'remove', onObjectRemoved );
  10944. removeObject( child );
  10945. } );
  10946. };
  10947. var onGeometryDispose = function ( event ) {
  10948. var geometry = event.target;
  10949. geometry.removeEventListener( 'dispose', onGeometryDispose );
  10950. deallocateGeometry( geometry );
  10951. };
  10952. var onTextureDispose = function ( event ) {
  10953. var texture = event.target;
  10954. texture.removeEventListener( 'dispose', onTextureDispose );
  10955. deallocateTexture( texture );
  10956. _this.info.memory.textures --;
  10957. };
  10958. var onRenderTargetDispose = function ( event ) {
  10959. var renderTarget = event.target;
  10960. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  10961. deallocateRenderTarget( renderTarget );
  10962. _this.info.memory.textures --;
  10963. };
  10964. var onMaterialDispose = function ( event ) {
  10965. var material = event.target;
  10966. material.removeEventListener( 'dispose', onMaterialDispose );
  10967. deallocateMaterial( material );
  10968. };
  10969. // Buffer deallocation
  10970. var deleteBuffers = function ( geometry ) {
  10971. var buffers = [
  10972. '__webglVertexBuffer',
  10973. '__webglNormalBuffer',
  10974. '__webglTangentBuffer',
  10975. '__webglColorBuffer',
  10976. '__webglUVBuffer',
  10977. '__webglUV2Buffer',
  10978. '__webglSkinIndicesBuffer',
  10979. '__webglSkinWeightsBuffer',
  10980. '__webglFaceBuffer',
  10981. '__webglLineBuffer',
  10982. '__webglLineDistanceBuffer'
  10983. ];
  10984. for ( var i = 0, l = buffers.length; i < l; i ++ ) {
  10985. var name = buffers[ i ];
  10986. if ( geometry[ name ] !== undefined ) {
  10987. _gl.deleteBuffer( geometry[ name ] );
  10988. delete geometry[ name ];
  10989. }
  10990. }
  10991. // custom attributes
  10992. if ( geometry.__webglCustomAttributesList !== undefined ) {
  10993. for ( var name in geometry.__webglCustomAttributesList ) {
  10994. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ name ].buffer );
  10995. }
  10996. delete geometry.__webglCustomAttributesList;
  10997. }
  10998. _this.info.memory.geometries --;
  10999. };
  11000. var deallocateGeometry = function ( geometry ) {
  11001. delete geometry.__webglInit;
  11002. if ( geometry instanceof THREE.BufferGeometry ) {
  11003. for ( var name in geometry.attributes ) {
  11004. var attribute = geometry.attributes[ name ];
  11005. if ( attribute.buffer !== undefined ) {
  11006. _gl.deleteBuffer( attribute.buffer );
  11007. delete attribute.buffer;
  11008. }
  11009. }
  11010. _this.info.memory.geometries --;
  11011. } else {
  11012. var geometryGroupsList = geometryGroups[ geometry.id ];
  11013. if ( geometryGroupsList !== undefined ) {
  11014. for ( var i = 0, l = geometryGroupsList.length; i < l; i ++ ) {
  11015. var geometryGroup = geometryGroupsList[ i ];
  11016. if ( geometryGroup.numMorphTargets !== undefined ) {
  11017. for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11018. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  11019. }
  11020. delete geometryGroup.__webglMorphTargetsBuffers;
  11021. }
  11022. if ( geometryGroup.numMorphNormals !== undefined ) {
  11023. for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11024. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  11025. }
  11026. delete geometryGroup.__webglMorphNormalsBuffers;
  11027. }
  11028. deleteBuffers( geometryGroup );
  11029. }
  11030. delete geometryGroups[ geometry.id ];
  11031. } else {
  11032. deleteBuffers( geometry );
  11033. }
  11034. }
  11035. // TOFIX: Workaround for deleted geometry being currently bound
  11036. _currentGeometryProgram = '';
  11037. };
  11038. var deallocateTexture = function ( texture ) {
  11039. if ( texture.image && texture.image.__webglTextureCube ) {
  11040. // cube texture
  11041. _gl.deleteTexture( texture.image.__webglTextureCube );
  11042. delete texture.image.__webglTextureCube;
  11043. } else {
  11044. // 2D texture
  11045. if ( texture.__webglInit === undefined ) return;
  11046. _gl.deleteTexture( texture.__webglTexture );
  11047. delete texture.__webglTexture;
  11048. delete texture.__webglInit;
  11049. }
  11050. };
  11051. var deallocateRenderTarget = function ( renderTarget ) {
  11052. if ( ! renderTarget || renderTarget.__webglTexture === undefined ) return;
  11053. _gl.deleteTexture( renderTarget.__webglTexture );
  11054. delete renderTarget.__webglTexture;
  11055. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  11056. for ( var i = 0; i < 6; i ++ ) {
  11057. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  11058. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  11059. }
  11060. } else {
  11061. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  11062. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  11063. }
  11064. delete renderTarget.__webglFramebuffer;
  11065. delete renderTarget.__webglRenderbuffer;
  11066. };
  11067. var deallocateMaterial = function ( material ) {
  11068. var program = material.program.program;
  11069. if ( program === undefined ) return;
  11070. material.program = undefined;
  11071. // only deallocate GL program if this was the last use of shared program
  11072. // assumed there is only single copy of any program in the _programs list
  11073. // (that's how it's constructed)
  11074. var i, il, programInfo;
  11075. var deleteProgram = false;
  11076. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  11077. programInfo = _programs[ i ];
  11078. if ( programInfo.program === program ) {
  11079. programInfo.usedTimes --;
  11080. if ( programInfo.usedTimes === 0 ) {
  11081. deleteProgram = true;
  11082. }
  11083. break;
  11084. }
  11085. }
  11086. if ( deleteProgram === true ) {
  11087. // avoid using array.splice, this is costlier than creating new array from scratch
  11088. var newPrograms = [];
  11089. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  11090. programInfo = _programs[ i ];
  11091. if ( programInfo.program !== program ) {
  11092. newPrograms.push( programInfo );
  11093. }
  11094. }
  11095. _programs = newPrograms;
  11096. _gl.deleteProgram( program );
  11097. _this.info.memory.programs --;
  11098. }
  11099. };
  11100. // Buffer initialization
  11101. function initCustomAttributes ( object ) {
  11102. var geometry = object.geometry;
  11103. var material = object.material;
  11104. var nvertices = geometry.vertices.length;
  11105. if ( material.attributes ) {
  11106. if ( geometry.__webglCustomAttributesList === undefined ) {
  11107. geometry.__webglCustomAttributesList = [];
  11108. }
  11109. for ( var name in material.attributes ) {
  11110. var attribute = material.attributes[ name ];
  11111. if ( ! attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  11112. attribute.__webglInitialized = true;
  11113. var size = 1; // "f" and "i"
  11114. if ( attribute.type === 'v2' ) size = 2;
  11115. else if ( attribute.type === 'v3' ) size = 3;
  11116. else if ( attribute.type === 'v4' ) size = 4;
  11117. else if ( attribute.type === 'c' ) size = 3;
  11118. attribute.size = size;
  11119. attribute.array = new Float32Array( nvertices * size );
  11120. attribute.buffer = _gl.createBuffer();
  11121. attribute.buffer.belongsToAttribute = name;
  11122. attribute.needsUpdate = true;
  11123. }
  11124. geometry.__webglCustomAttributesList.push( attribute );
  11125. }
  11126. }
  11127. };
  11128. function initParticleBuffers ( geometry, object ) {
  11129. var nvertices = geometry.vertices.length;
  11130. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  11131. geometry.__colorArray = new Float32Array( nvertices * 3 );
  11132. geometry.__webglParticleCount = nvertices;
  11133. initCustomAttributes( object );
  11134. };
  11135. function initLineBuffers ( geometry, object ) {
  11136. var nvertices = geometry.vertices.length;
  11137. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  11138. geometry.__colorArray = new Float32Array( nvertices * 3 );
  11139. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  11140. geometry.__webglLineCount = nvertices;
  11141. initCustomAttributes( object );
  11142. };
  11143. function initMeshBuffers ( geometryGroup, object ) {
  11144. var geometry = object.geometry,
  11145. faces3 = geometryGroup.faces3,
  11146. nvertices = faces3.length * 3,
  11147. ntris = faces3.length * 1,
  11148. nlines = faces3.length * 3,
  11149. material = getBufferMaterial( object, geometryGroup );
  11150. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  11151. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  11152. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  11153. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  11154. if ( geometry.faceVertexUvs.length > 1 ) {
  11155. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  11156. }
  11157. if ( geometry.hasTangents ) {
  11158. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  11159. }
  11160. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  11161. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  11162. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  11163. }
  11164. var UintArray = extensions.get( 'OES_element_index_uint' ) !== null && ntris > 21845 ? Uint32Array : Uint16Array; // 65535 / 3
  11165. geometryGroup.__typeArray = UintArray;
  11166. geometryGroup.__faceArray = new UintArray( ntris * 3 );
  11167. geometryGroup.__lineArray = new UintArray( nlines * 2 );
  11168. var numMorphTargets = geometryGroup.numMorphTargets;
  11169. if ( numMorphTargets ) {
  11170. geometryGroup.__morphTargetsArrays = [];
  11171. for ( var m = 0, ml = numMorphTargets; m < ml; m ++ ) {
  11172. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  11173. }
  11174. }
  11175. var numMorphNormals = geometryGroup.numMorphNormals;
  11176. if ( numMorphNormals ) {
  11177. geometryGroup.__morphNormalsArrays = [];
  11178. for ( var m = 0, ml = numMorphNormals; m < ml; m ++ ) {
  11179. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  11180. }
  11181. }
  11182. geometryGroup.__webglFaceCount = ntris * 3;
  11183. geometryGroup.__webglLineCount = nlines * 2;
  11184. // custom attributes
  11185. if ( material.attributes ) {
  11186. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  11187. geometryGroup.__webglCustomAttributesList = [];
  11188. }
  11189. for ( var name in material.attributes ) {
  11190. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  11191. // attribute buffers which are correctly indexed in the setMeshBuffers function
  11192. var originalAttribute = material.attributes[ name ];
  11193. var attribute = {};
  11194. for ( var property in originalAttribute ) {
  11195. attribute[ property ] = originalAttribute[ property ];
  11196. }
  11197. if ( ! attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  11198. attribute.__webglInitialized = true;
  11199. var size = 1; // "f" and "i"
  11200. if ( attribute.type === 'v2' ) size = 2;
  11201. else if ( attribute.type === 'v3' ) size = 3;
  11202. else if ( attribute.type === 'v4' ) size = 4;
  11203. else if ( attribute.type === 'c' ) size = 3;
  11204. attribute.size = size;
  11205. attribute.array = new Float32Array( nvertices * size );
  11206. attribute.buffer = _gl.createBuffer();
  11207. attribute.buffer.belongsToAttribute = name;
  11208. originalAttribute.needsUpdate = true;
  11209. attribute.__original = originalAttribute;
  11210. }
  11211. geometryGroup.__webglCustomAttributesList.push( attribute );
  11212. }
  11213. }
  11214. geometryGroup.__inittedArrays = true;
  11215. };
  11216. function getBufferMaterial( object, geometryGroup ) {
  11217. return object.material instanceof THREE.MeshFaceMaterial
  11218. ? object.material.materials[ geometryGroup.materialIndex ]
  11219. : object.material;
  11220. }
  11221. function materialNeedsFaceNormals ( material ) {
  11222. return material instanceof THREE.MeshPhongMaterial === false && material.shading === THREE.FlatShading;
  11223. }
  11224. // Buffer setting
  11225. function setParticleBuffers ( geometry, hint, object ) {
  11226. var v, c, vertex, offset, color,
  11227. vertices = geometry.vertices,
  11228. vl = vertices.length,
  11229. colors = geometry.colors,
  11230. cl = colors.length,
  11231. vertexArray = geometry.__vertexArray,
  11232. colorArray = geometry.__colorArray,
  11233. dirtyVertices = geometry.verticesNeedUpdate,
  11234. dirtyColors = geometry.colorsNeedUpdate,
  11235. customAttributes = geometry.__webglCustomAttributesList,
  11236. i, il,
  11237. ca, cal, value,
  11238. customAttribute;
  11239. if ( dirtyVertices ) {
  11240. for ( v = 0; v < vl; v ++ ) {
  11241. vertex = vertices[ v ];
  11242. offset = v * 3;
  11243. vertexArray[ offset ] = vertex.x;
  11244. vertexArray[ offset + 1 ] = vertex.y;
  11245. vertexArray[ offset + 2 ] = vertex.z;
  11246. }
  11247. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  11248. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11249. }
  11250. if ( dirtyColors ) {
  11251. for ( c = 0; c < cl; c ++ ) {
  11252. color = colors[ c ];
  11253. offset = c * 3;
  11254. colorArray[ offset ] = color.r;
  11255. colorArray[ offset + 1 ] = color.g;
  11256. colorArray[ offset + 2 ] = color.b;
  11257. }
  11258. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  11259. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11260. }
  11261. if ( customAttributes ) {
  11262. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11263. customAttribute = customAttributes[ i ];
  11264. if ( customAttribute.needsUpdate && ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) ) {
  11265. cal = customAttribute.value.length;
  11266. offset = 0;
  11267. if ( customAttribute.size === 1 ) {
  11268. for ( ca = 0; ca < cal; ca ++ ) {
  11269. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  11270. }
  11271. } else if ( customAttribute.size === 2 ) {
  11272. for ( ca = 0; ca < cal; ca ++ ) {
  11273. value = customAttribute.value[ ca ];
  11274. customAttribute.array[ offset ] = value.x;
  11275. customAttribute.array[ offset + 1 ] = value.y;
  11276. offset += 2;
  11277. }
  11278. } else if ( customAttribute.size === 3 ) {
  11279. if ( customAttribute.type === 'c' ) {
  11280. for ( ca = 0; ca < cal; ca ++ ) {
  11281. value = customAttribute.value[ ca ];
  11282. customAttribute.array[ offset ] = value.r;
  11283. customAttribute.array[ offset + 1 ] = value.g;
  11284. customAttribute.array[ offset + 2 ] = value.b;
  11285. offset += 3;
  11286. }
  11287. } else {
  11288. for ( ca = 0; ca < cal; ca ++ ) {
  11289. value = customAttribute.value[ ca ];
  11290. customAttribute.array[ offset ] = value.x;
  11291. customAttribute.array[ offset + 1 ] = value.y;
  11292. customAttribute.array[ offset + 2 ] = value.z;
  11293. offset += 3;
  11294. }
  11295. }
  11296. } else if ( customAttribute.size === 4 ) {
  11297. for ( ca = 0; ca < cal; ca ++ ) {
  11298. value = customAttribute.value[ ca ];
  11299. customAttribute.array[ offset ] = value.x;
  11300. customAttribute.array[ offset + 1 ] = value.y;
  11301. customAttribute.array[ offset + 2 ] = value.z;
  11302. customAttribute.array[ offset + 3 ] = value.w;
  11303. offset += 4;
  11304. }
  11305. }
  11306. }
  11307. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11308. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11309. customAttribute.needsUpdate = false;
  11310. }
  11311. }
  11312. }
  11313. function setLineBuffers ( geometry, hint ) {
  11314. var v, c, d, vertex, offset, color,
  11315. vertices = geometry.vertices,
  11316. colors = geometry.colors,
  11317. lineDistances = geometry.lineDistances,
  11318. vl = vertices.length,
  11319. cl = colors.length,
  11320. dl = lineDistances.length,
  11321. vertexArray = geometry.__vertexArray,
  11322. colorArray = geometry.__colorArray,
  11323. lineDistanceArray = geometry.__lineDistanceArray,
  11324. dirtyVertices = geometry.verticesNeedUpdate,
  11325. dirtyColors = geometry.colorsNeedUpdate,
  11326. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  11327. customAttributes = geometry.__webglCustomAttributesList,
  11328. i, il,
  11329. ca, cal, value,
  11330. customAttribute;
  11331. if ( dirtyVertices ) {
  11332. for ( v = 0; v < vl; v ++ ) {
  11333. vertex = vertices[ v ];
  11334. offset = v * 3;
  11335. vertexArray[ offset ] = vertex.x;
  11336. vertexArray[ offset + 1 ] = vertex.y;
  11337. vertexArray[ offset + 2 ] = vertex.z;
  11338. }
  11339. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  11340. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11341. }
  11342. if ( dirtyColors ) {
  11343. for ( c = 0; c < cl; c ++ ) {
  11344. color = colors[ c ];
  11345. offset = c * 3;
  11346. colorArray[ offset ] = color.r;
  11347. colorArray[ offset + 1 ] = color.g;
  11348. colorArray[ offset + 2 ] = color.b;
  11349. }
  11350. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  11351. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11352. }
  11353. if ( dirtyLineDistances ) {
  11354. for ( d = 0; d < dl; d ++ ) {
  11355. lineDistanceArray[ d ] = lineDistances[ d ];
  11356. }
  11357. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  11358. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  11359. }
  11360. if ( customAttributes ) {
  11361. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11362. customAttribute = customAttributes[ i ];
  11363. if ( customAttribute.needsUpdate && ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) ) {
  11364. offset = 0;
  11365. cal = customAttribute.value.length;
  11366. if ( customAttribute.size === 1 ) {
  11367. for ( ca = 0; ca < cal; ca ++ ) {
  11368. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  11369. }
  11370. } else if ( customAttribute.size === 2 ) {
  11371. for ( ca = 0; ca < cal; ca ++ ) {
  11372. value = customAttribute.value[ ca ];
  11373. customAttribute.array[ offset ] = value.x;
  11374. customAttribute.array[ offset + 1 ] = value.y;
  11375. offset += 2;
  11376. }
  11377. } else if ( customAttribute.size === 3 ) {
  11378. if ( customAttribute.type === 'c' ) {
  11379. for ( ca = 0; ca < cal; ca ++ ) {
  11380. value = customAttribute.value[ ca ];
  11381. customAttribute.array[ offset ] = value.r;
  11382. customAttribute.array[ offset + 1 ] = value.g;
  11383. customAttribute.array[ offset + 2 ] = value.b;
  11384. offset += 3;
  11385. }
  11386. } else {
  11387. for ( ca = 0; ca < cal; ca ++ ) {
  11388. value = customAttribute.value[ ca ];
  11389. customAttribute.array[ offset ] = value.x;
  11390. customAttribute.array[ offset + 1 ] = value.y;
  11391. customAttribute.array[ offset + 2 ] = value.z;
  11392. offset += 3;
  11393. }
  11394. }
  11395. } else if ( customAttribute.size === 4 ) {
  11396. for ( ca = 0; ca < cal; ca ++ ) {
  11397. value = customAttribute.value[ ca ];
  11398. customAttribute.array[ offset ] = value.x;
  11399. customAttribute.array[ offset + 1 ] = value.y;
  11400. customAttribute.array[ offset + 2 ] = value.z;
  11401. customAttribute.array[ offset + 3 ] = value.w;
  11402. offset += 4;
  11403. }
  11404. }
  11405. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11406. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11407. customAttribute.needsUpdate = false;
  11408. }
  11409. }
  11410. }
  11411. }
  11412. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  11413. if ( ! geometryGroup.__inittedArrays ) {
  11414. return;
  11415. }
  11416. var needsFaceNormals = materialNeedsFaceNormals( material );
  11417. var f, fl, fi, face,
  11418. vertexNormals, faceNormal,
  11419. vertexColors, faceColor,
  11420. vertexTangents,
  11421. uv, uv2, v1, v2, v3, t1, t2, t3, n1, n2, n3,
  11422. c1, c2, c3,
  11423. sw1, sw2, sw3,
  11424. si1, si2, si3,
  11425. i, il,
  11426. vn, uvi, uv2i,
  11427. vk, vkl, vka,
  11428. nka, chf, faceVertexNormals,
  11429. vertexIndex = 0,
  11430. offset = 0,
  11431. offset_uv = 0,
  11432. offset_uv2 = 0,
  11433. offset_face = 0,
  11434. offset_normal = 0,
  11435. offset_tangent = 0,
  11436. offset_line = 0,
  11437. offset_color = 0,
  11438. offset_skin = 0,
  11439. offset_morphTarget = 0,
  11440. offset_custom = 0,
  11441. value,
  11442. vertexArray = geometryGroup.__vertexArray,
  11443. uvArray = geometryGroup.__uvArray,
  11444. uv2Array = geometryGroup.__uv2Array,
  11445. normalArray = geometryGroup.__normalArray,
  11446. tangentArray = geometryGroup.__tangentArray,
  11447. colorArray = geometryGroup.__colorArray,
  11448. skinIndexArray = geometryGroup.__skinIndexArray,
  11449. skinWeightArray = geometryGroup.__skinWeightArray,
  11450. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  11451. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  11452. customAttributes = geometryGroup.__webglCustomAttributesList,
  11453. customAttribute,
  11454. faceArray = geometryGroup.__faceArray,
  11455. lineArray = geometryGroup.__lineArray,
  11456. geometry = object.geometry, // this is shared for all chunks
  11457. dirtyVertices = geometry.verticesNeedUpdate,
  11458. dirtyElements = geometry.elementsNeedUpdate,
  11459. dirtyUvs = geometry.uvsNeedUpdate,
  11460. dirtyNormals = geometry.normalsNeedUpdate,
  11461. dirtyTangents = geometry.tangentsNeedUpdate,
  11462. dirtyColors = geometry.colorsNeedUpdate,
  11463. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  11464. vertices = geometry.vertices,
  11465. chunk_faces3 = geometryGroup.faces3,
  11466. obj_faces = geometry.faces,
  11467. obj_uvs = geometry.faceVertexUvs[ 0 ],
  11468. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  11469. obj_skinIndices = geometry.skinIndices,
  11470. obj_skinWeights = geometry.skinWeights,
  11471. morphTargets = geometry.morphTargets,
  11472. morphNormals = geometry.morphNormals;
  11473. if ( dirtyVertices ) {
  11474. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11475. face = obj_faces[ chunk_faces3[ f ] ];
  11476. v1 = vertices[ face.a ];
  11477. v2 = vertices[ face.b ];
  11478. v3 = vertices[ face.c ];
  11479. vertexArray[ offset ] = v1.x;
  11480. vertexArray[ offset + 1 ] = v1.y;
  11481. vertexArray[ offset + 2 ] = v1.z;
  11482. vertexArray[ offset + 3 ] = v2.x;
  11483. vertexArray[ offset + 4 ] = v2.y;
  11484. vertexArray[ offset + 5 ] = v2.z;
  11485. vertexArray[ offset + 6 ] = v3.x;
  11486. vertexArray[ offset + 7 ] = v3.y;
  11487. vertexArray[ offset + 8 ] = v3.z;
  11488. offset += 9;
  11489. }
  11490. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  11491. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11492. }
  11493. if ( dirtyMorphTargets ) {
  11494. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  11495. offset_morphTarget = 0;
  11496. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11497. chf = chunk_faces3[ f ];
  11498. face = obj_faces[ chf ];
  11499. // morph positions
  11500. v1 = morphTargets[ vk ].vertices[ face.a ];
  11501. v2 = morphTargets[ vk ].vertices[ face.b ];
  11502. v3 = morphTargets[ vk ].vertices[ face.c ];
  11503. vka = morphTargetsArrays[ vk ];
  11504. vka[ offset_morphTarget ] = v1.x;
  11505. vka[ offset_morphTarget + 1 ] = v1.y;
  11506. vka[ offset_morphTarget + 2 ] = v1.z;
  11507. vka[ offset_morphTarget + 3 ] = v2.x;
  11508. vka[ offset_morphTarget + 4 ] = v2.y;
  11509. vka[ offset_morphTarget + 5 ] = v2.z;
  11510. vka[ offset_morphTarget + 6 ] = v3.x;
  11511. vka[ offset_morphTarget + 7 ] = v3.y;
  11512. vka[ offset_morphTarget + 8 ] = v3.z;
  11513. // morph normals
  11514. if ( material.morphNormals ) {
  11515. if ( needsFaceNormals ) {
  11516. n1 = morphNormals[ vk ].faceNormals[ chf ];
  11517. n2 = n1;
  11518. n3 = n1;
  11519. } else {
  11520. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  11521. n1 = faceVertexNormals.a;
  11522. n2 = faceVertexNormals.b;
  11523. n3 = faceVertexNormals.c;
  11524. }
  11525. nka = morphNormalsArrays[ vk ];
  11526. nka[ offset_morphTarget ] = n1.x;
  11527. nka[ offset_morphTarget + 1 ] = n1.y;
  11528. nka[ offset_morphTarget + 2 ] = n1.z;
  11529. nka[ offset_morphTarget + 3 ] = n2.x;
  11530. nka[ offset_morphTarget + 4 ] = n2.y;
  11531. nka[ offset_morphTarget + 5 ] = n2.z;
  11532. nka[ offset_morphTarget + 6 ] = n3.x;
  11533. nka[ offset_morphTarget + 7 ] = n3.y;
  11534. nka[ offset_morphTarget + 8 ] = n3.z;
  11535. }
  11536. //
  11537. offset_morphTarget += 9;
  11538. }
  11539. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  11540. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  11541. if ( material.morphNormals ) {
  11542. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  11543. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  11544. }
  11545. }
  11546. }
  11547. if ( obj_skinWeights.length ) {
  11548. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11549. face = obj_faces[ chunk_faces3[ f ] ];
  11550. // weights
  11551. sw1 = obj_skinWeights[ face.a ];
  11552. sw2 = obj_skinWeights[ face.b ];
  11553. sw3 = obj_skinWeights[ face.c ];
  11554. skinWeightArray[ offset_skin ] = sw1.x;
  11555. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  11556. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  11557. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  11558. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  11559. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  11560. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  11561. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  11562. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  11563. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  11564. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  11565. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  11566. // indices
  11567. si1 = obj_skinIndices[ face.a ];
  11568. si2 = obj_skinIndices[ face.b ];
  11569. si3 = obj_skinIndices[ face.c ];
  11570. skinIndexArray[ offset_skin ] = si1.x;
  11571. skinIndexArray[ offset_skin + 1 ] = si1.y;
  11572. skinIndexArray[ offset_skin + 2 ] = si1.z;
  11573. skinIndexArray[ offset_skin + 3 ] = si1.w;
  11574. skinIndexArray[ offset_skin + 4 ] = si2.x;
  11575. skinIndexArray[ offset_skin + 5 ] = si2.y;
  11576. skinIndexArray[ offset_skin + 6 ] = si2.z;
  11577. skinIndexArray[ offset_skin + 7 ] = si2.w;
  11578. skinIndexArray[ offset_skin + 8 ] = si3.x;
  11579. skinIndexArray[ offset_skin + 9 ] = si3.y;
  11580. skinIndexArray[ offset_skin + 10 ] = si3.z;
  11581. skinIndexArray[ offset_skin + 11 ] = si3.w;
  11582. offset_skin += 12;
  11583. }
  11584. if ( offset_skin > 0 ) {
  11585. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  11586. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  11587. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  11588. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  11589. }
  11590. }
  11591. if ( dirtyColors ) {
  11592. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11593. face = obj_faces[ chunk_faces3[ f ] ];
  11594. vertexColors = face.vertexColors;
  11595. faceColor = face.color;
  11596. if ( vertexColors.length === 3 && material.vertexColors === THREE.VertexColors ) {
  11597. c1 = vertexColors[ 0 ];
  11598. c2 = vertexColors[ 1 ];
  11599. c3 = vertexColors[ 2 ];
  11600. } else {
  11601. c1 = faceColor;
  11602. c2 = faceColor;
  11603. c3 = faceColor;
  11604. }
  11605. colorArray[ offset_color ] = c1.r;
  11606. colorArray[ offset_color + 1 ] = c1.g;
  11607. colorArray[ offset_color + 2 ] = c1.b;
  11608. colorArray[ offset_color + 3 ] = c2.r;
  11609. colorArray[ offset_color + 4 ] = c2.g;
  11610. colorArray[ offset_color + 5 ] = c2.b;
  11611. colorArray[ offset_color + 6 ] = c3.r;
  11612. colorArray[ offset_color + 7 ] = c3.g;
  11613. colorArray[ offset_color + 8 ] = c3.b;
  11614. offset_color += 9;
  11615. }
  11616. if ( offset_color > 0 ) {
  11617. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  11618. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11619. }
  11620. }
  11621. if ( dirtyTangents && geometry.hasTangents ) {
  11622. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11623. face = obj_faces[ chunk_faces3[ f ] ];
  11624. vertexTangents = face.vertexTangents;
  11625. t1 = vertexTangents[ 0 ];
  11626. t2 = vertexTangents[ 1 ];
  11627. t3 = vertexTangents[ 2 ];
  11628. tangentArray[ offset_tangent ] = t1.x;
  11629. tangentArray[ offset_tangent + 1 ] = t1.y;
  11630. tangentArray[ offset_tangent + 2 ] = t1.z;
  11631. tangentArray[ offset_tangent + 3 ] = t1.w;
  11632. tangentArray[ offset_tangent + 4 ] = t2.x;
  11633. tangentArray[ offset_tangent + 5 ] = t2.y;
  11634. tangentArray[ offset_tangent + 6 ] = t2.z;
  11635. tangentArray[ offset_tangent + 7 ] = t2.w;
  11636. tangentArray[ offset_tangent + 8 ] = t3.x;
  11637. tangentArray[ offset_tangent + 9 ] = t3.y;
  11638. tangentArray[ offset_tangent + 10 ] = t3.z;
  11639. tangentArray[ offset_tangent + 11 ] = t3.w;
  11640. offset_tangent += 12;
  11641. }
  11642. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  11643. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  11644. }
  11645. if ( dirtyNormals ) {
  11646. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11647. face = obj_faces[ chunk_faces3[ f ] ];
  11648. vertexNormals = face.vertexNormals;
  11649. faceNormal = face.normal;
  11650. if ( vertexNormals.length === 3 && needsFaceNormals === false ) {
  11651. for ( i = 0; i < 3; i ++ ) {
  11652. vn = vertexNormals[ i ];
  11653. normalArray[ offset_normal ] = vn.x;
  11654. normalArray[ offset_normal + 1 ] = vn.y;
  11655. normalArray[ offset_normal + 2 ] = vn.z;
  11656. offset_normal += 3;
  11657. }
  11658. } else {
  11659. for ( i = 0; i < 3; i ++ ) {
  11660. normalArray[ offset_normal ] = faceNormal.x;
  11661. normalArray[ offset_normal + 1 ] = faceNormal.y;
  11662. normalArray[ offset_normal + 2 ] = faceNormal.z;
  11663. offset_normal += 3;
  11664. }
  11665. }
  11666. }
  11667. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  11668. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  11669. }
  11670. if ( dirtyUvs && obj_uvs ) {
  11671. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11672. fi = chunk_faces3[ f ];
  11673. uv = obj_uvs[ fi ];
  11674. if ( uv === undefined ) continue;
  11675. for ( i = 0; i < 3; i ++ ) {
  11676. uvi = uv[ i ];
  11677. uvArray[ offset_uv ] = uvi.x;
  11678. uvArray[ offset_uv + 1 ] = uvi.y;
  11679. offset_uv += 2;
  11680. }
  11681. }
  11682. if ( offset_uv > 0 ) {
  11683. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  11684. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  11685. }
  11686. }
  11687. if ( dirtyUvs && obj_uvs2 ) {
  11688. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11689. fi = chunk_faces3[ f ];
  11690. uv2 = obj_uvs2[ fi ];
  11691. if ( uv2 === undefined ) continue;
  11692. for ( i = 0; i < 3; i ++ ) {
  11693. uv2i = uv2[ i ];
  11694. uv2Array[ offset_uv2 ] = uv2i.x;
  11695. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  11696. offset_uv2 += 2;
  11697. }
  11698. }
  11699. if ( offset_uv2 > 0 ) {
  11700. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  11701. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  11702. }
  11703. }
  11704. if ( dirtyElements ) {
  11705. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11706. faceArray[ offset_face ] = vertexIndex;
  11707. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  11708. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  11709. offset_face += 3;
  11710. lineArray[ offset_line ] = vertexIndex;
  11711. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  11712. lineArray[ offset_line + 2 ] = vertexIndex;
  11713. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  11714. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  11715. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  11716. offset_line += 6;
  11717. vertexIndex += 3;
  11718. }
  11719. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  11720. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  11721. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  11722. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  11723. }
  11724. if ( customAttributes ) {
  11725. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11726. customAttribute = customAttributes[ i ];
  11727. if ( ! customAttribute.__original.needsUpdate ) continue;
  11728. offset_custom = 0;
  11729. if ( customAttribute.size === 1 ) {
  11730. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) {
  11731. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11732. face = obj_faces[ chunk_faces3[ f ] ];
  11733. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  11734. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  11735. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  11736. offset_custom += 3;
  11737. }
  11738. } else if ( customAttribute.boundTo === 'faces' ) {
  11739. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11740. value = customAttribute.value[ chunk_faces3[ f ] ];
  11741. customAttribute.array[ offset_custom ] = value;
  11742. customAttribute.array[ offset_custom + 1 ] = value;
  11743. customAttribute.array[ offset_custom + 2 ] = value;
  11744. offset_custom += 3;
  11745. }
  11746. }
  11747. } else if ( customAttribute.size === 2 ) {
  11748. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) {
  11749. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11750. face = obj_faces[ chunk_faces3[ f ] ];
  11751. v1 = customAttribute.value[ face.a ];
  11752. v2 = customAttribute.value[ face.b ];
  11753. v3 = customAttribute.value[ face.c ];
  11754. customAttribute.array[ offset_custom ] = v1.x;
  11755. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11756. customAttribute.array[ offset_custom + 2 ] = v2.x;
  11757. customAttribute.array[ offset_custom + 3 ] = v2.y;
  11758. customAttribute.array[ offset_custom + 4 ] = v3.x;
  11759. customAttribute.array[ offset_custom + 5 ] = v3.y;
  11760. offset_custom += 6;
  11761. }
  11762. } else if ( customAttribute.boundTo === 'faces' ) {
  11763. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11764. value = customAttribute.value[ chunk_faces3[ f ] ];
  11765. v1 = value;
  11766. v2 = value;
  11767. v3 = value;
  11768. customAttribute.array[ offset_custom ] = v1.x;
  11769. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11770. customAttribute.array[ offset_custom + 2 ] = v2.x;
  11771. customAttribute.array[ offset_custom + 3 ] = v2.y;
  11772. customAttribute.array[ offset_custom + 4 ] = v3.x;
  11773. customAttribute.array[ offset_custom + 5 ] = v3.y;
  11774. offset_custom += 6;
  11775. }
  11776. }
  11777. } else if ( customAttribute.size === 3 ) {
  11778. var pp;
  11779. if ( customAttribute.type === 'c' ) {
  11780. pp = [ 'r', 'g', 'b' ];
  11781. } else {
  11782. pp = [ 'x', 'y', 'z' ];
  11783. }
  11784. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) {
  11785. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11786. face = obj_faces[ chunk_faces3[ f ] ];
  11787. v1 = customAttribute.value[ face.a ];
  11788. v2 = customAttribute.value[ face.b ];
  11789. v3 = customAttribute.value[ face.c ];
  11790. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11791. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11792. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11793. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11794. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11795. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11796. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11797. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11798. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11799. offset_custom += 9;
  11800. }
  11801. } else if ( customAttribute.boundTo === 'faces' ) {
  11802. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11803. value = customAttribute.value[ chunk_faces3[ f ] ];
  11804. v1 = value;
  11805. v2 = value;
  11806. v3 = value;
  11807. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11808. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11809. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11810. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11811. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11812. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11813. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11814. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11815. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11816. offset_custom += 9;
  11817. }
  11818. } else if ( customAttribute.boundTo === 'faceVertices' ) {
  11819. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11820. value = customAttribute.value[ chunk_faces3[ f ] ];
  11821. v1 = value[ 0 ];
  11822. v2 = value[ 1 ];
  11823. v3 = value[ 2 ];
  11824. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11825. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11826. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11827. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11828. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11829. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11830. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11831. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11832. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11833. offset_custom += 9;
  11834. }
  11835. }
  11836. } else if ( customAttribute.size === 4 ) {
  11837. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) {
  11838. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11839. face = obj_faces[ chunk_faces3[ f ] ];
  11840. v1 = customAttribute.value[ face.a ];
  11841. v2 = customAttribute.value[ face.b ];
  11842. v3 = customAttribute.value[ face.c ];
  11843. customAttribute.array[ offset_custom ] = v1.x;
  11844. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11845. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11846. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11847. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11848. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11849. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11850. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11851. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11852. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11853. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11854. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11855. offset_custom += 12;
  11856. }
  11857. } else if ( customAttribute.boundTo === 'faces' ) {
  11858. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11859. value = customAttribute.value[ chunk_faces3[ f ] ];
  11860. v1 = value;
  11861. v2 = value;
  11862. v3 = value;
  11863. customAttribute.array[ offset_custom ] = v1.x;
  11864. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11865. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11866. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11867. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11868. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11869. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11870. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11871. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11872. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11873. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11874. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11875. offset_custom += 12;
  11876. }
  11877. } else if ( customAttribute.boundTo === 'faceVertices' ) {
  11878. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11879. value = customAttribute.value[ chunk_faces3[ f ] ];
  11880. v1 = value[ 0 ];
  11881. v2 = value[ 1 ];
  11882. v3 = value[ 2 ];
  11883. customAttribute.array[ offset_custom ] = v1.x;
  11884. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11885. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11886. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11887. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11888. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11889. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11890. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11891. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11892. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11893. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11894. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11895. offset_custom += 12;
  11896. }
  11897. }
  11898. }
  11899. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11900. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11901. }
  11902. }
  11903. if ( dispose ) {
  11904. delete geometryGroup.__inittedArrays;
  11905. delete geometryGroup.__colorArray;
  11906. delete geometryGroup.__normalArray;
  11907. delete geometryGroup.__tangentArray;
  11908. delete geometryGroup.__uvArray;
  11909. delete geometryGroup.__uv2Array;
  11910. delete geometryGroup.__faceArray;
  11911. delete geometryGroup.__vertexArray;
  11912. delete geometryGroup.__lineArray;
  11913. delete geometryGroup.__skinIndexArray;
  11914. delete geometryGroup.__skinWeightArray;
  11915. }
  11916. };
  11917. // Buffer rendering
  11918. this.renderBufferImmediate = function ( object, program, material ) {
  11919. state.initAttributes();
  11920. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  11921. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  11922. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  11923. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  11924. if ( object.hasPositions ) {
  11925. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  11926. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  11927. state.enableAttribute( program.attributes.position );
  11928. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11929. }
  11930. if ( object.hasNormals ) {
  11931. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  11932. if ( material instanceof THREE.MeshPhongMaterial === false &&
  11933. material.shading === THREE.FlatShading ) {
  11934. var nx, ny, nz,
  11935. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  11936. normalArray,
  11937. i, il = object.count * 3;
  11938. for ( i = 0; i < il; i += 9 ) {
  11939. normalArray = object.normalArray;
  11940. nax = normalArray[ i ];
  11941. nay = normalArray[ i + 1 ];
  11942. naz = normalArray[ i + 2 ];
  11943. nbx = normalArray[ i + 3 ];
  11944. nby = normalArray[ i + 4 ];
  11945. nbz = normalArray[ i + 5 ];
  11946. ncx = normalArray[ i + 6 ];
  11947. ncy = normalArray[ i + 7 ];
  11948. ncz = normalArray[ i + 8 ];
  11949. nx = ( nax + nbx + ncx ) / 3;
  11950. ny = ( nay + nby + ncy ) / 3;
  11951. nz = ( naz + nbz + ncz ) / 3;
  11952. normalArray[ i ] = nx;
  11953. normalArray[ i + 1 ] = ny;
  11954. normalArray[ i + 2 ] = nz;
  11955. normalArray[ i + 3 ] = nx;
  11956. normalArray[ i + 4 ] = ny;
  11957. normalArray[ i + 5 ] = nz;
  11958. normalArray[ i + 6 ] = nx;
  11959. normalArray[ i + 7 ] = ny;
  11960. normalArray[ i + 8 ] = nz;
  11961. }
  11962. }
  11963. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  11964. state.enableAttribute( program.attributes.normal );
  11965. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  11966. }
  11967. if ( object.hasUvs && material.map ) {
  11968. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  11969. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  11970. state.enableAttribute( program.attributes.uv );
  11971. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  11972. }
  11973. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  11974. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  11975. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  11976. state.enableAttribute( program.attributes.color );
  11977. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  11978. }
  11979. state.disableUnusedAttributes();
  11980. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  11981. object.count = 0;
  11982. };
  11983. function setupVertexAttributes( material, program, geometry, startIndex ) {
  11984. var geometryAttributes = geometry.attributes;
  11985. var programAttributes = program.attributes;
  11986. var programAttributesKeys = program.attributesKeys;
  11987. for ( var i = 0, l = programAttributesKeys.length; i < l; i ++ ) {
  11988. var key = programAttributesKeys[ i ];
  11989. var programAttribute = programAttributes[ key ];
  11990. if ( programAttribute >= 0 ) {
  11991. var geometryAttribute = geometryAttributes[ key ];
  11992. if ( geometryAttribute !== undefined ) {
  11993. var size = geometryAttribute.itemSize;
  11994. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryAttribute.buffer );
  11995. state.enableAttribute( programAttribute );
  11996. _gl.vertexAttribPointer( programAttribute, size, _gl.FLOAT, false, 0, startIndex * size * 4 ); // 4 bytes per Float32
  11997. } else if ( material.defaultAttributeValues !== undefined ) {
  11998. if ( material.defaultAttributeValues[ key ].length === 2 ) {
  11999. _gl.vertexAttrib2fv( programAttribute, material.defaultAttributeValues[ key ] );
  12000. } else if ( material.defaultAttributeValues[ key ].length === 3 ) {
  12001. _gl.vertexAttrib3fv( programAttribute, material.defaultAttributeValues[ key ] );
  12002. }
  12003. }
  12004. }
  12005. }
  12006. state.disableUnusedAttributes();
  12007. }
  12008. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  12009. if ( material.visible === false ) return;
  12010. updateObject( object );
  12011. var program = setProgram( camera, lights, fog, material, object );
  12012. var updateBuffers = false,
  12013. wireframeBit = material.wireframe ? 1 : 0,
  12014. geometryProgram = 'direct_' + geometry.id + '_' + program.id + '_' + wireframeBit;
  12015. if ( geometryProgram !== _currentGeometryProgram ) {
  12016. _currentGeometryProgram = geometryProgram;
  12017. updateBuffers = true;
  12018. }
  12019. if ( updateBuffers ) {
  12020. state.initAttributes();
  12021. }
  12022. // render mesh
  12023. if ( object instanceof THREE.Mesh ) {
  12024. var mode = material.wireframe === true ? _gl.LINES : _gl.TRIANGLES;
  12025. var index = geometry.attributes.index;
  12026. if ( index ) {
  12027. // indexed triangles
  12028. var type, size;
  12029. if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) {
  12030. type = _gl.UNSIGNED_INT;
  12031. size = 4;
  12032. } else {
  12033. type = _gl.UNSIGNED_SHORT;
  12034. size = 2;
  12035. }
  12036. var offsets = geometry.offsets;
  12037. if ( offsets.length === 0 ) {
  12038. if ( updateBuffers ) {
  12039. setupVertexAttributes( material, program, geometry, 0 );
  12040. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  12041. }
  12042. _gl.drawElements( mode, index.array.length, type, 0 );
  12043. _this.info.render.calls ++;
  12044. _this.info.render.vertices += index.array.length; // not really true, here vertices can be shared
  12045. _this.info.render.faces += index.array.length / 3;
  12046. } else {
  12047. // if there is more than 1 chunk
  12048. // must set attribute pointers to use new offsets for each chunk
  12049. // even if geometry and materials didn't change
  12050. updateBuffers = true;
  12051. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  12052. var startIndex = offsets[ i ].index;
  12053. if ( updateBuffers ) {
  12054. setupVertexAttributes( material, program, geometry, startIndex );
  12055. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  12056. }
  12057. // render indexed triangles
  12058. _gl.drawElements( mode, offsets[ i ].count, type, offsets[ i ].start * size );
  12059. _this.info.render.calls ++;
  12060. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  12061. _this.info.render.faces += offsets[ i ].count / 3;
  12062. }
  12063. }
  12064. } else {
  12065. // non-indexed triangles
  12066. if ( updateBuffers ) {
  12067. setupVertexAttributes( material, program, geometry, 0 );
  12068. }
  12069. var position = geometry.attributes[ 'position' ];
  12070. // render non-indexed triangles
  12071. _gl.drawArrays( mode, 0, position.array.length / position.itemSize );
  12072. _this.info.render.calls ++;
  12073. _this.info.render.vertices += position.array.length / position.itemSize;
  12074. _this.info.render.faces += position.array.length / ( 3 * position.itemSize );
  12075. }
  12076. } else if ( object instanceof THREE.PointCloud ) {
  12077. // render particles
  12078. var mode = _gl.POINTS;
  12079. var index = geometry.attributes.index;
  12080. if ( index ) {
  12081. // indexed points
  12082. var type, size;
  12083. if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) {
  12084. type = _gl.UNSIGNED_INT;
  12085. size = 4;
  12086. } else {
  12087. type = _gl.UNSIGNED_SHORT;
  12088. size = 2;
  12089. }
  12090. var offsets = geometry.offsets;
  12091. if ( offsets.length === 0 ) {
  12092. if ( updateBuffers ) {
  12093. setupVertexAttributes( material, program, geometry, 0 );
  12094. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  12095. }
  12096. _gl.drawElements( mode, index.array.length, type, 0);
  12097. _this.info.render.calls ++;
  12098. _this.info.render.points += index.array.length;
  12099. } else {
  12100. // if there is more than 1 chunk
  12101. // must set attribute pointers to use new offsets for each chunk
  12102. // even if geometry and materials didn't change
  12103. if ( offsets.length > 1 ) updateBuffers = true;
  12104. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  12105. var startIndex = offsets[ i ].index;
  12106. if ( updateBuffers ) {
  12107. setupVertexAttributes( material, program, geometry, startIndex );
  12108. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  12109. }
  12110. // render indexed points
  12111. _gl.drawElements( mode, offsets[ i ].count, type, offsets[ i ].start * size );
  12112. _this.info.render.calls ++;
  12113. _this.info.render.points += offsets[ i ].count;
  12114. }
  12115. }
  12116. } else {
  12117. // non-indexed points
  12118. if ( updateBuffers ) {
  12119. setupVertexAttributes( material, program, geometry, 0 );
  12120. }
  12121. var position = geometry.attributes.position;
  12122. var offsets = geometry.offsets;
  12123. if ( offsets.length === 0 ) {
  12124. _gl.drawArrays( mode, 0, position.array.length / 3 );
  12125. _this.info.render.calls ++;
  12126. _this.info.render.points += position.array.length / 3;
  12127. } else {
  12128. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  12129. _gl.drawArrays( mode, offsets[ i ].index, offsets[ i ].count );
  12130. _this.info.render.calls ++;
  12131. _this.info.render.points += offsets[ i ].count;
  12132. }
  12133. }
  12134. }
  12135. } else if ( object instanceof THREE.Line ) {
  12136. var mode = ( object.mode === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  12137. state.setLineWidth( material.linewidth * pixelRatio );
  12138. var index = geometry.attributes.index;
  12139. if ( index ) {
  12140. // indexed lines
  12141. var type, size;
  12142. if ( index.array instanceof Uint32Array ) {
  12143. type = _gl.UNSIGNED_INT;
  12144. size = 4;
  12145. } else {
  12146. type = _gl.UNSIGNED_SHORT;
  12147. size = 2;
  12148. }
  12149. var offsets = geometry.offsets;
  12150. if ( offsets.length === 0 ) {
  12151. if ( updateBuffers ) {
  12152. setupVertexAttributes( material, program, geometry, 0 );
  12153. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  12154. }
  12155. _gl.drawElements( mode, index.array.length, type, 0 ); // 2 bytes per Uint16Array
  12156. _this.info.render.calls ++;
  12157. _this.info.render.vertices += index.array.length; // not really true, here vertices can be shared
  12158. } else {
  12159. // if there is more than 1 chunk
  12160. // must set attribute pointers to use new offsets for each chunk
  12161. // even if geometry and materials didn't change
  12162. if ( offsets.length > 1 ) updateBuffers = true;
  12163. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  12164. var startIndex = offsets[ i ].index;
  12165. if ( updateBuffers ) {
  12166. setupVertexAttributes( material, program, geometry, startIndex );
  12167. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  12168. }
  12169. // render indexed lines
  12170. _gl.drawElements( mode, offsets[ i ].count, type, offsets[ i ].start * size ); // 2 bytes per Uint16Array
  12171. _this.info.render.calls ++;
  12172. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  12173. }
  12174. }
  12175. } else {
  12176. // non-indexed lines
  12177. if ( updateBuffers ) {
  12178. setupVertexAttributes( material, program, geometry, 0 );
  12179. }
  12180. var position = geometry.attributes.position;
  12181. var offsets = geometry.offsets;
  12182. if ( offsets.length === 0 ) {
  12183. _gl.drawArrays( mode, 0, position.array.length / 3 );
  12184. _this.info.render.calls ++;
  12185. _this.info.render.vertices += position.array.length / 3;
  12186. } else {
  12187. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  12188. _gl.drawArrays( mode, offsets[ i ].index, offsets[ i ].count );
  12189. _this.info.render.calls ++;
  12190. _this.info.render.vertices += offsets[ i ].count;
  12191. }
  12192. }
  12193. }
  12194. }
  12195. };
  12196. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  12197. if ( material.visible === false ) return;
  12198. updateObject( object );
  12199. var program = setProgram( camera, lights, fog, material, object );
  12200. var attributes = program.attributes;
  12201. var updateBuffers = false,
  12202. wireframeBit = material.wireframe ? 1 : 0,
  12203. geometryProgram = geometryGroup.id + '_' + program.id + '_' + wireframeBit;
  12204. if ( geometryProgram !== _currentGeometryProgram ) {
  12205. _currentGeometryProgram = geometryProgram;
  12206. updateBuffers = true;
  12207. }
  12208. if ( updateBuffers ) {
  12209. state.initAttributes();
  12210. }
  12211. // vertices
  12212. if ( ! material.morphTargets && attributes.position >= 0 ) {
  12213. if ( updateBuffers ) {
  12214. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12215. state.enableAttribute( attributes.position );
  12216. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12217. }
  12218. } else {
  12219. if ( object.morphTargetBase ) {
  12220. setupMorphTargets( material, geometryGroup, object );
  12221. }
  12222. }
  12223. if ( updateBuffers ) {
  12224. // custom attributes
  12225. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  12226. if ( geometryGroup.__webglCustomAttributesList ) {
  12227. for ( var i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  12228. var attribute = geometryGroup.__webglCustomAttributesList[ i ];
  12229. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  12230. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  12231. state.enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  12232. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  12233. }
  12234. }
  12235. }
  12236. // colors
  12237. if ( attributes.color >= 0 ) {
  12238. if ( object.geometry.colors.length > 0 || object.geometry.faces.length > 0 ) {
  12239. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  12240. state.enableAttribute( attributes.color );
  12241. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  12242. } else if ( material.defaultAttributeValues !== undefined ) {
  12243. _gl.vertexAttrib3fv( attributes.color, material.defaultAttributeValues.color );
  12244. }
  12245. }
  12246. // normals
  12247. if ( attributes.normal >= 0 ) {
  12248. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  12249. state.enableAttribute( attributes.normal );
  12250. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  12251. }
  12252. // tangents
  12253. if ( attributes.tangent >= 0 ) {
  12254. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  12255. state.enableAttribute( attributes.tangent );
  12256. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  12257. }
  12258. // uvs
  12259. if ( attributes.uv >= 0 ) {
  12260. if ( object.geometry.faceVertexUvs[ 0 ] ) {
  12261. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  12262. state.enableAttribute( attributes.uv );
  12263. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  12264. } else if ( material.defaultAttributeValues !== undefined ) {
  12265. _gl.vertexAttrib2fv( attributes.uv, material.defaultAttributeValues.uv );
  12266. }
  12267. }
  12268. if ( attributes.uv2 >= 0 ) {
  12269. if ( object.geometry.faceVertexUvs[ 1 ] ) {
  12270. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  12271. state.enableAttribute( attributes.uv2 );
  12272. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  12273. } else if ( material.defaultAttributeValues !== undefined ) {
  12274. _gl.vertexAttrib2fv( attributes.uv2, material.defaultAttributeValues.uv2 );
  12275. }
  12276. }
  12277. if ( material.skinning &&
  12278. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  12279. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  12280. state.enableAttribute( attributes.skinIndex );
  12281. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  12282. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  12283. state.enableAttribute( attributes.skinWeight );
  12284. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  12285. }
  12286. // line distances
  12287. if ( attributes.lineDistance >= 0 ) {
  12288. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  12289. state.enableAttribute( attributes.lineDistance );
  12290. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  12291. }
  12292. }
  12293. state.disableUnusedAttributes();
  12294. // render mesh
  12295. if ( object instanceof THREE.Mesh ) {
  12296. var type = geometryGroup.__typeArray === Uint32Array ? _gl.UNSIGNED_INT : _gl.UNSIGNED_SHORT;
  12297. // wireframe
  12298. if ( material.wireframe ) {
  12299. state.setLineWidth( material.wireframeLinewidth * pixelRatio );
  12300. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  12301. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, type, 0 );
  12302. // triangles
  12303. } else {
  12304. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  12305. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, type, 0 );
  12306. }
  12307. _this.info.render.calls ++;
  12308. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  12309. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  12310. // render lines
  12311. } else if ( object instanceof THREE.Line ) {
  12312. var mode = ( object.mode === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  12313. state.setLineWidth( material.linewidth * pixelRatio );
  12314. _gl.drawArrays( mode, 0, geometryGroup.__webglLineCount );
  12315. _this.info.render.calls ++;
  12316. // render particles
  12317. } else if ( object instanceof THREE.PointCloud ) {
  12318. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  12319. _this.info.render.calls ++;
  12320. _this.info.render.points += geometryGroup.__webglParticleCount;
  12321. }
  12322. };
  12323. function setupMorphTargets ( material, geometryGroup, object ) {
  12324. // set base
  12325. var attributes = material.program.attributes;
  12326. if ( object.morphTargetBase !== - 1 && attributes.position >= 0 ) {
  12327. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  12328. state.enableAttribute( attributes.position );
  12329. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12330. } else if ( attributes.position >= 0 ) {
  12331. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12332. state.enableAttribute( attributes.position );
  12333. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12334. }
  12335. if ( object.morphTargetForcedOrder.length ) {
  12336. // set forced order
  12337. var m = 0;
  12338. var order = object.morphTargetForcedOrder;
  12339. var influences = object.morphTargetInfluences;
  12340. var attribute;
  12341. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  12342. attribute = attributes[ 'morphTarget' + m ];
  12343. if ( attribute >= 0 ) {
  12344. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  12345. state.enableAttribute( attribute );
  12346. _gl.vertexAttribPointer( attribute, 3, _gl.FLOAT, false, 0, 0 );
  12347. }
  12348. attribute = attributes[ 'morphNormal' + m ];
  12349. if ( attribute >= 0 && material.morphNormals ) {
  12350. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  12351. state.enableAttribute( attribute );
  12352. _gl.vertexAttribPointer( attribute, 3, _gl.FLOAT, false, 0, 0 );
  12353. }
  12354. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  12355. m ++;
  12356. }
  12357. } else {
  12358. // find the most influencing
  12359. var activeInfluenceIndices = [];
  12360. var influences = object.morphTargetInfluences;
  12361. var morphTargets = object.geometry.morphTargets;
  12362. if ( influences.length > morphTargets.length ) {
  12363. console.warn( 'THREE.WebGLRenderer: Influences array is bigger than morphTargets array.' );
  12364. influences.length = morphTargets.length;
  12365. }
  12366. for ( var i = 0, il = influences.length; i < il; i ++ ) {
  12367. var influence = influences[ i ];
  12368. activeInfluenceIndices.push( [ influence, i ] );
  12369. }
  12370. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  12371. activeInfluenceIndices.sort( numericalSort );
  12372. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  12373. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  12374. activeInfluenceIndices.sort( numericalSort );
  12375. } else if ( activeInfluenceIndices.length === 0 ) {
  12376. activeInfluenceIndices.push( [ 0, 0 ] );
  12377. }
  12378. var attribute;
  12379. for ( var m = 0, ml = material.numSupportedMorphTargets; m < ml; m ++ ) {
  12380. if ( activeInfluenceIndices[ m ] ) {
  12381. var influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  12382. attribute = attributes[ 'morphTarget' + m ];
  12383. if ( attribute >= 0 ) {
  12384. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  12385. state.enableAttribute( attribute );
  12386. _gl.vertexAttribPointer( attribute, 3, _gl.FLOAT, false, 0, 0 );
  12387. }
  12388. attribute = attributes[ 'morphNormal' + m ];
  12389. if ( attribute >= 0 && material.morphNormals ) {
  12390. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  12391. state.enableAttribute( attribute );
  12392. _gl.vertexAttribPointer( attribute, 3, _gl.FLOAT, false, 0, 0 );
  12393. }
  12394. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  12395. } else {
  12396. /*
  12397. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12398. if ( material.morphNormals ) {
  12399. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12400. }
  12401. */
  12402. object.__webglMorphTargetInfluences[ m ] = 0;
  12403. }
  12404. }
  12405. }
  12406. // load updated influences uniform
  12407. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  12408. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  12409. }
  12410. }
  12411. // Sorting
  12412. function painterSortStable ( a, b ) {
  12413. if ( a.object.renderOrder !== b.object.renderOrder ) {
  12414. return a.object.renderOrder - b.object.renderOrder;
  12415. } else if ( a.material.id !== b.material.id ) {
  12416. return a.material.id - b.material.id;
  12417. } else if ( a.z !== b.z ) {
  12418. return a.z - b.z;
  12419. } else {
  12420. return a.id - b.id;
  12421. }
  12422. }
  12423. function reversePainterSortStable ( a, b ) {
  12424. if ( a.object.renderOrder !== b.object.renderOrder ) {
  12425. return a.object.renderOrder - b.object.renderOrder;
  12426. } if ( a.z !== b.z ) {
  12427. return b.z - a.z;
  12428. } else {
  12429. return a.id - b.id;
  12430. }
  12431. }
  12432. function numericalSort ( a, b ) {
  12433. return b[ 0 ] - a[ 0 ];
  12434. }
  12435. // Rendering
  12436. this.render = function ( scene, camera, renderTarget, forceClear ) {
  12437. if ( camera instanceof THREE.Camera === false ) {
  12438. THREE.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  12439. return;
  12440. }
  12441. var fog = scene.fog;
  12442. // reset caching for this frame
  12443. _currentGeometryProgram = '';
  12444. _currentMaterialId = - 1;
  12445. _currentCamera = null;
  12446. _lightsNeedUpdate = true;
  12447. // update scene graph
  12448. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  12449. // update camera matrices and frustum
  12450. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  12451. // update Skeleton objects
  12452. scene.traverse( function ( object ) {
  12453. if ( object instanceof THREE.SkinnedMesh ) {
  12454. object.skeleton.update();
  12455. }
  12456. } );
  12457. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  12458. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  12459. _frustum.setFromMatrix( _projScreenMatrix );
  12460. lights.length = 0;
  12461. opaqueObjects.length = 0;
  12462. transparentObjects.length = 0;
  12463. sprites.length = 0;
  12464. lensFlares.length = 0;
  12465. projectObject( scene );
  12466. if ( _this.sortObjects === true ) {
  12467. opaqueObjects.sort( painterSortStable );
  12468. transparentObjects.sort( reversePainterSortStable );
  12469. }
  12470. // custom render plugins (pre pass)
  12471. shadowMapPlugin.render( scene, camera );
  12472. //
  12473. _this.info.render.calls = 0;
  12474. _this.info.render.vertices = 0;
  12475. _this.info.render.faces = 0;
  12476. _this.info.render.points = 0;
  12477. this.setRenderTarget( renderTarget );
  12478. if ( this.autoClear || forceClear ) {
  12479. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  12480. }
  12481. // set matrices for immediate objects
  12482. for ( var i = 0, il = _webglObjectsImmediate.length; i < il; i ++ ) {
  12483. var webglObject = _webglObjectsImmediate[ i ];
  12484. var object = webglObject.object;
  12485. if ( object.visible ) {
  12486. setupMatrices( object, camera );
  12487. unrollImmediateBufferMaterial( webglObject );
  12488. }
  12489. }
  12490. if ( scene.overrideMaterial ) {
  12491. var overrideMaterial = scene.overrideMaterial;
  12492. setMaterial( overrideMaterial );
  12493. renderObjects( opaqueObjects, camera, lights, fog, overrideMaterial );
  12494. renderObjects( transparentObjects, camera, lights, fog, overrideMaterial );
  12495. renderObjectsImmediate( _webglObjectsImmediate, '', camera, lights, fog, overrideMaterial );
  12496. } else {
  12497. // opaque pass (front-to-back order)
  12498. state.setBlending( THREE.NoBlending );
  12499. renderObjects( opaqueObjects, camera, lights, fog, null );
  12500. renderObjectsImmediate( _webglObjectsImmediate, 'opaque', camera, lights, fog, null );
  12501. // transparent pass (back-to-front order)
  12502. renderObjects( transparentObjects, camera, lights, fog, null );
  12503. renderObjectsImmediate( _webglObjectsImmediate, 'transparent', camera, lights, fog, null );
  12504. }
  12505. // custom render plugins (post pass)
  12506. spritePlugin.render( scene, camera );
  12507. lensFlarePlugin.render( scene, camera, _currentWidth, _currentHeight );
  12508. // Generate mipmap if we're using any kind of mipmap filtering
  12509. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  12510. updateRenderTargetMipmap( renderTarget );
  12511. }
  12512. // Ensure depth buffer writing is enabled so it can be cleared on next render
  12513. state.setDepthTest( true );
  12514. state.setDepthWrite( true );
  12515. state.setColorWrite( true );
  12516. // _gl.finish();
  12517. };
  12518. function projectObject( object ) {
  12519. if ( object.visible === false ) return;
  12520. if ( object instanceof THREE.Scene || object instanceof THREE.Group ) {
  12521. // skip
  12522. } else {
  12523. initObject( object );
  12524. if ( object instanceof THREE.Light ) {
  12525. lights.push( object );
  12526. } else if ( object instanceof THREE.Sprite ) {
  12527. sprites.push( object );
  12528. } else if ( object instanceof THREE.LensFlare ) {
  12529. lensFlares.push( object );
  12530. } else {
  12531. var webglObjects = _webglObjects[ object.id ];
  12532. if ( webglObjects && ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) ) {
  12533. for ( var i = 0, l = webglObjects.length; i < l; i ++ ) {
  12534. var webglObject = webglObjects[ i ];
  12535. unrollBufferMaterial( webglObject );
  12536. webglObject.render = true;
  12537. if ( _this.sortObjects === true ) {
  12538. _vector3.setFromMatrixPosition( object.matrixWorld );
  12539. _vector3.applyProjection( _projScreenMatrix );
  12540. webglObject.z = _vector3.z;
  12541. }
  12542. }
  12543. }
  12544. }
  12545. }
  12546. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  12547. projectObject( object.children[ i ] );
  12548. }
  12549. }
  12550. function renderObjects( renderList, camera, lights, fog, overrideMaterial ) {
  12551. var material;
  12552. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  12553. var webglObject = renderList[ i ];
  12554. var object = webglObject.object;
  12555. var buffer = webglObject.buffer;
  12556. setupMatrices( object, camera );
  12557. if ( overrideMaterial ) {
  12558. material = overrideMaterial;
  12559. } else {
  12560. material = webglObject.material;
  12561. if ( ! material ) continue;
  12562. setMaterial( material );
  12563. }
  12564. _this.setMaterialFaces( material );
  12565. if ( buffer instanceof THREE.BufferGeometry ) {
  12566. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  12567. } else {
  12568. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  12569. }
  12570. }
  12571. }
  12572. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, overrideMaterial ) {
  12573. var material;
  12574. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  12575. var webglObject = renderList[ i ];
  12576. var object = webglObject.object;
  12577. if ( object.visible ) {
  12578. if ( overrideMaterial ) {
  12579. material = overrideMaterial;
  12580. } else {
  12581. material = webglObject[ materialType ];
  12582. if ( ! material ) continue;
  12583. setMaterial( material );
  12584. }
  12585. _this.renderImmediateObject( camera, lights, fog, material, object );
  12586. }
  12587. }
  12588. }
  12589. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  12590. var program = setProgram( camera, lights, fog, material, object );
  12591. _currentGeometryProgram = '';
  12592. _this.setMaterialFaces( material );
  12593. if ( object.immediateRenderCallback ) {
  12594. object.immediateRenderCallback( program, _gl, _frustum );
  12595. } else {
  12596. object.render( function ( object ) { _this.renderBufferImmediate( object, program, material ); } );
  12597. }
  12598. };
  12599. function unrollImmediateBufferMaterial ( globject ) {
  12600. var object = globject.object,
  12601. material = object.material;
  12602. if ( material.transparent ) {
  12603. globject.transparent = material;
  12604. globject.opaque = null;
  12605. } else {
  12606. globject.opaque = material;
  12607. globject.transparent = null;
  12608. }
  12609. }
  12610. function unrollBufferMaterial ( globject ) {
  12611. var object = globject.object;
  12612. var buffer = globject.buffer;
  12613. var geometry = object.geometry;
  12614. var material = object.material;
  12615. if ( material instanceof THREE.MeshFaceMaterial ) {
  12616. var materialIndex = geometry instanceof THREE.BufferGeometry ? 0 : buffer.materialIndex;
  12617. material = material.materials[ materialIndex ];
  12618. globject.material = material;
  12619. if ( material.transparent ) {
  12620. transparentObjects.push( globject );
  12621. } else {
  12622. opaqueObjects.push( globject );
  12623. }
  12624. } else if ( material ) {
  12625. globject.material = material;
  12626. if ( material.transparent ) {
  12627. transparentObjects.push( globject );
  12628. } else {
  12629. opaqueObjects.push( globject );
  12630. }
  12631. }
  12632. }
  12633. function initObject( object ) {
  12634. if ( object.__webglInit === undefined ) {
  12635. object.__webglInit = true;
  12636. object._modelViewMatrix = new THREE.Matrix4();
  12637. object._normalMatrix = new THREE.Matrix3();
  12638. object.addEventListener( 'removed', onObjectRemoved );
  12639. }
  12640. var geometry = object.geometry;
  12641. if ( geometry === undefined ) {
  12642. // ImmediateRenderObject
  12643. } else if ( geometry.__webglInit === undefined ) {
  12644. geometry.__webglInit = true;
  12645. geometry.addEventListener( 'dispose', onGeometryDispose );
  12646. if ( geometry instanceof THREE.BufferGeometry ) {
  12647. _this.info.memory.geometries ++;
  12648. } else if ( object instanceof THREE.Mesh ) {
  12649. initGeometryGroups( object, geometry );
  12650. } else if ( object instanceof THREE.Line ) {
  12651. if ( geometry.__webglVertexBuffer === undefined ) {
  12652. createLineBuffers( geometry );
  12653. initLineBuffers( geometry, object );
  12654. geometry.verticesNeedUpdate = true;
  12655. geometry.colorsNeedUpdate = true;
  12656. geometry.lineDistancesNeedUpdate = true;
  12657. }
  12658. } else if ( object instanceof THREE.PointCloud ) {
  12659. if ( geometry.__webglVertexBuffer === undefined ) {
  12660. createParticleBuffers( geometry );
  12661. initParticleBuffers( geometry, object );
  12662. geometry.verticesNeedUpdate = true;
  12663. geometry.colorsNeedUpdate = true;
  12664. }
  12665. }
  12666. }
  12667. if ( object.__webglActive === undefined) {
  12668. object.__webglActive = true;
  12669. if ( object instanceof THREE.Mesh ) {
  12670. if ( geometry instanceof THREE.BufferGeometry ) {
  12671. addBuffer( _webglObjects, geometry, object );
  12672. } else if ( geometry instanceof THREE.Geometry ) {
  12673. var geometryGroupsList = geometryGroups[ geometry.id ];
  12674. for ( var i = 0,l = geometryGroupsList.length; i < l; i ++ ) {
  12675. addBuffer( _webglObjects, geometryGroupsList[ i ], object );
  12676. }
  12677. }
  12678. } else if ( object instanceof THREE.Line || object instanceof THREE.PointCloud ) {
  12679. addBuffer( _webglObjects, geometry, object );
  12680. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  12681. addBufferImmediate( _webglObjectsImmediate, object );
  12682. }
  12683. }
  12684. }
  12685. // Geometry splitting
  12686. var geometryGroups = {};
  12687. var geometryGroupCounter = 0;
  12688. function makeGroups( geometry, usesFaceMaterial ) {
  12689. var maxVerticesInGroup = extensions.get( 'OES_element_index_uint' ) ? 4294967296 : 65535;
  12690. var groupHash, hash_map = {};
  12691. var numMorphTargets = geometry.morphTargets.length;
  12692. var numMorphNormals = geometry.morphNormals.length;
  12693. var group;
  12694. var groups = {};
  12695. var groupsList = [];
  12696. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  12697. var face = geometry.faces[ f ];
  12698. var materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  12699. if ( ! ( materialIndex in hash_map ) ) {
  12700. hash_map[ materialIndex ] = { hash: materialIndex, counter: 0 };
  12701. }
  12702. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  12703. if ( ! ( groupHash in groups ) ) {
  12704. group = {
  12705. id: geometryGroupCounter ++,
  12706. faces3: [],
  12707. materialIndex: materialIndex,
  12708. vertices: 0,
  12709. numMorphTargets: numMorphTargets,
  12710. numMorphNormals: numMorphNormals
  12711. };
  12712. groups[ groupHash ] = group;
  12713. groupsList.push( group );
  12714. }
  12715. if ( groups[ groupHash ].vertices + 3 > maxVerticesInGroup ) {
  12716. hash_map[ materialIndex ].counter += 1;
  12717. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  12718. if ( ! ( groupHash in groups ) ) {
  12719. group = {
  12720. id: geometryGroupCounter ++,
  12721. faces3: [],
  12722. materialIndex: materialIndex,
  12723. vertices: 0,
  12724. numMorphTargets: numMorphTargets,
  12725. numMorphNormals: numMorphNormals
  12726. };
  12727. groups[ groupHash ] = group;
  12728. groupsList.push( group );
  12729. }
  12730. }
  12731. groups[ groupHash ].faces3.push( f );
  12732. groups[ groupHash ].vertices += 3;
  12733. }
  12734. return groupsList;
  12735. }
  12736. function initGeometryGroups( object, geometry ) {
  12737. var material = object.material, addBuffers = false;
  12738. if ( geometryGroups[ geometry.id ] === undefined || geometry.groupsNeedUpdate === true ) {
  12739. delete _webglObjects[ object.id ];
  12740. geometryGroups[ geometry.id ] = makeGroups( geometry, material instanceof THREE.MeshFaceMaterial );
  12741. geometry.groupsNeedUpdate = false;
  12742. }
  12743. var geometryGroupsList = geometryGroups[ geometry.id ];
  12744. // create separate VBOs per geometry chunk
  12745. for ( var i = 0, il = geometryGroupsList.length; i < il; i ++ ) {
  12746. var geometryGroup = geometryGroupsList[ i ];
  12747. // initialise VBO on the first access
  12748. if ( geometryGroup.__webglVertexBuffer === undefined ) {
  12749. createMeshBuffers( geometryGroup );
  12750. initMeshBuffers( geometryGroup, object );
  12751. geometry.verticesNeedUpdate = true;
  12752. geometry.morphTargetsNeedUpdate = true;
  12753. geometry.elementsNeedUpdate = true;
  12754. geometry.uvsNeedUpdate = true;
  12755. geometry.normalsNeedUpdate = true;
  12756. geometry.tangentsNeedUpdate = true;
  12757. geometry.colorsNeedUpdate = true;
  12758. addBuffers = true;
  12759. } else {
  12760. addBuffers = false;
  12761. }
  12762. if ( addBuffers || object.__webglActive === undefined ) {
  12763. addBuffer( _webglObjects, geometryGroup, object );
  12764. }
  12765. }
  12766. object.__webglActive = true;
  12767. }
  12768. function addBuffer( objlist, buffer, object ) {
  12769. var id = object.id;
  12770. objlist[id] = objlist[id] || [];
  12771. objlist[id].push(
  12772. {
  12773. id: id,
  12774. buffer: buffer,
  12775. object: object,
  12776. material: null,
  12777. z: 0
  12778. }
  12779. );
  12780. };
  12781. function addBufferImmediate( objlist, object ) {
  12782. objlist.push(
  12783. {
  12784. id: null,
  12785. object: object,
  12786. opaque: null,
  12787. transparent: null,
  12788. z: 0
  12789. }
  12790. );
  12791. };
  12792. // Objects updates
  12793. function updateObject( object ) {
  12794. var geometry = object.geometry;
  12795. if ( geometry instanceof THREE.BufferGeometry ) {
  12796. var attributes = geometry.attributes;
  12797. var attributesKeys = geometry.attributesKeys;
  12798. for ( var i = 0, l = attributesKeys.length; i < l; i ++ ) {
  12799. var key = attributesKeys[ i ];
  12800. var attribute = attributes[ key ];
  12801. var bufferType = ( key === 'index' ) ? _gl.ELEMENT_ARRAY_BUFFER : _gl.ARRAY_BUFFER;
  12802. if ( attribute.buffer === undefined ) {
  12803. attribute.buffer = _gl.createBuffer();
  12804. _gl.bindBuffer( bufferType, attribute.buffer );
  12805. _gl.bufferData( bufferType, attribute.array, ( attribute instanceof THREE.DynamicBufferAttribute ) ? _gl.DYNAMIC_DRAW : _gl.STATIC_DRAW );
  12806. attribute.needsUpdate = false;
  12807. } else if ( attribute.needsUpdate === true ) {
  12808. _gl.bindBuffer( bufferType, attribute.buffer );
  12809. if ( attribute.updateRange === undefined || attribute.updateRange.count === -1 ) { // Not using update ranges
  12810. _gl.bufferSubData( bufferType, 0, attribute.array );
  12811. } else if ( attribute.updateRange.count === 0 ) {
  12812. 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.' );
  12813. } else {
  12814. _gl.bufferSubData( bufferType, attribute.updateRange.offset * attribute.array.BYTES_PER_ELEMENT,
  12815. attribute.array.subarray( attribute.updateRange.offset, attribute.updateRange.offset + attribute.updateRange.count ) );
  12816. attribute.updateRange.count = 0; // reset range
  12817. }
  12818. attribute.needsUpdate = false;
  12819. }
  12820. }
  12821. } else if ( object instanceof THREE.Mesh ) {
  12822. // check all geometry groups
  12823. if ( geometry.groupsNeedUpdate === true ) {
  12824. initGeometryGroups( object, geometry );
  12825. }
  12826. var geometryGroupsList = geometryGroups[ geometry.id ];
  12827. for ( var i = 0, il = geometryGroupsList.length; i < il; i ++ ) {
  12828. var geometryGroup = geometryGroupsList[ i ];
  12829. var material = getBufferMaterial( object, geometryGroup );
  12830. var customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12831. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  12832. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  12833. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  12834. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, ! geometry.dynamic, material );
  12835. }
  12836. }
  12837. geometry.verticesNeedUpdate = false;
  12838. geometry.morphTargetsNeedUpdate = false;
  12839. geometry.elementsNeedUpdate = false;
  12840. geometry.uvsNeedUpdate = false;
  12841. geometry.normalsNeedUpdate = false;
  12842. geometry.colorsNeedUpdate = false;
  12843. geometry.tangentsNeedUpdate = false;
  12844. material.attributes && clearCustomAttributes( material );
  12845. } else if ( object instanceof THREE.Line ) {
  12846. var material = getBufferMaterial( object, geometry );
  12847. var customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12848. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  12849. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  12850. }
  12851. geometry.verticesNeedUpdate = false;
  12852. geometry.colorsNeedUpdate = false;
  12853. geometry.lineDistancesNeedUpdate = false;
  12854. material.attributes && clearCustomAttributes( material );
  12855. } else if ( object instanceof THREE.PointCloud ) {
  12856. var material = getBufferMaterial( object, geometry );
  12857. var customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12858. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || customAttributesDirty ) {
  12859. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  12860. }
  12861. geometry.verticesNeedUpdate = false;
  12862. geometry.colorsNeedUpdate = false;
  12863. material.attributes && clearCustomAttributes( material );
  12864. }
  12865. }
  12866. // Objects updates - custom attributes check
  12867. function areCustomAttributesDirty( material ) {
  12868. for ( var name in material.attributes ) {
  12869. if ( material.attributes[ name ].needsUpdate ) return true;
  12870. }
  12871. return false;
  12872. }
  12873. function clearCustomAttributes( material ) {
  12874. for ( var name in material.attributes ) {
  12875. material.attributes[ name ].needsUpdate = false;
  12876. }
  12877. }
  12878. // Objects removal
  12879. function removeObject( object ) {
  12880. if ( object instanceof THREE.Mesh ||
  12881. object instanceof THREE.PointCloud ||
  12882. object instanceof THREE.Line ) {
  12883. delete _webglObjects[ object.id ];
  12884. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  12885. removeInstances( _webglObjectsImmediate, object );
  12886. }
  12887. delete object.__webglInit;
  12888. delete object._modelViewMatrix;
  12889. delete object._normalMatrix;
  12890. delete object.__webglActive;
  12891. }
  12892. function removeInstances( objlist, object ) {
  12893. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  12894. if ( objlist[ o ].object === object ) {
  12895. objlist.splice( o, 1 );
  12896. }
  12897. }
  12898. }
  12899. // Materials
  12900. var shaderIDs = {
  12901. MeshDepthMaterial: 'depth',
  12902. MeshNormalMaterial: 'normal',
  12903. MeshBasicMaterial: 'basic',
  12904. MeshLambertMaterial: 'lambert',
  12905. MeshPhongMaterial: 'phong',
  12906. LineBasicMaterial: 'basic',
  12907. LineDashedMaterial: 'dashed',
  12908. PointCloudMaterial: 'particle_basic'
  12909. };
  12910. function initMaterial( material, lights, fog, object ) {
  12911. material.addEventListener( 'dispose', onMaterialDispose );
  12912. var shaderID = shaderIDs[ material.type ];
  12913. if ( shaderID ) {
  12914. var shader = THREE.ShaderLib[ shaderID ];
  12915. material.__webglShader = {
  12916. uniforms: THREE.UniformsUtils.clone( shader.uniforms ),
  12917. vertexShader: shader.vertexShader,
  12918. fragmentShader: shader.fragmentShader
  12919. }
  12920. } else {
  12921. material.__webglShader = {
  12922. uniforms: material.uniforms,
  12923. vertexShader: material.vertexShader,
  12924. fragmentShader: material.fragmentShader
  12925. }
  12926. }
  12927. // heuristics to create shader parameters according to lights in the scene
  12928. // (not to blow over maxLights budget)
  12929. var maxLightCount = allocateLights( lights );
  12930. var maxShadows = allocateShadows( lights );
  12931. var maxBones = allocateBones( object );
  12932. var parameters = {
  12933. precision: _precision,
  12934. supportsVertexTextures: _supportsVertexTextures,
  12935. map: !! material.map,
  12936. envMap: !! material.envMap,
  12937. envMapMode: material.envMap && material.envMap.mapping,
  12938. lightMap: !! material.lightMap,
  12939. bumpMap: !! material.bumpMap,
  12940. normalMap: !! material.normalMap,
  12941. specularMap: !! material.specularMap,
  12942. alphaMap: !! material.alphaMap,
  12943. combine: material.combine,
  12944. vertexColors: material.vertexColors,
  12945. fog: fog,
  12946. useFog: material.fog,
  12947. fogExp: fog instanceof THREE.FogExp2,
  12948. flatShading: material.shading === THREE.FlatShading,
  12949. sizeAttenuation: material.sizeAttenuation,
  12950. logarithmicDepthBuffer: _logarithmicDepthBuffer,
  12951. skinning: material.skinning,
  12952. maxBones: maxBones,
  12953. useVertexTexture: _supportsBoneTextures && object && object.skeleton && object.skeleton.useVertexTexture,
  12954. morphTargets: material.morphTargets,
  12955. morphNormals: material.morphNormals,
  12956. maxMorphTargets: _this.maxMorphTargets,
  12957. maxMorphNormals: _this.maxMorphNormals,
  12958. maxDirLights: maxLightCount.directional,
  12959. maxPointLights: maxLightCount.point,
  12960. maxSpotLights: maxLightCount.spot,
  12961. maxHemiLights: maxLightCount.hemi,
  12962. maxShadows: maxShadows,
  12963. shadowMapEnabled: _this.shadowMapEnabled && object.receiveShadow && maxShadows > 0,
  12964. shadowMapType: _this.shadowMapType,
  12965. shadowMapDebug: _this.shadowMapDebug,
  12966. shadowMapCascade: _this.shadowMapCascade,
  12967. alphaTest: material.alphaTest,
  12968. metal: material.metal,
  12969. wrapAround: material.wrapAround,
  12970. doubleSided: material.side === THREE.DoubleSide,
  12971. flipSided: material.side === THREE.BackSide
  12972. };
  12973. // Generate code
  12974. var chunks = [];
  12975. if ( shaderID ) {
  12976. chunks.push( shaderID );
  12977. } else {
  12978. chunks.push( material.fragmentShader );
  12979. chunks.push( material.vertexShader );
  12980. }
  12981. if ( material.defines !== undefined ) {
  12982. for ( var name in material.defines ) {
  12983. chunks.push( name );
  12984. chunks.push( material.defines[ name ] );
  12985. }
  12986. }
  12987. for ( var name in parameters ) {
  12988. chunks.push( name );
  12989. chunks.push( parameters[ name ] );
  12990. }
  12991. var code = chunks.join();
  12992. var program;
  12993. // Check if code has been already compiled
  12994. for ( var p = 0, pl = _programs.length; p < pl; p ++ ) {
  12995. var programInfo = _programs[ p ];
  12996. if ( programInfo.code === code ) {
  12997. program = programInfo;
  12998. program.usedTimes ++;
  12999. break;
  13000. }
  13001. }
  13002. if ( program === undefined ) {
  13003. program = new THREE.WebGLProgram( _this, code, material, parameters );
  13004. _programs.push( program );
  13005. _this.info.memory.programs = _programs.length;
  13006. }
  13007. material.program = program;
  13008. var attributes = program.attributes;
  13009. if ( material.morphTargets ) {
  13010. material.numSupportedMorphTargets = 0;
  13011. var id, base = 'morphTarget';
  13012. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  13013. id = base + i;
  13014. if ( attributes[ id ] >= 0 ) {
  13015. material.numSupportedMorphTargets ++;
  13016. }
  13017. }
  13018. }
  13019. if ( material.morphNormals ) {
  13020. material.numSupportedMorphNormals = 0;
  13021. var id, base = 'morphNormal';
  13022. for ( i = 0; i < _this.maxMorphNormals; i ++ ) {
  13023. id = base + i;
  13024. if ( attributes[ id ] >= 0 ) {
  13025. material.numSupportedMorphNormals ++;
  13026. }
  13027. }
  13028. }
  13029. material.uniformsList = [];
  13030. for ( var u in material.__webglShader.uniforms ) {
  13031. var location = material.program.uniforms[ u ];
  13032. if ( location ) {
  13033. material.uniformsList.push( [ material.__webglShader.uniforms[ u ], location ] );
  13034. }
  13035. }
  13036. }
  13037. function setMaterial( material ) {
  13038. if ( material.transparent === true ) {
  13039. state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha );
  13040. } else {
  13041. state.setBlending( THREE.NoBlending );
  13042. }
  13043. state.setDepthTest( material.depthTest );
  13044. state.setDepthWrite( material.depthWrite );
  13045. state.setColorWrite( material.colorWrite );
  13046. state.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13047. }
  13048. function setProgram( camera, lights, fog, material, object ) {
  13049. _usedTextureUnits = 0;
  13050. if ( material.needsUpdate ) {
  13051. if ( material.program ) deallocateMaterial( material );
  13052. initMaterial( material, lights, fog, object );
  13053. material.needsUpdate = false;
  13054. }
  13055. if ( material.morphTargets ) {
  13056. if ( ! object.__webglMorphTargetInfluences ) {
  13057. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  13058. }
  13059. }
  13060. var refreshProgram = false;
  13061. var refreshMaterial = false;
  13062. var refreshLights = false;
  13063. var program = material.program,
  13064. p_uniforms = program.uniforms,
  13065. m_uniforms = material.__webglShader.uniforms;
  13066. if ( program.id !== _currentProgram ) {
  13067. _gl.useProgram( program.program );
  13068. _currentProgram = program.id;
  13069. refreshProgram = true;
  13070. refreshMaterial = true;
  13071. refreshLights = true;
  13072. }
  13073. if ( material.id !== _currentMaterialId ) {
  13074. if ( _currentMaterialId === -1 ) refreshLights = true;
  13075. _currentMaterialId = material.id;
  13076. refreshMaterial = true;
  13077. }
  13078. if ( refreshProgram || camera !== _currentCamera ) {
  13079. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  13080. if ( _logarithmicDepthBuffer ) {
  13081. _gl.uniform1f( p_uniforms.logDepthBufFC, 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  13082. }
  13083. if ( camera !== _currentCamera ) _currentCamera = camera;
  13084. // load material specific uniforms
  13085. // (shader material also gets them for the sake of genericity)
  13086. if ( material instanceof THREE.ShaderMaterial ||
  13087. material instanceof THREE.MeshPhongMaterial ||
  13088. material.envMap ) {
  13089. if ( p_uniforms.cameraPosition !== null ) {
  13090. _vector3.setFromMatrixPosition( camera.matrixWorld );
  13091. _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  13092. }
  13093. }
  13094. if ( material instanceof THREE.MeshPhongMaterial ||
  13095. material instanceof THREE.MeshLambertMaterial ||
  13096. material instanceof THREE.MeshBasicMaterial ||
  13097. material instanceof THREE.ShaderMaterial ||
  13098. material.skinning ) {
  13099. if ( p_uniforms.viewMatrix !== null ) {
  13100. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  13101. }
  13102. }
  13103. }
  13104. // skinning uniforms must be set even if material didn't change
  13105. // auto-setting of texture unit for bone texture must go before other textures
  13106. // not sure why, but otherwise weird things happen
  13107. if ( material.skinning ) {
  13108. if ( object.bindMatrix && p_uniforms.bindMatrix !== null ) {
  13109. _gl.uniformMatrix4fv( p_uniforms.bindMatrix, false, object.bindMatrix.elements );
  13110. }
  13111. if ( object.bindMatrixInverse && p_uniforms.bindMatrixInverse !== null ) {
  13112. _gl.uniformMatrix4fv( p_uniforms.bindMatrixInverse, false, object.bindMatrixInverse.elements );
  13113. }
  13114. if ( _supportsBoneTextures && object.skeleton && object.skeleton.useVertexTexture ) {
  13115. if ( p_uniforms.boneTexture !== null ) {
  13116. var textureUnit = getTextureUnit();
  13117. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  13118. _this.setTexture( object.skeleton.boneTexture, textureUnit );
  13119. }
  13120. if ( p_uniforms.boneTextureWidth !== null ) {
  13121. _gl.uniform1i( p_uniforms.boneTextureWidth, object.skeleton.boneTextureWidth );
  13122. }
  13123. if ( p_uniforms.boneTextureHeight !== null ) {
  13124. _gl.uniform1i( p_uniforms.boneTextureHeight, object.skeleton.boneTextureHeight );
  13125. }
  13126. } else if ( object.skeleton && object.skeleton.boneMatrices ) {
  13127. if ( p_uniforms.boneGlobalMatrices !== null ) {
  13128. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.skeleton.boneMatrices );
  13129. }
  13130. }
  13131. }
  13132. if ( refreshMaterial ) {
  13133. // refresh uniforms common to several materials
  13134. if ( fog && material.fog ) {
  13135. refreshUniformsFog( m_uniforms, fog );
  13136. }
  13137. if ( material instanceof THREE.MeshPhongMaterial ||
  13138. material instanceof THREE.MeshLambertMaterial ||
  13139. material.lights ) {
  13140. if ( _lightsNeedUpdate ) {
  13141. refreshLights = true;
  13142. setupLights( lights );
  13143. _lightsNeedUpdate = false;
  13144. }
  13145. if ( refreshLights ) {
  13146. refreshUniformsLights( m_uniforms, _lights );
  13147. markUniformsLightsNeedsUpdate( m_uniforms, true );
  13148. } else {
  13149. markUniformsLightsNeedsUpdate( m_uniforms, false );
  13150. }
  13151. }
  13152. if ( material instanceof THREE.MeshBasicMaterial ||
  13153. material instanceof THREE.MeshLambertMaterial ||
  13154. material instanceof THREE.MeshPhongMaterial ) {
  13155. refreshUniformsCommon( m_uniforms, material );
  13156. }
  13157. // refresh single material specific uniforms
  13158. if ( material instanceof THREE.LineBasicMaterial ) {
  13159. refreshUniformsLine( m_uniforms, material );
  13160. } else if ( material instanceof THREE.LineDashedMaterial ) {
  13161. refreshUniformsLine( m_uniforms, material );
  13162. refreshUniformsDash( m_uniforms, material );
  13163. } else if ( material instanceof THREE.PointCloudMaterial ) {
  13164. refreshUniformsParticle( m_uniforms, material );
  13165. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  13166. refreshUniformsPhong( m_uniforms, material );
  13167. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  13168. refreshUniformsLambert( m_uniforms, material );
  13169. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  13170. m_uniforms.mNear.value = camera.near;
  13171. m_uniforms.mFar.value = camera.far;
  13172. m_uniforms.opacity.value = material.opacity;
  13173. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  13174. m_uniforms.opacity.value = material.opacity;
  13175. }
  13176. if ( object.receiveShadow && ! material._shadowPass ) {
  13177. refreshUniformsShadow( m_uniforms, lights );
  13178. }
  13179. // load common uniforms
  13180. loadUniformsGeneric( material.uniformsList );
  13181. }
  13182. loadUniformsMatrices( p_uniforms, object );
  13183. if ( p_uniforms.modelMatrix !== null ) {
  13184. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  13185. }
  13186. return program;
  13187. }
  13188. // Uniforms (refresh uniforms objects)
  13189. function refreshUniformsCommon ( uniforms, material ) {
  13190. uniforms.opacity.value = material.opacity;
  13191. uniforms.diffuse.value = material.color;
  13192. uniforms.map.value = material.map;
  13193. uniforms.lightMap.value = material.lightMap;
  13194. uniforms.specularMap.value = material.specularMap;
  13195. uniforms.alphaMap.value = material.alphaMap;
  13196. if ( material.bumpMap ) {
  13197. uniforms.bumpMap.value = material.bumpMap;
  13198. uniforms.bumpScale.value = material.bumpScale;
  13199. }
  13200. if ( material.normalMap ) {
  13201. uniforms.normalMap.value = material.normalMap;
  13202. uniforms.normalScale.value.copy( material.normalScale );
  13203. }
  13204. // uv repeat and offset setting priorities
  13205. // 1. color map
  13206. // 2. specular map
  13207. // 3. normal map
  13208. // 4. bump map
  13209. // 5. alpha map
  13210. var uvScaleMap;
  13211. if ( material.map ) {
  13212. uvScaleMap = material.map;
  13213. } else if ( material.specularMap ) {
  13214. uvScaleMap = material.specularMap;
  13215. } else if ( material.normalMap ) {
  13216. uvScaleMap = material.normalMap;
  13217. } else if ( material.bumpMap ) {
  13218. uvScaleMap = material.bumpMap;
  13219. } else if ( material.alphaMap ) {
  13220. uvScaleMap = material.alphaMap;
  13221. }
  13222. if ( uvScaleMap !== undefined ) {
  13223. var offset = uvScaleMap.offset;
  13224. var repeat = uvScaleMap.repeat;
  13225. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  13226. }
  13227. uniforms.envMap.value = material.envMap;
  13228. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : - 1;
  13229. uniforms.reflectivity.value = material.reflectivity;
  13230. uniforms.refractionRatio.value = material.refractionRatio;
  13231. }
  13232. function refreshUniformsLine ( uniforms, material ) {
  13233. uniforms.diffuse.value = material.color;
  13234. uniforms.opacity.value = material.opacity;
  13235. }
  13236. function refreshUniformsDash ( uniforms, material ) {
  13237. uniforms.dashSize.value = material.dashSize;
  13238. uniforms.totalSize.value = material.dashSize + material.gapSize;
  13239. uniforms.scale.value = material.scale;
  13240. }
  13241. function refreshUniformsParticle ( uniforms, material ) {
  13242. uniforms.psColor.value = material.color;
  13243. uniforms.opacity.value = material.opacity;
  13244. uniforms.size.value = material.size;
  13245. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  13246. uniforms.map.value = material.map;
  13247. if ( material.map !== null ) {
  13248. var offset = material.map.offset;
  13249. var repeat = material.map.repeat;
  13250. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  13251. }
  13252. }
  13253. function refreshUniformsFog ( uniforms, fog ) {
  13254. uniforms.fogColor.value = fog.color;
  13255. if ( fog instanceof THREE.Fog ) {
  13256. uniforms.fogNear.value = fog.near;
  13257. uniforms.fogFar.value = fog.far;
  13258. } else if ( fog instanceof THREE.FogExp2 ) {
  13259. uniforms.fogDensity.value = fog.density;
  13260. }
  13261. }
  13262. function refreshUniformsPhong ( uniforms, material ) {
  13263. uniforms.shininess.value = material.shininess;
  13264. uniforms.emissive.value = material.emissive;
  13265. uniforms.specular.value = material.specular;
  13266. if ( material.wrapAround ) {
  13267. uniforms.wrapRGB.value.copy( material.wrapRGB );
  13268. }
  13269. }
  13270. function refreshUniformsLambert ( uniforms, material ) {
  13271. uniforms.emissive.value = material.emissive;
  13272. if ( material.wrapAround ) {
  13273. uniforms.wrapRGB.value.copy( material.wrapRGB );
  13274. }
  13275. }
  13276. function refreshUniformsLights ( uniforms, lights ) {
  13277. uniforms.ambientLightColor.value = lights.ambient;
  13278. uniforms.directionalLightColor.value = lights.directional.colors;
  13279. uniforms.directionalLightDirection.value = lights.directional.positions;
  13280. uniforms.pointLightColor.value = lights.point.colors;
  13281. uniforms.pointLightPosition.value = lights.point.positions;
  13282. uniforms.pointLightDistance.value = lights.point.distances;
  13283. uniforms.pointLightDecay.value = lights.point.decays;
  13284. uniforms.spotLightColor.value = lights.spot.colors;
  13285. uniforms.spotLightPosition.value = lights.spot.positions;
  13286. uniforms.spotLightDistance.value = lights.spot.distances;
  13287. uniforms.spotLightDirection.value = lights.spot.directions;
  13288. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  13289. uniforms.spotLightExponent.value = lights.spot.exponents;
  13290. uniforms.spotLightDecay.value = lights.spot.decays;
  13291. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  13292. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  13293. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  13294. }
  13295. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  13296. function markUniformsLightsNeedsUpdate ( uniforms, value ) {
  13297. uniforms.ambientLightColor.needsUpdate = value;
  13298. uniforms.directionalLightColor.needsUpdate = value;
  13299. uniforms.directionalLightDirection.needsUpdate = value;
  13300. uniforms.pointLightColor.needsUpdate = value;
  13301. uniforms.pointLightPosition.needsUpdate = value;
  13302. uniforms.pointLightDistance.needsUpdate = value;
  13303. uniforms.pointLightDecay.needsUpdate = value;
  13304. uniforms.spotLightColor.needsUpdate = value;
  13305. uniforms.spotLightPosition.needsUpdate = value;
  13306. uniforms.spotLightDistance.needsUpdate = value;
  13307. uniforms.spotLightDirection.needsUpdate = value;
  13308. uniforms.spotLightAngleCos.needsUpdate = value;
  13309. uniforms.spotLightExponent.needsUpdate = value;
  13310. uniforms.spotLightDecay.needsUpdate = value;
  13311. uniforms.hemisphereLightSkyColor.needsUpdate = value;
  13312. uniforms.hemisphereLightGroundColor.needsUpdate = value;
  13313. uniforms.hemisphereLightDirection.needsUpdate = value;
  13314. }
  13315. function refreshUniformsShadow ( uniforms, lights ) {
  13316. if ( uniforms.shadowMatrix ) {
  13317. var j = 0;
  13318. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  13319. var light = lights[ i ];
  13320. if ( ! light.castShadow ) continue;
  13321. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  13322. uniforms.shadowMap.value[ j ] = light.shadowMap;
  13323. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  13324. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  13325. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  13326. uniforms.shadowBias.value[ j ] = light.shadowBias;
  13327. j ++;
  13328. }
  13329. }
  13330. }
  13331. }
  13332. // Uniforms (load to GPU)
  13333. function loadUniformsMatrices ( uniforms, object ) {
  13334. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  13335. if ( uniforms.normalMatrix ) {
  13336. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  13337. }
  13338. }
  13339. function getTextureUnit() {
  13340. var textureUnit = _usedTextureUnits;
  13341. if ( textureUnit >= _maxTextures ) {
  13342. THREE.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + _maxTextures );
  13343. }
  13344. _usedTextureUnits += 1;
  13345. return textureUnit;
  13346. }
  13347. function loadUniformsGeneric ( uniforms ) {
  13348. var texture, textureUnit, offset;
  13349. for ( var j = 0, jl = uniforms.length; j < jl; j ++ ) {
  13350. var uniform = uniforms[ j ][ 0 ];
  13351. // needsUpdate property is not added to all uniforms.
  13352. if ( uniform.needsUpdate === false ) continue;
  13353. var type = uniform.type;
  13354. var value = uniform.value;
  13355. var location = uniforms[ j ][ 1 ];
  13356. switch ( type ) {
  13357. case '1i':
  13358. _gl.uniform1i( location, value );
  13359. break;
  13360. case '1f':
  13361. _gl.uniform1f( location, value );
  13362. break;
  13363. case '2f':
  13364. _gl.uniform2f( location, value[ 0 ], value[ 1 ] );
  13365. break;
  13366. case '3f':
  13367. _gl.uniform3f( location, value[ 0 ], value[ 1 ], value[ 2 ] );
  13368. break;
  13369. case '4f':
  13370. _gl.uniform4f( location, value[ 0 ], value[ 1 ], value[ 2 ], value[ 3 ] );
  13371. break;
  13372. case '1iv':
  13373. _gl.uniform1iv( location, value );
  13374. break;
  13375. case '3iv':
  13376. _gl.uniform3iv( location, value );
  13377. break;
  13378. case '1fv':
  13379. _gl.uniform1fv( location, value );
  13380. break;
  13381. case '2fv':
  13382. _gl.uniform2fv( location, value );
  13383. break;
  13384. case '3fv':
  13385. _gl.uniform3fv( location, value );
  13386. break;
  13387. case '4fv':
  13388. _gl.uniform4fv( location, value );
  13389. break;
  13390. case 'Matrix3fv':
  13391. _gl.uniformMatrix3fv( location, false, value );
  13392. break;
  13393. case 'Matrix4fv':
  13394. _gl.uniformMatrix4fv( location, false, value );
  13395. break;
  13396. //
  13397. case 'i':
  13398. // single integer
  13399. _gl.uniform1i( location, value );
  13400. break;
  13401. case 'f':
  13402. // single float
  13403. _gl.uniform1f( location, value );
  13404. break;
  13405. case 'v2':
  13406. // single THREE.Vector2
  13407. _gl.uniform2f( location, value.x, value.y );
  13408. break;
  13409. case 'v3':
  13410. // single THREE.Vector3
  13411. _gl.uniform3f( location, value.x, value.y, value.z );
  13412. break;
  13413. case 'v4':
  13414. // single THREE.Vector4
  13415. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  13416. break;
  13417. case 'c':
  13418. // single THREE.Color
  13419. _gl.uniform3f( location, value.r, value.g, value.b );
  13420. break;
  13421. case 'iv1':
  13422. // flat array of integers (JS or typed array)
  13423. _gl.uniform1iv( location, value );
  13424. break;
  13425. case 'iv':
  13426. // flat array of integers with 3 x N size (JS or typed array)
  13427. _gl.uniform3iv( location, value );
  13428. break;
  13429. case 'fv1':
  13430. // flat array of floats (JS or typed array)
  13431. _gl.uniform1fv( location, value );
  13432. break;
  13433. case 'fv':
  13434. // flat array of floats with 3 x N size (JS or typed array)
  13435. _gl.uniform3fv( location, value );
  13436. break;
  13437. case 'v2v':
  13438. // array of THREE.Vector2
  13439. if ( uniform._array === undefined ) {
  13440. uniform._array = new Float32Array( 2 * value.length );
  13441. }
  13442. for ( var i = 0, il = value.length; i < il; i ++ ) {
  13443. offset = i * 2;
  13444. uniform._array[ offset ] = value[ i ].x;
  13445. uniform._array[ offset + 1 ] = value[ i ].y;
  13446. }
  13447. _gl.uniform2fv( location, uniform._array );
  13448. break;
  13449. case 'v3v':
  13450. // array of THREE.Vector3
  13451. if ( uniform._array === undefined ) {
  13452. uniform._array = new Float32Array( 3 * value.length );
  13453. }
  13454. for ( var i = 0, il = value.length; i < il; i ++ ) {
  13455. offset = i * 3;
  13456. uniform._array[ offset ] = value[ i ].x;
  13457. uniform._array[ offset + 1 ] = value[ i ].y;
  13458. uniform._array[ offset + 2 ] = value[ i ].z;
  13459. }
  13460. _gl.uniform3fv( location, uniform._array );
  13461. break;
  13462. case 'v4v':
  13463. // array of THREE.Vector4
  13464. if ( uniform._array === undefined ) {
  13465. uniform._array = new Float32Array( 4 * value.length );
  13466. }
  13467. for ( var i = 0, il = value.length; i < il; i ++ ) {
  13468. offset = i * 4;
  13469. uniform._array[ offset ] = value[ i ].x;
  13470. uniform._array[ offset + 1 ] = value[ i ].y;
  13471. uniform._array[ offset + 2 ] = value[ i ].z;
  13472. uniform._array[ offset + 3 ] = value[ i ].w;
  13473. }
  13474. _gl.uniform4fv( location, uniform._array );
  13475. break;
  13476. case 'm3':
  13477. // single THREE.Matrix3
  13478. _gl.uniformMatrix3fv( location, false, value.elements );
  13479. break;
  13480. case 'm3v':
  13481. // array of THREE.Matrix3
  13482. if ( uniform._array === undefined ) {
  13483. uniform._array = new Float32Array( 9 * value.length );
  13484. }
  13485. for ( var i = 0, il = value.length; i < il; i ++ ) {
  13486. value[ i ].flattenToArrayOffset( uniform._array, i * 9 );
  13487. }
  13488. _gl.uniformMatrix3fv( location, false, uniform._array );
  13489. break;
  13490. case 'm4':
  13491. // single THREE.Matrix4
  13492. _gl.uniformMatrix4fv( location, false, value.elements );
  13493. break;
  13494. case 'm4v':
  13495. // array of THREE.Matrix4
  13496. if ( uniform._array === undefined ) {
  13497. uniform._array = new Float32Array( 16 * value.length );
  13498. }
  13499. for ( var i = 0, il = value.length; i < il; i ++ ) {
  13500. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  13501. }
  13502. _gl.uniformMatrix4fv( location, false, uniform._array );
  13503. break;
  13504. case 't':
  13505. // single THREE.Texture (2d or cube)
  13506. texture = value;
  13507. textureUnit = getTextureUnit();
  13508. _gl.uniform1i( location, textureUnit );
  13509. if ( ! texture ) continue;
  13510. if ( texture instanceof THREE.CubeTexture ||
  13511. ( texture.image instanceof Array && texture.image.length === 6 ) ) { // CompressedTexture can have Array in image :/
  13512. setCubeTexture( texture, textureUnit );
  13513. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  13514. setCubeTextureDynamic( texture, textureUnit );
  13515. } else {
  13516. _this.setTexture( texture, textureUnit );
  13517. }
  13518. break;
  13519. case 'tv':
  13520. // array of THREE.Texture (2d)
  13521. if ( uniform._array === undefined ) {
  13522. uniform._array = [];
  13523. }
  13524. for ( var i = 0, il = uniform.value.length; i < il; i ++ ) {
  13525. uniform._array[ i ] = getTextureUnit();
  13526. }
  13527. _gl.uniform1iv( location, uniform._array );
  13528. for ( var i = 0, il = uniform.value.length; i < il; i ++ ) {
  13529. texture = uniform.value[ i ];
  13530. textureUnit = uniform._array[ i ];
  13531. if ( ! texture ) continue;
  13532. _this.setTexture( texture, textureUnit );
  13533. }
  13534. break;
  13535. default:
  13536. THREE.warn( 'THREE.WebGLRenderer: Unknown uniform type: ' + type );
  13537. }
  13538. }
  13539. }
  13540. function setupMatrices ( object, camera ) {
  13541. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  13542. object._normalMatrix.getNormalMatrix( object._modelViewMatrix );
  13543. }
  13544. function setColorLinear( array, offset, color, intensity ) {
  13545. array[ offset ] = color.r * intensity;
  13546. array[ offset + 1 ] = color.g * intensity;
  13547. array[ offset + 2 ] = color.b * intensity;
  13548. }
  13549. function setupLights ( lights ) {
  13550. var l, ll, light,
  13551. r = 0, g = 0, b = 0,
  13552. color, skyColor, groundColor,
  13553. intensity,
  13554. distance,
  13555. zlights = _lights,
  13556. dirColors = zlights.directional.colors,
  13557. dirPositions = zlights.directional.positions,
  13558. pointColors = zlights.point.colors,
  13559. pointPositions = zlights.point.positions,
  13560. pointDistances = zlights.point.distances,
  13561. pointDecays = zlights.point.decays,
  13562. spotColors = zlights.spot.colors,
  13563. spotPositions = zlights.spot.positions,
  13564. spotDistances = zlights.spot.distances,
  13565. spotDirections = zlights.spot.directions,
  13566. spotAnglesCos = zlights.spot.anglesCos,
  13567. spotExponents = zlights.spot.exponents,
  13568. spotDecays = zlights.spot.decays,
  13569. hemiSkyColors = zlights.hemi.skyColors,
  13570. hemiGroundColors = zlights.hemi.groundColors,
  13571. hemiPositions = zlights.hemi.positions,
  13572. dirLength = 0,
  13573. pointLength = 0,
  13574. spotLength = 0,
  13575. hemiLength = 0,
  13576. dirCount = 0,
  13577. pointCount = 0,
  13578. spotCount = 0,
  13579. hemiCount = 0,
  13580. dirOffset = 0,
  13581. pointOffset = 0,
  13582. spotOffset = 0,
  13583. hemiOffset = 0;
  13584. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  13585. light = lights[ l ];
  13586. if ( light.onlyShadow ) continue;
  13587. color = light.color;
  13588. intensity = light.intensity;
  13589. distance = light.distance;
  13590. if ( light instanceof THREE.AmbientLight ) {
  13591. if ( ! light.visible ) continue;
  13592. r += color.r;
  13593. g += color.g;
  13594. b += color.b;
  13595. } else if ( light instanceof THREE.DirectionalLight ) {
  13596. dirCount += 1;
  13597. if ( ! light.visible ) continue;
  13598. _direction.setFromMatrixPosition( light.matrixWorld );
  13599. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  13600. _direction.sub( _vector3 );
  13601. _direction.normalize();
  13602. dirOffset = dirLength * 3;
  13603. dirPositions[ dirOffset ] = _direction.x;
  13604. dirPositions[ dirOffset + 1 ] = _direction.y;
  13605. dirPositions[ dirOffset + 2 ] = _direction.z;
  13606. setColorLinear( dirColors, dirOffset, color, intensity );
  13607. dirLength += 1;
  13608. } else if ( light instanceof THREE.PointLight ) {
  13609. pointCount += 1;
  13610. if ( ! light.visible ) continue;
  13611. pointOffset = pointLength * 3;
  13612. setColorLinear( pointColors, pointOffset, color, intensity );
  13613. _vector3.setFromMatrixPosition( light.matrixWorld );
  13614. pointPositions[ pointOffset ] = _vector3.x;
  13615. pointPositions[ pointOffset + 1 ] = _vector3.y;
  13616. pointPositions[ pointOffset + 2 ] = _vector3.z;
  13617. // distance is 0 if decay is 0, because there is no attenuation at all.
  13618. pointDistances[ pointLength ] = distance;
  13619. pointDecays[ pointLength ] = ( light.distance === 0 ) ? 0.0 : light.decay;
  13620. pointLength += 1;
  13621. } else if ( light instanceof THREE.SpotLight ) {
  13622. spotCount += 1;
  13623. if ( ! light.visible ) continue;
  13624. spotOffset = spotLength * 3;
  13625. setColorLinear( spotColors, spotOffset, color, intensity );
  13626. _direction.setFromMatrixPosition( light.matrixWorld );
  13627. spotPositions[ spotOffset ] = _direction.x;
  13628. spotPositions[ spotOffset + 1 ] = _direction.y;
  13629. spotPositions[ spotOffset + 2 ] = _direction.z;
  13630. spotDistances[ spotLength ] = distance;
  13631. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  13632. _direction.sub( _vector3 );
  13633. _direction.normalize();
  13634. spotDirections[ spotOffset ] = _direction.x;
  13635. spotDirections[ spotOffset + 1 ] = _direction.y;
  13636. spotDirections[ spotOffset + 2 ] = _direction.z;
  13637. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  13638. spotExponents[ spotLength ] = light.exponent;
  13639. spotDecays[ spotLength ] = ( light.distance === 0 ) ? 0.0 : light.decay;
  13640. spotLength += 1;
  13641. } else if ( light instanceof THREE.HemisphereLight ) {
  13642. hemiCount += 1;
  13643. if ( ! light.visible ) continue;
  13644. _direction.setFromMatrixPosition( light.matrixWorld );
  13645. _direction.normalize();
  13646. hemiOffset = hemiLength * 3;
  13647. hemiPositions[ hemiOffset ] = _direction.x;
  13648. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  13649. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  13650. skyColor = light.color;
  13651. groundColor = light.groundColor;
  13652. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  13653. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  13654. hemiLength += 1;
  13655. }
  13656. }
  13657. // null eventual remains from removed lights
  13658. // (this is to avoid if in shader)
  13659. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  13660. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  13661. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  13662. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  13663. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  13664. zlights.directional.length = dirLength;
  13665. zlights.point.length = pointLength;
  13666. zlights.spot.length = spotLength;
  13667. zlights.hemi.length = hemiLength;
  13668. zlights.ambient[ 0 ] = r;
  13669. zlights.ambient[ 1 ] = g;
  13670. zlights.ambient[ 2 ] = b;
  13671. }
  13672. // GL state setting
  13673. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  13674. if ( cullFace === THREE.CullFaceNone ) {
  13675. _gl.disable( _gl.CULL_FACE );
  13676. } else {
  13677. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  13678. _gl.frontFace( _gl.CW );
  13679. } else {
  13680. _gl.frontFace( _gl.CCW );
  13681. }
  13682. if ( cullFace === THREE.CullFaceBack ) {
  13683. _gl.cullFace( _gl.BACK );
  13684. } else if ( cullFace === THREE.CullFaceFront ) {
  13685. _gl.cullFace( _gl.FRONT );
  13686. } else {
  13687. _gl.cullFace( _gl.FRONT_AND_BACK );
  13688. }
  13689. _gl.enable( _gl.CULL_FACE );
  13690. }
  13691. };
  13692. this.setMaterialFaces = function ( material ) {
  13693. state.setDoubleSided( material.side === THREE.DoubleSide );
  13694. state.setFlipSided( material.side === THREE.BackSide );
  13695. };
  13696. // Textures
  13697. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  13698. var extension;
  13699. if ( isImagePowerOfTwo ) {
  13700. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  13701. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  13702. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  13703. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  13704. } else {
  13705. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  13706. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  13707. if ( texture.wrapS !== THREE.ClampToEdgeWrapping || texture.wrapT !== THREE.ClampToEdgeWrapping ) {
  13708. THREE.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping. ( ' + texture.sourceFile + ' )' );
  13709. }
  13710. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  13711. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  13712. if ( texture.minFilter !== THREE.NearestFilter && texture.minFilter !== THREE.LinearFilter ) {
  13713. THREE.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter. ( ' + texture.sourceFile + ' )' );
  13714. }
  13715. }
  13716. extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  13717. if ( extension && texture.type !== THREE.FloatType && texture.type !== THREE.HalfFloatType ) {
  13718. if ( texture.anisotropy > 1 || texture.__currentAnisotropy ) {
  13719. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _this.getMaxAnisotropy() ) );
  13720. texture.__currentAnisotropy = texture.anisotropy;
  13721. }
  13722. }
  13723. }
  13724. this.uploadTexture = function ( texture ) {
  13725. if ( texture.__webglInit === undefined ) {
  13726. texture.__webglInit = true;
  13727. texture.addEventListener( 'dispose', onTextureDispose );
  13728. texture.__webglTexture = _gl.createTexture();
  13729. _this.info.memory.textures ++;
  13730. }
  13731. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  13732. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  13733. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  13734. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  13735. texture.image = clampToMaxSize( texture.image, _maxTextureSize );
  13736. var image = texture.image,
  13737. isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ),
  13738. glFormat = paramThreeToGL( texture.format ),
  13739. glType = paramThreeToGL( texture.type );
  13740. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  13741. var mipmap, mipmaps = texture.mipmaps;
  13742. if ( texture instanceof THREE.DataTexture ) {
  13743. // use manually created mipmaps if available
  13744. // if there are no manual mipmaps
  13745. // set 0 level mipmap and then use GL to generate other mipmap levels
  13746. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  13747. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  13748. mipmap = mipmaps[ i ];
  13749. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13750. }
  13751. texture.generateMipmaps = false;
  13752. } else {
  13753. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  13754. }
  13755. } else if ( texture instanceof THREE.CompressedTexture ) {
  13756. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  13757. mipmap = mipmaps[ i ];
  13758. if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) {
  13759. if ( getCompressedTextureFormats().indexOf( glFormat ) > -1 ) {
  13760. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13761. } else {
  13762. THREE.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()" );
  13763. }
  13764. } else {
  13765. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13766. }
  13767. }
  13768. } else { // regular Texture (image, video, canvas)
  13769. // use manually created mipmaps if available
  13770. // if there are no manual mipmaps
  13771. // set 0 level mipmap and then use GL to generate other mipmap levels
  13772. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  13773. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  13774. mipmap = mipmaps[ i ];
  13775. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  13776. }
  13777. texture.generateMipmaps = false;
  13778. } else {
  13779. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  13780. }
  13781. }
  13782. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  13783. texture.needsUpdate = false;
  13784. if ( texture.onUpdate ) texture.onUpdate();
  13785. };
  13786. this.setTexture = function ( texture, slot ) {
  13787. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13788. if ( texture.needsUpdate ) {
  13789. _this.uploadTexture( texture );
  13790. } else {
  13791. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  13792. }
  13793. };
  13794. function clampToMaxSize ( image, maxSize ) {
  13795. if ( image.width > maxSize || image.height > maxSize ) {
  13796. // Warning: Scaling through the canvas will only work with images that use
  13797. // premultiplied alpha.
  13798. var scale = maxSize / Math.max( image.width, image.height );
  13799. var canvas = document.createElement( 'canvas' );
  13800. canvas.width = Math.floor( image.width * scale );
  13801. canvas.height = Math.floor( image.height * scale );
  13802. var context = canvas.getContext( '2d' );
  13803. context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
  13804. THREE.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  13805. return canvas;
  13806. }
  13807. return image;
  13808. }
  13809. function setCubeTexture ( texture, slot ) {
  13810. if ( texture.image.length === 6 ) {
  13811. if ( texture.needsUpdate ) {
  13812. if ( ! texture.image.__webglTextureCube ) {
  13813. texture.addEventListener( 'dispose', onTextureDispose );
  13814. texture.image.__webglTextureCube = _gl.createTexture();
  13815. _this.info.memory.textures ++;
  13816. }
  13817. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13818. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  13819. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  13820. var isCompressed = texture instanceof THREE.CompressedTexture;
  13821. var isDataTexture = texture.image[ 0 ] instanceof THREE.DataTexture;
  13822. var cubeImage = [];
  13823. for ( var i = 0; i < 6; i ++ ) {
  13824. if ( _this.autoScaleCubemaps && ! isCompressed && ! isDataTexture ) {
  13825. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  13826. } else {
  13827. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  13828. }
  13829. }
  13830. var image = cubeImage[ 0 ],
  13831. isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ),
  13832. glFormat = paramThreeToGL( texture.format ),
  13833. glType = paramThreeToGL( texture.type );
  13834. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  13835. for ( var i = 0; i < 6; i ++ ) {
  13836. if ( ! isCompressed ) {
  13837. if ( isDataTexture ) {
  13838. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  13839. } else {
  13840. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  13841. }
  13842. } else {
  13843. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  13844. for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  13845. mipmap = mipmaps[ j ];
  13846. if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) {
  13847. if ( getCompressedTextureFormats().indexOf( glFormat ) > -1 ) {
  13848. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13849. } else {
  13850. THREE.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setCubeTexture()" );
  13851. }
  13852. } else {
  13853. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13854. }
  13855. }
  13856. }
  13857. }
  13858. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  13859. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  13860. }
  13861. texture.needsUpdate = false;
  13862. if ( texture.onUpdate ) texture.onUpdate();
  13863. } else {
  13864. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13865. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  13866. }
  13867. }
  13868. }
  13869. function setCubeTextureDynamic ( texture, slot ) {
  13870. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13871. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  13872. }
  13873. // Render targets
  13874. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  13875. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13876. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  13877. }
  13878. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  13879. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  13880. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  13881. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  13882. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  13883. /* For some reason this is not working. Defaulting to RGBA4.
  13884. } else if ( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  13885. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  13886. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  13887. */
  13888. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  13889. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  13890. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  13891. } else {
  13892. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  13893. }
  13894. }
  13895. this.setRenderTarget = function ( renderTarget ) {
  13896. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  13897. if ( renderTarget && renderTarget.__webglFramebuffer === undefined ) {
  13898. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  13899. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  13900. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  13901. renderTarget.__webglTexture = _gl.createTexture();
  13902. _this.info.memory.textures ++;
  13903. // Setup texture, create render and frame buffers
  13904. var isTargetPowerOfTwo = THREE.Math.isPowerOfTwo( renderTarget.width ) && THREE.Math.isPowerOfTwo( renderTarget.height ),
  13905. glFormat = paramThreeToGL( renderTarget.format ),
  13906. glType = paramThreeToGL( renderTarget.type );
  13907. if ( isCube ) {
  13908. renderTarget.__webglFramebuffer = [];
  13909. renderTarget.__webglRenderbuffer = [];
  13910. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  13911. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  13912. for ( var i = 0; i < 6; i ++ ) {
  13913. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  13914. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  13915. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  13916. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  13917. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  13918. }
  13919. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  13920. } else {
  13921. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  13922. if ( renderTarget.shareDepthFrom ) {
  13923. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  13924. } else {
  13925. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  13926. }
  13927. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  13928. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  13929. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  13930. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  13931. if ( renderTarget.shareDepthFrom ) {
  13932. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  13933. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  13934. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  13935. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  13936. }
  13937. } else {
  13938. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  13939. }
  13940. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  13941. }
  13942. // Release everything
  13943. if ( isCube ) {
  13944. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  13945. } else {
  13946. _gl.bindTexture( _gl.TEXTURE_2D, null );
  13947. }
  13948. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  13949. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  13950. }
  13951. var framebuffer, width, height, vx, vy;
  13952. if ( renderTarget ) {
  13953. if ( isCube ) {
  13954. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  13955. } else {
  13956. framebuffer = renderTarget.__webglFramebuffer;
  13957. }
  13958. width = renderTarget.width;
  13959. height = renderTarget.height;
  13960. vx = 0;
  13961. vy = 0;
  13962. } else {
  13963. framebuffer = null;
  13964. width = _viewportWidth;
  13965. height = _viewportHeight;
  13966. vx = _viewportX;
  13967. vy = _viewportY;
  13968. }
  13969. if ( framebuffer !== _currentFramebuffer ) {
  13970. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13971. _gl.viewport( vx, vy, width, height );
  13972. _currentFramebuffer = framebuffer;
  13973. }
  13974. _currentWidth = width;
  13975. _currentHeight = height;
  13976. };
  13977. this.readRenderTargetPixels = function( renderTarget, x, y, width, height, buffer ) {
  13978. if ( ! ( renderTarget instanceof THREE.WebGLRenderTarget ) ) {
  13979. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  13980. return;
  13981. }
  13982. if ( renderTarget.__webglFramebuffer ) {
  13983. if ( renderTarget.format !== THREE.RGBAFormat ) {
  13984. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA format. readPixels can read only RGBA format.' );
  13985. return;
  13986. }
  13987. var restore = false;
  13988. if ( renderTarget.__webglFramebuffer !== _currentFramebuffer ) {
  13989. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTarget.__webglFramebuffer );
  13990. restore = true;
  13991. }
  13992. if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
  13993. _gl.readPixels( x, y, width, height, _gl.RGBA, _gl.UNSIGNED_BYTE, buffer );
  13994. } else {
  13995. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  13996. }
  13997. if ( restore ) {
  13998. _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
  13999. }
  14000. }
  14001. };
  14002. function updateRenderTargetMipmap ( renderTarget ) {
  14003. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  14004. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  14005. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14006. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  14007. } else {
  14008. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  14009. _gl.generateMipmap( _gl.TEXTURE_2D );
  14010. _gl.bindTexture( _gl.TEXTURE_2D, null );
  14011. }
  14012. }
  14013. // Fallback filters for non-power-of-2 textures
  14014. function filterFallback ( f ) {
  14015. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  14016. return _gl.NEAREST;
  14017. }
  14018. return _gl.LINEAR;
  14019. }
  14020. // Map three.js constants to WebGL constants
  14021. function paramThreeToGL ( p ) {
  14022. var extension;
  14023. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  14024. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  14025. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  14026. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  14027. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  14028. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  14029. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  14030. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  14031. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  14032. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  14033. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  14034. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  14035. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  14036. if ( p === THREE.ByteType ) return _gl.BYTE;
  14037. if ( p === THREE.ShortType ) return _gl.SHORT;
  14038. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  14039. if ( p === THREE.IntType ) return _gl.INT;
  14040. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  14041. if ( p === THREE.FloatType ) return _gl.FLOAT;
  14042. extension = extensions.get( 'OES_texture_half_float' );
  14043. if ( extension !== null ) {
  14044. if ( p === THREE.HalfFloatType ) return extension.HALF_FLOAT_OES;
  14045. }
  14046. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  14047. if ( p === THREE.RGBFormat ) return _gl.RGB;
  14048. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  14049. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  14050. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  14051. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  14052. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  14053. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  14054. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  14055. if ( p === THREE.OneFactor ) return _gl.ONE;
  14056. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  14057. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  14058. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  14059. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  14060. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  14061. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  14062. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  14063. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  14064. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  14065. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  14066. if ( extension !== null ) {
  14067. if ( p === THREE.RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  14068. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  14069. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  14070. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  14071. }
  14072. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  14073. if ( extension !== null ) {
  14074. if ( p === THREE.RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  14075. if ( p === THREE.RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  14076. if ( p === THREE.RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  14077. if ( p === THREE.RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  14078. }
  14079. extension = extensions.get( 'EXT_blend_minmax' );
  14080. if ( extension !== null ) {
  14081. if ( p === THREE.MinEquation ) return extension.MIN_EXT;
  14082. if ( p === THREE.MaxEquation ) return extension.MAX_EXT;
  14083. }
  14084. return 0;
  14085. }
  14086. // Allocations
  14087. function allocateBones ( object ) {
  14088. if ( _supportsBoneTextures && object && object.skeleton && object.skeleton.useVertexTexture ) {
  14089. return 1024;
  14090. } else {
  14091. // default for when object is not specified
  14092. // ( for example when prebuilding shader
  14093. // to be used with multiple objects )
  14094. //
  14095. // - leave some extra space for other uniforms
  14096. // - limit here is ANGLE's 254 max uniform vectors
  14097. // (up to 54 should be safe)
  14098. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  14099. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  14100. var maxBones = nVertexMatrices;
  14101. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  14102. maxBones = Math.min( object.skeleton.bones.length, maxBones );
  14103. if ( maxBones < object.skeleton.bones.length ) {
  14104. THREE.warn( 'WebGLRenderer: too many bones - ' + object.skeleton.bones.length + ', this GPU supports just ' + maxBones + ' (try OpenGL instead of ANGLE)' );
  14105. }
  14106. }
  14107. return maxBones;
  14108. }
  14109. }
  14110. function allocateLights( lights ) {
  14111. var dirLights = 0;
  14112. var pointLights = 0;
  14113. var spotLights = 0;
  14114. var hemiLights = 0;
  14115. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  14116. var light = lights[ l ];
  14117. if ( light.onlyShadow || light.visible === false ) continue;
  14118. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  14119. if ( light instanceof THREE.PointLight ) pointLights ++;
  14120. if ( light instanceof THREE.SpotLight ) spotLights ++;
  14121. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  14122. }
  14123. return { 'directional': dirLights, 'point': pointLights, 'spot': spotLights, 'hemi': hemiLights };
  14124. }
  14125. function allocateShadows( lights ) {
  14126. var maxShadows = 0;
  14127. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  14128. var light = lights[ l ];
  14129. if ( ! light.castShadow ) continue;
  14130. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  14131. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  14132. }
  14133. return maxShadows;
  14134. }
  14135. // DEPRECATED
  14136. this.initMaterial = function () {
  14137. THREE.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  14138. };
  14139. this.addPrePlugin = function () {
  14140. THREE.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  14141. };
  14142. this.addPostPlugin = function () {
  14143. THREE.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  14144. };
  14145. this.updateShadowMap = function () {
  14146. THREE.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  14147. };
  14148. };
  14149. // File:src/renderers/WebGLRenderTarget.js
  14150. /**
  14151. * @author szimek / https://github.com/szimek/
  14152. * @author alteredq / http://alteredqualia.com/
  14153. */
  14154. THREE.WebGLRenderTarget = function ( width, height, options ) {
  14155. this.width = width;
  14156. this.height = height;
  14157. options = options || {};
  14158. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  14159. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  14160. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  14161. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  14162. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  14163. this.offset = new THREE.Vector2( 0, 0 );
  14164. this.repeat = new THREE.Vector2( 1, 1 );
  14165. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  14166. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  14167. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  14168. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  14169. this.generateMipmaps = true;
  14170. this.shareDepthFrom = options.shareDepthFrom !== undefined ? options.shareDepthFrom : null;
  14171. };
  14172. THREE.WebGLRenderTarget.prototype = {
  14173. constructor: THREE.WebGLRenderTarget,
  14174. setSize: function ( width, height ) {
  14175. this.width = width;
  14176. this.height = height;
  14177. },
  14178. clone: function () {
  14179. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  14180. tmp.wrapS = this.wrapS;
  14181. tmp.wrapT = this.wrapT;
  14182. tmp.magFilter = this.magFilter;
  14183. tmp.minFilter = this.minFilter;
  14184. tmp.anisotropy = this.anisotropy;
  14185. tmp.offset.copy( this.offset );
  14186. tmp.repeat.copy( this.repeat );
  14187. tmp.format = this.format;
  14188. tmp.type = this.type;
  14189. tmp.depthBuffer = this.depthBuffer;
  14190. tmp.stencilBuffer = this.stencilBuffer;
  14191. tmp.generateMipmaps = this.generateMipmaps;
  14192. tmp.shareDepthFrom = this.shareDepthFrom;
  14193. return tmp;
  14194. },
  14195. dispose: function () {
  14196. this.dispatchEvent( { type: 'dispose' } );
  14197. }
  14198. };
  14199. THREE.EventDispatcher.prototype.apply( THREE.WebGLRenderTarget.prototype );
  14200. // File:src/renderers/WebGLRenderTargetCube.js
  14201. /**
  14202. * @author alteredq / http://alteredqualia.com
  14203. */
  14204. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  14205. THREE.WebGLRenderTarget.call( this, width, height, options );
  14206. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  14207. };
  14208. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  14209. THREE.WebGLRenderTargetCube.prototype.constructor = THREE.WebGLRenderTargetCube;
  14210. // File:src/renderers/webgl/WebGLExtensions.js
  14211. /**
  14212. * @author mrdoob / http://mrdoob.com/
  14213. */
  14214. THREE.WebGLExtensions = function ( gl ) {
  14215. var extensions = {};
  14216. this.get = function ( name ) {
  14217. if ( extensions[ name ] !== undefined ) {
  14218. return extensions[ name ];
  14219. }
  14220. var extension;
  14221. switch ( name ) {
  14222. case 'EXT_texture_filter_anisotropic':
  14223. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  14224. break;
  14225. case 'WEBGL_compressed_texture_s3tc':
  14226. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  14227. break;
  14228. case 'WEBGL_compressed_texture_pvrtc':
  14229. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  14230. break;
  14231. default:
  14232. extension = gl.getExtension( name );
  14233. }
  14234. if ( extension === null ) {
  14235. THREE.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  14236. }
  14237. extensions[ name ] = extension;
  14238. return extension;
  14239. };
  14240. };
  14241. // File:src/renderers/webgl/WebGLProgram.js
  14242. THREE.WebGLProgram = ( function () {
  14243. var programIdCount = 0;
  14244. var generateDefines = function ( defines ) {
  14245. var value, chunk, chunks = [];
  14246. for ( var d in defines ) {
  14247. value = defines[ d ];
  14248. if ( value === false ) continue;
  14249. chunk = '#define ' + d + ' ' + value;
  14250. chunks.push( chunk );
  14251. }
  14252. return chunks.join( '\n' );
  14253. };
  14254. var cacheUniformLocations = function ( gl, program, identifiers ) {
  14255. var uniforms = {};
  14256. for ( var i = 0, l = identifiers.length; i < l; i ++ ) {
  14257. var id = identifiers[ i ];
  14258. uniforms[ id ] = gl.getUniformLocation( program, id );
  14259. }
  14260. return uniforms;
  14261. };
  14262. var cacheAttributeLocations = function ( gl, program, identifiers ) {
  14263. var attributes = {};
  14264. for ( var i = 0, l = identifiers.length; i < l; i ++ ) {
  14265. var id = identifiers[ i ];
  14266. attributes[ id ] = gl.getAttribLocation( program, id );
  14267. }
  14268. return attributes;
  14269. };
  14270. return function ( renderer, code, material, parameters ) {
  14271. var _this = renderer;
  14272. var _gl = _this.context;
  14273. var defines = material.defines;
  14274. var uniforms = material.__webglShader.uniforms;
  14275. var attributes = material.attributes;
  14276. var vertexShader = material.__webglShader.vertexShader;
  14277. var fragmentShader = material.__webglShader.fragmentShader;
  14278. var index0AttributeName = material.index0AttributeName;
  14279. if ( index0AttributeName === undefined && parameters.morphTargets === true ) {
  14280. // programs with morphTargets displace position out of attribute 0
  14281. index0AttributeName = 'position';
  14282. }
  14283. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  14284. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  14285. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  14286. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  14287. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  14288. }
  14289. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  14290. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  14291. var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  14292. if ( parameters.envMap ) {
  14293. switch ( material.envMap.mapping ) {
  14294. case THREE.CubeReflectionMapping:
  14295. case THREE.CubeRefractionMapping:
  14296. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  14297. break;
  14298. case THREE.EquirectangularReflectionMapping:
  14299. case THREE.EquirectangularRefractionMapping:
  14300. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  14301. break;
  14302. case THREE.SphericalReflectionMapping:
  14303. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  14304. break;
  14305. }
  14306. switch ( material.envMap.mapping ) {
  14307. case THREE.CubeRefractionMapping:
  14308. case THREE.EquirectangularRefractionMapping:
  14309. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  14310. break;
  14311. }
  14312. switch ( material.combine ) {
  14313. case THREE.MultiplyOperation:
  14314. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  14315. break;
  14316. case THREE.MixOperation:
  14317. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  14318. break;
  14319. case THREE.AddOperation:
  14320. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  14321. break;
  14322. }
  14323. }
  14324. var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  14325. // console.log( 'building new program ' );
  14326. //
  14327. var customDefines = generateDefines( defines );
  14328. //
  14329. var program = _gl.createProgram();
  14330. var prefix_vertex, prefix_fragment;
  14331. if ( material instanceof THREE.RawShaderMaterial ) {
  14332. prefix_vertex = '';
  14333. prefix_fragment = '';
  14334. } else {
  14335. prefix_vertex = [
  14336. 'precision ' + parameters.precision + ' float;',
  14337. 'precision ' + parameters.precision + ' int;',
  14338. customDefines,
  14339. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  14340. _this.gammaInput ? '#define GAMMA_INPUT' : '',
  14341. _this.gammaOutput ? '#define GAMMA_OUTPUT' : '',
  14342. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  14343. '#define MAX_DIR_LIGHTS ' + parameters.maxDirLights,
  14344. '#define MAX_POINT_LIGHTS ' + parameters.maxPointLights,
  14345. '#define MAX_SPOT_LIGHTS ' + parameters.maxSpotLights,
  14346. '#define MAX_HEMI_LIGHTS ' + parameters.maxHemiLights,
  14347. '#define MAX_SHADOWS ' + parameters.maxShadows,
  14348. '#define MAX_BONES ' + parameters.maxBones,
  14349. parameters.map ? '#define USE_MAP' : '',
  14350. parameters.envMap ? '#define USE_ENVMAP' : '',
  14351. parameters.envMap ? '#define ' + envMapModeDefine : '',
  14352. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  14353. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  14354. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  14355. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  14356. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  14357. parameters.vertexColors ? '#define USE_COLOR' : '',
  14358. parameters.flatShading ? '#define FLAT_SHADED': '',
  14359. parameters.skinning ? '#define USE_SKINNING' : '',
  14360. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  14361. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  14362. parameters.morphNormals ? '#define USE_MORPHNORMALS' : '',
  14363. parameters.wrapAround ? '#define WRAP_AROUND' : '',
  14364. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  14365. parameters.flipSided ? '#define FLIP_SIDED' : '',
  14366. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  14367. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  14368. parameters.shadowMapDebug ? '#define SHADOWMAP_DEBUG' : '',
  14369. parameters.shadowMapCascade ? '#define SHADOWMAP_CASCADE' : '',
  14370. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  14371. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  14372. //_this._glExtensionFragDepth ? '#define USE_LOGDEPTHBUF_EXT' : '',
  14373. 'uniform mat4 modelMatrix;',
  14374. 'uniform mat4 modelViewMatrix;',
  14375. 'uniform mat4 projectionMatrix;',
  14376. 'uniform mat4 viewMatrix;',
  14377. 'uniform mat3 normalMatrix;',
  14378. 'uniform vec3 cameraPosition;',
  14379. 'attribute vec3 position;',
  14380. 'attribute vec3 normal;',
  14381. 'attribute vec2 uv;',
  14382. 'attribute vec2 uv2;',
  14383. '#ifdef USE_COLOR',
  14384. ' attribute vec3 color;',
  14385. '#endif',
  14386. '#ifdef USE_MORPHTARGETS',
  14387. ' attribute vec3 morphTarget0;',
  14388. ' attribute vec3 morphTarget1;',
  14389. ' attribute vec3 morphTarget2;',
  14390. ' attribute vec3 morphTarget3;',
  14391. ' #ifdef USE_MORPHNORMALS',
  14392. ' attribute vec3 morphNormal0;',
  14393. ' attribute vec3 morphNormal1;',
  14394. ' attribute vec3 morphNormal2;',
  14395. ' attribute vec3 morphNormal3;',
  14396. ' #else',
  14397. ' attribute vec3 morphTarget4;',
  14398. ' attribute vec3 morphTarget5;',
  14399. ' attribute vec3 morphTarget6;',
  14400. ' attribute vec3 morphTarget7;',
  14401. ' #endif',
  14402. '#endif',
  14403. '#ifdef USE_SKINNING',
  14404. ' attribute vec4 skinIndex;',
  14405. ' attribute vec4 skinWeight;',
  14406. '#endif',
  14407. ''
  14408. ].join( '\n' );
  14409. prefix_fragment = [
  14410. 'precision ' + parameters.precision + ' float;',
  14411. 'precision ' + parameters.precision + ' int;',
  14412. ( parameters.bumpMap || parameters.normalMap || parameters.flatShading ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  14413. customDefines,
  14414. '#define MAX_DIR_LIGHTS ' + parameters.maxDirLights,
  14415. '#define MAX_POINT_LIGHTS ' + parameters.maxPointLights,
  14416. '#define MAX_SPOT_LIGHTS ' + parameters.maxSpotLights,
  14417. '#define MAX_HEMI_LIGHTS ' + parameters.maxHemiLights,
  14418. '#define MAX_SHADOWS ' + parameters.maxShadows,
  14419. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest : '',
  14420. _this.gammaInput ? '#define GAMMA_INPUT' : '',
  14421. _this.gammaOutput ? '#define GAMMA_OUTPUT' : '',
  14422. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  14423. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  14424. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  14425. parameters.map ? '#define USE_MAP' : '',
  14426. parameters.envMap ? '#define USE_ENVMAP' : '',
  14427. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  14428. parameters.envMap ? '#define ' + envMapModeDefine : '',
  14429. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  14430. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  14431. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  14432. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  14433. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  14434. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  14435. parameters.vertexColors ? '#define USE_COLOR' : '',
  14436. parameters.flatShading ? '#define FLAT_SHADED': '',
  14437. parameters.metal ? '#define METAL' : '',
  14438. parameters.wrapAround ? '#define WRAP_AROUND' : '',
  14439. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  14440. parameters.flipSided ? '#define FLIP_SIDED' : '',
  14441. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  14442. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  14443. parameters.shadowMapDebug ? '#define SHADOWMAP_DEBUG' : '',
  14444. parameters.shadowMapCascade ? '#define SHADOWMAP_CASCADE' : '',
  14445. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  14446. //_this._glExtensionFragDepth ? '#define USE_LOGDEPTHBUF_EXT' : '',
  14447. 'uniform mat4 viewMatrix;',
  14448. 'uniform vec3 cameraPosition;',
  14449. ''
  14450. ].join( '\n' );
  14451. }
  14452. var glVertexShader = new THREE.WebGLShader( _gl, _gl.VERTEX_SHADER, prefix_vertex + vertexShader );
  14453. var glFragmentShader = new THREE.WebGLShader( _gl, _gl.FRAGMENT_SHADER, prefix_fragment + fragmentShader );
  14454. _gl.attachShader( program, glVertexShader );
  14455. _gl.attachShader( program, glFragmentShader );
  14456. if ( index0AttributeName !== undefined ) {
  14457. // Force a particular attribute to index 0.
  14458. // because potentially expensive emulation is done by browser if attribute 0 is disabled.
  14459. // And, color, for example is often automatically bound to index 0 so disabling it
  14460. _gl.bindAttribLocation( program, 0, index0AttributeName );
  14461. }
  14462. _gl.linkProgram( program );
  14463. var programLogInfo = _gl.getProgramInfoLog( program );
  14464. if ( _gl.getProgramParameter( program, _gl.LINK_STATUS ) === false ) {
  14465. THREE.error( 'THREE.WebGLProgram: shader error: ' + _gl.getError(), 'gl.VALIDATE_STATUS', _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ), 'gl.getPRogramInfoLog', programLogInfo );
  14466. }
  14467. if ( programLogInfo !== '' ) {
  14468. THREE.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()' + programLogInfo );
  14469. // THREE.warn( _gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glVertexShader ) );
  14470. // THREE.warn( _gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glFragmentShader ) );
  14471. }
  14472. // clean up
  14473. _gl.deleteShader( glVertexShader );
  14474. _gl.deleteShader( glFragmentShader );
  14475. // cache uniform locations
  14476. var identifiers = [
  14477. 'viewMatrix',
  14478. 'modelViewMatrix',
  14479. 'projectionMatrix',
  14480. 'normalMatrix',
  14481. 'modelMatrix',
  14482. 'cameraPosition',
  14483. 'morphTargetInfluences',
  14484. 'bindMatrix',
  14485. 'bindMatrixInverse'
  14486. ];
  14487. if ( parameters.useVertexTexture ) {
  14488. identifiers.push( 'boneTexture' );
  14489. identifiers.push( 'boneTextureWidth' );
  14490. identifiers.push( 'boneTextureHeight' );
  14491. } else {
  14492. identifiers.push( 'boneGlobalMatrices' );
  14493. }
  14494. if ( parameters.logarithmicDepthBuffer ) {
  14495. identifiers.push('logDepthBufFC');
  14496. }
  14497. for ( var u in uniforms ) {
  14498. identifiers.push( u );
  14499. }
  14500. this.uniforms = cacheUniformLocations( _gl, program, identifiers );
  14501. // cache attributes locations
  14502. identifiers = [
  14503. 'position',
  14504. 'normal',
  14505. 'uv',
  14506. 'uv2',
  14507. 'tangent',
  14508. 'color',
  14509. 'skinIndex',
  14510. 'skinWeight',
  14511. 'lineDistance'
  14512. ];
  14513. for ( var i = 0; i < parameters.maxMorphTargets; i ++ ) {
  14514. identifiers.push( 'morphTarget' + i );
  14515. }
  14516. for ( var i = 0; i < parameters.maxMorphNormals; i ++ ) {
  14517. identifiers.push( 'morphNormal' + i );
  14518. }
  14519. for ( var a in attributes ) {
  14520. identifiers.push( a );
  14521. }
  14522. this.attributes = cacheAttributeLocations( _gl, program, identifiers );
  14523. this.attributesKeys = Object.keys( this.attributes );
  14524. //
  14525. this.id = programIdCount ++;
  14526. this.code = code;
  14527. this.usedTimes = 1;
  14528. this.program = program;
  14529. this.vertexShader = glVertexShader;
  14530. this.fragmentShader = glFragmentShader;
  14531. return this;
  14532. };
  14533. } )();
  14534. // File:src/renderers/webgl/WebGLShader.js
  14535. THREE.WebGLShader = ( function () {
  14536. var addLineNumbers = function ( string ) {
  14537. var lines = string.split( '\n' );
  14538. for ( var i = 0; i < lines.length; i ++ ) {
  14539. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  14540. }
  14541. return lines.join( '\n' );
  14542. };
  14543. return function ( gl, type, string ) {
  14544. var shader = gl.createShader( type );
  14545. gl.shaderSource( shader, string );
  14546. gl.compileShader( shader );
  14547. if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) {
  14548. THREE.error( 'THREE.WebGLShader: Shader couldn\'t compile.' );
  14549. }
  14550. if ( gl.getShaderInfoLog( shader ) !== '' ) {
  14551. THREE.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', gl.getShaderInfoLog( shader ), addLineNumbers( string ) );
  14552. }
  14553. // --enable-privileged-webgl-extension
  14554. // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  14555. return shader;
  14556. };
  14557. } )();
  14558. // File:src/renderers/webgl/WebGLState.js
  14559. /**
  14560. * @author mrdoob / http://mrdoob.com/
  14561. */
  14562. THREE.WebGLState = function ( gl, paramThreeToGL ) {
  14563. var newAttributes = new Uint8Array( 16 );
  14564. var enabledAttributes = new Uint8Array( 16 );
  14565. var currentBlending = null;
  14566. var currentBlendEquation = null;
  14567. var currentBlendSrc = null;
  14568. var currentBlendDst = null;
  14569. var currentBlendEquationAlpha = null;
  14570. var currentBlendSrcAlpha = null;
  14571. var currentBlendDstAlpha = null;
  14572. var currentDepthTest = null;
  14573. var currentDepthWrite = null;
  14574. var currentColorWrite = null;
  14575. var currentDoubleSided = null;
  14576. var currentFlipSided = null;
  14577. var currentLineWidth = null;
  14578. var currentPolygonOffset = null;
  14579. var currentPolygonOffsetFactor = null;
  14580. var currentPolygonOffsetUnits = null;
  14581. this.initAttributes = function () {
  14582. for ( var i = 0, l = newAttributes.length; i < l; i ++ ) {
  14583. newAttributes[ i ] = 0;
  14584. }
  14585. };
  14586. this.enableAttribute = function ( attribute ) {
  14587. newAttributes[ attribute ] = 1;
  14588. if ( enabledAttributes[ attribute ] === 0 ) {
  14589. gl.enableVertexAttribArray( attribute );
  14590. enabledAttributes[ attribute ] = 1;
  14591. }
  14592. };
  14593. this.disableUnusedAttributes = function () {
  14594. for ( var i = 0, l = enabledAttributes.length; i < l; i ++ ) {
  14595. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  14596. gl.disableVertexAttribArray( i );
  14597. enabledAttributes[ i ] = 0;
  14598. }
  14599. }
  14600. };
  14601. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha ) {
  14602. if ( blending !== currentBlending ) {
  14603. if ( blending === THREE.NoBlending ) {
  14604. gl.disable( gl.BLEND );
  14605. } else if ( blending === THREE.AdditiveBlending ) {
  14606. gl.enable( gl.BLEND );
  14607. gl.blendEquation( gl.FUNC_ADD );
  14608. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  14609. } else if ( blending === THREE.SubtractiveBlending ) {
  14610. // TODO: Find blendFuncSeparate() combination
  14611. gl.enable( gl.BLEND );
  14612. gl.blendEquation( gl.FUNC_ADD );
  14613. gl.blendFunc( gl.ZERO, gl.ONE_MINUS_SRC_COLOR );
  14614. } else if ( blending === THREE.MultiplyBlending ) {
  14615. // TODO: Find blendFuncSeparate() combination
  14616. gl.enable( gl.BLEND );
  14617. gl.blendEquation( gl.FUNC_ADD );
  14618. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  14619. } else if ( blending === THREE.CustomBlending ) {
  14620. gl.enable( gl.BLEND );
  14621. } else {
  14622. gl.enable( gl.BLEND );
  14623. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  14624. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  14625. }
  14626. currentBlending = blending;
  14627. }
  14628. if ( blending === THREE.CustomBlending ) {
  14629. blendEquationAlpha = blendEquationAlpha || blendEquation;
  14630. blendSrcAlpha = blendSrcAlpha || blendSrc;
  14631. blendDstAlpha = blendDstAlpha || blendDst;
  14632. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  14633. gl.blendEquationSeparate( paramThreeToGL( blendEquation ), paramThreeToGL( blendEquationAlpha ) );
  14634. currentBlendEquation = blendEquation;
  14635. currentBlendEquationAlpha = blendEquationAlpha;
  14636. }
  14637. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  14638. gl.blendFuncSeparate( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ), paramThreeToGL( blendSrcAlpha ), paramThreeToGL( blendDstAlpha ) );
  14639. currentBlendSrc = blendSrc;
  14640. currentBlendDst = blendDst;
  14641. currentBlendSrcAlpha = blendSrcAlpha;
  14642. currentBlendDstAlpha = blendDstAlpha;
  14643. }
  14644. } else {
  14645. currentBlendEquation = null;
  14646. currentBlendSrc = null;
  14647. currentBlendDst = null;
  14648. currentBlendEquationAlpha = null;
  14649. currentBlendSrcAlpha = null;
  14650. currentBlendDstAlpha = null;
  14651. }
  14652. };
  14653. this.setDepthTest = function ( depthTest ) {
  14654. if ( currentDepthTest !== depthTest ) {
  14655. if ( depthTest ) {
  14656. gl.enable( gl.DEPTH_TEST );
  14657. } else {
  14658. gl.disable( gl.DEPTH_TEST );
  14659. }
  14660. currentDepthTest = depthTest;
  14661. }
  14662. };
  14663. this.setDepthWrite = function ( depthWrite ) {
  14664. if ( currentDepthWrite !== depthWrite ) {
  14665. gl.depthMask( depthWrite );
  14666. currentDepthWrite = depthWrite;
  14667. }
  14668. };
  14669. this.setColorWrite = function ( colorWrite ) {
  14670. if ( currentColorWrite !== colorWrite ) {
  14671. gl.colorMask( colorWrite, colorWrite, colorWrite, colorWrite );
  14672. currentColorWrite = colorWrite;
  14673. }
  14674. };
  14675. this.setDoubleSided = function ( doubleSided ) {
  14676. if ( currentDoubleSided !== doubleSided ) {
  14677. if ( doubleSided ) {
  14678. gl.disable( gl.CULL_FACE );
  14679. } else {
  14680. gl.enable( gl.CULL_FACE );
  14681. }
  14682. currentDoubleSided = doubleSided;
  14683. }
  14684. };
  14685. this.setFlipSided = function ( flipSided ) {
  14686. if ( currentFlipSided !== flipSided ) {
  14687. if ( flipSided ) {
  14688. gl.frontFace( gl.CW );
  14689. } else {
  14690. gl.frontFace( gl.CCW );
  14691. }
  14692. currentFlipSided = flipSided;
  14693. }
  14694. };
  14695. this.setLineWidth = function ( width ) {
  14696. if ( width !== currentLineWidth ) {
  14697. gl.lineWidth( width );
  14698. currentLineWidth = width;
  14699. }
  14700. };
  14701. this.setPolygonOffset = function ( polygonoffset, factor, units ) {
  14702. if ( currentPolygonOffset !== polygonoffset ) {
  14703. if ( polygonoffset ) {
  14704. gl.enable( gl.POLYGON_OFFSET_FILL );
  14705. } else {
  14706. gl.disable( gl.POLYGON_OFFSET_FILL );
  14707. }
  14708. currentPolygonOffset = polygonoffset;
  14709. }
  14710. if ( polygonoffset && ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) ) {
  14711. gl.polygonOffset( factor, units );
  14712. currentPolygonOffsetFactor = factor;
  14713. currentPolygonOffsetUnits = units;
  14714. }
  14715. };
  14716. this.reset = function () {
  14717. for ( var i = 0; i < enabledAttributes.length; i ++ ) {
  14718. enabledAttributes[ i ] = 0;
  14719. }
  14720. currentBlending = null;
  14721. currentDepthTest = null;
  14722. currentDepthWrite = null;
  14723. currentColorWrite = null;
  14724. currentDoubleSided = null;
  14725. currentFlipSided = null;
  14726. };
  14727. };
  14728. // File:src/renderers/webgl/plugins/LensFlarePlugin.js
  14729. /**
  14730. * @author mikael emtinger / http://gomo.se/
  14731. * @author alteredq / http://alteredqualia.com/
  14732. */
  14733. THREE.LensFlarePlugin = function ( renderer, flares ) {
  14734. var gl = renderer.context;
  14735. var vertexBuffer, elementBuffer;
  14736. var program, attributes, uniforms;
  14737. var hasVertexTexture;
  14738. var tempTexture, occlusionTexture;
  14739. var init = function () {
  14740. var vertices = new Float32Array( [
  14741. -1, -1, 0, 0,
  14742. 1, -1, 1, 0,
  14743. 1, 1, 1, 1,
  14744. -1, 1, 0, 1
  14745. ] );
  14746. var faces = new Uint16Array( [
  14747. 0, 1, 2,
  14748. 0, 2, 3
  14749. ] );
  14750. // buffers
  14751. vertexBuffer = gl.createBuffer();
  14752. elementBuffer = gl.createBuffer();
  14753. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  14754. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  14755. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  14756. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  14757. // textures
  14758. tempTexture = gl.createTexture();
  14759. occlusionTexture = gl.createTexture();
  14760. gl.bindTexture( gl.TEXTURE_2D, tempTexture );
  14761. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB, 16, 16, 0, gl.RGB, gl.UNSIGNED_BYTE, null );
  14762. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  14763. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  14764. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  14765. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  14766. gl.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  14767. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, 16, 16, 0, gl.RGBA, gl.UNSIGNED_BYTE, null );
  14768. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  14769. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  14770. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  14771. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  14772. hasVertexTexture = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) > 0;
  14773. var shader;
  14774. if ( hasVertexTexture ) {
  14775. shader = {
  14776. vertexShader: [
  14777. "uniform lowp int renderType;",
  14778. "uniform vec3 screenPosition;",
  14779. "uniform vec2 scale;",
  14780. "uniform float rotation;",
  14781. "uniform sampler2D occlusionMap;",
  14782. "attribute vec2 position;",
  14783. "attribute vec2 uv;",
  14784. "varying vec2 vUV;",
  14785. "varying float vVisibility;",
  14786. "void main() {",
  14787. "vUV = uv;",
  14788. "vec2 pos = position;",
  14789. "if( renderType == 2 ) {",
  14790. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  14791. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  14792. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  14793. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  14794. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  14795. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  14796. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  14797. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  14798. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  14799. "vVisibility = visibility.r / 9.0;",
  14800. "vVisibility *= 1.0 - visibility.g / 9.0;",
  14801. "vVisibility *= visibility.b / 9.0;",
  14802. "vVisibility *= 1.0 - visibility.a / 9.0;",
  14803. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  14804. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  14805. "}",
  14806. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  14807. "}"
  14808. ].join( "\n" ),
  14809. fragmentShader: [
  14810. "uniform lowp int renderType;",
  14811. "uniform sampler2D map;",
  14812. "uniform float opacity;",
  14813. "uniform vec3 color;",
  14814. "varying vec2 vUV;",
  14815. "varying float vVisibility;",
  14816. "void main() {",
  14817. // pink square
  14818. "if( renderType == 0 ) {",
  14819. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  14820. // restore
  14821. "} else if( renderType == 1 ) {",
  14822. "gl_FragColor = texture2D( map, vUV );",
  14823. // flare
  14824. "} else {",
  14825. "vec4 texture = texture2D( map, vUV );",
  14826. "texture.a *= opacity * vVisibility;",
  14827. "gl_FragColor = texture;",
  14828. "gl_FragColor.rgb *= color;",
  14829. "}",
  14830. "}"
  14831. ].join( "\n" )
  14832. };
  14833. } else {
  14834. shader = {
  14835. vertexShader: [
  14836. "uniform lowp int renderType;",
  14837. "uniform vec3 screenPosition;",
  14838. "uniform vec2 scale;",
  14839. "uniform float rotation;",
  14840. "attribute vec2 position;",
  14841. "attribute vec2 uv;",
  14842. "varying vec2 vUV;",
  14843. "void main() {",
  14844. "vUV = uv;",
  14845. "vec2 pos = position;",
  14846. "if( renderType == 2 ) {",
  14847. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  14848. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  14849. "}",
  14850. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  14851. "}"
  14852. ].join( "\n" ),
  14853. fragmentShader: [
  14854. "precision mediump float;",
  14855. "uniform lowp int renderType;",
  14856. "uniform sampler2D map;",
  14857. "uniform sampler2D occlusionMap;",
  14858. "uniform float opacity;",
  14859. "uniform vec3 color;",
  14860. "varying vec2 vUV;",
  14861. "void main() {",
  14862. // pink square
  14863. "if( renderType == 0 ) {",
  14864. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  14865. // restore
  14866. "} else if( renderType == 1 ) {",
  14867. "gl_FragColor = texture2D( map, vUV );",
  14868. // flare
  14869. "} else {",
  14870. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a;",
  14871. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a;",
  14872. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a;",
  14873. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  14874. "visibility = ( 1.0 - visibility / 4.0 );",
  14875. "vec4 texture = texture2D( map, vUV );",
  14876. "texture.a *= opacity * visibility;",
  14877. "gl_FragColor = texture;",
  14878. "gl_FragColor.rgb *= color;",
  14879. "}",
  14880. "}"
  14881. ].join( "\n" )
  14882. };
  14883. }
  14884. program = createProgram( shader );
  14885. attributes = {
  14886. vertex: gl.getAttribLocation ( program, "position" ),
  14887. uv: gl.getAttribLocation ( program, "uv" )
  14888. }
  14889. uniforms = {
  14890. renderType: gl.getUniformLocation( program, "renderType" ),
  14891. map: gl.getUniformLocation( program, "map" ),
  14892. occlusionMap: gl.getUniformLocation( program, "occlusionMap" ),
  14893. opacity: gl.getUniformLocation( program, "opacity" ),
  14894. color: gl.getUniformLocation( program, "color" ),
  14895. scale: gl.getUniformLocation( program, "scale" ),
  14896. rotation: gl.getUniformLocation( program, "rotation" ),
  14897. screenPosition: gl.getUniformLocation( program, "screenPosition" )
  14898. };
  14899. };
  14900. /*
  14901. * Render lens flares
  14902. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  14903. * reads these back and calculates occlusion.
  14904. */
  14905. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  14906. if ( flares.length === 0 ) return;
  14907. var tempPosition = new THREE.Vector3();
  14908. var invAspect = viewportHeight / viewportWidth,
  14909. halfViewportWidth = viewportWidth * 0.5,
  14910. halfViewportHeight = viewportHeight * 0.5;
  14911. var size = 16 / viewportHeight,
  14912. scale = new THREE.Vector2( size * invAspect, size );
  14913. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  14914. screenPositionPixels = new THREE.Vector2( 1, 1 );
  14915. if ( program === undefined ) {
  14916. init();
  14917. }
  14918. gl.useProgram( program );
  14919. gl.enableVertexAttribArray( attributes.vertex );
  14920. gl.enableVertexAttribArray( attributes.uv );
  14921. // loop through all lens flares to update their occlusion and positions
  14922. // setup gl and common used attribs/unforms
  14923. gl.uniform1i( uniforms.occlusionMap, 0 );
  14924. gl.uniform1i( uniforms.map, 1 );
  14925. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  14926. gl.vertexAttribPointer( attributes.vertex, 2, gl.FLOAT, false, 2 * 8, 0 );
  14927. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  14928. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  14929. gl.disable( gl.CULL_FACE );
  14930. gl.depthMask( false );
  14931. for ( var i = 0, l = flares.length; i < l; i ++ ) {
  14932. size = 16 / viewportHeight;
  14933. scale.set( size * invAspect, size );
  14934. // calc object screen position
  14935. var flare = flares[ i ];
  14936. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  14937. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  14938. tempPosition.applyProjection( camera.projectionMatrix );
  14939. // setup arrays for gl programs
  14940. screenPosition.copy( tempPosition )
  14941. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  14942. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  14943. // screen cull
  14944. if ( hasVertexTexture || (
  14945. screenPositionPixels.x > 0 &&
  14946. screenPositionPixels.x < viewportWidth &&
  14947. screenPositionPixels.y > 0 &&
  14948. screenPositionPixels.y < viewportHeight ) ) {
  14949. // save current RGB to temp texture
  14950. gl.activeTexture( gl.TEXTURE1 );
  14951. gl.bindTexture( gl.TEXTURE_2D, tempTexture );
  14952. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  14953. // render pink quad
  14954. gl.uniform1i( uniforms.renderType, 0 );
  14955. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  14956. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  14957. gl.disable( gl.BLEND );
  14958. gl.enable( gl.DEPTH_TEST );
  14959. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  14960. // copy result to occlusionMap
  14961. gl.activeTexture( gl.TEXTURE0 );
  14962. gl.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  14963. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  14964. // restore graphics
  14965. gl.uniform1i( uniforms.renderType, 1 );
  14966. gl.disable( gl.DEPTH_TEST );
  14967. gl.activeTexture( gl.TEXTURE1 );
  14968. gl.bindTexture( gl.TEXTURE_2D, tempTexture );
  14969. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  14970. // update object positions
  14971. flare.positionScreen.copy( screenPosition )
  14972. if ( flare.customUpdateCallback ) {
  14973. flare.customUpdateCallback( flare );
  14974. } else {
  14975. flare.updateLensFlares();
  14976. }
  14977. // render flares
  14978. gl.uniform1i( uniforms.renderType, 2 );
  14979. gl.enable( gl.BLEND );
  14980. for ( var j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  14981. var sprite = flare.lensFlares[ j ];
  14982. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  14983. screenPosition.x = sprite.x;
  14984. screenPosition.y = sprite.y;
  14985. screenPosition.z = sprite.z;
  14986. size = sprite.size * sprite.scale / viewportHeight;
  14987. scale.x = size * invAspect;
  14988. scale.y = size;
  14989. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  14990. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  14991. gl.uniform1f( uniforms.rotation, sprite.rotation );
  14992. gl.uniform1f( uniforms.opacity, sprite.opacity );
  14993. gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  14994. renderer.state.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  14995. renderer.setTexture( sprite.texture, 1 );
  14996. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  14997. }
  14998. }
  14999. }
  15000. }
  15001. // restore gl
  15002. gl.enable( gl.CULL_FACE );
  15003. gl.enable( gl.DEPTH_TEST );
  15004. gl.depthMask( true );
  15005. renderer.resetGLState();
  15006. };
  15007. function createProgram ( shader ) {
  15008. var program = gl.createProgram();
  15009. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  15010. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  15011. var prefix = "precision " + renderer.getPrecision() + " float;\n";
  15012. gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  15013. gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  15014. gl.compileShader( fragmentShader );
  15015. gl.compileShader( vertexShader );
  15016. gl.attachShader( program, fragmentShader );
  15017. gl.attachShader( program, vertexShader );
  15018. gl.linkProgram( program );
  15019. return program;
  15020. }
  15021. };
  15022. // File:src/renderers/webgl/plugins/ShadowMapPlugin.js
  15023. /**
  15024. * @author alteredq / http://alteredqualia.com/
  15025. */
  15026. THREE.ShadowMapPlugin = function ( _renderer, _lights, _webglObjects, _webglObjectsImmediate ) {
  15027. var _gl = _renderer.context;
  15028. var _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  15029. _frustum = new THREE.Frustum(),
  15030. _projScreenMatrix = new THREE.Matrix4(),
  15031. _min = new THREE.Vector3(),
  15032. _max = new THREE.Vector3(),
  15033. _matrixPosition = new THREE.Vector3(),
  15034. _renderList = [];
  15035. // init
  15036. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  15037. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  15038. _depthMaterial = new THREE.ShaderMaterial( {
  15039. uniforms: depthUniforms,
  15040. vertexShader: depthShader.vertexShader,
  15041. fragmentShader: depthShader.fragmentShader
  15042. } );
  15043. _depthMaterialMorph = new THREE.ShaderMaterial( {
  15044. uniforms: depthUniforms,
  15045. vertexShader: depthShader.vertexShader,
  15046. fragmentShader: depthShader.fragmentShader,
  15047. morphTargets: true
  15048. } );
  15049. _depthMaterialSkin = new THREE.ShaderMaterial( {
  15050. uniforms: depthUniforms,
  15051. vertexShader: depthShader.vertexShader,
  15052. fragmentShader: depthShader.fragmentShader,
  15053. skinning: true
  15054. } );
  15055. _depthMaterialMorphSkin = new THREE.ShaderMaterial( {
  15056. uniforms: depthUniforms,
  15057. vertexShader: depthShader.vertexShader,
  15058. fragmentShader: depthShader.fragmentShader,
  15059. morphTargets: true,
  15060. skinning: true
  15061. } );
  15062. _depthMaterial._shadowPass = true;
  15063. _depthMaterialMorph._shadowPass = true;
  15064. _depthMaterialSkin._shadowPass = true;
  15065. _depthMaterialMorphSkin._shadowPass = true;
  15066. this.render = function ( scene, camera ) {
  15067. if ( _renderer.shadowMapEnabled === false ) return;
  15068. var i, il, j, jl, n,
  15069. shadowMap, shadowMatrix, shadowCamera,
  15070. buffer, material,
  15071. webglObject, object, light,
  15072. lights = [],
  15073. k = 0,
  15074. fog = null;
  15075. // set GL state for depth map
  15076. _gl.clearColor( 1, 1, 1, 1 );
  15077. _gl.disable( _gl.BLEND );
  15078. _gl.enable( _gl.CULL_FACE );
  15079. _gl.frontFace( _gl.CCW );
  15080. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  15081. _gl.cullFace( _gl.FRONT );
  15082. } else {
  15083. _gl.cullFace( _gl.BACK );
  15084. }
  15085. _renderer.state.setDepthTest( true );
  15086. // preprocess lights
  15087. // - skip lights that are not casting shadows
  15088. // - create virtual lights for cascaded shadow maps
  15089. for ( i = 0, il = _lights.length; i < il; i ++ ) {
  15090. light = _lights[ i ];
  15091. if ( ! light.castShadow ) continue;
  15092. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  15093. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  15094. var virtualLight;
  15095. if ( ! light.shadowCascadeArray[ n ] ) {
  15096. virtualLight = createVirtualLight( light, n );
  15097. virtualLight.originalCamera = camera;
  15098. var gyro = new THREE.Gyroscope();
  15099. gyro.position.copy( light.shadowCascadeOffset );
  15100. gyro.add( virtualLight );
  15101. gyro.add( virtualLight.target );
  15102. camera.add( gyro );
  15103. light.shadowCascadeArray[ n ] = virtualLight;
  15104. //console.log( "Created virtualLight", virtualLight );
  15105. } else {
  15106. virtualLight = light.shadowCascadeArray[ n ];
  15107. }
  15108. updateVirtualLight( light, n );
  15109. lights[ k ] = virtualLight;
  15110. k ++;
  15111. }
  15112. } else {
  15113. lights[ k ] = light;
  15114. k ++;
  15115. }
  15116. }
  15117. // render depth map
  15118. for ( i = 0, il = lights.length; i < il; i ++ ) {
  15119. light = lights[ i ];
  15120. if ( ! light.shadowMap ) {
  15121. var shadowFilter = THREE.LinearFilter;
  15122. if ( _renderer.shadowMapType === THREE.PCFSoftShadowMap ) {
  15123. shadowFilter = THREE.NearestFilter;
  15124. }
  15125. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  15126. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  15127. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  15128. light.shadowMatrix = new THREE.Matrix4();
  15129. }
  15130. if ( ! light.shadowCamera ) {
  15131. if ( light instanceof THREE.SpotLight ) {
  15132. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  15133. } else if ( light instanceof THREE.DirectionalLight ) {
  15134. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  15135. } else {
  15136. THREE.error( "THREE.ShadowMapPlugin: Unsupported light type for shadow", light );
  15137. continue;
  15138. }
  15139. scene.add( light.shadowCamera );
  15140. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  15141. }
  15142. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  15143. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  15144. scene.add( light.cameraHelper );
  15145. }
  15146. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  15147. updateShadowCamera( camera, light );
  15148. }
  15149. shadowMap = light.shadowMap;
  15150. shadowMatrix = light.shadowMatrix;
  15151. shadowCamera = light.shadowCamera;
  15152. //
  15153. shadowCamera.position.setFromMatrixPosition( light.matrixWorld );
  15154. _matrixPosition.setFromMatrixPosition( light.target.matrixWorld );
  15155. shadowCamera.lookAt( _matrixPosition );
  15156. shadowCamera.updateMatrixWorld();
  15157. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  15158. //
  15159. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  15160. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  15161. // compute shadow matrix
  15162. shadowMatrix.set(
  15163. 0.5, 0.0, 0.0, 0.5,
  15164. 0.0, 0.5, 0.0, 0.5,
  15165. 0.0, 0.0, 0.5, 0.5,
  15166. 0.0, 0.0, 0.0, 1.0
  15167. );
  15168. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  15169. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  15170. // update camera matrices and frustum
  15171. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  15172. _frustum.setFromMatrix( _projScreenMatrix );
  15173. // render shadow map
  15174. _renderer.setRenderTarget( shadowMap );
  15175. _renderer.clear();
  15176. // set object matrices & frustum culling
  15177. _renderList.length = 0;
  15178. projectObject( scene, scene, shadowCamera );
  15179. // render regular objects
  15180. var objectMaterial, useMorphing, useSkinning;
  15181. for ( j = 0, jl = _renderList.length; j < jl; j ++ ) {
  15182. webglObject = _renderList[ j ];
  15183. object = webglObject.object;
  15184. buffer = webglObject.buffer;
  15185. // culling is overriden globally for all objects
  15186. // while rendering depth map
  15187. // need to deal with MeshFaceMaterial somehow
  15188. // in that case just use the first of material.materials for now
  15189. // (proper solution would require to break objects by materials
  15190. // similarly to regular rendering and then set corresponding
  15191. // depth materials per each chunk instead of just once per object)
  15192. objectMaterial = getObjectMaterial( object );
  15193. useMorphing = object.geometry.morphTargets !== undefined && object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  15194. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  15195. if ( object.customDepthMaterial ) {
  15196. material = object.customDepthMaterial;
  15197. } else if ( useSkinning ) {
  15198. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  15199. } else if ( useMorphing ) {
  15200. material = _depthMaterialMorph;
  15201. } else {
  15202. material = _depthMaterial;
  15203. }
  15204. _renderer.setMaterialFaces( objectMaterial );
  15205. if ( buffer instanceof THREE.BufferGeometry ) {
  15206. _renderer.renderBufferDirect( shadowCamera, _lights, fog, material, buffer, object );
  15207. } else {
  15208. _renderer.renderBuffer( shadowCamera, _lights, fog, material, buffer, object );
  15209. }
  15210. }
  15211. // set matrices and render immediate objects
  15212. for ( j = 0, jl = _webglObjectsImmediate.length; j < jl; j ++ ) {
  15213. webglObject = _webglObjectsImmediate[ j ];
  15214. object = webglObject.object;
  15215. if ( object.visible && object.castShadow ) {
  15216. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  15217. _renderer.renderImmediateObject( shadowCamera, _lights, fog, _depthMaterial, object );
  15218. }
  15219. }
  15220. }
  15221. // restore GL state
  15222. var clearColor = _renderer.getClearColor(),
  15223. clearAlpha = _renderer.getClearAlpha();
  15224. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  15225. _gl.enable( _gl.BLEND );
  15226. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  15227. _gl.cullFace( _gl.BACK );
  15228. }
  15229. _renderer.resetGLState();
  15230. };
  15231. function projectObject( scene, object, shadowCamera ) {
  15232. if ( object.visible ) {
  15233. var webglObjects = _webglObjects[ object.id ];
  15234. if ( webglObjects && object.castShadow && (object.frustumCulled === false || _frustum.intersectsObject( object ) === true) ) {
  15235. for ( var i = 0, l = webglObjects.length; i < l; i ++ ) {
  15236. var webglObject = webglObjects[ i ];
  15237. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  15238. _renderList.push( webglObject );
  15239. }
  15240. }
  15241. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  15242. projectObject( scene, object.children[ i ], shadowCamera );
  15243. }
  15244. }
  15245. }
  15246. function createVirtualLight( light, cascade ) {
  15247. var virtualLight = new THREE.DirectionalLight();
  15248. virtualLight.isVirtual = true;
  15249. virtualLight.onlyShadow = true;
  15250. virtualLight.castShadow = true;
  15251. virtualLight.shadowCameraNear = light.shadowCameraNear;
  15252. virtualLight.shadowCameraFar = light.shadowCameraFar;
  15253. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  15254. virtualLight.shadowCameraRight = light.shadowCameraRight;
  15255. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  15256. virtualLight.shadowCameraTop = light.shadowCameraTop;
  15257. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  15258. virtualLight.shadowDarkness = light.shadowDarkness;
  15259. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  15260. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  15261. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  15262. virtualLight.pointsWorld = [];
  15263. virtualLight.pointsFrustum = [];
  15264. var pointsWorld = virtualLight.pointsWorld,
  15265. pointsFrustum = virtualLight.pointsFrustum;
  15266. for ( var i = 0; i < 8; i ++ ) {
  15267. pointsWorld[ i ] = new THREE.Vector3();
  15268. pointsFrustum[ i ] = new THREE.Vector3();
  15269. }
  15270. var nearZ = light.shadowCascadeNearZ[ cascade ];
  15271. var farZ = light.shadowCascadeFarZ[ cascade ];
  15272. pointsFrustum[ 0 ].set( - 1, - 1, nearZ );
  15273. pointsFrustum[ 1 ].set( 1, - 1, nearZ );
  15274. pointsFrustum[ 2 ].set( - 1, 1, nearZ );
  15275. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  15276. pointsFrustum[ 4 ].set( - 1, - 1, farZ );
  15277. pointsFrustum[ 5 ].set( 1, - 1, farZ );
  15278. pointsFrustum[ 6 ].set( - 1, 1, farZ );
  15279. pointsFrustum[ 7 ].set( 1, 1, farZ );
  15280. return virtualLight;
  15281. }
  15282. // Synchronize virtual light with the original light
  15283. function updateVirtualLight( light, cascade ) {
  15284. var virtualLight = light.shadowCascadeArray[ cascade ];
  15285. virtualLight.position.copy( light.position );
  15286. virtualLight.target.position.copy( light.target.position );
  15287. virtualLight.lookAt( virtualLight.target );
  15288. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  15289. virtualLight.shadowDarkness = light.shadowDarkness;
  15290. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  15291. var nearZ = light.shadowCascadeNearZ[ cascade ];
  15292. var farZ = light.shadowCascadeFarZ[ cascade ];
  15293. var pointsFrustum = virtualLight.pointsFrustum;
  15294. pointsFrustum[ 0 ].z = nearZ;
  15295. pointsFrustum[ 1 ].z = nearZ;
  15296. pointsFrustum[ 2 ].z = nearZ;
  15297. pointsFrustum[ 3 ].z = nearZ;
  15298. pointsFrustum[ 4 ].z = farZ;
  15299. pointsFrustum[ 5 ].z = farZ;
  15300. pointsFrustum[ 6 ].z = farZ;
  15301. pointsFrustum[ 7 ].z = farZ;
  15302. }
  15303. // Fit shadow camera's ortho frustum to camera frustum
  15304. function updateShadowCamera( camera, light ) {
  15305. var shadowCamera = light.shadowCamera,
  15306. pointsFrustum = light.pointsFrustum,
  15307. pointsWorld = light.pointsWorld;
  15308. _min.set( Infinity, Infinity, Infinity );
  15309. _max.set( - Infinity, - Infinity, - Infinity );
  15310. for ( var i = 0; i < 8; i ++ ) {
  15311. var p = pointsWorld[ i ];
  15312. p.copy( pointsFrustum[ i ] );
  15313. p.unproject( camera );
  15314. p.applyMatrix4( shadowCamera.matrixWorldInverse );
  15315. if ( p.x < _min.x ) _min.x = p.x;
  15316. if ( p.x > _max.x ) _max.x = p.x;
  15317. if ( p.y < _min.y ) _min.y = p.y;
  15318. if ( p.y > _max.y ) _max.y = p.y;
  15319. if ( p.z < _min.z ) _min.z = p.z;
  15320. if ( p.z > _max.z ) _max.z = p.z;
  15321. }
  15322. shadowCamera.left = _min.x;
  15323. shadowCamera.right = _max.x;
  15324. shadowCamera.top = _max.y;
  15325. shadowCamera.bottom = _min.y;
  15326. // can't really fit near/far
  15327. //shadowCamera.near = _min.z;
  15328. //shadowCamera.far = _max.z;
  15329. shadowCamera.updateProjectionMatrix();
  15330. }
  15331. // For the moment just ignore objects that have multiple materials with different animation methods
  15332. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  15333. function getObjectMaterial( object ) {
  15334. return object.material instanceof THREE.MeshFaceMaterial
  15335. ? object.material.materials[ 0 ]
  15336. : object.material;
  15337. };
  15338. };
  15339. // File:src/renderers/webgl/plugins/SpritePlugin.js
  15340. /**
  15341. * @author mikael emtinger / http://gomo.se/
  15342. * @author alteredq / http://alteredqualia.com/
  15343. */
  15344. THREE.SpritePlugin = function ( renderer, sprites ) {
  15345. var gl = renderer.context;
  15346. var vertexBuffer, elementBuffer;
  15347. var program, attributes, uniforms;
  15348. var texture;
  15349. // decompose matrixWorld
  15350. var spritePosition = new THREE.Vector3();
  15351. var spriteRotation = new THREE.Quaternion();
  15352. var spriteScale = new THREE.Vector3();
  15353. var init = function () {
  15354. var vertices = new Float32Array( [
  15355. - 0.5, - 0.5, 0, 0,
  15356. 0.5, - 0.5, 1, 0,
  15357. 0.5, 0.5, 1, 1,
  15358. - 0.5, 0.5, 0, 1
  15359. ] );
  15360. var faces = new Uint16Array( [
  15361. 0, 1, 2,
  15362. 0, 2, 3
  15363. ] );
  15364. vertexBuffer = gl.createBuffer();
  15365. elementBuffer = gl.createBuffer();
  15366. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  15367. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  15368. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  15369. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  15370. program = createProgram();
  15371. attributes = {
  15372. position: gl.getAttribLocation ( program, 'position' ),
  15373. uv: gl.getAttribLocation ( program, 'uv' )
  15374. };
  15375. uniforms = {
  15376. uvOffset: gl.getUniformLocation( program, 'uvOffset' ),
  15377. uvScale: gl.getUniformLocation( program, 'uvScale' ),
  15378. rotation: gl.getUniformLocation( program, 'rotation' ),
  15379. scale: gl.getUniformLocation( program, 'scale' ),
  15380. color: gl.getUniformLocation( program, 'color' ),
  15381. map: gl.getUniformLocation( program, 'map' ),
  15382. opacity: gl.getUniformLocation( program, 'opacity' ),
  15383. modelViewMatrix: gl.getUniformLocation( program, 'modelViewMatrix' ),
  15384. projectionMatrix: gl.getUniformLocation( program, 'projectionMatrix' ),
  15385. fogType: gl.getUniformLocation( program, 'fogType' ),
  15386. fogDensity: gl.getUniformLocation( program, 'fogDensity' ),
  15387. fogNear: gl.getUniformLocation( program, 'fogNear' ),
  15388. fogFar: gl.getUniformLocation( program, 'fogFar' ),
  15389. fogColor: gl.getUniformLocation( program, 'fogColor' ),
  15390. alphaTest: gl.getUniformLocation( program, 'alphaTest' )
  15391. };
  15392. var canvas = document.createElement( 'canvas' );
  15393. canvas.width = 8;
  15394. canvas.height = 8;
  15395. var context = canvas.getContext( '2d' );
  15396. context.fillStyle = 'white';
  15397. context.fillRect( 0, 0, 8, 8 );
  15398. texture = new THREE.Texture( canvas );
  15399. texture.needsUpdate = true;
  15400. };
  15401. this.render = function ( scene, camera ) {
  15402. if ( sprites.length === 0 ) return;
  15403. // setup gl
  15404. if ( program === undefined ) {
  15405. init();
  15406. }
  15407. gl.useProgram( program );
  15408. gl.enableVertexAttribArray( attributes.position );
  15409. gl.enableVertexAttribArray( attributes.uv );
  15410. gl.disable( gl.CULL_FACE );
  15411. gl.enable( gl.BLEND );
  15412. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  15413. gl.vertexAttribPointer( attributes.position, 2, gl.FLOAT, false, 2 * 8, 0 );
  15414. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  15415. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  15416. gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  15417. gl.activeTexture( gl.TEXTURE0 );
  15418. gl.uniform1i( uniforms.map, 0 );
  15419. var oldFogType = 0;
  15420. var sceneFogType = 0;
  15421. var fog = scene.fog;
  15422. if ( fog ) {
  15423. gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  15424. if ( fog instanceof THREE.Fog ) {
  15425. gl.uniform1f( uniforms.fogNear, fog.near );
  15426. gl.uniform1f( uniforms.fogFar, fog.far );
  15427. gl.uniform1i( uniforms.fogType, 1 );
  15428. oldFogType = 1;
  15429. sceneFogType = 1;
  15430. } else if ( fog instanceof THREE.FogExp2 ) {
  15431. gl.uniform1f( uniforms.fogDensity, fog.density );
  15432. gl.uniform1i( uniforms.fogType, 2 );
  15433. oldFogType = 2;
  15434. sceneFogType = 2;
  15435. }
  15436. } else {
  15437. gl.uniform1i( uniforms.fogType, 0 );
  15438. oldFogType = 0;
  15439. sceneFogType = 0;
  15440. }
  15441. // update positions and sort
  15442. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  15443. var sprite = sprites[ i ];
  15444. sprite._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  15445. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  15446. }
  15447. sprites.sort( painterSortStable );
  15448. // render all sprites
  15449. var scale = [];
  15450. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  15451. var sprite = sprites[ i ];
  15452. var material = sprite.material;
  15453. gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  15454. gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  15455. sprite.matrixWorld.decompose( spritePosition, spriteRotation, spriteScale );
  15456. scale[ 0 ] = spriteScale.x;
  15457. scale[ 1 ] = spriteScale.y;
  15458. var fogType = 0;
  15459. if ( scene.fog && material.fog ) {
  15460. fogType = sceneFogType;
  15461. }
  15462. if ( oldFogType !== fogType ) {
  15463. gl.uniform1i( uniforms.fogType, fogType );
  15464. oldFogType = fogType;
  15465. }
  15466. if ( material.map !== null ) {
  15467. gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y );
  15468. gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y );
  15469. } else {
  15470. gl.uniform2f( uniforms.uvOffset, 0, 0 );
  15471. gl.uniform2f( uniforms.uvScale, 1, 1 );
  15472. }
  15473. gl.uniform1f( uniforms.opacity, material.opacity );
  15474. gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  15475. gl.uniform1f( uniforms.rotation, material.rotation );
  15476. gl.uniform2fv( uniforms.scale, scale );
  15477. renderer.state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  15478. renderer.state.setDepthTest( material.depthTest );
  15479. renderer.state.setDepthWrite( material.depthWrite );
  15480. if ( material.map && material.map.image && material.map.image.width ) {
  15481. renderer.setTexture( material.map, 0 );
  15482. } else {
  15483. renderer.setTexture( texture, 0 );
  15484. }
  15485. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  15486. }
  15487. // restore gl
  15488. gl.enable( gl.CULL_FACE );
  15489. renderer.resetGLState();
  15490. };
  15491. function createProgram () {
  15492. var program = gl.createProgram();
  15493. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  15494. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  15495. gl.shaderSource( vertexShader, [
  15496. 'precision ' + renderer.getPrecision() + ' float;',
  15497. 'uniform mat4 modelViewMatrix;',
  15498. 'uniform mat4 projectionMatrix;',
  15499. 'uniform float rotation;',
  15500. 'uniform vec2 scale;',
  15501. 'uniform vec2 uvOffset;',
  15502. 'uniform vec2 uvScale;',
  15503. 'attribute vec2 position;',
  15504. 'attribute vec2 uv;',
  15505. 'varying vec2 vUV;',
  15506. 'void main() {',
  15507. 'vUV = uvOffset + uv * uvScale;',
  15508. 'vec2 alignedPosition = position * scale;',
  15509. 'vec2 rotatedPosition;',
  15510. 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  15511. 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  15512. 'vec4 finalPosition;',
  15513. 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  15514. 'finalPosition.xy += rotatedPosition;',
  15515. 'finalPosition = projectionMatrix * finalPosition;',
  15516. 'gl_Position = finalPosition;',
  15517. '}'
  15518. ].join( '\n' ) );
  15519. gl.shaderSource( fragmentShader, [
  15520. 'precision ' + renderer.getPrecision() + ' float;',
  15521. 'uniform vec3 color;',
  15522. 'uniform sampler2D map;',
  15523. 'uniform float opacity;',
  15524. 'uniform int fogType;',
  15525. 'uniform vec3 fogColor;',
  15526. 'uniform float fogDensity;',
  15527. 'uniform float fogNear;',
  15528. 'uniform float fogFar;',
  15529. 'uniform float alphaTest;',
  15530. 'varying vec2 vUV;',
  15531. 'void main() {',
  15532. 'vec4 texture = texture2D( map, vUV );',
  15533. 'if ( texture.a < alphaTest ) discard;',
  15534. 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  15535. 'if ( fogType > 0 ) {',
  15536. 'float depth = gl_FragCoord.z / gl_FragCoord.w;',
  15537. 'float fogFactor = 0.0;',
  15538. 'if ( fogType == 1 ) {',
  15539. 'fogFactor = smoothstep( fogNear, fogFar, depth );',
  15540. '} else {',
  15541. 'const float LOG2 = 1.442695;',
  15542. 'float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );',
  15543. 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  15544. '}',
  15545. 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );',
  15546. '}',
  15547. '}'
  15548. ].join( '\n' ) );
  15549. gl.compileShader( vertexShader );
  15550. gl.compileShader( fragmentShader );
  15551. gl.attachShader( program, vertexShader );
  15552. gl.attachShader( program, fragmentShader );
  15553. gl.linkProgram( program );
  15554. return program;
  15555. };
  15556. function painterSortStable ( a, b ) {
  15557. if ( a.z !== b.z ) {
  15558. return b.z - a.z;
  15559. } else {
  15560. return b.id - a.id;
  15561. }
  15562. };
  15563. };
  15564. // File:src/extras/GeometryUtils.js
  15565. /**
  15566. * @author mrdoob / http://mrdoob.com/
  15567. */
  15568. THREE.GeometryUtils = {
  15569. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  15570. THREE.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  15571. var matrix;
  15572. if ( geometry2 instanceof THREE.Mesh ) {
  15573. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  15574. matrix = geometry2.matrix;
  15575. geometry2 = geometry2.geometry;
  15576. }
  15577. geometry1.merge( geometry2, matrix, materialIndexOffset );
  15578. },
  15579. center: function ( geometry ) {
  15580. THREE.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
  15581. return geometry.center();
  15582. }
  15583. };
  15584. // File:src/extras/ImageUtils.js
  15585. /**
  15586. * @author alteredq / http://alteredqualia.com/
  15587. * @author mrdoob / http://mrdoob.com/
  15588. * @author Daosheng Mu / https://github.com/DaoshengMu/
  15589. */
  15590. THREE.ImageUtils = {
  15591. crossOrigin: undefined,
  15592. loadTexture: function ( url, mapping, onLoad, onError ) {
  15593. var loader = new THREE.ImageLoader();
  15594. loader.crossOrigin = this.crossOrigin;
  15595. var texture = new THREE.Texture( undefined, mapping );
  15596. loader.load( url, function ( image ) {
  15597. texture.image = image;
  15598. texture.needsUpdate = true;
  15599. if ( onLoad ) onLoad( texture );
  15600. }, undefined, function ( event ) {
  15601. if ( onError ) onError( event );
  15602. } );
  15603. texture.sourceFile = url;
  15604. return texture;
  15605. },
  15606. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  15607. var images = [];
  15608. var loader = new THREE.ImageLoader();
  15609. loader.crossOrigin = this.crossOrigin;
  15610. var texture = new THREE.CubeTexture( images, mapping );
  15611. // no flipping needed for cube textures
  15612. texture.flipY = false;
  15613. var loaded = 0;
  15614. var loadTexture = function ( i ) {
  15615. loader.load( array[ i ], function ( image ) {
  15616. texture.images[ i ] = image;
  15617. loaded += 1;
  15618. if ( loaded === 6 ) {
  15619. texture.needsUpdate = true;
  15620. if ( onLoad ) onLoad( texture );
  15621. }
  15622. }, undefined, onError );
  15623. }
  15624. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15625. loadTexture( i );
  15626. }
  15627. return texture;
  15628. },
  15629. loadCompressedTexture: function () {
  15630. THREE.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' )
  15631. },
  15632. loadCompressedTextureCube: function () {
  15633. THREE.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' )
  15634. },
  15635. getNormalMap: function ( image, depth ) {
  15636. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  15637. var cross = function ( a, b ) {
  15638. 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 ] ];
  15639. }
  15640. var subtract = function ( a, b ) {
  15641. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  15642. }
  15643. var normalize = function ( a ) {
  15644. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  15645. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  15646. }
  15647. depth = depth | 1;
  15648. var width = image.width;
  15649. var height = image.height;
  15650. var canvas = document.createElement( 'canvas' );
  15651. canvas.width = width;
  15652. canvas.height = height;
  15653. var context = canvas.getContext( '2d' );
  15654. context.drawImage( image, 0, 0 );
  15655. var data = context.getImageData( 0, 0, width, height ).data;
  15656. var imageData = context.createImageData( width, height );
  15657. var output = imageData.data;
  15658. for ( var x = 0; x < width; x ++ ) {
  15659. for ( var y = 0; y < height; y ++ ) {
  15660. var ly = y - 1 < 0 ? 0 : y - 1;
  15661. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  15662. var lx = x - 1 < 0 ? 0 : x - 1;
  15663. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  15664. var points = [];
  15665. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  15666. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  15667. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  15668. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  15669. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  15670. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  15671. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  15672. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  15673. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  15674. var normals = [];
  15675. var num_points = points.length;
  15676. for ( var i = 0; i < num_points; i ++ ) {
  15677. var v1 = points[ i ];
  15678. var v2 = points[ ( i + 1 ) % num_points ];
  15679. v1 = subtract( v1, origin );
  15680. v2 = subtract( v2, origin );
  15681. normals.push( normalize( cross( v1, v2 ) ) );
  15682. }
  15683. var normal = [ 0, 0, 0 ];
  15684. for ( var i = 0; i < normals.length; i ++ ) {
  15685. normal[ 0 ] += normals[ i ][ 0 ];
  15686. normal[ 1 ] += normals[ i ][ 1 ];
  15687. normal[ 2 ] += normals[ i ][ 2 ];
  15688. }
  15689. normal[ 0 ] /= normals.length;
  15690. normal[ 1 ] /= normals.length;
  15691. normal[ 2 ] /= normals.length;
  15692. var idx = ( y * width + x ) * 4;
  15693. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  15694. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  15695. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  15696. output[ idx + 3 ] = 255;
  15697. }
  15698. }
  15699. context.putImageData( imageData, 0, 0 );
  15700. return canvas;
  15701. },
  15702. generateDataTexture: function ( width, height, color ) {
  15703. var size = width * height;
  15704. var data = new Uint8Array( 3 * size );
  15705. var r = Math.floor( color.r * 255 );
  15706. var g = Math.floor( color.g * 255 );
  15707. var b = Math.floor( color.b * 255 );
  15708. for ( var i = 0; i < size; i ++ ) {
  15709. data[ i * 3 ] = r;
  15710. data[ i * 3 + 1 ] = g;
  15711. data[ i * 3 + 2 ] = b;
  15712. }
  15713. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  15714. texture.needsUpdate = true;
  15715. return texture;
  15716. }
  15717. };
  15718. // File:src/extras/SceneUtils.js
  15719. /**
  15720. * @author alteredq / http://alteredqualia.com/
  15721. */
  15722. THREE.SceneUtils = {
  15723. createMultiMaterialObject: function ( geometry, materials ) {
  15724. var group = new THREE.Object3D();
  15725. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  15726. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  15727. }
  15728. return group;
  15729. },
  15730. detach: function ( child, parent, scene ) {
  15731. child.applyMatrix( parent.matrixWorld );
  15732. parent.remove( child );
  15733. scene.add( child );
  15734. },
  15735. attach: function ( child, scene, parent ) {
  15736. var matrixWorldInverse = new THREE.Matrix4();
  15737. matrixWorldInverse.getInverse( parent.matrixWorld );
  15738. child.applyMatrix( matrixWorldInverse );
  15739. scene.remove( child );
  15740. parent.add( child );
  15741. }
  15742. };
  15743. // File:src/extras/FontUtils.js
  15744. /**
  15745. * @author zz85 / http://www.lab4games.net/zz85/blog
  15746. * @author alteredq / http://alteredqualia.com/
  15747. *
  15748. * For Text operations in three.js (See TextGeometry)
  15749. *
  15750. * It uses techniques used in:
  15751. *
  15752. * typeface.js and canvastext
  15753. * For converting fonts and rendering with javascript
  15754. * http://typeface.neocracy.org
  15755. *
  15756. * Triangulation ported from AS3
  15757. * Simple Polygon Triangulation
  15758. * http://actionsnippet.com/?p=1462
  15759. *
  15760. * A Method to triangulate shapes with holes
  15761. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  15762. *
  15763. */
  15764. THREE.FontUtils = {
  15765. faces: {},
  15766. // Just for now. face[weight][style]
  15767. face: 'helvetiker',
  15768. weight: 'normal',
  15769. style: 'normal',
  15770. size: 150,
  15771. divisions: 10,
  15772. getFace: function () {
  15773. try {
  15774. return this.faces[ this.face ][ this.weight ][ this.style ];
  15775. } catch (e) {
  15776. throw "The font " + this.face + " with " + this.weight + " weight and " + this.style + " style is missing."
  15777. };
  15778. },
  15779. loadFace: function ( data ) {
  15780. var family = data.familyName.toLowerCase();
  15781. var ThreeFont = this;
  15782. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  15783. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  15784. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  15785. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  15786. return data;
  15787. },
  15788. drawText: function ( text ) {
  15789. // RenderText
  15790. var i,
  15791. face = this.getFace(),
  15792. scale = this.size / face.resolution,
  15793. offset = 0,
  15794. chars = String( text ).split( '' ),
  15795. length = chars.length;
  15796. var fontPaths = [];
  15797. for ( i = 0; i < length; i ++ ) {
  15798. var path = new THREE.Path();
  15799. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  15800. offset += ret.offset;
  15801. fontPaths.push( ret.path );
  15802. }
  15803. // get the width
  15804. var width = offset / 2;
  15805. //
  15806. // for ( p = 0; p < allPts.length; p++ ) {
  15807. //
  15808. // allPts[ p ].x -= width;
  15809. //
  15810. // }
  15811. //var extract = this.extractPoints( allPts, characterPts );
  15812. //extract.contour = allPts;
  15813. //extract.paths = fontPaths;
  15814. //extract.offset = width;
  15815. return { paths: fontPaths, offset: width };
  15816. },
  15817. extractGlyphPoints: function ( c, face, scale, offset, path ) {
  15818. var pts = [];
  15819. var i, i2, divisions,
  15820. outline, action, length,
  15821. scaleX, scaleY,
  15822. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  15823. laste,
  15824. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  15825. if ( ! glyph ) return;
  15826. if ( glyph.o ) {
  15827. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  15828. length = outline.length;
  15829. scaleX = scale;
  15830. scaleY = scale;
  15831. for ( i = 0; i < length; ) {
  15832. action = outline[ i ++ ];
  15833. //console.log( action );
  15834. switch ( action ) {
  15835. case 'm':
  15836. // Move To
  15837. x = outline[ i ++ ] * scaleX + offset;
  15838. y = outline[ i ++ ] * scaleY;
  15839. path.moveTo( x, y );
  15840. break;
  15841. case 'l':
  15842. // Line To
  15843. x = outline[ i ++ ] * scaleX + offset;
  15844. y = outline[ i ++ ] * scaleY;
  15845. path.lineTo( x, y );
  15846. break;
  15847. case 'q':
  15848. // QuadraticCurveTo
  15849. cpx = outline[ i ++ ] * scaleX + offset;
  15850. cpy = outline[ i ++ ] * scaleY;
  15851. cpx1 = outline[ i ++ ] * scaleX + offset;
  15852. cpy1 = outline[ i ++ ] * scaleY;
  15853. path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
  15854. laste = pts[ pts.length - 1 ];
  15855. if ( laste ) {
  15856. cpx0 = laste.x;
  15857. cpy0 = laste.y;
  15858. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  15859. var t = i2 / divisions;
  15860. THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  15861. THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  15862. }
  15863. }
  15864. break;
  15865. case 'b':
  15866. // Cubic Bezier Curve
  15867. cpx = outline[ i ++ ] * scaleX + offset;
  15868. cpy = outline[ i ++ ] * scaleY;
  15869. cpx1 = outline[ i ++ ] * scaleX + offset;
  15870. cpy1 = outline[ i ++ ] * scaleY;
  15871. cpx2 = outline[ i ++ ] * scaleX + offset;
  15872. cpy2 = outline[ i ++ ] * scaleY;
  15873. path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
  15874. laste = pts[ pts.length - 1 ];
  15875. if ( laste ) {
  15876. cpx0 = laste.x;
  15877. cpy0 = laste.y;
  15878. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  15879. var t = i2 / divisions;
  15880. THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  15881. THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  15882. }
  15883. }
  15884. break;
  15885. }
  15886. }
  15887. }
  15888. return { offset: glyph.ha * scale, path:path };
  15889. }
  15890. };
  15891. THREE.FontUtils.generateShapes = function ( text, parameters ) {
  15892. // Parameters
  15893. parameters = parameters || {};
  15894. var size = parameters.size !== undefined ? parameters.size : 100;
  15895. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments : 4;
  15896. var font = parameters.font !== undefined ? parameters.font : 'helvetiker';
  15897. var weight = parameters.weight !== undefined ? parameters.weight : 'normal';
  15898. var style = parameters.style !== undefined ? parameters.style : 'normal';
  15899. THREE.FontUtils.size = size;
  15900. THREE.FontUtils.divisions = curveSegments;
  15901. THREE.FontUtils.face = font;
  15902. THREE.FontUtils.weight = weight;
  15903. THREE.FontUtils.style = style;
  15904. // Get a Font data json object
  15905. var data = THREE.FontUtils.drawText( text );
  15906. var paths = data.paths;
  15907. var shapes = [];
  15908. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  15909. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  15910. }
  15911. return shapes;
  15912. };
  15913. /**
  15914. * This code is a quick port of code written in C++ which was submitted to
  15915. * flipcode.com by John W. Ratcliff // July 22, 2000
  15916. * See original code and more information here:
  15917. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  15918. *
  15919. * ported to actionscript by Zevan Rosser
  15920. * www.actionsnippet.com
  15921. *
  15922. * ported to javascript by Joshua Koo
  15923. * http://www.lab4games.net/zz85/blog
  15924. *
  15925. */
  15926. ( function ( namespace ) {
  15927. var EPSILON = 0.0000000001;
  15928. // takes in an contour array and returns
  15929. var process = function ( contour, indices ) {
  15930. var n = contour.length;
  15931. if ( n < 3 ) return null;
  15932. var result = [],
  15933. verts = [],
  15934. vertIndices = [];
  15935. /* we want a counter-clockwise polygon in verts */
  15936. var u, v, w;
  15937. if ( area( contour ) > 0.0 ) {
  15938. for ( v = 0; v < n; v ++ ) verts[ v ] = v;
  15939. } else {
  15940. for ( v = 0; v < n; v ++ ) verts[ v ] = ( n - 1 ) - v;
  15941. }
  15942. var nv = n;
  15943. /* remove nv - 2 vertices, creating 1 triangle every time */
  15944. var count = 2 * nv; /* error detection */
  15945. for ( v = nv - 1; nv > 2; ) {
  15946. /* if we loop, it is probably a non-simple polygon */
  15947. if ( ( count -- ) <= 0 ) {
  15948. //** Triangulate: ERROR - probable bad polygon!
  15949. //throw ( "Warning, unable to triangulate polygon!" );
  15950. //return null;
  15951. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  15952. THREE.warn( 'THREE.FontUtils: Warning, unable to triangulate polygon! in Triangulate.process()' );
  15953. if ( indices ) return vertIndices;
  15954. return result;
  15955. }
  15956. /* three consecutive vertices in current polygon, <u,v,w> */
  15957. u = v; if ( nv <= u ) u = 0; /* previous */
  15958. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  15959. w = v + 1; if ( nv <= w ) w = 0; /* next */
  15960. if ( snip( contour, u, v, w, nv, verts ) ) {
  15961. var a, b, c, s, t;
  15962. /* true names of the vertices */
  15963. a = verts[ u ];
  15964. b = verts[ v ];
  15965. c = verts[ w ];
  15966. /* output Triangle */
  15967. result.push( [ contour[ a ],
  15968. contour[ b ],
  15969. contour[ c ] ] );
  15970. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  15971. /* remove v from the remaining polygon */
  15972. for ( s = v, t = v + 1; t < nv; s ++, t ++ ) {
  15973. verts[ s ] = verts[ t ];
  15974. }
  15975. nv --;
  15976. /* reset error detection counter */
  15977. count = 2 * nv;
  15978. }
  15979. }
  15980. if ( indices ) return vertIndices;
  15981. return result;
  15982. };
  15983. // calculate area of the contour polygon
  15984. var area = function ( contour ) {
  15985. var n = contour.length;
  15986. var a = 0.0;
  15987. for ( var p = n - 1, q = 0; q < n; p = q ++ ) {
  15988. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  15989. }
  15990. return a * 0.5;
  15991. };
  15992. var snip = function ( contour, u, v, w, n, verts ) {
  15993. var p;
  15994. var ax, ay, bx, by;
  15995. var cx, cy, px, py;
  15996. ax = contour[ verts[ u ] ].x;
  15997. ay = contour[ verts[ u ] ].y;
  15998. bx = contour[ verts[ v ] ].x;
  15999. by = contour[ verts[ v ] ].y;
  16000. cx = contour[ verts[ w ] ].x;
  16001. cy = contour[ verts[ w ] ].y;
  16002. if ( EPSILON > ( ( ( bx - ax ) * ( cy - ay ) ) - ( ( by - ay ) * ( cx - ax ) ) ) ) return false;
  16003. var aX, aY, bX, bY, cX, cY;
  16004. var apx, apy, bpx, bpy, cpx, cpy;
  16005. var cCROSSap, bCROSScp, aCROSSbp;
  16006. aX = cx - bx; aY = cy - by;
  16007. bX = ax - cx; bY = ay - cy;
  16008. cX = bx - ax; cY = by - ay;
  16009. for ( p = 0; p < n; p ++ ) {
  16010. px = contour[ verts[ p ] ].x
  16011. py = contour[ verts[ p ] ].y
  16012. if ( ( ( px === ax ) && ( py === ay ) ) ||
  16013. ( ( px === bx ) && ( py === by ) ) ||
  16014. ( ( px === cx ) && ( py === cy ) ) ) continue;
  16015. apx = px - ax; apy = py - ay;
  16016. bpx = px - bx; bpy = py - by;
  16017. cpx = px - cx; cpy = py - cy;
  16018. // see if p is inside triangle abc
  16019. aCROSSbp = aX * bpy - aY * bpx;
  16020. cCROSSap = cX * apy - cY * apx;
  16021. bCROSScp = bX * cpy - bY * cpx;
  16022. if ( ( aCROSSbp >= - EPSILON ) && ( bCROSScp >= - EPSILON ) && ( cCROSSap >= - EPSILON ) ) return false;
  16023. }
  16024. return true;
  16025. };
  16026. namespace.Triangulate = process;
  16027. namespace.Triangulate.area = area;
  16028. return namespace;
  16029. } )( THREE.FontUtils );
  16030. // To use the typeface.js face files, hook up the API
  16031. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };
  16032. THREE.typeface_js = self._typeface_js;
  16033. // File:src/extras/audio/Audio.js
  16034. /**
  16035. * @author mrdoob / http://mrdoob.com/
  16036. */
  16037. THREE.Audio = function ( listener ) {
  16038. THREE.Object3D.call( this );
  16039. this.type = 'Audio';
  16040. this.context = listener.context;
  16041. this.source = this.context.createBufferSource();
  16042. this.gain = this.context.createGain();
  16043. this.gain.connect( this.context.destination );
  16044. this.panner = this.context.createPanner();
  16045. this.panner.connect( this.gain );
  16046. };
  16047. THREE.Audio.prototype = Object.create( THREE.Object3D.prototype );
  16048. THREE.Audio.prototype.constructor = THREE.Audio;
  16049. THREE.Audio.prototype.load = function ( file ) {
  16050. var scope = this;
  16051. var request = new XMLHttpRequest();
  16052. request.open( 'GET', file, true );
  16053. request.responseType = 'arraybuffer';
  16054. request.onload = function ( e ) {
  16055. scope.context.decodeAudioData( this.response, function ( buffer ) {
  16056. scope.source.buffer = buffer;
  16057. scope.source.connect( scope.panner );
  16058. scope.source.start( 0 );
  16059. } );
  16060. };
  16061. request.send();
  16062. return this;
  16063. };
  16064. THREE.Audio.prototype.setLoop = function ( value ) {
  16065. this.source.loop = value;
  16066. };
  16067. THREE.Audio.prototype.setRefDistance = function ( value ) {
  16068. this.panner.refDistance = value;
  16069. };
  16070. THREE.Audio.prototype.setRolloffFactor = function ( value ) {
  16071. this.panner.rolloffFactor = value;
  16072. };
  16073. THREE.Audio.prototype.updateMatrixWorld = ( function () {
  16074. var position = new THREE.Vector3();
  16075. return function ( force ) {
  16076. THREE.Object3D.prototype.updateMatrixWorld.call( this, force );
  16077. position.setFromMatrixPosition( this.matrixWorld );
  16078. this.panner.setPosition( position.x, position.y, position.z );
  16079. };
  16080. } )();
  16081. // File:src/extras/audio/AudioListener.js
  16082. /**
  16083. * @author mrdoob / http://mrdoob.com/
  16084. */
  16085. THREE.AudioListener = function () {
  16086. THREE.Object3D.call( this );
  16087. this.type = 'AudioListener';
  16088. this.context = new ( window.AudioContext || window.webkitAudioContext )();
  16089. };
  16090. THREE.AudioListener.prototype = Object.create( THREE.Object3D.prototype );
  16091. THREE.AudioListener.prototype.constructor = THREE.AudioListener;
  16092. THREE.AudioListener.prototype.updateMatrixWorld = ( function () {
  16093. var position = new THREE.Vector3();
  16094. var quaternion = new THREE.Quaternion();
  16095. var scale = new THREE.Vector3();
  16096. var orientation = new THREE.Vector3();
  16097. var velocity = new THREE.Vector3();
  16098. var positionPrev = new THREE.Vector3();
  16099. return function ( force ) {
  16100. THREE.Object3D.prototype.updateMatrixWorld.call( this, force );
  16101. var listener = this.context.listener;
  16102. var up = this.up;
  16103. this.matrixWorld.decompose( position, quaternion, scale );
  16104. orientation.set( 0, 0, -1 ).applyQuaternion( quaternion );
  16105. velocity.subVectors( position, positionPrev );
  16106. listener.setPosition( position.x, position.y, position.z );
  16107. listener.setOrientation( orientation.x, orientation.y, orientation.z, up.x, up.y, up.z );
  16108. listener.setVelocity( velocity.x, velocity.y, velocity.z );
  16109. positionPrev.copy( position );
  16110. };
  16111. } )();
  16112. // File:src/extras/core/Curve.js
  16113. /**
  16114. * @author zz85 / http://www.lab4games.net/zz85/blog
  16115. * Extensible curve object
  16116. *
  16117. * Some common of Curve methods
  16118. * .getPoint(t), getTangent(t)
  16119. * .getPointAt(u), getTagentAt(u)
  16120. * .getPoints(), .getSpacedPoints()
  16121. * .getLength()
  16122. * .updateArcLengths()
  16123. *
  16124. * This following classes subclasses THREE.Curve:
  16125. *
  16126. * -- 2d classes --
  16127. * THREE.LineCurve
  16128. * THREE.QuadraticBezierCurve
  16129. * THREE.CubicBezierCurve
  16130. * THREE.SplineCurve
  16131. * THREE.ArcCurve
  16132. * THREE.EllipseCurve
  16133. *
  16134. * -- 3d classes --
  16135. * THREE.LineCurve3
  16136. * THREE.QuadraticBezierCurve3
  16137. * THREE.CubicBezierCurve3
  16138. * THREE.SplineCurve3
  16139. * THREE.ClosedSplineCurve3
  16140. *
  16141. * A series of curves can be represented as a THREE.CurvePath
  16142. *
  16143. **/
  16144. /**************************************************************
  16145. * Abstract Curve base class
  16146. **************************************************************/
  16147. THREE.Curve = function () {
  16148. };
  16149. // Virtual base class method to overwrite and implement in subclasses
  16150. // - t [0 .. 1]
  16151. THREE.Curve.prototype.getPoint = function ( t ) {
  16152. THREE.warn( "THREE.Curve: Warning, getPoint() not implemented!" );
  16153. return null;
  16154. };
  16155. // Get point at relative position in curve according to arc length
  16156. // - u [0 .. 1]
  16157. THREE.Curve.prototype.getPointAt = function ( u ) {
  16158. var t = this.getUtoTmapping( u );
  16159. return this.getPoint( t );
  16160. };
  16161. // Get sequence of points using getPoint( t )
  16162. THREE.Curve.prototype.getPoints = function ( divisions ) {
  16163. if ( ! divisions ) divisions = 5;
  16164. var d, pts = [];
  16165. for ( d = 0; d <= divisions; d ++ ) {
  16166. pts.push( this.getPoint( d / divisions ) );
  16167. }
  16168. return pts;
  16169. };
  16170. // Get sequence of points using getPointAt( u )
  16171. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  16172. if ( ! divisions ) divisions = 5;
  16173. var d, pts = [];
  16174. for ( d = 0; d <= divisions; d ++ ) {
  16175. pts.push( this.getPointAt( d / divisions ) );
  16176. }
  16177. return pts;
  16178. };
  16179. // Get total curve arc length
  16180. THREE.Curve.prototype.getLength = function () {
  16181. var lengths = this.getLengths();
  16182. return lengths[ lengths.length - 1 ];
  16183. };
  16184. // Get list of cumulative segment lengths
  16185. THREE.Curve.prototype.getLengths = function ( divisions ) {
  16186. if ( ! divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions) : 200;
  16187. if ( this.cacheArcLengths
  16188. && ( this.cacheArcLengths.length == divisions + 1 )
  16189. && ! this.needsUpdate) {
  16190. //console.log( "cached", this.cacheArcLengths );
  16191. return this.cacheArcLengths;
  16192. }
  16193. this.needsUpdate = false;
  16194. var cache = [];
  16195. var current, last = this.getPoint( 0 );
  16196. var p, sum = 0;
  16197. cache.push( 0 );
  16198. for ( p = 1; p <= divisions; p ++ ) {
  16199. current = this.getPoint ( p / divisions );
  16200. sum += current.distanceTo( last );
  16201. cache.push( sum );
  16202. last = current;
  16203. }
  16204. this.cacheArcLengths = cache;
  16205. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  16206. };
  16207. THREE.Curve.prototype.updateArcLengths = function() {
  16208. this.needsUpdate = true;
  16209. this.getLengths();
  16210. };
  16211. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  16212. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  16213. var arcLengths = this.getLengths();
  16214. var i = 0, il = arcLengths.length;
  16215. var targetArcLength; // The targeted u distance value to get
  16216. if ( distance ) {
  16217. targetArcLength = distance;
  16218. } else {
  16219. targetArcLength = u * arcLengths[ il - 1 ];
  16220. }
  16221. //var time = Date.now();
  16222. // binary search for the index with largest value smaller than target u distance
  16223. var low = 0, high = il - 1, comparison;
  16224. while ( low <= high ) {
  16225. 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
  16226. comparison = arcLengths[ i ] - targetArcLength;
  16227. if ( comparison < 0 ) {
  16228. low = i + 1;
  16229. } else if ( comparison > 0 ) {
  16230. high = i - 1;
  16231. } else {
  16232. high = i;
  16233. break;
  16234. // DONE
  16235. }
  16236. }
  16237. i = high;
  16238. //console.log('b' , i, low, high, Date.now()- time);
  16239. if ( arcLengths[ i ] == targetArcLength ) {
  16240. var t = i / ( il - 1 );
  16241. return t;
  16242. }
  16243. // we could get finer grain at lengths, or use simple interpolatation between two points
  16244. var lengthBefore = arcLengths[ i ];
  16245. var lengthAfter = arcLengths[ i + 1 ];
  16246. var segmentLength = lengthAfter - lengthBefore;
  16247. // determine where we are between the 'before' and 'after' points
  16248. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  16249. // add that fractional amount to t
  16250. var t = ( i + segmentFraction ) / ( il - 1 );
  16251. return t;
  16252. };
  16253. // Returns a unit vector tangent at t
  16254. // In case any sub curve does not implement its tangent derivation,
  16255. // 2 points a small delta apart will be used to find its gradient
  16256. // which seems to give a reasonable approximation
  16257. THREE.Curve.prototype.getTangent = function( t ) {
  16258. var delta = 0.0001;
  16259. var t1 = t - delta;
  16260. var t2 = t + delta;
  16261. // Capping in case of danger
  16262. if ( t1 < 0 ) t1 = 0;
  16263. if ( t2 > 1 ) t2 = 1;
  16264. var pt1 = this.getPoint( t1 );
  16265. var pt2 = this.getPoint( t2 );
  16266. var vec = pt2.clone().sub(pt1);
  16267. return vec.normalize();
  16268. };
  16269. THREE.Curve.prototype.getTangentAt = function ( u ) {
  16270. var t = this.getUtoTmapping( u );
  16271. return this.getTangent( t );
  16272. };
  16273. /**************************************************************
  16274. * Utils
  16275. **************************************************************/
  16276. THREE.Curve.Utils = {
  16277. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  16278. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  16279. },
  16280. // Puay Bing, thanks for helping with this derivative!
  16281. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  16282. return - 3 * p0 * (1 - t) * (1 - t) +
  16283. 3 * p1 * (1 - t) * (1 - t) - 6 * t * p1 * (1 - t) +
  16284. 6 * t * p2 * (1 - t) - 3 * t * t * p2 +
  16285. 3 * t * t * p3;
  16286. },
  16287. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  16288. // To check if my formulas are correct
  16289. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  16290. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  16291. var h01 = - 6 * t * t + 6 * t; // − 2t3 + 3t2
  16292. var h11 = 3 * t * t - 2 * t; // t3 − t2
  16293. return h00 + h10 + h01 + h11;
  16294. },
  16295. // Catmull-Rom
  16296. interpolate: function( p0, p1, p2, p3, t ) {
  16297. var v0 = ( p2 - p0 ) * 0.5;
  16298. var v1 = ( p3 - p1 ) * 0.5;
  16299. var t2 = t * t;
  16300. var t3 = t * t2;
  16301. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  16302. }
  16303. };
  16304. // TODO: Transformation for Curves?
  16305. /**************************************************************
  16306. * 3D Curves
  16307. **************************************************************/
  16308. // A Factory method for creating new curve subclasses
  16309. THREE.Curve.create = function ( constructor, getPointFunc ) {
  16310. constructor.prototype = Object.create( THREE.Curve.prototype );
  16311. constructor.prototype.constructor = constructor;
  16312. constructor.prototype.getPoint = getPointFunc;
  16313. return constructor;
  16314. };
  16315. // File:src/extras/core/CurvePath.js
  16316. /**
  16317. * @author zz85 / http://www.lab4games.net/zz85/blog
  16318. *
  16319. **/
  16320. /**************************************************************
  16321. * Curved Path - a curve path is simply a array of connected
  16322. * curves, but retains the api of a curve
  16323. **************************************************************/
  16324. THREE.CurvePath = function () {
  16325. this.curves = [];
  16326. this.bends = [];
  16327. this.autoClose = false; // Automatically closes the path
  16328. };
  16329. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  16330. THREE.CurvePath.prototype.constructor = THREE.CurvePath;
  16331. THREE.CurvePath.prototype.add = function ( curve ) {
  16332. this.curves.push( curve );
  16333. };
  16334. THREE.CurvePath.prototype.checkConnection = function() {
  16335. // TODO
  16336. // If the ending of curve is not connected to the starting
  16337. // or the next curve, then, this is not a real path
  16338. };
  16339. THREE.CurvePath.prototype.closePath = function() {
  16340. // TODO Test
  16341. // and verify for vector3 (needs to implement equals)
  16342. // Add a line curve if start and end of lines are not connected
  16343. var startPoint = this.curves[0].getPoint(0);
  16344. var endPoint = this.curves[this.curves.length - 1].getPoint(1);
  16345. if (! startPoint.equals(endPoint)) {
  16346. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  16347. }
  16348. };
  16349. // To get accurate point with reference to
  16350. // entire path distance at time t,
  16351. // following has to be done:
  16352. // 1. Length of each sub path have to be known
  16353. // 2. Locate and identify type of curve
  16354. // 3. Get t for the curve
  16355. // 4. Return curve.getPointAt(t')
  16356. THREE.CurvePath.prototype.getPoint = function( t ) {
  16357. var d = t * this.getLength();
  16358. var curveLengths = this.getCurveLengths();
  16359. var i = 0, diff, curve;
  16360. // To think about boundaries points.
  16361. while ( i < curveLengths.length ) {
  16362. if ( curveLengths[ i ] >= d ) {
  16363. diff = curveLengths[ i ] - d;
  16364. curve = this.curves[ i ];
  16365. var u = 1 - diff / curve.getLength();
  16366. return curve.getPointAt( u );
  16367. }
  16368. i ++;
  16369. }
  16370. return null;
  16371. // loop where sum != 0, sum > d , sum+1 <d
  16372. };
  16373. /*
  16374. THREE.CurvePath.prototype.getTangent = function( t ) {
  16375. };*/
  16376. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  16377. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  16378. // getPoint() depends on getLength
  16379. THREE.CurvePath.prototype.getLength = function() {
  16380. var lens = this.getCurveLengths();
  16381. return lens[ lens.length - 1 ];
  16382. };
  16383. // Compute lengths and cache them
  16384. // We cannot overwrite getLengths() because UtoT mapping uses it.
  16385. THREE.CurvePath.prototype.getCurveLengths = function() {
  16386. // We use cache values if curves and cache array are same length
  16387. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  16388. return this.cacheLengths;
  16389. };
  16390. // Get length of subsurve
  16391. // Push sums into cached array
  16392. var lengths = [], sums = 0;
  16393. var i, il = this.curves.length;
  16394. for ( i = 0; i < il; i ++ ) {
  16395. sums += this.curves[ i ].getLength();
  16396. lengths.push( sums );
  16397. }
  16398. this.cacheLengths = lengths;
  16399. return lengths;
  16400. };
  16401. // Returns min and max coordinates
  16402. THREE.CurvePath.prototype.getBoundingBox = function () {
  16403. var points = this.getPoints();
  16404. var maxX, maxY, maxZ;
  16405. var minX, minY, minZ;
  16406. maxX = maxY = Number.NEGATIVE_INFINITY;
  16407. minX = minY = Number.POSITIVE_INFINITY;
  16408. var p, i, il, sum;
  16409. var v3 = points[0] instanceof THREE.Vector3;
  16410. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  16411. for ( i = 0, il = points.length; i < il; i ++ ) {
  16412. p = points[ i ];
  16413. if ( p.x > maxX ) maxX = p.x;
  16414. else if ( p.x < minX ) minX = p.x;
  16415. if ( p.y > maxY ) maxY = p.y;
  16416. else if ( p.y < minY ) minY = p.y;
  16417. if ( v3 ) {
  16418. if ( p.z > maxZ ) maxZ = p.z;
  16419. else if ( p.z < minZ ) minZ = p.z;
  16420. }
  16421. sum.add( p );
  16422. }
  16423. var ret = {
  16424. minX: minX,
  16425. minY: minY,
  16426. maxX: maxX,
  16427. maxY: maxY
  16428. };
  16429. if ( v3 ) {
  16430. ret.maxZ = maxZ;
  16431. ret.minZ = minZ;
  16432. }
  16433. return ret;
  16434. };
  16435. /**************************************************************
  16436. * Create Geometries Helpers
  16437. **************************************************************/
  16438. /// Generate geometry from path points (for Line or Points objects)
  16439. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  16440. var pts = this.getPoints( divisions, true );
  16441. return this.createGeometry( pts );
  16442. };
  16443. // Generate geometry from equidistance sampling along the path
  16444. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  16445. var pts = this.getSpacedPoints( divisions, true );
  16446. return this.createGeometry( pts );
  16447. };
  16448. THREE.CurvePath.prototype.createGeometry = function( points ) {
  16449. var geometry = new THREE.Geometry();
  16450. for ( var i = 0; i < points.length; i ++ ) {
  16451. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  16452. }
  16453. return geometry;
  16454. };
  16455. /**************************************************************
  16456. * Bend / Wrap Helper Methods
  16457. **************************************************************/
  16458. // Wrap path / Bend modifiers?
  16459. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  16460. this.bends.push( bendpath );
  16461. };
  16462. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  16463. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  16464. var i, il;
  16465. if ( ! bends ) {
  16466. bends = this.bends;
  16467. }
  16468. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16469. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16470. }
  16471. return oldPts;
  16472. };
  16473. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  16474. var oldPts = this.getSpacedPoints( segments );
  16475. var i, il;
  16476. if ( ! bends ) {
  16477. bends = this.bends;
  16478. }
  16479. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16480. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16481. }
  16482. return oldPts;
  16483. };
  16484. // This returns getPoints() bend/wrapped around the contour of a path.
  16485. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  16486. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  16487. var bounds = this.getBoundingBox();
  16488. var i, il, p, oldX, oldY, xNorm;
  16489. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  16490. p = oldPts[ i ];
  16491. oldX = p.x;
  16492. oldY = p.y;
  16493. xNorm = oldX / bounds.maxX;
  16494. // If using actual distance, for length > path, requires line extrusions
  16495. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  16496. xNorm = path.getUtoTmapping( xNorm, oldX );
  16497. // check for out of bounds?
  16498. var pathPt = path.getPoint( xNorm );
  16499. var normal = path.getTangent( xNorm );
  16500. normal.set( - normal.y, normal.x ).multiplyScalar( oldY );
  16501. p.x = pathPt.x + normal.x;
  16502. p.y = pathPt.y + normal.y;
  16503. }
  16504. return oldPts;
  16505. };
  16506. // File:src/extras/core/Gyroscope.js
  16507. /**
  16508. * @author alteredq / http://alteredqualia.com/
  16509. */
  16510. THREE.Gyroscope = function () {
  16511. THREE.Object3D.call( this );
  16512. };
  16513. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  16514. THREE.Gyroscope.prototype.constructor = THREE.Gyroscope;
  16515. THREE.Gyroscope.prototype.updateMatrixWorld = ( function () {
  16516. var translationObject = new THREE.Vector3();
  16517. var quaternionObject = new THREE.Quaternion();
  16518. var scaleObject = new THREE.Vector3();
  16519. var translationWorld = new THREE.Vector3();
  16520. var quaternionWorld = new THREE.Quaternion();
  16521. var scaleWorld = new THREE.Vector3();
  16522. return function ( force ) {
  16523. this.matrixAutoUpdate && this.updateMatrix();
  16524. // update matrixWorld
  16525. if ( this.matrixWorldNeedsUpdate || force ) {
  16526. if ( this.parent ) {
  16527. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  16528. this.matrixWorld.decompose( translationWorld, quaternionWorld, scaleWorld );
  16529. this.matrix.decompose( translationObject, quaternionObject, scaleObject );
  16530. this.matrixWorld.compose( translationWorld, quaternionObject, scaleWorld );
  16531. } else {
  16532. this.matrixWorld.copy( this.matrix );
  16533. }
  16534. this.matrixWorldNeedsUpdate = false;
  16535. force = true;
  16536. }
  16537. // update children
  16538. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  16539. this.children[ i ].updateMatrixWorld( force );
  16540. }
  16541. };
  16542. }() );
  16543. // File:src/extras/core/Path.js
  16544. /**
  16545. * @author zz85 / http://www.lab4games.net/zz85/blog
  16546. * Creates free form 2d path using series of points, lines or curves.
  16547. *
  16548. **/
  16549. THREE.Path = function ( points ) {
  16550. THREE.CurvePath.call(this);
  16551. this.actions = [];
  16552. if ( points ) {
  16553. this.fromPoints( points );
  16554. }
  16555. };
  16556. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  16557. THREE.Path.prototype.constructor = THREE.Path;
  16558. THREE.PathActions = {
  16559. MOVE_TO: 'moveTo',
  16560. LINE_TO: 'lineTo',
  16561. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  16562. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  16563. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  16564. ARC: 'arc', // Circle
  16565. ELLIPSE: 'ellipse'
  16566. };
  16567. // TODO Clean up PATH API
  16568. // Create path using straight lines to connect all points
  16569. // - vectors: array of Vector2
  16570. THREE.Path.prototype.fromPoints = function ( vectors ) {
  16571. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  16572. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  16573. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  16574. };
  16575. };
  16576. // startPath() endPath()?
  16577. THREE.Path.prototype.moveTo = function ( x, y ) {
  16578. var args = Array.prototype.slice.call( arguments );
  16579. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  16580. };
  16581. THREE.Path.prototype.lineTo = function ( x, y ) {
  16582. var args = Array.prototype.slice.call( arguments );
  16583. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16584. var x0 = lastargs[ lastargs.length - 2 ];
  16585. var y0 = lastargs[ lastargs.length - 1 ];
  16586. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  16587. this.curves.push( curve );
  16588. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  16589. };
  16590. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  16591. var args = Array.prototype.slice.call( arguments );
  16592. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16593. var x0 = lastargs[ lastargs.length - 2 ];
  16594. var y0 = lastargs[ lastargs.length - 1 ];
  16595. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  16596. new THREE.Vector2( aCPx, aCPy ),
  16597. new THREE.Vector2( aX, aY ) );
  16598. this.curves.push( curve );
  16599. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  16600. };
  16601. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  16602. aCP2x, aCP2y,
  16603. aX, aY ) {
  16604. var args = Array.prototype.slice.call( arguments );
  16605. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16606. var x0 = lastargs[ lastargs.length - 2 ];
  16607. var y0 = lastargs[ lastargs.length - 1 ];
  16608. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  16609. new THREE.Vector2( aCP1x, aCP1y ),
  16610. new THREE.Vector2( aCP2x, aCP2y ),
  16611. new THREE.Vector2( aX, aY ) );
  16612. this.curves.push( curve );
  16613. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  16614. };
  16615. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  16616. var args = Array.prototype.slice.call( arguments );
  16617. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16618. var x0 = lastargs[ lastargs.length - 2 ];
  16619. var y0 = lastargs[ lastargs.length - 1 ];
  16620. //---
  16621. var npts = [ new THREE.Vector2( x0, y0 ) ];
  16622. Array.prototype.push.apply( npts, pts );
  16623. var curve = new THREE.SplineCurve( npts );
  16624. this.curves.push( curve );
  16625. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  16626. };
  16627. // FUTURE: Change the API or follow canvas API?
  16628. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  16629. aStartAngle, aEndAngle, aClockwise ) {
  16630. var lastargs = this.actions[ this.actions.length - 1].args;
  16631. var x0 = lastargs[ lastargs.length - 2 ];
  16632. var y0 = lastargs[ lastargs.length - 1 ];
  16633. this.absarc(aX + x0, aY + y0, aRadius,
  16634. aStartAngle, aEndAngle, aClockwise );
  16635. };
  16636. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  16637. aStartAngle, aEndAngle, aClockwise ) {
  16638. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  16639. };
  16640. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  16641. aStartAngle, aEndAngle, aClockwise ) {
  16642. var lastargs = this.actions[ this.actions.length - 1].args;
  16643. var x0 = lastargs[ lastargs.length - 2 ];
  16644. var y0 = lastargs[ lastargs.length - 1 ];
  16645. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  16646. aStartAngle, aEndAngle, aClockwise );
  16647. };
  16648. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  16649. aStartAngle, aEndAngle, aClockwise ) {
  16650. var args = Array.prototype.slice.call( arguments );
  16651. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  16652. aStartAngle, aEndAngle, aClockwise );
  16653. this.curves.push( curve );
  16654. var lastPoint = curve.getPoint(1);
  16655. args.push(lastPoint.x);
  16656. args.push(lastPoint.y);
  16657. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  16658. };
  16659. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  16660. if ( ! divisions ) divisions = 40;
  16661. var points = [];
  16662. for ( var i = 0; i < divisions; i ++ ) {
  16663. points.push( this.getPoint( i / divisions ) );
  16664. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  16665. }
  16666. // if ( closedPath ) {
  16667. //
  16668. // points.push( points[ 0 ] );
  16669. //
  16670. // }
  16671. return points;
  16672. };
  16673. /* Return an array of vectors based on contour of the path */
  16674. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  16675. if (this.useSpacedPoints) {
  16676. console.log('tata');
  16677. return this.getSpacedPoints( divisions, closedPath );
  16678. }
  16679. divisions = divisions || 12;
  16680. var points = [];
  16681. var i, il, item, action, args;
  16682. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  16683. laste, j,
  16684. t, tx, ty;
  16685. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  16686. item = this.actions[ i ];
  16687. action = item.action;
  16688. args = item.args;
  16689. switch ( action ) {
  16690. case THREE.PathActions.MOVE_TO:
  16691. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  16692. break;
  16693. case THREE.PathActions.LINE_TO:
  16694. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  16695. break;
  16696. case THREE.PathActions.QUADRATIC_CURVE_TO:
  16697. cpx = args[ 2 ];
  16698. cpy = args[ 3 ];
  16699. cpx1 = args[ 0 ];
  16700. cpy1 = args[ 1 ];
  16701. if ( points.length > 0 ) {
  16702. laste = points[ points.length - 1 ];
  16703. cpx0 = laste.x;
  16704. cpy0 = laste.y;
  16705. } else {
  16706. laste = this.actions[ i - 1 ].args;
  16707. cpx0 = laste[ laste.length - 2 ];
  16708. cpy0 = laste[ laste.length - 1 ];
  16709. }
  16710. for ( j = 1; j <= divisions; j ++ ) {
  16711. t = j / divisions;
  16712. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16713. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16714. points.push( new THREE.Vector2( tx, ty ) );
  16715. }
  16716. break;
  16717. case THREE.PathActions.BEZIER_CURVE_TO:
  16718. cpx = args[ 4 ];
  16719. cpy = args[ 5 ];
  16720. cpx1 = args[ 0 ];
  16721. cpy1 = args[ 1 ];
  16722. cpx2 = args[ 2 ];
  16723. cpy2 = args[ 3 ];
  16724. if ( points.length > 0 ) {
  16725. laste = points[ points.length - 1 ];
  16726. cpx0 = laste.x;
  16727. cpy0 = laste.y;
  16728. } else {
  16729. laste = this.actions[ i - 1 ].args;
  16730. cpx0 = laste[ laste.length - 2 ];
  16731. cpy0 = laste[ laste.length - 1 ];
  16732. }
  16733. for ( j = 1; j <= divisions; j ++ ) {
  16734. t = j / divisions;
  16735. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16736. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16737. points.push( new THREE.Vector2( tx, ty ) );
  16738. }
  16739. break;
  16740. case THREE.PathActions.CSPLINE_THRU:
  16741. laste = this.actions[ i - 1 ].args;
  16742. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  16743. var spts = [ last ];
  16744. var n = divisions * args[ 0 ].length;
  16745. spts = spts.concat( args[ 0 ] );
  16746. var spline = new THREE.SplineCurve( spts );
  16747. for ( j = 1; j <= n; j ++ ) {
  16748. points.push( spline.getPointAt( j / n ) ) ;
  16749. }
  16750. break;
  16751. case THREE.PathActions.ARC:
  16752. var aX = args[ 0 ], aY = args[ 1 ],
  16753. aRadius = args[ 2 ],
  16754. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  16755. aClockwise = !! args[ 5 ];
  16756. var deltaAngle = aEndAngle - aStartAngle;
  16757. var angle;
  16758. var tdivisions = divisions * 2;
  16759. for ( j = 1; j <= tdivisions; j ++ ) {
  16760. t = j / tdivisions;
  16761. if ( ! aClockwise ) {
  16762. t = 1 - t;
  16763. }
  16764. angle = aStartAngle + t * deltaAngle;
  16765. tx = aX + aRadius * Math.cos( angle );
  16766. ty = aY + aRadius * Math.sin( angle );
  16767. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  16768. points.push( new THREE.Vector2( tx, ty ) );
  16769. }
  16770. //console.log(points);
  16771. break;
  16772. case THREE.PathActions.ELLIPSE:
  16773. var aX = args[ 0 ], aY = args[ 1 ],
  16774. xRadius = args[ 2 ],
  16775. yRadius = args[ 3 ],
  16776. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  16777. aClockwise = !! args[ 6 ];
  16778. var deltaAngle = aEndAngle - aStartAngle;
  16779. var angle;
  16780. var tdivisions = divisions * 2;
  16781. for ( j = 1; j <= tdivisions; j ++ ) {
  16782. t = j / tdivisions;
  16783. if ( ! aClockwise ) {
  16784. t = 1 - t;
  16785. }
  16786. angle = aStartAngle + t * deltaAngle;
  16787. tx = aX + xRadius * Math.cos( angle );
  16788. ty = aY + yRadius * Math.sin( angle );
  16789. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  16790. points.push( new THREE.Vector2( tx, ty ) );
  16791. }
  16792. //console.log(points);
  16793. break;
  16794. } // end switch
  16795. }
  16796. // Normalize to remove the closing point by default.
  16797. var lastPoint = points[ points.length - 1];
  16798. var EPSILON = 0.0000000001;
  16799. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  16800. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  16801. points.splice( points.length - 1, 1);
  16802. if ( closedPath ) {
  16803. points.push( points[ 0 ] );
  16804. }
  16805. return points;
  16806. };
  16807. //
  16808. // Breaks path into shapes
  16809. //
  16810. // Assumptions (if parameter isCCW==true the opposite holds):
  16811. // - solid shapes are defined clockwise (CW)
  16812. // - holes are defined counterclockwise (CCW)
  16813. //
  16814. // If parameter noHoles==true:
  16815. // - all subPaths are regarded as solid shapes
  16816. // - definition order CW/CCW has no relevance
  16817. //
  16818. THREE.Path.prototype.toShapes = function( isCCW, noHoles ) {
  16819. function extractSubpaths( inActions ) {
  16820. var i, il, item, action, args;
  16821. var subPaths = [], lastPath = new THREE.Path();
  16822. for ( i = 0, il = inActions.length; i < il; i ++ ) {
  16823. item = inActions[ i ];
  16824. args = item.args;
  16825. action = item.action;
  16826. if ( action == THREE.PathActions.MOVE_TO ) {
  16827. if ( lastPath.actions.length != 0 ) {
  16828. subPaths.push( lastPath );
  16829. lastPath = new THREE.Path();
  16830. }
  16831. }
  16832. lastPath[ action ].apply( lastPath, args );
  16833. }
  16834. if ( lastPath.actions.length != 0 ) {
  16835. subPaths.push( lastPath );
  16836. }
  16837. // console.log(subPaths);
  16838. return subPaths;
  16839. }
  16840. function toShapesNoHoles( inSubpaths ) {
  16841. var shapes = [];
  16842. for ( var i = 0, il = inSubpaths.length; i < il; i ++ ) {
  16843. var tmpPath = inSubpaths[ i ];
  16844. var tmpShape = new THREE.Shape();
  16845. tmpShape.actions = tmpPath.actions;
  16846. tmpShape.curves = tmpPath.curves;
  16847. shapes.push( tmpShape );
  16848. }
  16849. //console.log("shape", shapes);
  16850. return shapes;
  16851. };
  16852. function isPointInsidePolygon( inPt, inPolygon ) {
  16853. var EPSILON = 0.0000000001;
  16854. var polyLen = inPolygon.length;
  16855. // inPt on polygon contour => immediate success or
  16856. // toggling of inside/outside at every single! intersection point of an edge
  16857. // with the horizontal line through inPt, left of inPt
  16858. // not counting lowerY endpoints of edges and whole edges on that line
  16859. var inside = false;
  16860. for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  16861. var edgeLowPt = inPolygon[ p ];
  16862. var edgeHighPt = inPolygon[ q ];
  16863. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  16864. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  16865. if ( Math.abs(edgeDy) > EPSILON ) { // not parallel
  16866. if ( edgeDy < 0 ) {
  16867. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  16868. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  16869. }
  16870. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  16871. if ( inPt.y == edgeLowPt.y ) {
  16872. if ( inPt.x == edgeLowPt.x ) return true; // inPt is on contour ?
  16873. // continue; // no intersection or edgeLowPt => doesn't count !!!
  16874. } else {
  16875. var perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  16876. if ( perpEdge == 0 ) return true; // inPt is on contour ?
  16877. if ( perpEdge < 0 ) continue;
  16878. inside = ! inside; // true intersection left of inPt
  16879. }
  16880. } else { // parallel or colinear
  16881. if ( inPt.y != edgeLowPt.y ) continue; // parallel
  16882. // egde lies on the same horizontal line as inPt
  16883. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  16884. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  16885. // continue;
  16886. }
  16887. }
  16888. return inside;
  16889. }
  16890. var subPaths = extractSubpaths( this.actions );
  16891. if ( subPaths.length == 0 ) return [];
  16892. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  16893. var solid, tmpPath, tmpShape, shapes = [];
  16894. if ( subPaths.length == 1) {
  16895. tmpPath = subPaths[0];
  16896. tmpShape = new THREE.Shape();
  16897. tmpShape.actions = tmpPath.actions;
  16898. tmpShape.curves = tmpPath.curves;
  16899. shapes.push( tmpShape );
  16900. return shapes;
  16901. }
  16902. var holesFirst = ! THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  16903. holesFirst = isCCW ? ! holesFirst : holesFirst;
  16904. // console.log("Holes first", holesFirst);
  16905. var betterShapeHoles = [];
  16906. var newShapes = [];
  16907. var newShapeHoles = [];
  16908. var mainIdx = 0;
  16909. var tmpPoints;
  16910. newShapes[mainIdx] = undefined;
  16911. newShapeHoles[mainIdx] = [];
  16912. var i, il;
  16913. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  16914. tmpPath = subPaths[ i ];
  16915. tmpPoints = tmpPath.getPoints();
  16916. solid = THREE.Shape.Utils.isClockWise( tmpPoints );
  16917. solid = isCCW ? ! solid : solid;
  16918. if ( solid ) {
  16919. if ( (! holesFirst ) && ( newShapes[mainIdx] ) ) mainIdx ++;
  16920. newShapes[mainIdx] = { s: new THREE.Shape(), p: tmpPoints };
  16921. newShapes[mainIdx].s.actions = tmpPath.actions;
  16922. newShapes[mainIdx].s.curves = tmpPath.curves;
  16923. if ( holesFirst ) mainIdx ++;
  16924. newShapeHoles[mainIdx] = [];
  16925. //console.log('cw', i);
  16926. } else {
  16927. newShapeHoles[mainIdx].push( { h: tmpPath, p: tmpPoints[0] } );
  16928. //console.log('ccw', i);
  16929. }
  16930. }
  16931. // only Holes? -> probably all Shapes with wrong orientation
  16932. if ( ! newShapes[0] ) return toShapesNoHoles( subPaths );
  16933. if ( newShapes.length > 1 ) {
  16934. var ambigious = false;
  16935. var toChange = [];
  16936. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  16937. betterShapeHoles[sIdx] = [];
  16938. }
  16939. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  16940. var sho = newShapeHoles[sIdx];
  16941. for (var hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  16942. var ho = sho[hIdx];
  16943. var hole_unassigned = true;
  16944. for (var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  16945. if ( isPointInsidePolygon( ho.p, newShapes[s2Idx].p ) ) {
  16946. if ( sIdx != s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  16947. if ( hole_unassigned ) {
  16948. hole_unassigned = false;
  16949. betterShapeHoles[s2Idx].push( ho );
  16950. } else {
  16951. ambigious = true;
  16952. }
  16953. }
  16954. }
  16955. if ( hole_unassigned ) { betterShapeHoles[sIdx].push( ho ); }
  16956. }
  16957. }
  16958. // console.log("ambigious: ", ambigious);
  16959. if ( toChange.length > 0 ) {
  16960. // console.log("to change: ", toChange);
  16961. if (! ambigious) newShapeHoles = betterShapeHoles;
  16962. }
  16963. }
  16964. var tmpHoles, j, jl;
  16965. for ( i = 0, il = newShapes.length; i < il; i ++ ) {
  16966. tmpShape = newShapes[i].s;
  16967. shapes.push( tmpShape );
  16968. tmpHoles = newShapeHoles[i];
  16969. for ( j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  16970. tmpShape.holes.push( tmpHoles[j].h );
  16971. }
  16972. }
  16973. //console.log("shape", shapes);
  16974. return shapes;
  16975. };
  16976. // File:src/extras/core/Shape.js
  16977. /**
  16978. * @author zz85 / http://www.lab4games.net/zz85/blog
  16979. * Defines a 2d shape plane using paths.
  16980. **/
  16981. // STEP 1 Create a path.
  16982. // STEP 2 Turn path into shape.
  16983. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  16984. // STEP 3a - Extract points from each shape, turn to vertices
  16985. // STEP 3b - Triangulate each shape, add faces.
  16986. THREE.Shape = function () {
  16987. THREE.Path.apply( this, arguments );
  16988. this.holes = [];
  16989. };
  16990. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  16991. THREE.Shape.prototype.constructor = THREE.Shape;
  16992. // Convenience method to return ExtrudeGeometry
  16993. THREE.Shape.prototype.extrude = function ( options ) {
  16994. var extruded = new THREE.ExtrudeGeometry( this, options );
  16995. return extruded;
  16996. };
  16997. // Convenience method to return ShapeGeometry
  16998. THREE.Shape.prototype.makeGeometry = function ( options ) {
  16999. var geometry = new THREE.ShapeGeometry( this, options );
  17000. return geometry;
  17001. };
  17002. // Get points of holes
  17003. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  17004. var i, il = this.holes.length, holesPts = [];
  17005. for ( i = 0; i < il; i ++ ) {
  17006. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  17007. }
  17008. return holesPts;
  17009. };
  17010. // Get points of holes (spaced by regular distance)
  17011. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  17012. var i, il = this.holes.length, holesPts = [];
  17013. for ( i = 0; i < il; i ++ ) {
  17014. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  17015. }
  17016. return holesPts;
  17017. };
  17018. // Get points of shape and holes (keypoints based on segments parameter)
  17019. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  17020. return {
  17021. shape: this.getTransformedPoints( divisions ),
  17022. holes: this.getPointsHoles( divisions )
  17023. };
  17024. };
  17025. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  17026. if (this.useSpacedPoints) {
  17027. return this.extractAllSpacedPoints(divisions);
  17028. }
  17029. return this.extractAllPoints(divisions);
  17030. };
  17031. //
  17032. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  17033. //
  17034. // return {
  17035. //
  17036. // shape: this.transform( bend, divisions ),
  17037. // holes: this.getPointsHoles( divisions, bend )
  17038. //
  17039. // };
  17040. //
  17041. // };
  17042. // Get points of shape and holes (spaced by regular distance)
  17043. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  17044. return {
  17045. shape: this.getTransformedSpacedPoints( divisions ),
  17046. holes: this.getSpacedPointsHoles( divisions )
  17047. };
  17048. };
  17049. /**************************************************************
  17050. * Utils
  17051. **************************************************************/
  17052. THREE.Shape.Utils = {
  17053. triangulateShape: function ( contour, holes ) {
  17054. function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) {
  17055. // inOtherPt needs to be colinear to the inSegment
  17056. if ( inSegPt1.x != inSegPt2.x ) {
  17057. if ( inSegPt1.x < inSegPt2.x ) {
  17058. return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) );
  17059. } else {
  17060. return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) );
  17061. }
  17062. } else {
  17063. if ( inSegPt1.y < inSegPt2.y ) {
  17064. return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) );
  17065. } else {
  17066. return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) );
  17067. }
  17068. }
  17069. }
  17070. function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) {
  17071. var EPSILON = 0.0000000001;
  17072. var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y;
  17073. var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y;
  17074. var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x;
  17075. var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y;
  17076. var limit = seg1dy * seg2dx - seg1dx * seg2dy;
  17077. var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy;
  17078. if ( Math.abs(limit) > EPSILON ) { // not parallel
  17079. var perpSeg2;
  17080. if ( limit > 0 ) {
  17081. if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return [];
  17082. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  17083. if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return [];
  17084. } else {
  17085. if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return [];
  17086. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  17087. if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return [];
  17088. }
  17089. // i.e. to reduce rounding errors
  17090. // intersection at endpoint of segment#1?
  17091. if ( perpSeg2 == 0 ) {
  17092. if ( ( inExcludeAdjacentSegs ) &&
  17093. ( ( perpSeg1 == 0 ) || ( perpSeg1 == limit ) ) ) return [];
  17094. return [ inSeg1Pt1 ];
  17095. }
  17096. if ( perpSeg2 == limit ) {
  17097. if ( ( inExcludeAdjacentSegs ) &&
  17098. ( ( perpSeg1 == 0 ) || ( perpSeg1 == limit ) ) ) return [];
  17099. return [ inSeg1Pt2 ];
  17100. }
  17101. // intersection at endpoint of segment#2?
  17102. if ( perpSeg1 == 0 ) return [ inSeg2Pt1 ];
  17103. if ( perpSeg1 == limit ) return [ inSeg2Pt2 ];
  17104. // return real intersection point
  17105. var factorSeg1 = perpSeg2 / limit;
  17106. return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx,
  17107. y: inSeg1Pt1.y + factorSeg1 * seg1dy } ];
  17108. } else { // parallel or colinear
  17109. if ( ( perpSeg1 != 0 ) ||
  17110. ( seg2dy * seg1seg2dx != seg2dx * seg1seg2dy ) ) return [];
  17111. // they are collinear or degenerate
  17112. var seg1Pt = ( (seg1dx == 0) && (seg1dy == 0) ); // segment1 ist just a point?
  17113. var seg2Pt = ( (seg2dx == 0) && (seg2dy == 0) ); // segment2 ist just a point?
  17114. // both segments are points
  17115. if ( seg1Pt && seg2Pt ) {
  17116. if ( (inSeg1Pt1.x != inSeg2Pt1.x) ||
  17117. (inSeg1Pt1.y != inSeg2Pt1.y) ) return []; // they are distinct points
  17118. return [ inSeg1Pt1 ]; // they are the same point
  17119. }
  17120. // segment#1 is a single point
  17121. if ( seg1Pt ) {
  17122. if (! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2
  17123. return [ inSeg1Pt1 ];
  17124. }
  17125. // segment#2 is a single point
  17126. if ( seg2Pt ) {
  17127. if (! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1
  17128. return [ inSeg2Pt1 ];
  17129. }
  17130. // they are collinear segments, which might overlap
  17131. var seg1min, seg1max, seg1minVal, seg1maxVal;
  17132. var seg2min, seg2max, seg2minVal, seg2maxVal;
  17133. if (seg1dx != 0) { // the segments are NOT on a vertical line
  17134. if ( inSeg1Pt1.x < inSeg1Pt2.x ) {
  17135. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x;
  17136. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x;
  17137. } else {
  17138. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x;
  17139. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x;
  17140. }
  17141. if ( inSeg2Pt1.x < inSeg2Pt2.x ) {
  17142. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x;
  17143. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x;
  17144. } else {
  17145. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x;
  17146. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x;
  17147. }
  17148. } else { // the segments are on a vertical line
  17149. if ( inSeg1Pt1.y < inSeg1Pt2.y ) {
  17150. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y;
  17151. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y;
  17152. } else {
  17153. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y;
  17154. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y;
  17155. }
  17156. if ( inSeg2Pt1.y < inSeg2Pt2.y ) {
  17157. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y;
  17158. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y;
  17159. } else {
  17160. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y;
  17161. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y;
  17162. }
  17163. }
  17164. if ( seg1minVal <= seg2minVal ) {
  17165. if ( seg1maxVal < seg2minVal ) return [];
  17166. if ( seg1maxVal == seg2minVal ) {
  17167. if ( inExcludeAdjacentSegs ) return [];
  17168. return [ seg2min ];
  17169. }
  17170. if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ];
  17171. return [ seg2min, seg2max ];
  17172. } else {
  17173. if ( seg1minVal > seg2maxVal ) return [];
  17174. if ( seg1minVal == seg2maxVal ) {
  17175. if ( inExcludeAdjacentSegs ) return [];
  17176. return [ seg1min ];
  17177. }
  17178. if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ];
  17179. return [ seg1min, seg2max ];
  17180. }
  17181. }
  17182. }
  17183. function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) {
  17184. // The order of legs is important
  17185. var EPSILON = 0.0000000001;
  17186. // translation of all points, so that Vertex is at (0,0)
  17187. var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y;
  17188. var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y;
  17189. var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y;
  17190. // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg.
  17191. var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX;
  17192. var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX;
  17193. if ( Math.abs(from2toAngle) > EPSILON ) { // angle != 180 deg.
  17194. var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX;
  17195. // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle );
  17196. if ( from2toAngle > 0 ) { // main angle < 180 deg.
  17197. return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) );
  17198. } else { // main angle > 180 deg.
  17199. return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) );
  17200. }
  17201. } else { // angle == 180 deg.
  17202. // console.log( "from2to: 180 deg., from2other: " + from2otherAngle );
  17203. return ( from2otherAngle > 0 );
  17204. }
  17205. }
  17206. function removeHoles( contour, holes ) {
  17207. var shape = contour.concat(); // work on this shape
  17208. var hole;
  17209. function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) {
  17210. // Check if hole point lies within angle around shape point
  17211. var lastShapeIdx = shape.length - 1;
  17212. var prevShapeIdx = inShapeIdx - 1;
  17213. if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx;
  17214. var nextShapeIdx = inShapeIdx + 1;
  17215. if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0;
  17216. var insideAngle = isPointInsideAngle( shape[inShapeIdx], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[inHoleIdx] );
  17217. if (! insideAngle ) {
  17218. // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y );
  17219. return false;
  17220. }
  17221. // Check if shape point lies within angle around hole point
  17222. var lastHoleIdx = hole.length - 1;
  17223. var prevHoleIdx = inHoleIdx - 1;
  17224. if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx;
  17225. var nextHoleIdx = inHoleIdx + 1;
  17226. if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0;
  17227. insideAngle = isPointInsideAngle( hole[inHoleIdx], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[inShapeIdx] );
  17228. if (! insideAngle ) {
  17229. // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y );
  17230. return false;
  17231. }
  17232. return true;
  17233. }
  17234. function intersectsShapeEdge( inShapePt, inHolePt ) {
  17235. // checks for intersections with shape edges
  17236. var sIdx, nextIdx, intersection;
  17237. for ( sIdx = 0; sIdx < shape.length; sIdx ++ ) {
  17238. nextIdx = sIdx + 1; nextIdx %= shape.length;
  17239. intersection = intersect_segments_2D( inShapePt, inHolePt, shape[sIdx], shape[nextIdx], true );
  17240. if ( intersection.length > 0 ) return true;
  17241. }
  17242. return false;
  17243. }
  17244. var indepHoles = [];
  17245. function intersectsHoleEdge( inShapePt, inHolePt ) {
  17246. // checks for intersections with hole edges
  17247. var ihIdx, chkHole,
  17248. hIdx, nextIdx, intersection;
  17249. for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx ++ ) {
  17250. chkHole = holes[indepHoles[ihIdx]];
  17251. for ( hIdx = 0; hIdx < chkHole.length; hIdx ++ ) {
  17252. nextIdx = hIdx + 1; nextIdx %= chkHole.length;
  17253. intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[hIdx], chkHole[nextIdx], true );
  17254. if ( intersection.length > 0 ) return true;
  17255. }
  17256. }
  17257. return false;
  17258. }
  17259. var holeIndex, shapeIndex,
  17260. shapePt, holePt,
  17261. holeIdx, cutKey, failedCuts = [],
  17262. tmpShape1, tmpShape2,
  17263. tmpHole1, tmpHole2;
  17264. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  17265. indepHoles.push( h );
  17266. }
  17267. var minShapeIndex = 0;
  17268. var counter = indepHoles.length * 2;
  17269. while ( indepHoles.length > 0 ) {
  17270. counter --;
  17271. if ( counter < 0 ) {
  17272. console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" );
  17273. break;
  17274. }
  17275. // search for shape-vertex and hole-vertex,
  17276. // which can be connected without intersections
  17277. for ( shapeIndex = minShapeIndex; shapeIndex < shape.length; shapeIndex ++ ) {
  17278. shapePt = shape[ shapeIndex ];
  17279. holeIndex = - 1;
  17280. // search for hole which can be reached without intersections
  17281. for ( var h = 0; h < indepHoles.length; h ++ ) {
  17282. holeIdx = indepHoles[h];
  17283. // prevent multiple checks
  17284. cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx;
  17285. if ( failedCuts[cutKey] !== undefined ) continue;
  17286. hole = holes[holeIdx];
  17287. for ( var h2 = 0; h2 < hole.length; h2 ++ ) {
  17288. holePt = hole[ h2 ];
  17289. if (! isCutLineInsideAngles( shapeIndex, h2 ) ) continue;
  17290. if ( intersectsShapeEdge( shapePt, holePt ) ) continue;
  17291. if ( intersectsHoleEdge( shapePt, holePt ) ) continue;
  17292. holeIndex = h2;
  17293. indepHoles.splice(h, 1);
  17294. tmpShape1 = shape.slice( 0, shapeIndex + 1 );
  17295. tmpShape2 = shape.slice( shapeIndex );
  17296. tmpHole1 = hole.slice( holeIndex );
  17297. tmpHole2 = hole.slice( 0, holeIndex + 1 );
  17298. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  17299. minShapeIndex = shapeIndex;
  17300. // Debug only, to show the selected cuts
  17301. // glob_CutLines.push( [ shapePt, holePt ] );
  17302. break;
  17303. }
  17304. if ( holeIndex >= 0 ) break; // hole-vertex found
  17305. failedCuts[cutKey] = true; // remember failure
  17306. }
  17307. if ( holeIndex >= 0 ) break; // hole-vertex found
  17308. }
  17309. }
  17310. return shape; /* shape with no holes */
  17311. }
  17312. var i, il, f, face,
  17313. key, index,
  17314. allPointsMap = {};
  17315. // 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.
  17316. var allpoints = contour.concat();
  17317. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  17318. Array.prototype.push.apply( allpoints, holes[h] );
  17319. }
  17320. //console.log( "allpoints",allpoints, allpoints.length );
  17321. // prepare all points map
  17322. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  17323. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  17324. if ( allPointsMap[ key ] !== undefined ) {
  17325. THREE.warn( "THREE.Shape: Duplicate point", key );
  17326. }
  17327. allPointsMap[ key ] = i;
  17328. }
  17329. // remove holes by cutting paths to holes and adding them to the shape
  17330. var shapeWithoutHoles = removeHoles( contour, holes );
  17331. var triangles = THREE.FontUtils.Triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape
  17332. //console.log( "triangles",triangles, triangles.length );
  17333. // check all face vertices against all points map
  17334. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  17335. face = triangles[ i ];
  17336. for ( f = 0; f < 3; f ++ ) {
  17337. key = face[ f ].x + ":" + face[ f ].y;
  17338. index = allPointsMap[ key ];
  17339. if ( index !== undefined ) {
  17340. face[ f ] = index;
  17341. }
  17342. }
  17343. }
  17344. return triangles.concat();
  17345. },
  17346. isClockWise: function ( pts ) {
  17347. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  17348. },
  17349. // Bezier Curves formulas obtained from
  17350. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  17351. // Quad Bezier Functions
  17352. b2p0: function ( t, p ) {
  17353. var k = 1 - t;
  17354. return k * k * p;
  17355. },
  17356. b2p1: function ( t, p ) {
  17357. return 2 * ( 1 - t ) * t * p;
  17358. },
  17359. b2p2: function ( t, p ) {
  17360. return t * t * p;
  17361. },
  17362. b2: function ( t, p0, p1, p2 ) {
  17363. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  17364. },
  17365. // Cubic Bezier Functions
  17366. b3p0: function ( t, p ) {
  17367. var k = 1 - t;
  17368. return k * k * k * p;
  17369. },
  17370. b3p1: function ( t, p ) {
  17371. var k = 1 - t;
  17372. return 3 * k * k * t * p;
  17373. },
  17374. b3p2: function ( t, p ) {
  17375. var k = 1 - t;
  17376. return 3 * k * t * t * p;
  17377. },
  17378. b3p3: function ( t, p ) {
  17379. return t * t * t * p;
  17380. },
  17381. b3: function ( t, p0, p1, p2, p3 ) {
  17382. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  17383. }
  17384. };
  17385. // File:src/extras/curves/LineCurve.js
  17386. /**************************************************************
  17387. * Line
  17388. **************************************************************/
  17389. THREE.LineCurve = function ( v1, v2 ) {
  17390. this.v1 = v1;
  17391. this.v2 = v2;
  17392. };
  17393. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  17394. THREE.LineCurve.prototype.constructor = THREE.LineCurve;
  17395. THREE.LineCurve.prototype.getPoint = function ( t ) {
  17396. var point = this.v2.clone().sub(this.v1);
  17397. point.multiplyScalar( t ).add( this.v1 );
  17398. return point;
  17399. };
  17400. // Line curve is linear, so we can overwrite default getPointAt
  17401. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  17402. return this.getPoint( u );
  17403. };
  17404. THREE.LineCurve.prototype.getTangent = function( t ) {
  17405. var tangent = this.v2.clone().sub(this.v1);
  17406. return tangent.normalize();
  17407. };
  17408. // File:src/extras/curves/QuadraticBezierCurve.js
  17409. /**************************************************************
  17410. * Quadratic Bezier curve
  17411. **************************************************************/
  17412. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  17413. this.v0 = v0;
  17414. this.v1 = v1;
  17415. this.v2 = v2;
  17416. };
  17417. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  17418. THREE.QuadraticBezierCurve.prototype.constructor = THREE.QuadraticBezierCurve;
  17419. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  17420. var vector = new THREE.Vector2();
  17421. vector.x = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  17422. vector.y = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  17423. return vector;
  17424. };
  17425. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  17426. var vector = new THREE.Vector2();
  17427. vector.x = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  17428. vector.y = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  17429. // returns unit vector
  17430. return vector.normalize();
  17431. };
  17432. // File:src/extras/curves/CubicBezierCurve.js
  17433. /**************************************************************
  17434. * Cubic Bezier curve
  17435. **************************************************************/
  17436. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  17437. this.v0 = v0;
  17438. this.v1 = v1;
  17439. this.v2 = v2;
  17440. this.v3 = v3;
  17441. };
  17442. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  17443. THREE.CubicBezierCurve.prototype.constructor = THREE.CubicBezierCurve;
  17444. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  17445. var tx, ty;
  17446. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17447. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17448. return new THREE.Vector2( tx, ty );
  17449. };
  17450. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  17451. var tx, ty;
  17452. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17453. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17454. var tangent = new THREE.Vector2( tx, ty );
  17455. tangent.normalize();
  17456. return tangent;
  17457. };
  17458. // File:src/extras/curves/SplineCurve.js
  17459. /**************************************************************
  17460. * Spline curve
  17461. **************************************************************/
  17462. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  17463. this.points = ( points == undefined ) ? [] : points;
  17464. };
  17465. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  17466. THREE.SplineCurve.prototype.constructor = THREE.SplineCurve;
  17467. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  17468. var points = this.points;
  17469. var point = ( points.length - 1 ) * t;
  17470. var intPoint = Math.floor( point );
  17471. var weight = point - intPoint;
  17472. var point0 = points[ intPoint == 0 ? intPoint : intPoint - 1 ]
  17473. var point1 = points[ intPoint ]
  17474. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ]
  17475. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ]
  17476. var vector = new THREE.Vector2();
  17477. vector.x = THREE.Curve.Utils.interpolate( point0.x, point1.x, point2.x, point3.x, weight );
  17478. vector.y = THREE.Curve.Utils.interpolate( point0.y, point1.y, point2.y, point3.y, weight );
  17479. return vector;
  17480. };
  17481. // File:src/extras/curves/EllipseCurve.js
  17482. /**************************************************************
  17483. * Ellipse curve
  17484. **************************************************************/
  17485. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise ) {
  17486. this.aX = aX;
  17487. this.aY = aY;
  17488. this.xRadius = xRadius;
  17489. this.yRadius = yRadius;
  17490. this.aStartAngle = aStartAngle;
  17491. this.aEndAngle = aEndAngle;
  17492. this.aClockwise = aClockwise;
  17493. };
  17494. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  17495. THREE.EllipseCurve.prototype.constructor = THREE.EllipseCurve;
  17496. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  17497. var deltaAngle = this.aEndAngle - this.aStartAngle;
  17498. if ( deltaAngle < 0 ) deltaAngle += Math.PI * 2;
  17499. if ( deltaAngle > Math.PI * 2 ) deltaAngle -= Math.PI * 2;
  17500. var angle;
  17501. if ( this.aClockwise === true ) {
  17502. angle = this.aEndAngle + ( 1 - t ) * ( Math.PI * 2 - deltaAngle );
  17503. } else {
  17504. angle = this.aStartAngle + t * deltaAngle;
  17505. }
  17506. var vector = new THREE.Vector2();
  17507. vector.x = this.aX + this.xRadius * Math.cos( angle );
  17508. vector.y = this.aY + this.yRadius * Math.sin( angle );
  17509. return vector;
  17510. };
  17511. // File:src/extras/curves/ArcCurve.js
  17512. /**************************************************************
  17513. * Arc curve
  17514. **************************************************************/
  17515. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  17516. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  17517. };
  17518. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  17519. THREE.ArcCurve.prototype.constructor = THREE.ArcCurve;
  17520. // File:src/extras/curves/LineCurve3.js
  17521. /**************************************************************
  17522. * Line3D
  17523. **************************************************************/
  17524. THREE.LineCurve3 = THREE.Curve.create(
  17525. function ( v1, v2 ) {
  17526. this.v1 = v1;
  17527. this.v2 = v2;
  17528. },
  17529. function ( t ) {
  17530. var vector = new THREE.Vector3();
  17531. vector.subVectors( this.v2, this.v1 ); // diff
  17532. vector.multiplyScalar( t );
  17533. vector.add( this.v1 );
  17534. return vector;
  17535. }
  17536. );
  17537. // File:src/extras/curves/QuadraticBezierCurve3.js
  17538. /**************************************************************
  17539. * Quadratic Bezier 3D curve
  17540. **************************************************************/
  17541. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  17542. function ( v0, v1, v2 ) {
  17543. this.v0 = v0;
  17544. this.v1 = v1;
  17545. this.v2 = v2;
  17546. },
  17547. function ( t ) {
  17548. var vector = new THREE.Vector3();
  17549. vector.x = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  17550. vector.y = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  17551. vector.z = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  17552. return vector;
  17553. }
  17554. );
  17555. // File:src/extras/curves/CubicBezierCurve3.js
  17556. /**************************************************************
  17557. * Cubic Bezier 3D curve
  17558. **************************************************************/
  17559. THREE.CubicBezierCurve3 = THREE.Curve.create(
  17560. function ( v0, v1, v2, v3 ) {
  17561. this.v0 = v0;
  17562. this.v1 = v1;
  17563. this.v2 = v2;
  17564. this.v3 = v3;
  17565. },
  17566. function ( t ) {
  17567. var vector = new THREE.Vector3();
  17568. vector.x = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17569. vector.y = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17570. vector.z = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  17571. return vector;
  17572. }
  17573. );
  17574. // File:src/extras/curves/SplineCurve3.js
  17575. /**************************************************************
  17576. * Spline 3D curve
  17577. **************************************************************/
  17578. THREE.SplineCurve3 = THREE.Curve.create(
  17579. function ( points /* array of Vector3 */) {
  17580. this.points = ( points == undefined ) ? [] : points;
  17581. },
  17582. function ( t ) {
  17583. var points = this.points;
  17584. var point = ( points.length - 1 ) * t;
  17585. var intPoint = Math.floor( point );
  17586. var weight = point - intPoint;
  17587. var point0 = points[ intPoint == 0 ? intPoint : intPoint - 1 ];
  17588. var point1 = points[ intPoint ];
  17589. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  17590. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  17591. var vector = new THREE.Vector3();
  17592. vector.x = THREE.Curve.Utils.interpolate( point0.x, point1.x, point2.x, point3.x, weight );
  17593. vector.y = THREE.Curve.Utils.interpolate( point0.y, point1.y, point2.y, point3.y, weight );
  17594. vector.z = THREE.Curve.Utils.interpolate( point0.z, point1.z, point2.z, point3.z, weight );
  17595. return vector;
  17596. }
  17597. );
  17598. // File:src/extras/curves/ClosedSplineCurve3.js
  17599. /**************************************************************
  17600. * Closed Spline 3D curve
  17601. **************************************************************/
  17602. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  17603. function ( points /* array of Vector3 */) {
  17604. this.points = ( points == undefined ) ? [] : points;
  17605. },
  17606. function ( t ) {
  17607. var points = this.points;
  17608. var point = ( points.length - 0 ) * t; // This needs to be from 0-length +1
  17609. var intPoint = Math.floor( point );
  17610. var weight = point - intPoint;
  17611. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  17612. var point0 = points[ ( intPoint - 1 ) % points.length ];
  17613. var point1 = points[ ( intPoint ) % points.length ];
  17614. var point2 = points[ ( intPoint + 1 ) % points.length ];
  17615. var point3 = points[ ( intPoint + 2 ) % points.length ];
  17616. var vector = new THREE.Vector3();
  17617. vector.x = THREE.Curve.Utils.interpolate( point0.x, point1.x, point2.x, point3.x, weight );
  17618. vector.y = THREE.Curve.Utils.interpolate( point0.y, point1.y, point2.y, point3.y, weight );
  17619. vector.z = THREE.Curve.Utils.interpolate( point0.z, point1.z, point2.z, point3.z, weight );
  17620. return vector;
  17621. }
  17622. );
  17623. // File:src/extras/animation/AnimationHandler.js
  17624. /**
  17625. * @author mikael emtinger / http://gomo.se/
  17626. */
  17627. THREE.AnimationHandler = {
  17628. LINEAR: 0,
  17629. CATMULLROM: 1,
  17630. CATMULLROM_FORWARD: 2,
  17631. //
  17632. add: function () { THREE.warn( 'THREE.AnimationHandler.add() has been deprecated.' ); },
  17633. get: function () { THREE.warn( 'THREE.AnimationHandler.get() has been deprecated.' ); },
  17634. remove: function () { THREE.warn( 'THREE.AnimationHandler.remove() has been deprecated.' ); },
  17635. //
  17636. animations: [],
  17637. init: function ( data ) {
  17638. if ( data.initialized === true ) return data;
  17639. // loop through all keys
  17640. for ( var h = 0; h < data.hierarchy.length; h ++ ) {
  17641. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17642. // remove minus times
  17643. if ( data.hierarchy[ h ].keys[ k ].time < 0 ) {
  17644. data.hierarchy[ h ].keys[ k ].time = 0;
  17645. }
  17646. // create quaternions
  17647. if ( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  17648. ! ( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  17649. var quat = data.hierarchy[ h ].keys[ k ].rot;
  17650. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion().fromArray( quat );
  17651. }
  17652. }
  17653. // prepare morph target keys
  17654. if ( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  17655. // get all used
  17656. var usedMorphTargets = {};
  17657. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17658. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17659. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  17660. usedMorphTargets[ morphTargetName ] = - 1;
  17661. }
  17662. }
  17663. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  17664. // set all used on all frames
  17665. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17666. var influences = {};
  17667. for ( var morphTargetName in usedMorphTargets ) {
  17668. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17669. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  17670. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  17671. break;
  17672. }
  17673. }
  17674. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  17675. influences[ morphTargetName ] = 0;
  17676. }
  17677. }
  17678. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  17679. }
  17680. }
  17681. // remove all keys that are on the same time
  17682. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17683. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  17684. data.hierarchy[ h ].keys.splice( k, 1 );
  17685. k --;
  17686. }
  17687. }
  17688. // set index
  17689. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17690. data.hierarchy[ h ].keys[ k ].index = k;
  17691. }
  17692. }
  17693. data.initialized = true;
  17694. return data;
  17695. },
  17696. parse: function ( root ) {
  17697. var parseRecurseHierarchy = function ( root, hierarchy ) {
  17698. hierarchy.push( root );
  17699. for ( var c = 0; c < root.children.length; c ++ )
  17700. parseRecurseHierarchy( root.children[ c ], hierarchy );
  17701. };
  17702. // setup hierarchy
  17703. var hierarchy = [];
  17704. if ( root instanceof THREE.SkinnedMesh ) {
  17705. for ( var b = 0; b < root.skeleton.bones.length; b ++ ) {
  17706. hierarchy.push( root.skeleton.bones[ b ] );
  17707. }
  17708. } else {
  17709. parseRecurseHierarchy( root, hierarchy );
  17710. }
  17711. return hierarchy;
  17712. },
  17713. play: function ( animation ) {
  17714. if ( this.animations.indexOf( animation ) === - 1 ) {
  17715. this.animations.push( animation );
  17716. }
  17717. },
  17718. stop: function ( animation ) {
  17719. var index = this.animations.indexOf( animation );
  17720. if ( index !== - 1 ) {
  17721. this.animations.splice( index, 1 );
  17722. }
  17723. },
  17724. update: function ( deltaTimeMS ) {
  17725. for ( var i = 0; i < this.animations.length; i ++ ) {
  17726. this.animations[ i ].resetBlendWeights( );
  17727. }
  17728. for ( var i = 0; i < this.animations.length; i ++ ) {
  17729. this.animations[ i ].update( deltaTimeMS );
  17730. }
  17731. }
  17732. };
  17733. // File:src/extras/animation/Animation.js
  17734. /**
  17735. * @author mikael emtinger / http://gomo.se/
  17736. * @author mrdoob / http://mrdoob.com/
  17737. * @author alteredq / http://alteredqualia.com/
  17738. */
  17739. THREE.Animation = function ( root, data ) {
  17740. this.root = root;
  17741. this.data = THREE.AnimationHandler.init( data );
  17742. this.hierarchy = THREE.AnimationHandler.parse( root );
  17743. this.currentTime = 0;
  17744. this.timeScale = 1;
  17745. this.isPlaying = false;
  17746. this.loop = true;
  17747. this.weight = 0;
  17748. this.interpolationType = THREE.AnimationHandler.LINEAR;
  17749. };
  17750. THREE.Animation.prototype.keyTypes = [ "pos", "rot", "scl" ];
  17751. THREE.Animation.prototype.play = function ( startTime, weight ) {
  17752. this.currentTime = startTime !== undefined ? startTime : 0;
  17753. this.weight = weight !== undefined ? weight : 1;
  17754. this.isPlaying = true;
  17755. this.reset();
  17756. THREE.AnimationHandler.play( this );
  17757. };
  17758. THREE.Animation.prototype.stop = function() {
  17759. this.isPlaying = false;
  17760. THREE.AnimationHandler.stop( this );
  17761. };
  17762. THREE.Animation.prototype.reset = function () {
  17763. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  17764. var object = this.hierarchy[ h ];
  17765. if ( object.animationCache === undefined ) {
  17766. object.animationCache = {
  17767. animations: {},
  17768. blending: {
  17769. positionWeight: 0.0,
  17770. quaternionWeight: 0.0,
  17771. scaleWeight: 0.0
  17772. }
  17773. };
  17774. }
  17775. if ( object.animationCache.animations[this.data.name] === undefined ) {
  17776. object.animationCache.animations[this.data.name] = {};
  17777. object.animationCache.animations[this.data.name].prevKey = { pos: 0, rot: 0, scl: 0 };
  17778. object.animationCache.animations[this.data.name].nextKey = { pos: 0, rot: 0, scl: 0 };
  17779. object.animationCache.animations[this.data.name].originalMatrix = object.matrix;
  17780. }
  17781. var animationCache = object.animationCache.animations[this.data.name];
  17782. // Get keys to match our current time
  17783. for ( var t = 0; t < 3; t ++ ) {
  17784. var type = this.keyTypes[ t ];
  17785. var prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  17786. var nextKey = this.getNextKeyWith( type, h, 1 );
  17787. while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {
  17788. prevKey = nextKey;
  17789. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17790. }
  17791. animationCache.prevKey[ type ] = prevKey;
  17792. animationCache.nextKey[ type ] = nextKey;
  17793. }
  17794. }
  17795. };
  17796. THREE.Animation.prototype.resetBlendWeights = function () {
  17797. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  17798. var object = this.hierarchy[ h ];
  17799. if ( object.animationCache !== undefined ) {
  17800. object.animationCache.blending.positionWeight = 0.0;
  17801. object.animationCache.blending.quaternionWeight = 0.0;
  17802. object.animationCache.blending.scaleWeight = 0.0;
  17803. }
  17804. }
  17805. };
  17806. THREE.Animation.prototype.update = (function() {
  17807. var points = [];
  17808. var target = new THREE.Vector3();
  17809. var newVector = new THREE.Vector3();
  17810. var newQuat = new THREE.Quaternion();
  17811. // Catmull-Rom spline
  17812. var interpolateCatmullRom = function ( points, scale ) {
  17813. var c = [], v3 = [],
  17814. point, intPoint, weight, w2, w3,
  17815. pa, pb, pc, pd;
  17816. point = ( points.length - 1 ) * scale;
  17817. intPoint = Math.floor( point );
  17818. weight = point - intPoint;
  17819. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  17820. c[ 1 ] = intPoint;
  17821. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  17822. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  17823. pa = points[ c[ 0 ] ];
  17824. pb = points[ c[ 1 ] ];
  17825. pc = points[ c[ 2 ] ];
  17826. pd = points[ c[ 3 ] ];
  17827. w2 = weight * weight;
  17828. w3 = weight * w2;
  17829. v3[ 0 ] = interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  17830. v3[ 1 ] = interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  17831. v3[ 2 ] = interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  17832. return v3;
  17833. };
  17834. var interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  17835. var v0 = ( p2 - p0 ) * 0.5,
  17836. v1 = ( p3 - p1 ) * 0.5;
  17837. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  17838. };
  17839. return function ( delta ) {
  17840. if ( this.isPlaying === false ) return;
  17841. this.currentTime += delta * this.timeScale;
  17842. if ( this.weight === 0 )
  17843. return;
  17844. //
  17845. var duration = this.data.length;
  17846. if ( this.currentTime > duration || this.currentTime < 0 ) {
  17847. if ( this.loop ) {
  17848. this.currentTime %= duration;
  17849. if ( this.currentTime < 0 )
  17850. this.currentTime += duration;
  17851. this.reset();
  17852. } else {
  17853. this.stop();
  17854. }
  17855. }
  17856. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  17857. var object = this.hierarchy[ h ];
  17858. var animationCache = object.animationCache.animations[this.data.name];
  17859. var blending = object.animationCache.blending;
  17860. // loop through pos/rot/scl
  17861. for ( var t = 0; t < 3; t ++ ) {
  17862. // get keys
  17863. var type = this.keyTypes[ t ];
  17864. var prevKey = animationCache.prevKey[ type ];
  17865. var nextKey = animationCache.nextKey[ type ];
  17866. if ( ( this.timeScale > 0 && nextKey.time <= this.currentTime ) ||
  17867. ( this.timeScale < 0 && prevKey.time >= this.currentTime ) ) {
  17868. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  17869. nextKey = this.getNextKeyWith( type, h, 1 );
  17870. while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {
  17871. prevKey = nextKey;
  17872. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17873. }
  17874. animationCache.prevKey[ type ] = prevKey;
  17875. animationCache.nextKey[ type ] = nextKey;
  17876. }
  17877. var scale = ( this.currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  17878. var prevXYZ = prevKey[ type ];
  17879. var nextXYZ = nextKey[ type ];
  17880. if ( scale < 0 ) scale = 0;
  17881. if ( scale > 1 ) scale = 1;
  17882. // interpolate
  17883. if ( type === "pos" ) {
  17884. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  17885. newVector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  17886. newVector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  17887. newVector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  17888. // blend
  17889. var proportionalWeight = this.weight / ( this.weight + blending.positionWeight );
  17890. object.position.lerp( newVector, proportionalWeight );
  17891. blending.positionWeight += this.weight;
  17892. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17893. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17894. points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  17895. points[ 1 ] = prevXYZ;
  17896. points[ 2 ] = nextXYZ;
  17897. points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  17898. scale = scale * 0.33 + 0.33;
  17899. var currentPoint = interpolateCatmullRom( points, scale );
  17900. var proportionalWeight = this.weight / ( this.weight + blending.positionWeight );
  17901. blending.positionWeight += this.weight;
  17902. // blend
  17903. var vector = object.position;
  17904. vector.x = vector.x + ( currentPoint[ 0 ] - vector.x ) * proportionalWeight;
  17905. vector.y = vector.y + ( currentPoint[ 1 ] - vector.y ) * proportionalWeight;
  17906. vector.z = vector.z + ( currentPoint[ 2 ] - vector.z ) * proportionalWeight;
  17907. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17908. var forwardPoint = interpolateCatmullRom( points, scale * 1.01 );
  17909. target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  17910. target.sub( vector );
  17911. target.y = 0;
  17912. target.normalize();
  17913. var angle = Math.atan2( target.x, target.z );
  17914. object.rotation.set( 0, angle, 0 );
  17915. }
  17916. }
  17917. } else if ( type === "rot" ) {
  17918. THREE.Quaternion.slerp( prevXYZ, nextXYZ, newQuat, scale );
  17919. // Avoid paying the cost of an additional slerp if we don't have to
  17920. if ( blending.quaternionWeight === 0 ) {
  17921. object.quaternion.copy(newQuat);
  17922. blending.quaternionWeight = this.weight;
  17923. } else {
  17924. var proportionalWeight = this.weight / ( this.weight + blending.quaternionWeight );
  17925. THREE.Quaternion.slerp( object.quaternion, newQuat, object.quaternion, proportionalWeight );
  17926. blending.quaternionWeight += this.weight;
  17927. }
  17928. } else if ( type === "scl" ) {
  17929. newVector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  17930. newVector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  17931. newVector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  17932. var proportionalWeight = this.weight / ( this.weight + blending.scaleWeight );
  17933. object.scale.lerp( newVector, proportionalWeight );
  17934. blending.scaleWeight += this.weight;
  17935. }
  17936. }
  17937. }
  17938. return true;
  17939. };
  17940. })();
  17941. // Get next key with
  17942. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  17943. var keys = this.data.hierarchy[ h ].keys;
  17944. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17945. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17946. key = key < keys.length - 1 ? key : keys.length - 1;
  17947. } else {
  17948. key = key % keys.length;
  17949. }
  17950. for ( ; key < keys.length; key ++ ) {
  17951. if ( keys[ key ][ type ] !== undefined ) {
  17952. return keys[ key ];
  17953. }
  17954. }
  17955. return this.data.hierarchy[ h ].keys[ 0 ];
  17956. };
  17957. // Get previous key with
  17958. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  17959. var keys = this.data.hierarchy[ h ].keys;
  17960. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17961. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17962. key = key > 0 ? key : 0;
  17963. } else {
  17964. key = key >= 0 ? key : key + keys.length;
  17965. }
  17966. for ( ; key >= 0; key -- ) {
  17967. if ( keys[ key ][ type ] !== undefined ) {
  17968. return keys[ key ];
  17969. }
  17970. }
  17971. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  17972. };
  17973. // File:src/extras/animation/KeyFrameAnimation.js
  17974. /**
  17975. * @author mikael emtinger / http://gomo.se/
  17976. * @author mrdoob / http://mrdoob.com/
  17977. * @author alteredq / http://alteredqualia.com/
  17978. * @author khang duong
  17979. * @author erik kitson
  17980. */
  17981. THREE.KeyFrameAnimation = function ( data ) {
  17982. this.root = data.node;
  17983. this.data = THREE.AnimationHandler.init( data );
  17984. this.hierarchy = THREE.AnimationHandler.parse( this.root );
  17985. this.currentTime = 0;
  17986. this.timeScale = 0.001;
  17987. this.isPlaying = false;
  17988. this.isPaused = true;
  17989. this.loop = true;
  17990. // initialize to first keyframes
  17991. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  17992. var keys = this.data.hierarchy[h].keys,
  17993. sids = this.data.hierarchy[h].sids,
  17994. obj = this.hierarchy[h];
  17995. if ( keys.length && sids ) {
  17996. for ( var s = 0; s < sids.length; s ++ ) {
  17997. var sid = sids[ s ],
  17998. next = this.getNextKeyWith( sid, h, 0 );
  17999. if ( next ) {
  18000. next.apply( sid );
  18001. }
  18002. }
  18003. obj.matrixAutoUpdate = false;
  18004. this.data.hierarchy[h].node.updateMatrix();
  18005. obj.matrixWorldNeedsUpdate = true;
  18006. }
  18007. }
  18008. };
  18009. THREE.KeyFrameAnimation.prototype.play = function ( startTime ) {
  18010. this.currentTime = startTime !== undefined ? startTime : 0;
  18011. if ( this.isPlaying === false ) {
  18012. this.isPlaying = true;
  18013. // reset key cache
  18014. var h, hl = this.hierarchy.length,
  18015. object,
  18016. node;
  18017. for ( h = 0; h < hl; h ++ ) {
  18018. object = this.hierarchy[ h ];
  18019. node = this.data.hierarchy[ h ];
  18020. if ( node.animationCache === undefined ) {
  18021. node.animationCache = {};
  18022. node.animationCache.prevKey = null;
  18023. node.animationCache.nextKey = null;
  18024. node.animationCache.originalMatrix = object.matrix;
  18025. }
  18026. var keys = this.data.hierarchy[h].keys;
  18027. if (keys.length) {
  18028. node.animationCache.prevKey = keys[ 0 ];
  18029. node.animationCache.nextKey = keys[ 1 ];
  18030. this.startTime = Math.min( keys[0].time, this.startTime );
  18031. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  18032. }
  18033. }
  18034. this.update( 0 );
  18035. }
  18036. this.isPaused = false;
  18037. THREE.AnimationHandler.play( this );
  18038. };
  18039. THREE.KeyFrameAnimation.prototype.stop = function() {
  18040. this.isPlaying = false;
  18041. this.isPaused = false;
  18042. THREE.AnimationHandler.stop( this );
  18043. // reset JIT matrix and remove cache
  18044. for ( var h = 0; h < this.data.hierarchy.length; h ++ ) {
  18045. var obj = this.hierarchy[ h ];
  18046. var node = this.data.hierarchy[ h ];
  18047. if ( node.animationCache !== undefined ) {
  18048. var original = node.animationCache.originalMatrix;
  18049. original.copy( obj.matrix );
  18050. obj.matrix = original;
  18051. delete node.animationCache;
  18052. }
  18053. }
  18054. };
  18055. // Update
  18056. THREE.KeyFrameAnimation.prototype.update = function ( delta ) {
  18057. if ( this.isPlaying === false ) return;
  18058. this.currentTime += delta * this.timeScale;
  18059. //
  18060. var duration = this.data.length;
  18061. if ( this.loop === true && this.currentTime > duration ) {
  18062. this.currentTime %= duration;
  18063. }
  18064. this.currentTime = Math.min( this.currentTime, duration );
  18065. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18066. var object = this.hierarchy[ h ];
  18067. var node = this.data.hierarchy[ h ];
  18068. var keys = node.keys,
  18069. animationCache = node.animationCache;
  18070. if ( keys.length ) {
  18071. var prevKey = animationCache.prevKey;
  18072. var nextKey = animationCache.nextKey;
  18073. if ( nextKey.time <= this.currentTime ) {
  18074. while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {
  18075. prevKey = nextKey;
  18076. nextKey = keys[ prevKey.index + 1 ];
  18077. }
  18078. animationCache.prevKey = prevKey;
  18079. animationCache.nextKey = nextKey;
  18080. }
  18081. if ( nextKey.time >= this.currentTime ) {
  18082. prevKey.interpolate( nextKey, this.currentTime );
  18083. } else {
  18084. prevKey.interpolate( nextKey, nextKey.time );
  18085. }
  18086. this.data.hierarchy[ h ].node.updateMatrix();
  18087. object.matrixWorldNeedsUpdate = true;
  18088. }
  18089. }
  18090. };
  18091. // Get next key with
  18092. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  18093. var keys = this.data.hierarchy[ h ].keys;
  18094. key = key % keys.length;
  18095. for ( ; key < keys.length; key ++ ) {
  18096. if ( keys[ key ].hasTarget( sid ) ) {
  18097. return keys[ key ];
  18098. }
  18099. }
  18100. return keys[ 0 ];
  18101. };
  18102. // Get previous key with
  18103. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  18104. var keys = this.data.hierarchy[ h ].keys;
  18105. key = key >= 0 ? key : key + keys.length;
  18106. for ( ; key >= 0; key -- ) {
  18107. if ( keys[ key ].hasTarget( sid ) ) {
  18108. return keys[ key ];
  18109. }
  18110. }
  18111. return keys[ keys.length - 1 ];
  18112. };
  18113. // File:src/extras/animation/MorphAnimation.js
  18114. /**
  18115. * @author mrdoob / http://mrdoob.com
  18116. * @author willy-vvu / http://willy-vvu.github.io
  18117. */
  18118. THREE.MorphAnimation = function ( mesh ) {
  18119. this.mesh = mesh;
  18120. this.frames = mesh.morphTargetInfluences.length;
  18121. this.currentTime = 0;
  18122. this.duration = 1000;
  18123. this.loop = true;
  18124. this.lastFrame = 0;
  18125. this.currentFrame = 0;
  18126. this.isPlaying = false;
  18127. };
  18128. THREE.MorphAnimation.prototype = {
  18129. constructor: THREE.MorphAnimation,
  18130. play: function () {
  18131. this.isPlaying = true;
  18132. },
  18133. pause: function () {
  18134. this.isPlaying = false;
  18135. },
  18136. update: function ( delta ) {
  18137. if ( this.isPlaying === false ) return;
  18138. this.currentTime += delta;
  18139. if ( this.loop === true && this.currentTime > this.duration ) {
  18140. this.currentTime %= this.duration;
  18141. }
  18142. this.currentTime = Math.min( this.currentTime, this.duration );
  18143. var interpolation = this.duration / this.frames;
  18144. var frame = Math.floor( this.currentTime / interpolation );
  18145. if ( frame != this.currentFrame ) {
  18146. this.mesh.morphTargetInfluences[ this.lastFrame ] = 0;
  18147. this.mesh.morphTargetInfluences[ this.currentFrame ] = 1;
  18148. this.mesh.morphTargetInfluences[ frame ] = 0;
  18149. this.lastFrame = this.currentFrame;
  18150. this.currentFrame = frame;
  18151. }
  18152. this.mesh.morphTargetInfluences[ frame ] = ( this.currentTime % interpolation ) / interpolation;
  18153. this.mesh.morphTargetInfluences[ this.lastFrame ] = 1 - this.mesh.morphTargetInfluences[ frame ];
  18154. }
  18155. };
  18156. // File:src/extras/geometries/BoxGeometry.js
  18157. /**
  18158. * @author mrdoob / http://mrdoob.com/
  18159. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  18160. */
  18161. THREE.BoxGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  18162. THREE.Geometry.call( this );
  18163. this.type = 'BoxGeometry';
  18164. this.parameters = {
  18165. width: width,
  18166. height: height,
  18167. depth: depth,
  18168. widthSegments: widthSegments,
  18169. heightSegments: heightSegments,
  18170. depthSegments: depthSegments
  18171. };
  18172. this.widthSegments = widthSegments || 1;
  18173. this.heightSegments = heightSegments || 1;
  18174. this.depthSegments = depthSegments || 1;
  18175. var scope = this;
  18176. var width_half = width / 2;
  18177. var height_half = height / 2;
  18178. var depth_half = depth / 2;
  18179. buildPlane( 'z', 'y', - 1, - 1, depth, height, width_half, 0 ); // px
  18180. buildPlane( 'z', 'y', 1, - 1, depth, height, - width_half, 1 ); // nx
  18181. buildPlane( 'x', 'z', 1, 1, width, depth, height_half, 2 ); // py
  18182. buildPlane( 'x', 'z', 1, - 1, width, depth, - height_half, 3 ); // ny
  18183. buildPlane( 'x', 'y', 1, - 1, width, height, depth_half, 4 ); // pz
  18184. buildPlane( 'x', 'y', - 1, - 1, width, height, - depth_half, 5 ); // nz
  18185. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  18186. var w, ix, iy,
  18187. gridX = scope.widthSegments,
  18188. gridY = scope.heightSegments,
  18189. width_half = width / 2,
  18190. height_half = height / 2,
  18191. offset = scope.vertices.length;
  18192. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  18193. w = 'z';
  18194. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  18195. w = 'y';
  18196. gridY = scope.depthSegments;
  18197. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  18198. w = 'x';
  18199. gridX = scope.depthSegments;
  18200. }
  18201. var gridX1 = gridX + 1,
  18202. gridY1 = gridY + 1,
  18203. segment_width = width / gridX,
  18204. segment_height = height / gridY,
  18205. normal = new THREE.Vector3();
  18206. normal[ w ] = depth > 0 ? 1 : - 1;
  18207. for ( iy = 0; iy < gridY1; iy ++ ) {
  18208. for ( ix = 0; ix < gridX1; ix ++ ) {
  18209. var vector = new THREE.Vector3();
  18210. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  18211. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  18212. vector[ w ] = depth;
  18213. scope.vertices.push( vector );
  18214. }
  18215. }
  18216. for ( iy = 0; iy < gridY; iy ++ ) {
  18217. for ( ix = 0; ix < gridX; ix ++ ) {
  18218. var a = ix + gridX1 * iy;
  18219. var b = ix + gridX1 * ( iy + 1 );
  18220. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  18221. var d = ( ix + 1 ) + gridX1 * iy;
  18222. var uva = new THREE.Vector2( ix / gridX, 1 - iy / gridY );
  18223. var uvb = new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY );
  18224. var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iy + 1 ) / gridY );
  18225. var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY );
  18226. var face = new THREE.Face3( a + offset, b + offset, d + offset );
  18227. face.normal.copy( normal );
  18228. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  18229. face.materialIndex = materialIndex;
  18230. scope.faces.push( face );
  18231. scope.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  18232. face = new THREE.Face3( b + offset, c + offset, d + offset );
  18233. face.normal.copy( normal );
  18234. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  18235. face.materialIndex = materialIndex;
  18236. scope.faces.push( face );
  18237. scope.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  18238. }
  18239. }
  18240. }
  18241. this.mergeVertices();
  18242. };
  18243. THREE.BoxGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18244. THREE.BoxGeometry.prototype.constructor = THREE.BoxGeometry;
  18245. // File:src/extras/geometries/CircleGeometry.js
  18246. /**
  18247. * @author hughes
  18248. */
  18249. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  18250. THREE.Geometry.call( this );
  18251. this.type = 'CircleGeometry';
  18252. this.parameters = {
  18253. radius: radius,
  18254. segments: segments,
  18255. thetaStart: thetaStart,
  18256. thetaLength: thetaLength
  18257. };
  18258. radius = radius || 50;
  18259. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  18260. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18261. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  18262. var i, uvs = [],
  18263. center = new THREE.Vector3(), centerUV = new THREE.Vector2( 0.5, 0.5 );
  18264. this.vertices.push(center);
  18265. uvs.push( centerUV );
  18266. for ( i = 0; i <= segments; i ++ ) {
  18267. var vertex = new THREE.Vector3();
  18268. var segment = thetaStart + i / segments * thetaLength;
  18269. vertex.x = radius * Math.cos( segment );
  18270. vertex.y = radius * Math.sin( segment );
  18271. this.vertices.push( vertex );
  18272. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, ( vertex.y / radius + 1 ) / 2 ) );
  18273. }
  18274. var n = new THREE.Vector3( 0, 0, 1 );
  18275. for ( i = 1; i <= segments; i ++ ) {
  18276. this.faces.push( new THREE.Face3( i, i + 1, 0, [ n.clone(), n.clone(), n.clone() ] ) );
  18277. this.faceVertexUvs[ 0 ].push( [ uvs[ i ].clone(), uvs[ i + 1 ].clone(), centerUV.clone() ] );
  18278. }
  18279. this.computeFaceNormals();
  18280. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  18281. };
  18282. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18283. THREE.CircleGeometry.prototype.constructor = THREE.CircleGeometry;
  18284. // File:src/extras/geometries/CubeGeometry.js
  18285. /**
  18286. * @author mrdoob / http://mrdoob.com/
  18287. */
  18288. THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  18289. THREE.warn( 'THREE.CubeGeometry has been renamed to THREE.BoxGeometry.' );
  18290. return new THREE.BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments );
  18291. };
  18292. // File:src/extras/geometries/CylinderGeometry.js
  18293. /**
  18294. * @author mrdoob / http://mrdoob.com/
  18295. */
  18296. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  18297. THREE.Geometry.call( this );
  18298. this.type = 'CylinderGeometry';
  18299. this.parameters = {
  18300. radiusTop: radiusTop,
  18301. radiusBottom: radiusBottom,
  18302. height: height,
  18303. radialSegments: radialSegments,
  18304. heightSegments: heightSegments,
  18305. openEnded: openEnded,
  18306. thetaStart: thetaStart,
  18307. thetaLength: thetaLength
  18308. };
  18309. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  18310. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  18311. height = height !== undefined ? height : 100;
  18312. radialSegments = radialSegments || 8;
  18313. heightSegments = heightSegments || 1;
  18314. openEnded = openEnded !== undefined ? openEnded : false;
  18315. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18316. thetaLength = thetaLength !== undefined ? thetaLength : 2 * Math.PI;
  18317. var heightHalf = height / 2;
  18318. var x, y, vertices = [], uvs = [];
  18319. for ( y = 0; y <= heightSegments; y ++ ) {
  18320. var verticesRow = [];
  18321. var uvsRow = [];
  18322. var v = y / heightSegments;
  18323. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  18324. for ( x = 0; x <= radialSegments; x ++ ) {
  18325. var u = x / radialSegments;
  18326. var vertex = new THREE.Vector3();
  18327. vertex.x = radius * Math.sin( u * thetaLength + thetaStart );
  18328. vertex.y = - v * height + heightHalf;
  18329. vertex.z = radius * Math.cos( u * thetaLength + thetaStart );
  18330. this.vertices.push( vertex );
  18331. verticesRow.push( this.vertices.length - 1 );
  18332. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  18333. }
  18334. vertices.push( verticesRow );
  18335. uvs.push( uvsRow );
  18336. }
  18337. var tanTheta = ( radiusBottom - radiusTop ) / height;
  18338. var na, nb;
  18339. for ( x = 0; x < radialSegments; x ++ ) {
  18340. if ( radiusTop !== 0 ) {
  18341. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  18342. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  18343. } else {
  18344. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  18345. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  18346. }
  18347. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  18348. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  18349. for ( y = 0; y < heightSegments; y ++ ) {
  18350. var v1 = vertices[ y ][ x ];
  18351. var v2 = vertices[ y + 1 ][ x ];
  18352. var v3 = vertices[ y + 1 ][ x + 1 ];
  18353. var v4 = vertices[ y ][ x + 1 ];
  18354. var n1 = na.clone();
  18355. var n2 = na.clone();
  18356. var n3 = nb.clone();
  18357. var n4 = nb.clone();
  18358. var uv1 = uvs[ y ][ x ].clone();
  18359. var uv2 = uvs[ y + 1 ][ x ].clone();
  18360. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  18361. var uv4 = uvs[ y ][ x + 1 ].clone();
  18362. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  18363. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  18364. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  18365. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  18366. }
  18367. }
  18368. // top cap
  18369. if ( openEnded === false && radiusTop > 0 ) {
  18370. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  18371. for ( x = 0; x < radialSegments; x ++ ) {
  18372. var v1 = vertices[ 0 ][ x ];
  18373. var v2 = vertices[ 0 ][ x + 1 ];
  18374. var v3 = this.vertices.length - 1;
  18375. var n1 = new THREE.Vector3( 0, 1, 0 );
  18376. var n2 = new THREE.Vector3( 0, 1, 0 );
  18377. var n3 = new THREE.Vector3( 0, 1, 0 );
  18378. var uv1 = uvs[ 0 ][ x ].clone();
  18379. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  18380. var uv3 = new THREE.Vector2( uv2.x, 0 );
  18381. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18382. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18383. }
  18384. }
  18385. // bottom cap
  18386. if ( openEnded === false && radiusBottom > 0 ) {
  18387. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  18388. for ( x = 0; x < radialSegments; x ++ ) {
  18389. var v1 = vertices[ heightSegments ][ x + 1 ];
  18390. var v2 = vertices[ heightSegments ][ x ];
  18391. var v3 = this.vertices.length - 1;
  18392. var n1 = new THREE.Vector3( 0, - 1, 0 );
  18393. var n2 = new THREE.Vector3( 0, - 1, 0 );
  18394. var n3 = new THREE.Vector3( 0, - 1, 0 );
  18395. var uv1 = uvs[ heightSegments ][ x + 1 ].clone();
  18396. var uv2 = uvs[ heightSegments ][ x ].clone();
  18397. var uv3 = new THREE.Vector2( uv2.x, 1 );
  18398. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18399. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18400. }
  18401. }
  18402. this.computeFaceNormals();
  18403. };
  18404. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18405. THREE.CylinderGeometry.prototype.constructor = THREE.CylinderGeometry;
  18406. // File:src/extras/geometries/ExtrudeGeometry.js
  18407. /**
  18408. * @author zz85 / http://www.lab4games.net/zz85/blog
  18409. *
  18410. * Creates extruded geometry from a path shape.
  18411. *
  18412. * parameters = {
  18413. *
  18414. * curveSegments: <int>, // number of points on the curves
  18415. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  18416. * amount: <int>, // Depth to extrude the shape
  18417. *
  18418. * bevelEnabled: <bool>, // turn on bevel
  18419. * bevelThickness: <float>, // how deep into the original shape bevel goes
  18420. * bevelSize: <float>, // how far from shape outline is bevel
  18421. * bevelSegments: <int>, // number of bevel layers
  18422. *
  18423. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  18424. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  18425. *
  18426. * material: <int> // material index for front and back faces
  18427. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  18428. * uvGenerator: <Object> // object that provides UV generator functions
  18429. *
  18430. * }
  18431. **/
  18432. THREE.ExtrudeGeometry = function ( shapes, options ) {
  18433. if ( typeof( shapes ) === "undefined" ) {
  18434. shapes = [];
  18435. return;
  18436. }
  18437. THREE.Geometry.call( this );
  18438. this.type = 'ExtrudeGeometry';
  18439. shapes = shapes instanceof Array ? shapes : [ shapes ];
  18440. this.addShapeList( shapes, options );
  18441. this.computeFaceNormals();
  18442. // can't really use automatic vertex normals
  18443. // as then front and back sides get smoothed too
  18444. // should do separate smoothing just for sides
  18445. //this.computeVertexNormals();
  18446. //console.log( "took", ( Date.now() - startTime ) );
  18447. };
  18448. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18449. THREE.ExtrudeGeometry.prototype.constructor = THREE.ExtrudeGeometry;
  18450. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18451. var sl = shapes.length;
  18452. for ( var s = 0; s < sl; s ++ ) {
  18453. var shape = shapes[ s ];
  18454. this.addShape( shape, options );
  18455. }
  18456. };
  18457. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  18458. var amount = options.amount !== undefined ? options.amount : 100;
  18459. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  18460. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  18461. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18462. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  18463. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18464. var steps = options.steps !== undefined ? options.steps : 1;
  18465. var extrudePath = options.extrudePath;
  18466. var extrudePts, extrudeByPath = false;
  18467. var material = options.material;
  18468. var extrudeMaterial = options.extrudeMaterial;
  18469. // Use default WorldUVGenerator if no UV generators are specified.
  18470. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  18471. var splineTube, binormal, normal, position2;
  18472. if ( extrudePath ) {
  18473. extrudePts = extrudePath.getSpacedPoints( steps );
  18474. extrudeByPath = true;
  18475. bevelEnabled = false; // bevels not supported for path extrusion
  18476. // SETUP TNB variables
  18477. // Reuse TNB from TubeGeomtry for now.
  18478. // TODO1 - have a .isClosed in spline?
  18479. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  18480. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18481. binormal = new THREE.Vector3();
  18482. normal = new THREE.Vector3();
  18483. position2 = new THREE.Vector3();
  18484. }
  18485. // Safeguards if bevels are not enabled
  18486. if ( ! bevelEnabled ) {
  18487. bevelSegments = 0;
  18488. bevelThickness = 0;
  18489. bevelSize = 0;
  18490. }
  18491. // Variables initalization
  18492. var ahole, h, hl; // looping of holes
  18493. var scope = this;
  18494. var shapesOffset = this.vertices.length;
  18495. var shapePoints = shape.extractPoints( curveSegments );
  18496. var vertices = shapePoints.shape;
  18497. var holes = shapePoints.holes;
  18498. var reverse = ! THREE.Shape.Utils.isClockWise( vertices ) ;
  18499. if ( reverse ) {
  18500. vertices = vertices.reverse();
  18501. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18502. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18503. ahole = holes[ h ];
  18504. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  18505. holes[ h ] = ahole.reverse();
  18506. }
  18507. }
  18508. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  18509. }
  18510. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  18511. /* Vertices */
  18512. var contour = vertices; // vertices has all points but contour has only points of circumference
  18513. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18514. ahole = holes[ h ];
  18515. vertices = vertices.concat( ahole );
  18516. }
  18517. function scalePt2 ( pt, vec, size ) {
  18518. if ( ! vec ) THREE.error( "THREE.ExtrudeGeometry: vec does not exist" );
  18519. return vec.clone().multiplyScalar( size ).add( pt );
  18520. }
  18521. var b, bs, t, z,
  18522. vert, vlen = vertices.length,
  18523. face, flen = faces.length;
  18524. // Find directions for point movement
  18525. function getBevelVec( inPt, inPrev, inNext ) {
  18526. var EPSILON = 0.0000000001;
  18527. // computes for inPt the corresponding point inPt' on a new contour
  18528. // shiftet by 1 unit (length of normalized vector) to the left
  18529. // if we walk along contour clockwise, this new contour is outside the old one
  18530. //
  18531. // inPt' is the intersection of the two lines parallel to the two
  18532. // adjacent edges of inPt at a distance of 1 unit on the left side.
  18533. var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt
  18534. // good reading for geometry algorithms (here: line-line intersection)
  18535. // http://geomalgorithms.com/a05-_intersect-1.html
  18536. var v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y;
  18537. var v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y;
  18538. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  18539. // check for colinear edges
  18540. var colinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  18541. if ( Math.abs( colinear0 ) > EPSILON ) { // not colinear
  18542. // length of vectors for normalizing
  18543. var v_prev_len = Math.sqrt( v_prev_lensq );
  18544. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  18545. // shift adjacent points by unit vectors to the left
  18546. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  18547. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  18548. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  18549. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  18550. // scaling factor for v_prev to intersection point
  18551. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  18552. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  18553. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  18554. // vector from inPt to intersection point
  18555. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  18556. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  18557. // Don't normalize!, otherwise sharp corners become ugly
  18558. // but prevent crazy spikes
  18559. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y )
  18560. if ( v_trans_lensq <= 2 ) {
  18561. return new THREE.Vector2( v_trans_x, v_trans_y );
  18562. } else {
  18563. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  18564. }
  18565. } else { // handle special case of colinear edges
  18566. var direction_eq = false; // assumes: opposite
  18567. if ( v_prev_x > EPSILON ) {
  18568. if ( v_next_x > EPSILON ) { direction_eq = true; }
  18569. } else {
  18570. if ( v_prev_x < - EPSILON ) {
  18571. if ( v_next_x < - EPSILON ) { direction_eq = true; }
  18572. } else {
  18573. if ( Math.sign(v_prev_y) == Math.sign(v_next_y) ) { direction_eq = true; }
  18574. }
  18575. }
  18576. if ( direction_eq ) {
  18577. // console.log("Warning: lines are a straight sequence");
  18578. v_trans_x = - v_prev_y;
  18579. v_trans_y = v_prev_x;
  18580. shrink_by = Math.sqrt( v_prev_lensq );
  18581. } else {
  18582. // console.log("Warning: lines are a straight spike");
  18583. v_trans_x = v_prev_x;
  18584. v_trans_y = v_prev_y;
  18585. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  18586. }
  18587. }
  18588. return new THREE.Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  18589. }
  18590. var contourMovements = [];
  18591. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18592. if ( j === il ) j = 0;
  18593. if ( k === il ) k = 0;
  18594. // (j)---(i)---(k)
  18595. // console.log('i,j,k', i, j , k)
  18596. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  18597. }
  18598. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  18599. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18600. ahole = holes[ h ];
  18601. oneHoleMovements = [];
  18602. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18603. if ( j === il ) j = 0;
  18604. if ( k === il ) k = 0;
  18605. // (j)---(i)---(k)
  18606. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  18607. }
  18608. holesMovements.push( oneHoleMovements );
  18609. verticesMovements = verticesMovements.concat( oneHoleMovements );
  18610. }
  18611. // Loop bevelSegments, 1 for the front, 1 for the back
  18612. for ( b = 0; b < bevelSegments; b ++ ) {
  18613. //for ( b = bevelSegments; b > 0; b -- ) {
  18614. t = b / bevelSegments;
  18615. z = bevelThickness * ( 1 - t );
  18616. //z = bevelThickness * t;
  18617. bs = bevelSize * ( Math.sin ( t * Math.PI / 2 ) ) ; // curved
  18618. //bs = bevelSize * t ; // linear
  18619. // contract shape
  18620. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18621. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18622. v( vert.x, vert.y, - z );
  18623. }
  18624. // expand holes
  18625. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18626. ahole = holes[ h ];
  18627. oneHoleMovements = holesMovements[ h ];
  18628. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  18629. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18630. v( vert.x, vert.y, - z );
  18631. }
  18632. }
  18633. }
  18634. bs = bevelSize;
  18635. // Back facing vertices
  18636. for ( i = 0; i < vlen; i ++ ) {
  18637. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18638. if ( ! extrudeByPath ) {
  18639. v( vert.x, vert.y, 0 );
  18640. } else {
  18641. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  18642. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  18643. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  18644. position2.copy( extrudePts[0] ).add(normal).add(binormal);
  18645. v( position2.x, position2.y, position2.z );
  18646. }
  18647. }
  18648. // Add stepped vertices...
  18649. // Including front facing vertices
  18650. var s;
  18651. for ( s = 1; s <= steps; s ++ ) {
  18652. for ( i = 0; i < vlen; i ++ ) {
  18653. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18654. if ( ! extrudeByPath ) {
  18655. v( vert.x, vert.y, amount / steps * s );
  18656. } else {
  18657. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  18658. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  18659. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  18660. position2.copy( extrudePts[s] ).add( normal ).add( binormal );
  18661. v( position2.x, position2.y, position2.z );
  18662. }
  18663. }
  18664. }
  18665. // Add bevel segments planes
  18666. //for ( b = 1; b <= bevelSegments; b ++ ) {
  18667. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  18668. t = b / bevelSegments;
  18669. z = bevelThickness * ( 1 - t );
  18670. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  18671. bs = bevelSize * Math.sin ( t * Math.PI / 2 ) ;
  18672. // contract shape
  18673. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18674. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18675. v( vert.x, vert.y, amount + z );
  18676. }
  18677. // expand holes
  18678. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18679. ahole = holes[ h ];
  18680. oneHoleMovements = holesMovements[ h ];
  18681. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  18682. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18683. if ( ! extrudeByPath ) {
  18684. v( vert.x, vert.y, amount + z );
  18685. } else {
  18686. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  18687. }
  18688. }
  18689. }
  18690. }
  18691. /* Faces */
  18692. // Top and bottom faces
  18693. buildLidFaces();
  18694. // Sides faces
  18695. buildSideFaces();
  18696. ///// Internal functions
  18697. function buildLidFaces() {
  18698. if ( bevelEnabled ) {
  18699. var layer = 0 ; // steps + 1
  18700. var offset = vlen * layer;
  18701. // Bottom faces
  18702. for ( i = 0; i < flen; i ++ ) {
  18703. face = faces[ i ];
  18704. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  18705. }
  18706. layer = steps + bevelSegments * 2;
  18707. offset = vlen * layer;
  18708. // Top faces
  18709. for ( i = 0; i < flen; i ++ ) {
  18710. face = faces[ i ];
  18711. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  18712. }
  18713. } else {
  18714. // Bottom faces
  18715. for ( i = 0; i < flen; i ++ ) {
  18716. face = faces[ i ];
  18717. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  18718. }
  18719. // Top faces
  18720. for ( i = 0; i < flen; i ++ ) {
  18721. face = faces[ i ];
  18722. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  18723. }
  18724. }
  18725. }
  18726. // Create faces for the z-sides of the shape
  18727. function buildSideFaces() {
  18728. var layeroffset = 0;
  18729. sidewalls( contour, layeroffset );
  18730. layeroffset += contour.length;
  18731. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18732. ahole = holes[ h ];
  18733. sidewalls( ahole, layeroffset );
  18734. //, true
  18735. layeroffset += ahole.length;
  18736. }
  18737. }
  18738. function sidewalls( contour, layeroffset ) {
  18739. var j, k;
  18740. i = contour.length;
  18741. while ( -- i >= 0 ) {
  18742. j = i;
  18743. k = i - 1;
  18744. if ( k < 0 ) k = contour.length - 1;
  18745. //console.log('b', i,j, i-1, k,vertices.length);
  18746. var s = 0, sl = steps + bevelSegments * 2;
  18747. for ( s = 0; s < sl; s ++ ) {
  18748. var slen1 = vlen * s;
  18749. var slen2 = vlen * ( s + 1 );
  18750. var a = layeroffset + j + slen1,
  18751. b = layeroffset + k + slen1,
  18752. c = layeroffset + k + slen2,
  18753. d = layeroffset + j + slen2;
  18754. f4( a, b, c, d, contour, s, sl, j, k );
  18755. }
  18756. }
  18757. }
  18758. function v( x, y, z ) {
  18759. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  18760. }
  18761. function f3( a, b, c ) {
  18762. a += shapesOffset;
  18763. b += shapesOffset;
  18764. c += shapesOffset;
  18765. // normal, color, material
  18766. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  18767. var uvs = uvgen.generateTopUV( scope, a, b, c );
  18768. scope.faceVertexUvs[ 0 ].push( uvs );
  18769. }
  18770. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  18771. a += shapesOffset;
  18772. b += shapesOffset;
  18773. c += shapesOffset;
  18774. d += shapesOffset;
  18775. scope.faces.push( new THREE.Face3( a, b, d, null, null, extrudeMaterial ) );
  18776. scope.faces.push( new THREE.Face3( b, c, d, null, null, extrudeMaterial ) );
  18777. var uvs = uvgen.generateSideWallUV( scope, a, b, c, d );
  18778. scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] );
  18779. scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] );
  18780. }
  18781. };
  18782. THREE.ExtrudeGeometry.WorldUVGenerator = {
  18783. generateTopUV: function ( geometry, indexA, indexB, indexC ) {
  18784. var vertices = geometry.vertices;
  18785. var a = vertices[ indexA ];
  18786. var b = vertices[ indexB ];
  18787. var c = vertices[ indexC ];
  18788. return [
  18789. new THREE.Vector2( a.x, a.y ),
  18790. new THREE.Vector2( b.x, b.y ),
  18791. new THREE.Vector2( c.x, c.y )
  18792. ];
  18793. },
  18794. generateSideWallUV: function ( geometry, indexA, indexB, indexC, indexD ) {
  18795. var vertices = geometry.vertices;
  18796. var a = vertices[ indexA ];
  18797. var b = vertices[ indexB ];
  18798. var c = vertices[ indexC ];
  18799. var d = vertices[ indexD ];
  18800. if ( Math.abs( a.y - b.y ) < 0.01 ) {
  18801. return [
  18802. new THREE.Vector2( a.x, 1 - a.z ),
  18803. new THREE.Vector2( b.x, 1 - b.z ),
  18804. new THREE.Vector2( c.x, 1 - c.z ),
  18805. new THREE.Vector2( d.x, 1 - d.z )
  18806. ];
  18807. } else {
  18808. return [
  18809. new THREE.Vector2( a.y, 1 - a.z ),
  18810. new THREE.Vector2( b.y, 1 - b.z ),
  18811. new THREE.Vector2( c.y, 1 - c.z ),
  18812. new THREE.Vector2( d.y, 1 - d.z )
  18813. ];
  18814. }
  18815. }
  18816. };
  18817. // File:src/extras/geometries/ShapeGeometry.js
  18818. /**
  18819. * @author jonobr1 / http://jonobr1.com
  18820. *
  18821. * Creates a one-sided polygonal geometry from a path shape. Similar to
  18822. * ExtrudeGeometry.
  18823. *
  18824. * parameters = {
  18825. *
  18826. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  18827. *
  18828. * material: <int> // material index for front and back faces
  18829. * uvGenerator: <Object> // object that provides UV generator functions
  18830. *
  18831. * }
  18832. **/
  18833. THREE.ShapeGeometry = function ( shapes, options ) {
  18834. THREE.Geometry.call( this );
  18835. this.type = 'ShapeGeometry';
  18836. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  18837. this.addShapeList( shapes, options );
  18838. this.computeFaceNormals();
  18839. };
  18840. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18841. THREE.ShapeGeometry.prototype.constructor = THREE.ShapeGeometry;
  18842. /**
  18843. * Add an array of shapes to THREE.ShapeGeometry.
  18844. */
  18845. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18846. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  18847. this.addShape( shapes[ i ], options );
  18848. }
  18849. return this;
  18850. };
  18851. /**
  18852. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  18853. */
  18854. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  18855. if ( options === undefined ) options = {};
  18856. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18857. var material = options.material;
  18858. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  18859. //
  18860. var i, l, hole;
  18861. var shapesOffset = this.vertices.length;
  18862. var shapePoints = shape.extractPoints( curveSegments );
  18863. var vertices = shapePoints.shape;
  18864. var holes = shapePoints.holes;
  18865. var reverse = ! THREE.Shape.Utils.isClockWise( vertices );
  18866. if ( reverse ) {
  18867. vertices = vertices.reverse();
  18868. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  18869. for ( i = 0, l = holes.length; i < l; i ++ ) {
  18870. hole = holes[ i ];
  18871. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  18872. holes[ i ] = hole.reverse();
  18873. }
  18874. }
  18875. reverse = false;
  18876. }
  18877. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  18878. // Vertices
  18879. var contour = vertices;
  18880. for ( i = 0, l = holes.length; i < l; i ++ ) {
  18881. hole = holes[ i ];
  18882. vertices = vertices.concat( hole );
  18883. }
  18884. //
  18885. var vert, vlen = vertices.length;
  18886. var face, flen = faces.length;
  18887. for ( i = 0; i < vlen; i ++ ) {
  18888. vert = vertices[ i ];
  18889. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  18890. }
  18891. for ( i = 0; i < flen; i ++ ) {
  18892. face = faces[ i ];
  18893. var a = face[ 0 ] + shapesOffset;
  18894. var b = face[ 1 ] + shapesOffset;
  18895. var c = face[ 2 ] + shapesOffset;
  18896. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  18897. this.faceVertexUvs[ 0 ].push( uvgen.generateTopUV( this, a, b, c ) );
  18898. }
  18899. };
  18900. // File:src/extras/geometries/LatheGeometry.js
  18901. /**
  18902. * @author astrodud / http://astrodud.isgreat.org/
  18903. * @author zz85 / https://github.com/zz85
  18904. * @author bhouston / http://exocortex.com
  18905. */
  18906. // points - to create a closed torus, one must use a set of points
  18907. // like so: [ a, b, c, d, a ], see first is the same as last.
  18908. // segments - the number of circumference segments to create
  18909. // phiStart - the starting radian
  18910. // phiLength - the radian (0 to 2*PI) range of the lathed section
  18911. // 2*pi is a closed lathe, less than 2PI is a portion.
  18912. THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
  18913. THREE.Geometry.call( this );
  18914. this.type = 'LatheGeometry';
  18915. this.parameters = {
  18916. points: points,
  18917. segments: segments,
  18918. phiStart: phiStart,
  18919. phiLength: phiLength
  18920. };
  18921. segments = segments || 12;
  18922. phiStart = phiStart || 0;
  18923. phiLength = phiLength || 2 * Math.PI;
  18924. var inversePointLength = 1.0 / ( points.length - 1 );
  18925. var inverseSegments = 1.0 / segments;
  18926. for ( var i = 0, il = segments; i <= il; i ++ ) {
  18927. var phi = phiStart + i * inverseSegments * phiLength;
  18928. var c = Math.cos( phi ),
  18929. s = Math.sin( phi );
  18930. for ( var j = 0, jl = points.length; j < jl; j ++ ) {
  18931. var pt = points[ j ];
  18932. var vertex = new THREE.Vector3();
  18933. vertex.x = c * pt.x - s * pt.y;
  18934. vertex.y = s * pt.x + c * pt.y;
  18935. vertex.z = pt.z;
  18936. this.vertices.push( vertex );
  18937. }
  18938. }
  18939. var np = points.length;
  18940. for ( var i = 0, il = segments; i < il; i ++ ) {
  18941. for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) {
  18942. var base = j + np * i;
  18943. var a = base;
  18944. var b = base + np;
  18945. var c = base + 1 + np;
  18946. var d = base + 1;
  18947. var u0 = i * inverseSegments;
  18948. var v0 = j * inversePointLength;
  18949. var u1 = u0 + inverseSegments;
  18950. var v1 = v0 + inversePointLength;
  18951. this.faces.push( new THREE.Face3( a, b, d ) );
  18952. this.faceVertexUvs[ 0 ].push( [
  18953. new THREE.Vector2( u0, v0 ),
  18954. new THREE.Vector2( u1, v0 ),
  18955. new THREE.Vector2( u0, v1 )
  18956. ] );
  18957. this.faces.push( new THREE.Face3( b, c, d ) );
  18958. this.faceVertexUvs[ 0 ].push( [
  18959. new THREE.Vector2( u1, v0 ),
  18960. new THREE.Vector2( u1, v1 ),
  18961. new THREE.Vector2( u0, v1 )
  18962. ] );
  18963. }
  18964. }
  18965. this.mergeVertices();
  18966. this.computeFaceNormals();
  18967. this.computeVertexNormals();
  18968. };
  18969. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18970. THREE.LatheGeometry.prototype.constructor = THREE.LatheGeometry;
  18971. // File:src/extras/geometries/PlaneGeometry.js
  18972. /**
  18973. * @author mrdoob / http://mrdoob.com/
  18974. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  18975. */
  18976. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  18977. console.info( 'THREE.PlaneGeometry: Consider using THREE.PlaneBufferGeometry for lower memory footprint.' );
  18978. THREE.Geometry.call( this );
  18979. this.type = 'PlaneGeometry';
  18980. this.parameters = {
  18981. width: width,
  18982. height: height,
  18983. widthSegments: widthSegments,
  18984. heightSegments: heightSegments
  18985. };
  18986. this.fromBufferGeometry( new THREE.PlaneBufferGeometry( width, height, widthSegments, heightSegments ) );
  18987. };
  18988. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18989. THREE.PlaneGeometry.prototype.constructor = THREE.PlaneGeometry;
  18990. // File:src/extras/geometries/PlaneBufferGeometry.js
  18991. /**
  18992. * @author mrdoob / http://mrdoob.com/
  18993. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  18994. */
  18995. THREE.PlaneBufferGeometry = function ( width, height, widthSegments, heightSegments ) {
  18996. THREE.BufferGeometry.call( this );
  18997. this.type = 'PlaneBufferGeometry';
  18998. this.parameters = {
  18999. width: width,
  19000. height: height,
  19001. widthSegments: widthSegments,
  19002. heightSegments: heightSegments
  19003. };
  19004. var width_half = width / 2;
  19005. var height_half = height / 2;
  19006. var gridX = widthSegments || 1;
  19007. var gridY = heightSegments || 1;
  19008. var gridX1 = gridX + 1;
  19009. var gridY1 = gridY + 1;
  19010. var segment_width = width / gridX;
  19011. var segment_height = height / gridY;
  19012. var vertices = new Float32Array( gridX1 * gridY1 * 3 );
  19013. var normals = new Float32Array( gridX1 * gridY1 * 3 );
  19014. var uvs = new Float32Array( gridX1 * gridY1 * 2 );
  19015. var offset = 0;
  19016. var offset2 = 0;
  19017. for ( var iy = 0; iy < gridY1; iy ++ ) {
  19018. var y = iy * segment_height - height_half;
  19019. for ( var ix = 0; ix < gridX1; ix ++ ) {
  19020. var x = ix * segment_width - width_half;
  19021. vertices[ offset ] = x;
  19022. vertices[ offset + 1 ] = - y;
  19023. normals[ offset + 2 ] = 1;
  19024. uvs[ offset2 ] = ix / gridX;
  19025. uvs[ offset2 + 1 ] = 1 - ( iy / gridY );
  19026. offset += 3;
  19027. offset2 += 2;
  19028. }
  19029. }
  19030. offset = 0;
  19031. var indices = new ( ( vertices.length / 3 ) > 65535 ? Uint32Array : Uint16Array )( gridX * gridY * 6 );
  19032. for ( var iy = 0; iy < gridY; iy ++ ) {
  19033. for ( var ix = 0; ix < gridX; ix ++ ) {
  19034. var a = ix + gridX1 * iy;
  19035. var b = ix + gridX1 * ( iy + 1 );
  19036. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  19037. var d = ( ix + 1 ) + gridX1 * iy;
  19038. indices[ offset ] = a;
  19039. indices[ offset + 1 ] = b;
  19040. indices[ offset + 2 ] = d;
  19041. indices[ offset + 3 ] = b;
  19042. indices[ offset + 4 ] = c;
  19043. indices[ offset + 5 ] = d;
  19044. offset += 6;
  19045. }
  19046. }
  19047. this.addAttribute( 'index', new THREE.BufferAttribute( indices, 1 ) );
  19048. this.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  19049. this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
  19050. this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) );
  19051. };
  19052. THREE.PlaneBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  19053. THREE.PlaneBufferGeometry.prototype.constructor = THREE.PlaneBufferGeometry;
  19054. // File:src/extras/geometries/RingGeometry.js
  19055. /**
  19056. * @author Kaleb Murphy
  19057. */
  19058. THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  19059. THREE.Geometry.call( this );
  19060. this.type = 'RingGeometry';
  19061. this.parameters = {
  19062. innerRadius: innerRadius,
  19063. outerRadius: outerRadius,
  19064. thetaSegments: thetaSegments,
  19065. phiSegments: phiSegments,
  19066. thetaStart: thetaStart,
  19067. thetaLength: thetaLength
  19068. };
  19069. innerRadius = innerRadius || 0;
  19070. outerRadius = outerRadius || 50;
  19071. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19072. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19073. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  19074. phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 8;
  19075. var i, o, uvs = [], radius = innerRadius, radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  19076. for ( i = 0; i < phiSegments + 1; i ++ ) { // concentric circles inside ring
  19077. for ( o = 0; o < thetaSegments + 1; o ++ ) { // number of segments per circle
  19078. var vertex = new THREE.Vector3();
  19079. var segment = thetaStart + o / thetaSegments * thetaLength;
  19080. vertex.x = radius * Math.cos( segment );
  19081. vertex.y = radius * Math.sin( segment );
  19082. this.vertices.push( vertex );
  19083. uvs.push( new THREE.Vector2( ( vertex.x / outerRadius + 1 ) / 2, ( vertex.y / outerRadius + 1 ) / 2 ) );
  19084. }
  19085. radius += radiusStep;
  19086. }
  19087. var n = new THREE.Vector3( 0, 0, 1 );
  19088. for ( i = 0; i < phiSegments; i ++ ) { // concentric circles inside ring
  19089. var thetaSegment = i * (thetaSegments + 1);
  19090. for ( o = 0; o < thetaSegments ; o ++ ) { // number of segments per circle
  19091. var segment = o + thetaSegment;
  19092. var v1 = segment;
  19093. var v2 = segment + thetaSegments + 1;
  19094. var v3 = segment + thetaSegments + 2;
  19095. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  19096. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]);
  19097. v1 = segment;
  19098. v2 = segment + thetaSegments + 2;
  19099. v3 = segment + 1;
  19100. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  19101. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]);
  19102. }
  19103. }
  19104. this.computeFaceNormals();
  19105. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19106. };
  19107. THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19108. THREE.RingGeometry.prototype.constructor = THREE.RingGeometry;
  19109. // File:src/extras/geometries/SphereGeometry.js
  19110. /**
  19111. * @author mrdoob / http://mrdoob.com/
  19112. */
  19113. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  19114. THREE.Geometry.call( this );
  19115. this.type = 'SphereGeometry';
  19116. this.parameters = {
  19117. radius: radius,
  19118. widthSegments: widthSegments,
  19119. heightSegments: heightSegments,
  19120. phiStart: phiStart,
  19121. phiLength: phiLength,
  19122. thetaStart: thetaStart,
  19123. thetaLength: thetaLength
  19124. };
  19125. radius = radius || 50;
  19126. widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  19127. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  19128. phiStart = phiStart !== undefined ? phiStart : 0;
  19129. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19130. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19131. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19132. var x, y, vertices = [], uvs = [];
  19133. for ( y = 0; y <= heightSegments; y ++ ) {
  19134. var verticesRow = [];
  19135. var uvsRow = [];
  19136. for ( x = 0; x <= widthSegments; x ++ ) {
  19137. var u = x / widthSegments;
  19138. var v = y / heightSegments;
  19139. var vertex = new THREE.Vector3();
  19140. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19141. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  19142. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19143. this.vertices.push( vertex );
  19144. verticesRow.push( this.vertices.length - 1 );
  19145. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19146. }
  19147. vertices.push( verticesRow );
  19148. uvs.push( uvsRow );
  19149. }
  19150. for ( y = 0; y < heightSegments; y ++ ) {
  19151. for ( x = 0; x < widthSegments; x ++ ) {
  19152. var v1 = vertices[ y ][ x + 1 ];
  19153. var v2 = vertices[ y ][ x ];
  19154. var v3 = vertices[ y + 1 ][ x ];
  19155. var v4 = vertices[ y + 1 ][ x + 1 ];
  19156. var n1 = this.vertices[ v1 ].clone().normalize();
  19157. var n2 = this.vertices[ v2 ].clone().normalize();
  19158. var n3 = this.vertices[ v3 ].clone().normalize();
  19159. var n4 = this.vertices[ v4 ].clone().normalize();
  19160. var uv1 = uvs[ y ][ x + 1 ].clone();
  19161. var uv2 = uvs[ y ][ x ].clone();
  19162. var uv3 = uvs[ y + 1 ][ x ].clone();
  19163. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  19164. if ( Math.abs( this.vertices[ v1 ].y ) === radius ) {
  19165. uv1.x = ( uv1.x + uv2.x ) / 2;
  19166. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  19167. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  19168. } else if ( Math.abs( this.vertices[ v3 ].y ) === radius ) {
  19169. uv3.x = ( uv3.x + uv4.x ) / 2;
  19170. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19171. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19172. } else {
  19173. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  19174. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  19175. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  19176. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  19177. }
  19178. }
  19179. }
  19180. this.computeFaceNormals();
  19181. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19182. };
  19183. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19184. THREE.SphereGeometry.prototype.constructor = THREE.SphereGeometry;
  19185. // File:src/extras/geometries/TextGeometry.js
  19186. /**
  19187. * @author zz85 / http://www.lab4games.net/zz85/blog
  19188. * @author alteredq / http://alteredqualia.com/
  19189. *
  19190. * For creating 3D text geometry in three.js
  19191. *
  19192. * Text = 3D Text
  19193. *
  19194. * parameters = {
  19195. * size: <float>, // size of the text
  19196. * height: <float>, // thickness to extrude text
  19197. * curveSegments: <int>, // number of points on the curves
  19198. *
  19199. * font: <string>, // font name
  19200. * weight: <string>, // font weight (normal, bold)
  19201. * style: <string>, // font style (normal, italics)
  19202. *
  19203. * bevelEnabled: <bool>, // turn on bevel
  19204. * bevelThickness: <float>, // how deep into text bevel goes
  19205. * bevelSize: <float>, // how far from text outline is bevel
  19206. * }
  19207. *
  19208. */
  19209. /* Usage Examples
  19210. // TextGeometry wrapper
  19211. var text3d = new TextGeometry( text, options );
  19212. // Complete manner
  19213. var textShapes = THREE.FontUtils.generateShapes( text, options );
  19214. var text3d = new ExtrudeGeometry( textShapes, options );
  19215. */
  19216. THREE.TextGeometry = function ( text, parameters ) {
  19217. parameters = parameters || {};
  19218. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  19219. // translate parameters to ExtrudeGeometry API
  19220. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  19221. // defaults
  19222. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  19223. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  19224. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  19225. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  19226. this.type = 'TextGeometry';
  19227. };
  19228. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  19229. THREE.TextGeometry.prototype.constructor = THREE.TextGeometry;
  19230. // File:src/extras/geometries/TorusGeometry.js
  19231. /**
  19232. * @author oosmoxiecode
  19233. * @author mrdoob / http://mrdoob.com/
  19234. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  19235. */
  19236. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  19237. THREE.Geometry.call( this );
  19238. this.type = 'TorusGeometry';
  19239. this.parameters = {
  19240. radius: radius,
  19241. tube: tube,
  19242. radialSegments: radialSegments,
  19243. tubularSegments: tubularSegments,
  19244. arc: arc
  19245. };
  19246. radius = radius || 100;
  19247. tube = tube || 40;
  19248. radialSegments = radialSegments || 8;
  19249. tubularSegments = tubularSegments || 6;
  19250. arc = arc || Math.PI * 2;
  19251. var center = new THREE.Vector3(), uvs = [], normals = [];
  19252. for ( var j = 0; j <= radialSegments; j ++ ) {
  19253. for ( var i = 0; i <= tubularSegments; i ++ ) {
  19254. var u = i / tubularSegments * arc;
  19255. var v = j / radialSegments * Math.PI * 2;
  19256. center.x = radius * Math.cos( u );
  19257. center.y = radius * Math.sin( u );
  19258. var vertex = new THREE.Vector3();
  19259. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  19260. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  19261. vertex.z = tube * Math.sin( v );
  19262. this.vertices.push( vertex );
  19263. uvs.push( new THREE.Vector2( i / tubularSegments, j / radialSegments ) );
  19264. normals.push( vertex.clone().sub( center ).normalize() );
  19265. }
  19266. }
  19267. for ( var j = 1; j <= radialSegments; j ++ ) {
  19268. for ( var i = 1; i <= tubularSegments; i ++ ) {
  19269. var a = ( tubularSegments + 1 ) * j + i - 1;
  19270. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  19271. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  19272. var d = ( tubularSegments + 1 ) * j + i;
  19273. var face = new THREE.Face3( a, b, d, [ normals[ a ].clone(), normals[ b ].clone(), normals[ d ].clone() ] );
  19274. this.faces.push( face );
  19275. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ d ].clone() ] );
  19276. face = new THREE.Face3( b, c, d, [ normals[ b ].clone(), normals[ c ].clone(), normals[ d ].clone() ] );
  19277. this.faces.push( face );
  19278. this.faceVertexUvs[ 0 ].push( [ uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  19279. }
  19280. }
  19281. this.computeFaceNormals();
  19282. };
  19283. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19284. THREE.TorusGeometry.prototype.constructor = THREE.TorusGeometry;
  19285. // File:src/extras/geometries/TorusKnotGeometry.js
  19286. /**
  19287. * @author oosmoxiecode
  19288. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  19289. */
  19290. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  19291. THREE.Geometry.call( this );
  19292. this.type = 'TorusKnotGeometry';
  19293. this.parameters = {
  19294. radius: radius,
  19295. tube: tube,
  19296. radialSegments: radialSegments,
  19297. tubularSegments: tubularSegments,
  19298. p: p,
  19299. q: q,
  19300. heightScale: heightScale
  19301. };
  19302. radius = radius || 100;
  19303. tube = tube || 40;
  19304. radialSegments = radialSegments || 64;
  19305. tubularSegments = tubularSegments || 8;
  19306. p = p || 2;
  19307. q = q || 3;
  19308. heightScale = heightScale || 1;
  19309. var grid = new Array( radialSegments );
  19310. var tang = new THREE.Vector3();
  19311. var n = new THREE.Vector3();
  19312. var bitan = new THREE.Vector3();
  19313. for ( var i = 0; i < radialSegments; ++ i ) {
  19314. grid[ i ] = new Array( tubularSegments );
  19315. var u = i / radialSegments * 2 * p * Math.PI;
  19316. var p1 = getPos( u, q, p, radius, heightScale );
  19317. var p2 = getPos( u + 0.01, q, p, radius, heightScale );
  19318. tang.subVectors( p2, p1 );
  19319. n.addVectors( p2, p1 );
  19320. bitan.crossVectors( tang, n );
  19321. n.crossVectors( bitan, tang );
  19322. bitan.normalize();
  19323. n.normalize();
  19324. for ( var j = 0; j < tubularSegments; ++ j ) {
  19325. var v = j / tubularSegments * 2 * Math.PI;
  19326. var cx = - tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19327. var cy = tube * Math.sin( v );
  19328. var pos = new THREE.Vector3();
  19329. pos.x = p1.x + cx * n.x + cy * bitan.x;
  19330. pos.y = p1.y + cx * n.y + cy * bitan.y;
  19331. pos.z = p1.z + cx * n.z + cy * bitan.z;
  19332. grid[ i ][ j ] = this.vertices.push( pos ) - 1;
  19333. }
  19334. }
  19335. for ( var i = 0; i < radialSegments; ++ i ) {
  19336. for ( var j = 0; j < tubularSegments; ++ j ) {
  19337. var ip = ( i + 1 ) % radialSegments;
  19338. var jp = ( j + 1 ) % tubularSegments;
  19339. var a = grid[ i ][ j ];
  19340. var b = grid[ ip ][ j ];
  19341. var c = grid[ ip ][ jp ];
  19342. var d = grid[ i ][ jp ];
  19343. var uva = new THREE.Vector2( i / radialSegments, j / tubularSegments );
  19344. var uvb = new THREE.Vector2( ( i + 1 ) / radialSegments, j / tubularSegments );
  19345. var uvc = new THREE.Vector2( ( i + 1 ) / radialSegments, ( j + 1 ) / tubularSegments );
  19346. var uvd = new THREE.Vector2( i / radialSegments, ( j + 1 ) / tubularSegments );
  19347. this.faces.push( new THREE.Face3( a, b, d ) );
  19348. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19349. this.faces.push( new THREE.Face3( b, c, d ) );
  19350. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19351. }
  19352. }
  19353. this.computeFaceNormals();
  19354. this.computeVertexNormals();
  19355. function getPos( u, in_q, in_p, radius, heightScale ) {
  19356. var cu = Math.cos( u );
  19357. var su = Math.sin( u );
  19358. var quOverP = in_q / in_p * u;
  19359. var cs = Math.cos( quOverP );
  19360. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  19361. var ty = radius * ( 2 + cs ) * su * 0.5;
  19362. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  19363. return new THREE.Vector3( tx, ty, tz );
  19364. }
  19365. };
  19366. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19367. THREE.TorusKnotGeometry.prototype.constructor = THREE.TorusKnotGeometry;
  19368. // File:src/extras/geometries/TubeGeometry.js
  19369. /**
  19370. * @author WestLangley / https://github.com/WestLangley
  19371. * @author zz85 / https://github.com/zz85
  19372. * @author miningold / https://github.com/miningold
  19373. * @author jonobr1 / https://github.com/jonobr1
  19374. *
  19375. * Modified from the TorusKnotGeometry by @oosmoxiecode
  19376. *
  19377. * Creates a tube which extrudes along a 3d spline
  19378. *
  19379. * Uses parallel transport frames as described in
  19380. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  19381. */
  19382. THREE.TubeGeometry = function ( path, segments, radius, radialSegments, closed, taper ) {
  19383. THREE.Geometry.call( this );
  19384. this.type = 'TubeGeometry';
  19385. this.parameters = {
  19386. path: path,
  19387. segments: segments,
  19388. radius: radius,
  19389. radialSegments: radialSegments,
  19390. closed: closed
  19391. };
  19392. segments = segments || 64;
  19393. radius = radius || 1;
  19394. radialSegments = radialSegments || 8;
  19395. closed = closed || false;
  19396. taper = taper || THREE.TubeGeometry.NoTaper;
  19397. var grid = [];
  19398. var scope = this,
  19399. tangent,
  19400. normal,
  19401. binormal,
  19402. numpoints = segments + 1,
  19403. u, v, r,
  19404. cx, cy,
  19405. pos, pos2 = new THREE.Vector3(),
  19406. i, j,
  19407. ip, jp,
  19408. a, b, c, d,
  19409. uva, uvb, uvc, uvd;
  19410. var frames = new THREE.TubeGeometry.FrenetFrames( path, segments, closed ),
  19411. tangents = frames.tangents,
  19412. normals = frames.normals,
  19413. binormals = frames.binormals;
  19414. // proxy internals
  19415. this.tangents = tangents;
  19416. this.normals = normals;
  19417. this.binormals = binormals;
  19418. function vert( x, y, z ) {
  19419. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19420. }
  19421. // consruct the grid
  19422. for ( i = 0; i < numpoints; i ++ ) {
  19423. grid[ i ] = [];
  19424. u = i / ( numpoints - 1 );
  19425. pos = path.getPointAt( u );
  19426. tangent = tangents[ i ];
  19427. normal = normals[ i ];
  19428. binormal = binormals[ i ];
  19429. r = radius * taper( u );
  19430. for ( j = 0; j < radialSegments; j ++ ) {
  19431. v = j / radialSegments * 2 * Math.PI;
  19432. cx = - r * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19433. cy = r * Math.sin( v );
  19434. pos2.copy( pos );
  19435. pos2.x += cx * normal.x + cy * binormal.x;
  19436. pos2.y += cx * normal.y + cy * binormal.y;
  19437. pos2.z += cx * normal.z + cy * binormal.z;
  19438. grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  19439. }
  19440. }
  19441. // construct the mesh
  19442. for ( i = 0; i < segments; i ++ ) {
  19443. for ( j = 0; j < radialSegments; j ++ ) {
  19444. ip = ( closed ) ? (i + 1) % segments : i + 1;
  19445. jp = (j + 1) % radialSegments;
  19446. a = grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  19447. b = grid[ ip ][ j ];
  19448. c = grid[ ip ][ jp ];
  19449. d = grid[ i ][ jp ];
  19450. uva = new THREE.Vector2( i / segments, j / radialSegments );
  19451. uvb = new THREE.Vector2( ( i + 1 ) / segments, j / radialSegments );
  19452. uvc = new THREE.Vector2( ( i + 1 ) / segments, ( j + 1 ) / radialSegments );
  19453. uvd = new THREE.Vector2( i / segments, ( j + 1 ) / radialSegments );
  19454. this.faces.push( new THREE.Face3( a, b, d ) );
  19455. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19456. this.faces.push( new THREE.Face3( b, c, d ) );
  19457. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19458. }
  19459. }
  19460. this.computeFaceNormals();
  19461. this.computeVertexNormals();
  19462. };
  19463. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19464. THREE.TubeGeometry.prototype.constructor = THREE.TubeGeometry;
  19465. THREE.TubeGeometry.NoTaper = function ( u ) {
  19466. return 1;
  19467. };
  19468. THREE.TubeGeometry.SinusoidalTaper = function ( u ) {
  19469. return Math.sin( Math.PI * u );
  19470. };
  19471. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  19472. THREE.TubeGeometry.FrenetFrames = function ( path, segments, closed ) {
  19473. var normal = new THREE.Vector3(),
  19474. tangents = [],
  19475. normals = [],
  19476. binormals = [],
  19477. vec = new THREE.Vector3(),
  19478. mat = new THREE.Matrix4(),
  19479. numpoints = segments + 1,
  19480. theta,
  19481. epsilon = 0.0001,
  19482. smallest,
  19483. tx, ty, tz,
  19484. i, u;
  19485. // expose internals
  19486. this.tangents = tangents;
  19487. this.normals = normals;
  19488. this.binormals = binormals;
  19489. // compute the tangent vectors for each segment on the path
  19490. for ( i = 0; i < numpoints; i ++ ) {
  19491. u = i / ( numpoints - 1 );
  19492. tangents[ i ] = path.getTangentAt( u );
  19493. tangents[ i ].normalize();
  19494. }
  19495. initialNormal3();
  19496. /*
  19497. function initialNormal1(lastBinormal) {
  19498. // fixed start binormal. Has dangers of 0 vectors
  19499. normals[ 0 ] = new THREE.Vector3();
  19500. binormals[ 0 ] = new THREE.Vector3();
  19501. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  19502. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  19503. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19504. }
  19505. function initialNormal2() {
  19506. // This uses the Frenet-Serret formula for deriving binormal
  19507. var t2 = path.getTangentAt( epsilon );
  19508. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  19509. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  19510. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  19511. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19512. }
  19513. */
  19514. function initialNormal3() {
  19515. // select an initial normal vector perpenicular to the first tangent vector,
  19516. // and in the direction of the smallest tangent xyz component
  19517. normals[ 0 ] = new THREE.Vector3();
  19518. binormals[ 0 ] = new THREE.Vector3();
  19519. smallest = Number.MAX_VALUE;
  19520. tx = Math.abs( tangents[ 0 ].x );
  19521. ty = Math.abs( tangents[ 0 ].y );
  19522. tz = Math.abs( tangents[ 0 ].z );
  19523. if ( tx <= smallest ) {
  19524. smallest = tx;
  19525. normal.set( 1, 0, 0 );
  19526. }
  19527. if ( ty <= smallest ) {
  19528. smallest = ty;
  19529. normal.set( 0, 1, 0 );
  19530. }
  19531. if ( tz <= smallest ) {
  19532. normal.set( 0, 0, 1 );
  19533. }
  19534. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  19535. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  19536. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  19537. }
  19538. // compute the slowly-varying normal and binormal vectors for each segment on the path
  19539. for ( i = 1; i < numpoints; i ++ ) {
  19540. normals[ i ] = normals[ i - 1 ].clone();
  19541. binormals[ i ] = binormals[ i - 1 ].clone();
  19542. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  19543. if ( vec.length() > epsilon ) {
  19544. vec.normalize();
  19545. theta = Math.acos( THREE.Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  19546. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  19547. }
  19548. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19549. }
  19550. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  19551. if ( closed ) {
  19552. theta = Math.acos( THREE.Math.clamp( normals[ 0 ].dot( normals[ numpoints - 1 ] ), - 1, 1 ) );
  19553. theta /= ( numpoints - 1 );
  19554. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints - 1 ] ) ) > 0 ) {
  19555. theta = - theta;
  19556. }
  19557. for ( i = 1; i < numpoints; i ++ ) {
  19558. // twist a little...
  19559. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  19560. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19561. }
  19562. }
  19563. };
  19564. // File:src/extras/geometries/PolyhedronGeometry.js
  19565. /**
  19566. * @author clockworkgeek / https://github.com/clockworkgeek
  19567. * @author timothypratley / https://github.com/timothypratley
  19568. * @author WestLangley / http://github.com/WestLangley
  19569. */
  19570. THREE.PolyhedronGeometry = function ( vertices, indices, radius, detail ) {
  19571. THREE.Geometry.call( this );
  19572. this.type = 'PolyhedronGeometry';
  19573. this.parameters = {
  19574. vertices: vertices,
  19575. indices: indices,
  19576. radius: radius,
  19577. detail: detail
  19578. };
  19579. radius = radius || 1;
  19580. detail = detail || 0;
  19581. var that = this;
  19582. for ( var i = 0, l = vertices.length; i < l; i += 3 ) {
  19583. prepare( new THREE.Vector3( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] ) );
  19584. }
  19585. var p = this.vertices;
  19586. var faces = [];
  19587. for ( var i = 0, j = 0, l = indices.length; i < l; i += 3, j ++ ) {
  19588. var v1 = p[ indices[ i ] ];
  19589. var v2 = p[ indices[ i + 1 ] ];
  19590. var v3 = p[ indices[ i + 2 ] ];
  19591. faces[ j ] = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19592. }
  19593. var centroid = new THREE.Vector3();
  19594. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  19595. subdivide( faces[ i ], detail );
  19596. }
  19597. // Handle case when face straddles the seam
  19598. for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) {
  19599. var uvs = this.faceVertexUvs[ 0 ][ i ];
  19600. var x0 = uvs[ 0 ].x;
  19601. var x1 = uvs[ 1 ].x;
  19602. var x2 = uvs[ 2 ].x;
  19603. var max = Math.max( x0, Math.max( x1, x2 ) );
  19604. var min = Math.min( x0, Math.min( x1, x2 ) );
  19605. if ( max > 0.9 && min < 0.1 ) { // 0.9 is somewhat arbitrary
  19606. if ( x0 < 0.2 ) uvs[ 0 ].x += 1;
  19607. if ( x1 < 0.2 ) uvs[ 1 ].x += 1;
  19608. if ( x2 < 0.2 ) uvs[ 2 ].x += 1;
  19609. }
  19610. }
  19611. // Apply radius
  19612. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  19613. this.vertices[ i ].multiplyScalar( radius );
  19614. }
  19615. // Merge vertices
  19616. this.mergeVertices();
  19617. this.computeFaceNormals();
  19618. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19619. // Project vector onto sphere's surface
  19620. function prepare( vector ) {
  19621. var vertex = vector.normalize().clone();
  19622. vertex.index = that.vertices.push( vertex ) - 1;
  19623. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  19624. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  19625. var v = inclination( vector ) / Math.PI + 0.5;
  19626. vertex.uv = new THREE.Vector2( u, 1 - v );
  19627. return vertex;
  19628. }
  19629. // Approximate a curved face with recursively sub-divided triangles.
  19630. function make( v1, v2, v3 ) {
  19631. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19632. that.faces.push( face );
  19633. centroid.copy( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  19634. var azi = azimuth( centroid );
  19635. that.faceVertexUvs[ 0 ].push( [
  19636. correctUV( v1.uv, v1, azi ),
  19637. correctUV( v2.uv, v2, azi ),
  19638. correctUV( v3.uv, v3, azi )
  19639. ] );
  19640. }
  19641. // Analytically subdivide a face to the required detail level.
  19642. function subdivide( face, detail ) {
  19643. var cols = Math.pow(2, detail);
  19644. var a = prepare( that.vertices[ face.a ] );
  19645. var b = prepare( that.vertices[ face.b ] );
  19646. var c = prepare( that.vertices[ face.c ] );
  19647. var v = [];
  19648. // Construct all of the vertices for this subdivision.
  19649. for ( var i = 0 ; i <= cols; i ++ ) {
  19650. v[ i ] = [];
  19651. var aj = prepare( a.clone().lerp( c, i / cols ) );
  19652. var bj = prepare( b.clone().lerp( c, i / cols ) );
  19653. var rows = cols - i;
  19654. for ( var j = 0; j <= rows; j ++) {
  19655. if ( j == 0 && i == cols ) {
  19656. v[ i ][ j ] = aj;
  19657. } else {
  19658. v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) );
  19659. }
  19660. }
  19661. }
  19662. // Construct all of the faces.
  19663. for ( var i = 0; i < cols ; i ++ ) {
  19664. for ( var j = 0; j < 2 * (cols - i) - 1; j ++ ) {
  19665. var k = Math.floor( j / 2 );
  19666. if ( j % 2 == 0 ) {
  19667. make(
  19668. v[ i ][ k + 1],
  19669. v[ i + 1 ][ k ],
  19670. v[ i ][ k ]
  19671. );
  19672. } else {
  19673. make(
  19674. v[ i ][ k + 1 ],
  19675. v[ i + 1][ k + 1],
  19676. v[ i + 1 ][ k ]
  19677. );
  19678. }
  19679. }
  19680. }
  19681. }
  19682. // Angle around the Y axis, counter-clockwise when looking from above.
  19683. function azimuth( vector ) {
  19684. return Math.atan2( vector.z, - vector.x );
  19685. }
  19686. // Angle above the XZ plane.
  19687. function inclination( vector ) {
  19688. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  19689. }
  19690. // Texture fixing helper. Spheres have some odd behaviours.
  19691. function correctUV( uv, vector, azimuth ) {
  19692. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  19693. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  19694. return uv.clone();
  19695. }
  19696. };
  19697. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19698. THREE.PolyhedronGeometry.prototype.constructor = THREE.PolyhedronGeometry;
  19699. // File:src/extras/geometries/DodecahedronGeometry.js
  19700. /**
  19701. * @author Abe Pazos / https://hamoid.com
  19702. */
  19703. THREE.DodecahedronGeometry = function ( radius, detail ) {
  19704. this.parameters = {
  19705. radius: radius,
  19706. detail: detail
  19707. };
  19708. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19709. var r = 1 / t;
  19710. var vertices = [
  19711. // (±1, ±1, ±1)
  19712. -1, -1, -1, -1, -1, 1,
  19713. -1, 1, -1, -1, 1, 1,
  19714. 1, -1, -1, 1, -1, 1,
  19715. 1, 1, -1, 1, 1, 1,
  19716. // (0, ±1/φ, ±φ)
  19717. 0, -r, -t, 0, -r, t,
  19718. 0, r, -t, 0, r, t,
  19719. // (±1/φ, ±φ, 0)
  19720. -r, -t, 0, -r, t, 0,
  19721. r, -t, 0, r, t, 0,
  19722. // (±φ, 0, ±1/φ)
  19723. -t, 0, -r, t, 0, -r,
  19724. -t, 0, r, t, 0, r
  19725. ];
  19726. var indices = [
  19727. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  19728. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  19729. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  19730. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  19731. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  19732. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  19733. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  19734. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  19735. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  19736. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  19737. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  19738. 1, 12, 14, 1, 14, 5, 1, 5, 9
  19739. ];
  19740. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  19741. };
  19742. THREE.DodecahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19743. THREE.DodecahedronGeometry.prototype.constructor = THREE.DodecahedronGeometry;
  19744. // File:src/extras/geometries/IcosahedronGeometry.js
  19745. /**
  19746. * @author timothypratley / https://github.com/timothypratley
  19747. */
  19748. THREE.IcosahedronGeometry = function ( radius, detail ) {
  19749. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19750. var vertices = [
  19751. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  19752. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  19753. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  19754. ];
  19755. var indices = [
  19756. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  19757. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  19758. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  19759. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  19760. ];
  19761. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  19762. this.type = 'IcosahedronGeometry';
  19763. this.parameters = {
  19764. radius: radius,
  19765. detail: detail
  19766. };
  19767. };
  19768. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19769. THREE.IcosahedronGeometry.prototype.constructor = THREE.IcosahedronGeometry;
  19770. // File:src/extras/geometries/OctahedronGeometry.js
  19771. /**
  19772. * @author timothypratley / https://github.com/timothypratley
  19773. */
  19774. THREE.OctahedronGeometry = function ( radius, detail ) {
  19775. this.parameters = {
  19776. radius: radius,
  19777. detail: detail
  19778. };
  19779. var vertices = [
  19780. 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0,- 1, 0, 0, 0, 1, 0, 0,- 1
  19781. ];
  19782. var indices = [
  19783. 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2
  19784. ];
  19785. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  19786. this.type = 'OctahedronGeometry';
  19787. this.parameters = {
  19788. radius: radius,
  19789. detail: detail
  19790. };
  19791. };
  19792. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19793. THREE.OctahedronGeometry.prototype.constructor = THREE.OctahedronGeometry;
  19794. // File:src/extras/geometries/TetrahedronGeometry.js
  19795. /**
  19796. * @author timothypratley / https://github.com/timothypratley
  19797. */
  19798. THREE.TetrahedronGeometry = function ( radius, detail ) {
  19799. var vertices = [
  19800. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  19801. ];
  19802. var indices = [
  19803. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  19804. ];
  19805. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  19806. this.type = 'TetrahedronGeometry';
  19807. this.parameters = {
  19808. radius: radius,
  19809. detail: detail
  19810. };
  19811. };
  19812. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19813. THREE.TetrahedronGeometry.prototype.constructor = THREE.TetrahedronGeometry;
  19814. // File:src/extras/geometries/ParametricGeometry.js
  19815. /**
  19816. * @author zz85 / https://github.com/zz85
  19817. * Parametric Surfaces Geometry
  19818. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  19819. *
  19820. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements );
  19821. *
  19822. */
  19823. THREE.ParametricGeometry = function ( func, slices, stacks ) {
  19824. THREE.Geometry.call( this );
  19825. this.type = 'ParametricGeometry';
  19826. this.parameters = {
  19827. func: func,
  19828. slices: slices,
  19829. stacks: stacks
  19830. };
  19831. var verts = this.vertices;
  19832. var faces = this.faces;
  19833. var uvs = this.faceVertexUvs[ 0 ];
  19834. var i, j, p;
  19835. var u, v;
  19836. var sliceCount = slices + 1;
  19837. for ( i = 0; i <= stacks; i ++ ) {
  19838. v = i / stacks;
  19839. for ( j = 0; j <= slices; j ++ ) {
  19840. u = j / slices;
  19841. p = func( u, v );
  19842. verts.push( p );
  19843. }
  19844. }
  19845. var a, b, c, d;
  19846. var uva, uvb, uvc, uvd;
  19847. for ( i = 0; i < stacks; i ++ ) {
  19848. for ( j = 0; j < slices; j ++ ) {
  19849. a = i * sliceCount + j;
  19850. b = i * sliceCount + j + 1;
  19851. c = (i + 1) * sliceCount + j + 1;
  19852. d = (i + 1) * sliceCount + j;
  19853. uva = new THREE.Vector2( j / slices, i / stacks );
  19854. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  19855. uvc = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  19856. uvd = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  19857. faces.push( new THREE.Face3( a, b, d ) );
  19858. uvs.push( [ uva, uvb, uvd ] );
  19859. faces.push( new THREE.Face3( b, c, d ) );
  19860. uvs.push( [ uvb.clone(), uvc, uvd.clone() ] );
  19861. }
  19862. }
  19863. // console.log(this);
  19864. // magic bullet
  19865. // var diff = this.mergeVertices();
  19866. // console.log('removed ', diff, ' vertices by merging');
  19867. this.computeFaceNormals();
  19868. this.computeVertexNormals();
  19869. };
  19870. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19871. THREE.ParametricGeometry.prototype.constructor = THREE.ParametricGeometry;
  19872. // File:src/extras/helpers/AxisHelper.js
  19873. /**
  19874. * @author sroucheray / http://sroucheray.org/
  19875. * @author mrdoob / http://mrdoob.com/
  19876. */
  19877. THREE.AxisHelper = function ( size ) {
  19878. size = size || 1;
  19879. var vertices = new Float32Array( [
  19880. 0, 0, 0, size, 0, 0,
  19881. 0, 0, 0, 0, size, 0,
  19882. 0, 0, 0, 0, 0, size
  19883. ] );
  19884. var colors = new Float32Array( [
  19885. 1, 0, 0, 1, 0.6, 0,
  19886. 0, 1, 0, 0.6, 1, 0,
  19887. 0, 0, 1, 0, 0.6, 1
  19888. ] );
  19889. var geometry = new THREE.BufferGeometry();
  19890. geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  19891. geometry.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) );
  19892. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  19893. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  19894. };
  19895. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  19896. THREE.AxisHelper.prototype.constructor = THREE.AxisHelper;
  19897. // File:src/extras/helpers/ArrowHelper.js
  19898. /**
  19899. * @author WestLangley / http://github.com/WestLangley
  19900. * @author zz85 / http://github.com/zz85
  19901. * @author bhouston / http://exocortex.com
  19902. *
  19903. * Creates an arrow for visualizing directions
  19904. *
  19905. * Parameters:
  19906. * dir - Vector3
  19907. * origin - Vector3
  19908. * length - Number
  19909. * color - color in hex value
  19910. * headLength - Number
  19911. * headWidth - Number
  19912. */
  19913. THREE.ArrowHelper = ( function () {
  19914. var lineGeometry = new THREE.Geometry();
  19915. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, 1, 0 ) );
  19916. var coneGeometry = new THREE.CylinderGeometry( 0, 0.5, 1, 5, 1 );
  19917. coneGeometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, - 0.5, 0 ) );
  19918. return function ( dir, origin, length, color, headLength, headWidth ) {
  19919. // dir is assumed to be normalized
  19920. THREE.Object3D.call( this );
  19921. if ( color === undefined ) color = 0xffff00;
  19922. if ( length === undefined ) length = 1;
  19923. if ( headLength === undefined ) headLength = 0.2 * length;
  19924. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  19925. this.position.copy( origin );
  19926. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: color } ) );
  19927. this.line.matrixAutoUpdate = false;
  19928. this.add( this.line );
  19929. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: color } ) );
  19930. this.cone.matrixAutoUpdate = false;
  19931. this.add( this.cone );
  19932. this.setDirection( dir );
  19933. this.setLength( length, headLength, headWidth );
  19934. }
  19935. }() );
  19936. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  19937. THREE.ArrowHelper.prototype.constructor = THREE.ArrowHelper;
  19938. THREE.ArrowHelper.prototype.setDirection = ( function () {
  19939. var axis = new THREE.Vector3();
  19940. var radians;
  19941. return function ( dir ) {
  19942. // dir is assumed to be normalized
  19943. if ( dir.y > 0.99999 ) {
  19944. this.quaternion.set( 0, 0, 0, 1 );
  19945. } else if ( dir.y < - 0.99999 ) {
  19946. this.quaternion.set( 1, 0, 0, 0 );
  19947. } else {
  19948. axis.set( dir.z, 0, - dir.x ).normalize();
  19949. radians = Math.acos( dir.y );
  19950. this.quaternion.setFromAxisAngle( axis, radians );
  19951. }
  19952. };
  19953. }() );
  19954. THREE.ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  19955. if ( headLength === undefined ) headLength = 0.2 * length;
  19956. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  19957. this.line.scale.set( 1, length - headLength, 1 );
  19958. this.line.updateMatrix();
  19959. this.cone.scale.set( headWidth, headLength, headWidth );
  19960. this.cone.position.y = length;
  19961. this.cone.updateMatrix();
  19962. };
  19963. THREE.ArrowHelper.prototype.setColor = function ( color ) {
  19964. this.line.material.color.set( color );
  19965. this.cone.material.color.set( color );
  19966. };
  19967. // File:src/extras/helpers/BoxHelper.js
  19968. /**
  19969. * @author mrdoob / http://mrdoob.com/
  19970. */
  19971. THREE.BoxHelper = function ( object ) {
  19972. var geometry = new THREE.BufferGeometry();
  19973. geometry.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( 72 ), 3 ) );
  19974. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffff00 } ), THREE.LinePieces );
  19975. if ( object !== undefined ) {
  19976. this.update( object );
  19977. }
  19978. };
  19979. THREE.BoxHelper.prototype = Object.create( THREE.Line.prototype );
  19980. THREE.BoxHelper.prototype.constructor = THREE.BoxHelper;
  19981. THREE.BoxHelper.prototype.update = function ( object ) {
  19982. var geometry = object.geometry;
  19983. if ( geometry.boundingBox === null ) {
  19984. geometry.computeBoundingBox();
  19985. }
  19986. var min = geometry.boundingBox.min;
  19987. var max = geometry.boundingBox.max;
  19988. /*
  19989. 5____4
  19990. 1/___0/|
  19991. | 6__|_7
  19992. 2/___3/
  19993. 0: max.x, max.y, max.z
  19994. 1: min.x, max.y, max.z
  19995. 2: min.x, min.y, max.z
  19996. 3: max.x, min.y, max.z
  19997. 4: max.x, max.y, min.z
  19998. 5: min.x, max.y, min.z
  19999. 6: min.x, min.y, min.z
  20000. 7: max.x, min.y, min.z
  20001. */
  20002. var vertices = this.geometry.attributes.position.array;
  20003. vertices[ 0 ] = max.x; vertices[ 1 ] = max.y; vertices[ 2 ] = max.z;
  20004. vertices[ 3 ] = min.x; vertices[ 4 ] = max.y; vertices[ 5 ] = max.z;
  20005. vertices[ 6 ] = min.x; vertices[ 7 ] = max.y; vertices[ 8 ] = max.z;
  20006. vertices[ 9 ] = min.x; vertices[ 10 ] = min.y; vertices[ 11 ] = max.z;
  20007. vertices[ 12 ] = min.x; vertices[ 13 ] = min.y; vertices[ 14 ] = max.z;
  20008. vertices[ 15 ] = max.x; vertices[ 16 ] = min.y; vertices[ 17 ] = max.z;
  20009. vertices[ 18 ] = max.x; vertices[ 19 ] = min.y; vertices[ 20 ] = max.z;
  20010. vertices[ 21 ] = max.x; vertices[ 22 ] = max.y; vertices[ 23 ] = max.z;
  20011. //
  20012. vertices[ 24 ] = max.x; vertices[ 25 ] = max.y; vertices[ 26 ] = min.z;
  20013. vertices[ 27 ] = min.x; vertices[ 28 ] = max.y; vertices[ 29 ] = min.z;
  20014. vertices[ 30 ] = min.x; vertices[ 31 ] = max.y; vertices[ 32 ] = min.z;
  20015. vertices[ 33 ] = min.x; vertices[ 34 ] = min.y; vertices[ 35 ] = min.z;
  20016. vertices[ 36 ] = min.x; vertices[ 37 ] = min.y; vertices[ 38 ] = min.z;
  20017. vertices[ 39 ] = max.x; vertices[ 40 ] = min.y; vertices[ 41 ] = min.z;
  20018. vertices[ 42 ] = max.x; vertices[ 43 ] = min.y; vertices[ 44 ] = min.z;
  20019. vertices[ 45 ] = max.x; vertices[ 46 ] = max.y; vertices[ 47 ] = min.z;
  20020. //
  20021. vertices[ 48 ] = max.x; vertices[ 49 ] = max.y; vertices[ 50 ] = max.z;
  20022. vertices[ 51 ] = max.x; vertices[ 52 ] = max.y; vertices[ 53 ] = min.z;
  20023. vertices[ 54 ] = min.x; vertices[ 55 ] = max.y; vertices[ 56 ] = max.z;
  20024. vertices[ 57 ] = min.x; vertices[ 58 ] = max.y; vertices[ 59 ] = min.z;
  20025. vertices[ 60 ] = min.x; vertices[ 61 ] = min.y; vertices[ 62 ] = max.z;
  20026. vertices[ 63 ] = min.x; vertices[ 64 ] = min.y; vertices[ 65 ] = min.z;
  20027. vertices[ 66 ] = max.x; vertices[ 67 ] = min.y; vertices[ 68 ] = max.z;
  20028. vertices[ 69 ] = max.x; vertices[ 70 ] = min.y; vertices[ 71 ] = min.z;
  20029. this.geometry.attributes.position.needsUpdate = true;
  20030. this.geometry.computeBoundingSphere();
  20031. this.matrix = object.matrixWorld;
  20032. this.matrixAutoUpdate = false;
  20033. };
  20034. // File:src/extras/helpers/BoundingBoxHelper.js
  20035. /**
  20036. * @author WestLangley / http://github.com/WestLangley
  20037. */
  20038. // a helper to show the world-axis-aligned bounding box for an object
  20039. THREE.BoundingBoxHelper = function ( object, hex ) {
  20040. var color = ( hex !== undefined ) ? hex : 0x888888;
  20041. this.object = object;
  20042. this.box = new THREE.Box3();
  20043. THREE.Mesh.call( this, new THREE.BoxGeometry( 1, 1, 1 ), new THREE.MeshBasicMaterial( { color: color, wireframe: true } ) );
  20044. };
  20045. THREE.BoundingBoxHelper.prototype = Object.create( THREE.Mesh.prototype );
  20046. THREE.BoundingBoxHelper.prototype.constructor = THREE.BoundingBoxHelper;
  20047. THREE.BoundingBoxHelper.prototype.update = function () {
  20048. this.box.setFromObject( this.object );
  20049. this.box.size( this.scale );
  20050. this.box.center( this.position );
  20051. };
  20052. // File:src/extras/helpers/CameraHelper.js
  20053. /**
  20054. * @author alteredq / http://alteredqualia.com/
  20055. *
  20056. * - shows frustum, line of sight and up of the camera
  20057. * - suitable for fast updates
  20058. * - based on frustum visualization in lightgl.js shadowmap example
  20059. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  20060. */
  20061. THREE.CameraHelper = function ( camera ) {
  20062. var geometry = new THREE.Geometry();
  20063. var material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  20064. var pointMap = {};
  20065. // colors
  20066. var hexFrustum = 0xffaa00;
  20067. var hexCone = 0xff0000;
  20068. var hexUp = 0x00aaff;
  20069. var hexTarget = 0xffffff;
  20070. var hexCross = 0x333333;
  20071. // near
  20072. addLine( "n1", "n2", hexFrustum );
  20073. addLine( "n2", "n4", hexFrustum );
  20074. addLine( "n4", "n3", hexFrustum );
  20075. addLine( "n3", "n1", hexFrustum );
  20076. // far
  20077. addLine( "f1", "f2", hexFrustum );
  20078. addLine( "f2", "f4", hexFrustum );
  20079. addLine( "f4", "f3", hexFrustum );
  20080. addLine( "f3", "f1", hexFrustum );
  20081. // sides
  20082. addLine( "n1", "f1", hexFrustum );
  20083. addLine( "n2", "f2", hexFrustum );
  20084. addLine( "n3", "f3", hexFrustum );
  20085. addLine( "n4", "f4", hexFrustum );
  20086. // cone
  20087. addLine( "p", "n1", hexCone );
  20088. addLine( "p", "n2", hexCone );
  20089. addLine( "p", "n3", hexCone );
  20090. addLine( "p", "n4", hexCone );
  20091. // up
  20092. addLine( "u1", "u2", hexUp );
  20093. addLine( "u2", "u3", hexUp );
  20094. addLine( "u3", "u1", hexUp );
  20095. // target
  20096. addLine( "c", "t", hexTarget );
  20097. addLine( "p", "c", hexCross );
  20098. // cross
  20099. addLine( "cn1", "cn2", hexCross );
  20100. addLine( "cn3", "cn4", hexCross );
  20101. addLine( "cf1", "cf2", hexCross );
  20102. addLine( "cf3", "cf4", hexCross );
  20103. function addLine( a, b, hex ) {
  20104. addPoint( a, hex );
  20105. addPoint( b, hex );
  20106. }
  20107. function addPoint( id, hex ) {
  20108. geometry.vertices.push( new THREE.Vector3() );
  20109. geometry.colors.push( new THREE.Color( hex ) );
  20110. if ( pointMap[ id ] === undefined ) {
  20111. pointMap[ id ] = [];
  20112. }
  20113. pointMap[ id ].push( geometry.vertices.length - 1 );
  20114. }
  20115. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20116. this.camera = camera;
  20117. this.matrix = camera.matrixWorld;
  20118. this.matrixAutoUpdate = false;
  20119. this.pointMap = pointMap;
  20120. this.update();
  20121. };
  20122. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  20123. THREE.CameraHelper.prototype.constructor = THREE.CameraHelper;
  20124. THREE.CameraHelper.prototype.update = function () {
  20125. var geometry, pointMap;
  20126. var vector = new THREE.Vector3();
  20127. var camera = new THREE.Camera();
  20128. var setPoint = function ( point, x, y, z ) {
  20129. vector.set( x, y, z ).unproject( camera );
  20130. var points = pointMap[ point ];
  20131. if ( points !== undefined ) {
  20132. for ( var i = 0, il = points.length; i < il; i ++ ) {
  20133. geometry.vertices[ points[ i ] ].copy( vector );
  20134. }
  20135. }
  20136. };
  20137. return function () {
  20138. geometry = this.geometry;
  20139. pointMap = this.pointMap;
  20140. var w = 1, h = 1;
  20141. // we need just camera projection matrix
  20142. // world matrix must be identity
  20143. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  20144. // center / target
  20145. setPoint( "c", 0, 0, - 1 );
  20146. setPoint( "t", 0, 0, 1 );
  20147. // near
  20148. setPoint( "n1", - w, - h, - 1 );
  20149. setPoint( "n2", w, - h, - 1 );
  20150. setPoint( "n3", - w, h, - 1 );
  20151. setPoint( "n4", w, h, - 1 );
  20152. // far
  20153. setPoint( "f1", - w, - h, 1 );
  20154. setPoint( "f2", w, - h, 1 );
  20155. setPoint( "f3", - w, h, 1 );
  20156. setPoint( "f4", w, h, 1 );
  20157. // up
  20158. setPoint( "u1", w * 0.7, h * 1.1, - 1 );
  20159. setPoint( "u2", - w * 0.7, h * 1.1, - 1 );
  20160. setPoint( "u3", 0, h * 2, - 1 );
  20161. // cross
  20162. setPoint( "cf1", - w, 0, 1 );
  20163. setPoint( "cf2", w, 0, 1 );
  20164. setPoint( "cf3", 0, - h, 1 );
  20165. setPoint( "cf4", 0, h, 1 );
  20166. setPoint( "cn1", - w, 0, - 1 );
  20167. setPoint( "cn2", w, 0, - 1 );
  20168. setPoint( "cn3", 0, - h, - 1 );
  20169. setPoint( "cn4", 0, h, - 1 );
  20170. geometry.verticesNeedUpdate = true;
  20171. };
  20172. }();
  20173. // File:src/extras/helpers/DirectionalLightHelper.js
  20174. /**
  20175. * @author alteredq / http://alteredqualia.com/
  20176. * @author mrdoob / http://mrdoob.com/
  20177. * @author WestLangley / http://github.com/WestLangley
  20178. */
  20179. THREE.DirectionalLightHelper = function ( light, size ) {
  20180. THREE.Object3D.call( this );
  20181. this.light = light;
  20182. this.light.updateMatrixWorld();
  20183. this.matrix = light.matrixWorld;
  20184. this.matrixAutoUpdate = false;
  20185. size = size || 1;
  20186. var geometry = new THREE.Geometry();
  20187. geometry.vertices.push(
  20188. new THREE.Vector3( - size, size, 0 ),
  20189. new THREE.Vector3( size, size, 0 ),
  20190. new THREE.Vector3( size, - size, 0 ),
  20191. new THREE.Vector3( - size, - size, 0 ),
  20192. new THREE.Vector3( - size, size, 0 )
  20193. );
  20194. var material = new THREE.LineBasicMaterial( { fog: false } );
  20195. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20196. this.lightPlane = new THREE.Line( geometry, material );
  20197. this.add( this.lightPlane );
  20198. geometry = new THREE.Geometry();
  20199. geometry.vertices.push(
  20200. new THREE.Vector3(),
  20201. new THREE.Vector3()
  20202. );
  20203. material = new THREE.LineBasicMaterial( { fog: false } );
  20204. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20205. this.targetLine = new THREE.Line( geometry, material );
  20206. this.add( this.targetLine );
  20207. this.update();
  20208. };
  20209. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20210. THREE.DirectionalLightHelper.prototype.constructor = THREE.DirectionalLightHelper;
  20211. THREE.DirectionalLightHelper.prototype.dispose = function () {
  20212. this.lightPlane.geometry.dispose();
  20213. this.lightPlane.material.dispose();
  20214. this.targetLine.geometry.dispose();
  20215. this.targetLine.material.dispose();
  20216. };
  20217. THREE.DirectionalLightHelper.prototype.update = function () {
  20218. var v1 = new THREE.Vector3();
  20219. var v2 = new THREE.Vector3();
  20220. var v3 = new THREE.Vector3();
  20221. return function () {
  20222. v1.setFromMatrixPosition( this.light.matrixWorld );
  20223. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  20224. v3.subVectors( v2, v1 );
  20225. this.lightPlane.lookAt( v3 );
  20226. this.lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20227. this.targetLine.geometry.vertices[ 1 ].copy( v3 );
  20228. this.targetLine.geometry.verticesNeedUpdate = true;
  20229. this.targetLine.material.color.copy( this.lightPlane.material.color );
  20230. };
  20231. }();
  20232. // File:src/extras/helpers/EdgesHelper.js
  20233. /**
  20234. * @author WestLangley / http://github.com/WestLangley
  20235. * @param object THREE.Mesh whose geometry will be used
  20236. * @param hex line color
  20237. * @param thresholdAngle the minimim angle (in degrees),
  20238. * between the face normals of adjacent faces,
  20239. * that is required to render an edge. A value of 10 means
  20240. * an edge is only rendered if the angle is at least 10 degrees.
  20241. */
  20242. THREE.EdgesHelper = function ( object, hex, thresholdAngle ) {
  20243. var color = ( hex !== undefined ) ? hex : 0xffffff;
  20244. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  20245. var thresholdDot = Math.cos( THREE.Math.degToRad( thresholdAngle ) );
  20246. var edge = [ 0, 0 ], hash = {};
  20247. var sortFunction = function ( a, b ) { return a - b };
  20248. var keys = [ 'a', 'b', 'c' ];
  20249. var geometry = new THREE.BufferGeometry();
  20250. var geometry2;
  20251. if ( object.geometry instanceof THREE.BufferGeometry ) {
  20252. geometry2 = new THREE.Geometry();
  20253. geometry2.fromBufferGeometry( object.geometry );
  20254. } else {
  20255. geometry2 = object.geometry.clone();
  20256. }
  20257. geometry2.mergeVertices();
  20258. geometry2.computeFaceNormals();
  20259. var vertices = geometry2.vertices;
  20260. var faces = geometry2.faces;
  20261. var numEdges = 0;
  20262. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20263. var face = faces[ i ];
  20264. for ( var j = 0; j < 3; j ++ ) {
  20265. edge[ 0 ] = face[ keys[ j ] ];
  20266. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  20267. edge.sort( sortFunction );
  20268. var key = edge.toString();
  20269. if ( hash[ key ] === undefined ) {
  20270. hash[ key ] = { vert1: edge[ 0 ], vert2: edge[ 1 ], face1: i, face2: undefined };
  20271. numEdges ++;
  20272. } else {
  20273. hash[ key ].face2 = i;
  20274. }
  20275. }
  20276. }
  20277. var coords = new Float32Array( numEdges * 2 * 3 );
  20278. var index = 0;
  20279. for ( var key in hash ) {
  20280. var h = hash[ key ];
  20281. if ( h.face2 === undefined || faces[ h.face1 ].normal.dot( faces[ h.face2 ].normal ) <= thresholdDot ) {
  20282. var vertex = vertices[ h.vert1 ];
  20283. coords[ index ++ ] = vertex.x;
  20284. coords[ index ++ ] = vertex.y;
  20285. coords[ index ++ ] = vertex.z;
  20286. vertex = vertices[ h.vert2 ];
  20287. coords[ index ++ ] = vertex.x;
  20288. coords[ index ++ ] = vertex.y;
  20289. coords[ index ++ ] = vertex.z;
  20290. }
  20291. }
  20292. geometry.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  20293. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color } ), THREE.LinePieces );
  20294. this.matrix = object.matrixWorld;
  20295. this.matrixAutoUpdate = false;
  20296. };
  20297. THREE.EdgesHelper.prototype = Object.create( THREE.Line.prototype );
  20298. THREE.EdgesHelper.prototype.constructor = THREE.EdgesHelper;
  20299. // File:src/extras/helpers/FaceNormalsHelper.js
  20300. /**
  20301. * @author mrdoob / http://mrdoob.com/
  20302. * @author WestLangley / http://github.com/WestLangley
  20303. */
  20304. THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) {
  20305. this.object = object;
  20306. this.size = ( size !== undefined ) ? size : 1;
  20307. var color = ( hex !== undefined ) ? hex : 0xffff00;
  20308. var width = ( linewidth !== undefined ) ? linewidth : 1;
  20309. var geometry = new THREE.Geometry();
  20310. var faces = this.object.geometry.faces;
  20311. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20312. geometry.vertices.push( new THREE.Vector3(), new THREE.Vector3() );
  20313. }
  20314. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  20315. this.matrixAutoUpdate = false;
  20316. this.normalMatrix = new THREE.Matrix3();
  20317. this.update();
  20318. };
  20319. THREE.FaceNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  20320. THREE.FaceNormalsHelper.prototype.constructor = THREE.FaceNormalsHelper;
  20321. THREE.FaceNormalsHelper.prototype.update = function () {
  20322. var vertices = this.geometry.vertices;
  20323. var object = this.object;
  20324. var objectVertices = object.geometry.vertices;
  20325. var objectFaces = object.geometry.faces;
  20326. var objectWorldMatrix = object.matrixWorld;
  20327. object.updateMatrixWorld( true );
  20328. this.normalMatrix.getNormalMatrix( objectWorldMatrix );
  20329. for ( var i = 0, i2 = 0, l = objectFaces.length; i < l; i ++, i2 += 2 ) {
  20330. var face = objectFaces[ i ];
  20331. vertices[ i2 ].copy( objectVertices[ face.a ] )
  20332. .add( objectVertices[ face.b ] )
  20333. .add( objectVertices[ face.c ] )
  20334. .divideScalar( 3 )
  20335. .applyMatrix4( objectWorldMatrix );
  20336. vertices[ i2 + 1 ].copy( face.normal )
  20337. .applyMatrix3( this.normalMatrix )
  20338. .normalize()
  20339. .multiplyScalar( this.size )
  20340. .add( vertices[ i2 ] );
  20341. }
  20342. this.geometry.verticesNeedUpdate = true;
  20343. return this;
  20344. };
  20345. // File:src/extras/helpers/GridHelper.js
  20346. /**
  20347. * @author mrdoob / http://mrdoob.com/
  20348. */
  20349. THREE.GridHelper = function ( size, step ) {
  20350. var geometry = new THREE.Geometry();
  20351. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20352. this.color1 = new THREE.Color( 0x444444 );
  20353. this.color2 = new THREE.Color( 0x888888 );
  20354. for ( var i = - size; i <= size; i += step ) {
  20355. geometry.vertices.push(
  20356. new THREE.Vector3( - size, 0, i ), new THREE.Vector3( size, 0, i ),
  20357. new THREE.Vector3( i, 0, - size ), new THREE.Vector3( i, 0, size )
  20358. );
  20359. var color = i === 0 ? this.color1 : this.color2;
  20360. geometry.colors.push( color, color, color, color );
  20361. }
  20362. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20363. };
  20364. THREE.GridHelper.prototype = Object.create( THREE.Line.prototype );
  20365. THREE.GridHelper.prototype.constructor = THREE.GridHelper;
  20366. THREE.GridHelper.prototype.setColors = function( colorCenterLine, colorGrid ) {
  20367. this.color1.set( colorCenterLine );
  20368. this.color2.set( colorGrid );
  20369. this.geometry.colorsNeedUpdate = true;
  20370. }
  20371. // File:src/extras/helpers/HemisphereLightHelper.js
  20372. /**
  20373. * @author alteredq / http://alteredqualia.com/
  20374. * @author mrdoob / http://mrdoob.com/
  20375. */
  20376. THREE.HemisphereLightHelper = function ( light, sphereSize ) {
  20377. THREE.Object3D.call( this );
  20378. this.light = light;
  20379. this.light.updateMatrixWorld();
  20380. this.matrix = light.matrixWorld;
  20381. this.matrixAutoUpdate = false;
  20382. this.colors = [ new THREE.Color(), new THREE.Color() ];
  20383. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20384. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  20385. for ( var i = 0, il = 8; i < il; i ++ ) {
  20386. geometry.faces[ i ].color = this.colors[ i < 4 ? 0 : 1 ];
  20387. }
  20388. var material = new THREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors, wireframe: true } );
  20389. this.lightSphere = new THREE.Mesh( geometry, material );
  20390. this.add( this.lightSphere );
  20391. this.update();
  20392. };
  20393. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20394. THREE.HemisphereLightHelper.prototype.constructor = THREE.HemisphereLightHelper;
  20395. THREE.HemisphereLightHelper.prototype.dispose = function () {
  20396. this.lightSphere.geometry.dispose();
  20397. this.lightSphere.material.dispose();
  20398. };
  20399. THREE.HemisphereLightHelper.prototype.update = function () {
  20400. var vector = new THREE.Vector3();
  20401. return function () {
  20402. this.colors[ 0 ].copy( this.light.color ).multiplyScalar( this.light.intensity );
  20403. this.colors[ 1 ].copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  20404. this.lightSphere.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  20405. this.lightSphere.geometry.colorsNeedUpdate = true;
  20406. }
  20407. }();
  20408. // File:src/extras/helpers/PointLightHelper.js
  20409. /**
  20410. * @author alteredq / http://alteredqualia.com/
  20411. * @author mrdoob / http://mrdoob.com/
  20412. */
  20413. THREE.PointLightHelper = function ( light, sphereSize ) {
  20414. this.light = light;
  20415. this.light.updateMatrixWorld();
  20416. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20417. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  20418. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20419. THREE.Mesh.call( this, geometry, material );
  20420. this.matrix = this.light.matrixWorld;
  20421. this.matrixAutoUpdate = false;
  20422. /*
  20423. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  20424. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  20425. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20426. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  20427. var d = light.distance;
  20428. if ( d === 0.0 ) {
  20429. this.lightDistance.visible = false;
  20430. } else {
  20431. this.lightDistance.scale.set( d, d, d );
  20432. }
  20433. this.add( this.lightDistance );
  20434. */
  20435. };
  20436. THREE.PointLightHelper.prototype = Object.create( THREE.Mesh.prototype );
  20437. THREE.PointLightHelper.prototype.constructor = THREE.PointLightHelper;
  20438. THREE.PointLightHelper.prototype.dispose = function () {
  20439. this.geometry.dispose();
  20440. this.material.dispose();
  20441. };
  20442. THREE.PointLightHelper.prototype.update = function () {
  20443. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20444. /*
  20445. var d = this.light.distance;
  20446. if ( d === 0.0 ) {
  20447. this.lightDistance.visible = false;
  20448. } else {
  20449. this.lightDistance.visible = true;
  20450. this.lightDistance.scale.set( d, d, d );
  20451. }
  20452. */
  20453. };
  20454. // File:src/extras/helpers/SkeletonHelper.js
  20455. /**
  20456. * @author Sean Griffin / http://twitter.com/sgrif
  20457. * @author Michael Guerrero / http://realitymeltdown.com
  20458. * @author mrdoob / http://mrdoob.com/
  20459. * @author ikerr / http://verold.com
  20460. */
  20461. THREE.SkeletonHelper = function ( object ) {
  20462. this.bones = this.getBoneList( object );
  20463. var geometry = new THREE.Geometry();
  20464. for ( var i = 0; i < this.bones.length; i ++ ) {
  20465. var bone = this.bones[ i ];
  20466. if ( bone.parent instanceof THREE.Bone ) {
  20467. geometry.vertices.push( new THREE.Vector3() );
  20468. geometry.vertices.push( new THREE.Vector3() );
  20469. geometry.colors.push( new THREE.Color( 0, 0, 1 ) );
  20470. geometry.colors.push( new THREE.Color( 0, 1, 0 ) );
  20471. }
  20472. }
  20473. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors, depthTest: false, depthWrite: false, transparent: true } );
  20474. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20475. this.root = object;
  20476. this.matrix = object.matrixWorld;
  20477. this.matrixAutoUpdate = false;
  20478. this.update();
  20479. };
  20480. THREE.SkeletonHelper.prototype = Object.create( THREE.Line.prototype );
  20481. THREE.SkeletonHelper.prototype.constructor = THREE.SkeletonHelper;
  20482. THREE.SkeletonHelper.prototype.getBoneList = function( object ) {
  20483. var boneList = [];
  20484. if ( object instanceof THREE.Bone ) {
  20485. boneList.push( object );
  20486. }
  20487. for ( var i = 0; i < object.children.length; i ++ ) {
  20488. boneList.push.apply( boneList, this.getBoneList( object.children[ i ] ) );
  20489. }
  20490. return boneList;
  20491. };
  20492. THREE.SkeletonHelper.prototype.update = function () {
  20493. var geometry = this.geometry;
  20494. var matrixWorldInv = new THREE.Matrix4().getInverse( this.root.matrixWorld );
  20495. var boneMatrix = new THREE.Matrix4();
  20496. var j = 0;
  20497. for ( var i = 0; i < this.bones.length; i ++ ) {
  20498. var bone = this.bones[ i ];
  20499. if ( bone.parent instanceof THREE.Bone ) {
  20500. boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld );
  20501. geometry.vertices[ j ].setFromMatrixPosition( boneMatrix );
  20502. boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld );
  20503. geometry.vertices[ j + 1 ].setFromMatrixPosition( boneMatrix );
  20504. j += 2;
  20505. }
  20506. }
  20507. geometry.verticesNeedUpdate = true;
  20508. geometry.computeBoundingSphere();
  20509. };
  20510. // File:src/extras/helpers/SpotLightHelper.js
  20511. /**
  20512. * @author alteredq / http://alteredqualia.com/
  20513. * @author mrdoob / http://mrdoob.com/
  20514. * @author WestLangley / http://github.com/WestLangley
  20515. */
  20516. THREE.SpotLightHelper = function ( light ) {
  20517. THREE.Object3D.call( this );
  20518. this.light = light;
  20519. this.light.updateMatrixWorld();
  20520. this.matrix = light.matrixWorld;
  20521. this.matrixAutoUpdate = false;
  20522. var geometry = new THREE.CylinderGeometry( 0, 1, 1, 8, 1, true );
  20523. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, - 0.5, 0 ) );
  20524. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  20525. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  20526. this.cone = new THREE.Mesh( geometry, material );
  20527. this.add( this.cone );
  20528. this.update();
  20529. };
  20530. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20531. THREE.SpotLightHelper.prototype.constructor = THREE.SpotLightHelper;
  20532. THREE.SpotLightHelper.prototype.dispose = function () {
  20533. this.cone.geometry.dispose();
  20534. this.cone.material.dispose();
  20535. };
  20536. THREE.SpotLightHelper.prototype.update = function () {
  20537. var vector = new THREE.Vector3();
  20538. var vector2 = new THREE.Vector3();
  20539. return function () {
  20540. var coneLength = this.light.distance ? this.light.distance : 10000;
  20541. var coneWidth = coneLength * Math.tan( this.light.angle );
  20542. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  20543. vector.setFromMatrixPosition( this.light.matrixWorld );
  20544. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  20545. this.cone.lookAt( vector2.sub( vector ) );
  20546. this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20547. };
  20548. }();
  20549. // File:src/extras/helpers/VertexNormalsHelper.js
  20550. /**
  20551. * @author mrdoob / http://mrdoob.com/
  20552. * @author WestLangley / http://github.com/WestLangley
  20553. */
  20554. THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) {
  20555. this.object = object;
  20556. this.size = ( size !== undefined ) ? size : 1;
  20557. var color = ( hex !== undefined ) ? hex : 0xff0000;
  20558. var width = ( linewidth !== undefined ) ? linewidth : 1;
  20559. var geometry = new THREE.Geometry();
  20560. var faces = object.geometry.faces;
  20561. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20562. var face = faces[ i ];
  20563. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  20564. geometry.vertices.push( new THREE.Vector3(), new THREE.Vector3() );
  20565. }
  20566. }
  20567. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  20568. this.matrixAutoUpdate = false;
  20569. this.normalMatrix = new THREE.Matrix3();
  20570. this.update();
  20571. };
  20572. THREE.VertexNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  20573. THREE.VertexNormalsHelper.prototype.constructor = THREE.VertexNormalsHelper;
  20574. THREE.VertexNormalsHelper.prototype.update = ( function ( object ) {
  20575. var v1 = new THREE.Vector3();
  20576. return function( object ) {
  20577. var keys = [ 'a', 'b', 'c', 'd' ];
  20578. this.object.updateMatrixWorld( true );
  20579. this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
  20580. var vertices = this.geometry.vertices;
  20581. var verts = this.object.geometry.vertices;
  20582. var faces = this.object.geometry.faces;
  20583. var worldMatrix = this.object.matrixWorld;
  20584. var idx = 0;
  20585. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20586. var face = faces[ i ];
  20587. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  20588. var vertexId = face[ keys[ j ] ];
  20589. var vertex = verts[ vertexId ];
  20590. var normal = face.vertexNormals[ j ];
  20591. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  20592. v1.copy( normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
  20593. v1.add( vertices[ idx ] );
  20594. idx = idx + 1;
  20595. vertices[ idx ].copy( v1 );
  20596. idx = idx + 1;
  20597. }
  20598. }
  20599. this.geometry.verticesNeedUpdate = true;
  20600. return this;
  20601. }
  20602. }());
  20603. // File:src/extras/helpers/VertexTangentsHelper.js
  20604. /**
  20605. * @author mrdoob / http://mrdoob.com/
  20606. * @author WestLangley / http://github.com/WestLangley
  20607. */
  20608. THREE.VertexTangentsHelper = function ( object, size, hex, linewidth ) {
  20609. this.object = object;
  20610. this.size = ( size !== undefined ) ? size : 1;
  20611. var color = ( hex !== undefined ) ? hex : 0x0000ff;
  20612. var width = ( linewidth !== undefined ) ? linewidth : 1;
  20613. var geometry = new THREE.Geometry();
  20614. var faces = object.geometry.faces;
  20615. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20616. var face = faces[ i ];
  20617. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  20618. geometry.vertices.push( new THREE.Vector3() );
  20619. geometry.vertices.push( new THREE.Vector3() );
  20620. }
  20621. }
  20622. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  20623. this.matrixAutoUpdate = false;
  20624. this.update();
  20625. };
  20626. THREE.VertexTangentsHelper.prototype = Object.create( THREE.Line.prototype );
  20627. THREE.VertexTangentsHelper.prototype.constructor = THREE.VertexTangentsHelper;
  20628. THREE.VertexTangentsHelper.prototype.update = ( function ( object ) {
  20629. var v1 = new THREE.Vector3();
  20630. return function( object ) {
  20631. var keys = [ 'a', 'b', 'c', 'd' ];
  20632. this.object.updateMatrixWorld( true );
  20633. var vertices = this.geometry.vertices;
  20634. var verts = this.object.geometry.vertices;
  20635. var faces = this.object.geometry.faces;
  20636. var worldMatrix = this.object.matrixWorld;
  20637. var idx = 0;
  20638. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20639. var face = faces[ i ];
  20640. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  20641. var vertexId = face[ keys[ j ] ];
  20642. var vertex = verts[ vertexId ];
  20643. var tangent = face.vertexTangents[ j ];
  20644. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  20645. v1.copy( tangent ).transformDirection( worldMatrix ).multiplyScalar( this.size );
  20646. v1.add( vertices[ idx ] );
  20647. idx = idx + 1;
  20648. vertices[ idx ].copy( v1 );
  20649. idx = idx + 1;
  20650. }
  20651. }
  20652. this.geometry.verticesNeedUpdate = true;
  20653. return this;
  20654. }
  20655. }());
  20656. // File:src/extras/helpers/WireframeHelper.js
  20657. /**
  20658. * @author mrdoob / http://mrdoob.com/
  20659. */
  20660. THREE.WireframeHelper = function ( object, hex ) {
  20661. var color = ( hex !== undefined ) ? hex : 0xffffff;
  20662. var edge = [ 0, 0 ], hash = {};
  20663. var sortFunction = function ( a, b ) { return a - b };
  20664. var keys = [ 'a', 'b', 'c' ];
  20665. var geometry = new THREE.BufferGeometry();
  20666. if ( object.geometry instanceof THREE.Geometry ) {
  20667. var vertices = object.geometry.vertices;
  20668. var faces = object.geometry.faces;
  20669. var numEdges = 0;
  20670. // allocate maximal size
  20671. var edges = new Uint32Array( 6 * faces.length );
  20672. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20673. var face = faces[ i ];
  20674. for ( var j = 0; j < 3; j ++ ) {
  20675. edge[ 0 ] = face[ keys[ j ] ];
  20676. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  20677. edge.sort( sortFunction );
  20678. var key = edge.toString();
  20679. if ( hash[ key ] === undefined ) {
  20680. edges[ 2 * numEdges ] = edge[ 0 ];
  20681. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  20682. hash[ key ] = true;
  20683. numEdges ++;
  20684. }
  20685. }
  20686. }
  20687. var coords = new Float32Array( numEdges * 2 * 3 );
  20688. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  20689. for ( var j = 0; j < 2; j ++ ) {
  20690. var vertex = vertices[ edges [ 2 * i + j] ];
  20691. var index = 6 * i + 3 * j;
  20692. coords[ index + 0 ] = vertex.x;
  20693. coords[ index + 1 ] = vertex.y;
  20694. coords[ index + 2 ] = vertex.z;
  20695. }
  20696. }
  20697. geometry.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  20698. } else if ( object.geometry instanceof THREE.BufferGeometry ) {
  20699. if ( object.geometry.attributes.index !== undefined ) { // Indexed BufferGeometry
  20700. var vertices = object.geometry.attributes.position.array;
  20701. var indices = object.geometry.attributes.index.array;
  20702. var drawcalls = object.geometry.drawcalls;
  20703. var numEdges = 0;
  20704. if ( drawcalls.length === 0 ) {
  20705. drawcalls = [ { count : indices.length, index : 0, start : 0 } ];
  20706. }
  20707. // allocate maximal size
  20708. var edges = new Uint32Array( 2 * indices.length );
  20709. for ( var o = 0, ol = drawcalls.length; o < ol; ++ o ) {
  20710. var start = drawcalls[ o ].start;
  20711. var count = drawcalls[ o ].count;
  20712. var index = drawcalls[ o ].index;
  20713. for ( var i = start, il = start + count; i < il; i += 3 ) {
  20714. for ( var j = 0; j < 3; j ++ ) {
  20715. edge[ 0 ] = index + indices[ i + j ];
  20716. edge[ 1 ] = index + indices[ i + ( j + 1 ) % 3 ];
  20717. edge.sort( sortFunction );
  20718. var key = edge.toString();
  20719. if ( hash[ key ] === undefined ) {
  20720. edges[ 2 * numEdges ] = edge[ 0 ];
  20721. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  20722. hash[ key ] = true;
  20723. numEdges ++;
  20724. }
  20725. }
  20726. }
  20727. }
  20728. var coords = new Float32Array( numEdges * 2 * 3 );
  20729. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  20730. for ( var j = 0; j < 2; j ++ ) {
  20731. var index = 6 * i + 3 * j;
  20732. var index2 = 3 * edges[ 2 * i + j];
  20733. coords[ index + 0 ] = vertices[ index2 ];
  20734. coords[ index + 1 ] = vertices[ index2 + 1 ];
  20735. coords[ index + 2 ] = vertices[ index2 + 2 ];
  20736. }
  20737. }
  20738. geometry.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  20739. } else { // non-indexed BufferGeometry
  20740. var vertices = object.geometry.attributes.position.array;
  20741. var numEdges = vertices.length / 3;
  20742. var numTris = numEdges / 3;
  20743. var coords = new Float32Array( numEdges * 2 * 3 );
  20744. for ( var i = 0, l = numTris; i < l; i ++ ) {
  20745. for ( var j = 0; j < 3; j ++ ) {
  20746. var index = 18 * i + 6 * j;
  20747. var index1 = 9 * i + 3 * j;
  20748. coords[ index + 0 ] = vertices[ index1 ];
  20749. coords[ index + 1 ] = vertices[ index1 + 1 ];
  20750. coords[ index + 2 ] = vertices[ index1 + 2 ];
  20751. var index2 = 9 * i + 3 * ( ( j + 1 ) % 3 );
  20752. coords[ index + 3 ] = vertices[ index2 ];
  20753. coords[ index + 4 ] = vertices[ index2 + 1 ];
  20754. coords[ index + 5 ] = vertices[ index2 + 2 ];
  20755. }
  20756. }
  20757. geometry.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  20758. }
  20759. }
  20760. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color } ), THREE.LinePieces );
  20761. this.matrix = object.matrixWorld;
  20762. this.matrixAutoUpdate = false;
  20763. };
  20764. THREE.WireframeHelper.prototype = Object.create( THREE.Line.prototype );
  20765. THREE.WireframeHelper.prototype.constructor = THREE.WireframeHelper;
  20766. // File:src/extras/objects/ImmediateRenderObject.js
  20767. /**
  20768. * @author alteredq / http://alteredqualia.com/
  20769. */
  20770. THREE.ImmediateRenderObject = function () {
  20771. THREE.Object3D.call( this );
  20772. this.render = function ( renderCallback ) {};
  20773. };
  20774. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  20775. THREE.ImmediateRenderObject.prototype.constructor = THREE.ImmediateRenderObject;
  20776. // File:src/extras/objects/MorphBlendMesh.js
  20777. /**
  20778. * @author alteredq / http://alteredqualia.com/
  20779. */
  20780. THREE.MorphBlendMesh = function( geometry, material ) {
  20781. THREE.Mesh.call( this, geometry, material );
  20782. this.animationsMap = {};
  20783. this.animationsList = [];
  20784. // prepare default animation
  20785. // (all frames played together in 1 second)
  20786. var numFrames = this.geometry.morphTargets.length;
  20787. var name = "__default";
  20788. var startFrame = 0;
  20789. var endFrame = numFrames - 1;
  20790. var fps = numFrames / 1;
  20791. this.createAnimation( name, startFrame, endFrame, fps );
  20792. this.setAnimationWeight( name, 1 );
  20793. };
  20794. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  20795. THREE.MorphBlendMesh.prototype.constructor = THREE.MorphBlendMesh;
  20796. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  20797. var animation = {
  20798. startFrame: start,
  20799. endFrame: end,
  20800. length: end - start + 1,
  20801. fps: fps,
  20802. duration: ( end - start ) / fps,
  20803. lastFrame: 0,
  20804. currentFrame: 0,
  20805. active: false,
  20806. time: 0,
  20807. direction: 1,
  20808. weight: 1,
  20809. directionBackwards: false,
  20810. mirroredLoop: false
  20811. };
  20812. this.animationsMap[ name ] = animation;
  20813. this.animationsList.push( animation );
  20814. };
  20815. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  20816. var pattern = /([a-z]+)_?(\d+)/;
  20817. var firstAnimation, frameRanges = {};
  20818. var geometry = this.geometry;
  20819. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  20820. var morph = geometry.morphTargets[ i ];
  20821. var chunks = morph.name.match( pattern );
  20822. if ( chunks && chunks.length > 1 ) {
  20823. var name = chunks[ 1 ];
  20824. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: - Infinity };
  20825. var range = frameRanges[ name ];
  20826. if ( i < range.start ) range.start = i;
  20827. if ( i > range.end ) range.end = i;
  20828. if ( ! firstAnimation ) firstAnimation = name;
  20829. }
  20830. }
  20831. for ( var name in frameRanges ) {
  20832. var range = frameRanges[ name ];
  20833. this.createAnimation( name, range.start, range.end, fps );
  20834. }
  20835. this.firstAnimation = firstAnimation;
  20836. };
  20837. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  20838. var animation = this.animationsMap[ name ];
  20839. if ( animation ) {
  20840. animation.direction = 1;
  20841. animation.directionBackwards = false;
  20842. }
  20843. };
  20844. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  20845. var animation = this.animationsMap[ name ];
  20846. if ( animation ) {
  20847. animation.direction = - 1;
  20848. animation.directionBackwards = true;
  20849. }
  20850. };
  20851. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  20852. var animation = this.animationsMap[ name ];
  20853. if ( animation ) {
  20854. animation.fps = fps;
  20855. animation.duration = ( animation.end - animation.start ) / animation.fps;
  20856. }
  20857. };
  20858. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  20859. var animation = this.animationsMap[ name ];
  20860. if ( animation ) {
  20861. animation.duration = duration;
  20862. animation.fps = ( animation.end - animation.start ) / animation.duration;
  20863. }
  20864. };
  20865. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  20866. var animation = this.animationsMap[ name ];
  20867. if ( animation ) {
  20868. animation.weight = weight;
  20869. }
  20870. };
  20871. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  20872. var animation = this.animationsMap[ name ];
  20873. if ( animation ) {
  20874. animation.time = time;
  20875. }
  20876. };
  20877. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  20878. var time = 0;
  20879. var animation = this.animationsMap[ name ];
  20880. if ( animation ) {
  20881. time = animation.time;
  20882. }
  20883. return time;
  20884. };
  20885. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  20886. var duration = - 1;
  20887. var animation = this.animationsMap[ name ];
  20888. if ( animation ) {
  20889. duration = animation.duration;
  20890. }
  20891. return duration;
  20892. };
  20893. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  20894. var animation = this.animationsMap[ name ];
  20895. if ( animation ) {
  20896. animation.time = 0;
  20897. animation.active = true;
  20898. } else {
  20899. THREE.warn( "THREE.MorphBlendMesh: animation[" + name + "] undefined in .playAnimation()" );
  20900. }
  20901. };
  20902. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  20903. var animation = this.animationsMap[ name ];
  20904. if ( animation ) {
  20905. animation.active = false;
  20906. }
  20907. };
  20908. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  20909. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  20910. var animation = this.animationsList[ i ];
  20911. if ( ! animation.active ) continue;
  20912. var frameTime = animation.duration / animation.length;
  20913. animation.time += animation.direction * delta;
  20914. if ( animation.mirroredLoop ) {
  20915. if ( animation.time > animation.duration || animation.time < 0 ) {
  20916. animation.direction *= - 1;
  20917. if ( animation.time > animation.duration ) {
  20918. animation.time = animation.duration;
  20919. animation.directionBackwards = true;
  20920. }
  20921. if ( animation.time < 0 ) {
  20922. animation.time = 0;
  20923. animation.directionBackwards = false;
  20924. }
  20925. }
  20926. } else {
  20927. animation.time = animation.time % animation.duration;
  20928. if ( animation.time < 0 ) animation.time += animation.duration;
  20929. }
  20930. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  20931. var weight = animation.weight;
  20932. if ( keyframe !== animation.currentFrame ) {
  20933. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  20934. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  20935. this.morphTargetInfluences[ keyframe ] = 0;
  20936. animation.lastFrame = animation.currentFrame;
  20937. animation.currentFrame = keyframe;
  20938. }
  20939. var mix = ( animation.time % frameTime ) / frameTime;
  20940. if ( animation.directionBackwards ) mix = 1 - mix;
  20941. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  20942. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  20943. }
  20944. };