three.js 805 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044
  1. // You shouldn't edit this build file.
  2. // The following source code is build from the src folder.
  3. // File:src/Three.js
  4. /**
  5. * @author mrdoob / http://mrdoob.com/
  6. */
  7. var THREE = { REVISION: '68dev' };
  8. // browserify support
  9. if ( typeof module === 'object' ) {
  10. module.exports = THREE;
  11. }
  12. // GL STATE CONSTANTS
  13. THREE.CullFaceNone = 0;
  14. THREE.CullFaceBack = 1;
  15. THREE.CullFaceFront = 2;
  16. THREE.CullFaceFrontBack = 3;
  17. THREE.FrontFaceDirectionCW = 0;
  18. THREE.FrontFaceDirectionCCW = 1;
  19. // SHADOWING TYPES
  20. THREE.BasicShadowMap = 0;
  21. THREE.PCFShadowMap = 1;
  22. THREE.PCFSoftShadowMap = 2;
  23. // MATERIAL CONSTANTS
  24. // side
  25. THREE.FrontSide = 0;
  26. THREE.BackSide = 1;
  27. THREE.DoubleSide = 2;
  28. // shading
  29. THREE.NoShading = 0;
  30. THREE.FlatShading = 1;
  31. THREE.SmoothShading = 2;
  32. // colors
  33. THREE.NoColors = 0;
  34. THREE.FaceColors = 1;
  35. THREE.VertexColors = 2;
  36. // blending modes
  37. THREE.NoBlending = 0;
  38. THREE.NormalBlending = 1;
  39. THREE.AdditiveBlending = 2;
  40. THREE.SubtractiveBlending = 3;
  41. THREE.MultiplyBlending = 4;
  42. THREE.CustomBlending = 5;
  43. // custom blending equations
  44. // (numbers start from 100 not to clash with other
  45. // mappings to OpenGL constants defined in Texture.js)
  46. THREE.AddEquation = 100;
  47. THREE.SubtractEquation = 101;
  48. THREE.ReverseSubtractEquation = 102;
  49. // custom blending destination factors
  50. THREE.ZeroFactor = 200;
  51. THREE.OneFactor = 201;
  52. THREE.SrcColorFactor = 202;
  53. THREE.OneMinusSrcColorFactor = 203;
  54. THREE.SrcAlphaFactor = 204;
  55. THREE.OneMinusSrcAlphaFactor = 205;
  56. THREE.DstAlphaFactor = 206;
  57. THREE.OneMinusDstAlphaFactor = 207;
  58. // custom blending source factors
  59. //THREE.ZeroFactor = 200;
  60. //THREE.OneFactor = 201;
  61. //THREE.SrcAlphaFactor = 204;
  62. //THREE.OneMinusSrcAlphaFactor = 205;
  63. //THREE.DstAlphaFactor = 206;
  64. //THREE.OneMinusDstAlphaFactor = 207;
  65. THREE.DstColorFactor = 208;
  66. THREE.OneMinusDstColorFactor = 209;
  67. THREE.SrcAlphaSaturateFactor = 210;
  68. // TEXTURE CONSTANTS
  69. THREE.MultiplyOperation = 0;
  70. THREE.MixOperation = 1;
  71. THREE.AddOperation = 2;
  72. // Mapping modes
  73. THREE.UVMapping = function () {};
  74. THREE.CubeReflectionMapping = function () {};
  75. THREE.CubeRefractionMapping = function () {};
  76. THREE.SphericalReflectionMapping = function () {};
  77. THREE.SphericalRefractionMapping = function () {};
  78. // Wrapping modes
  79. THREE.RepeatWrapping = 1000;
  80. THREE.ClampToEdgeWrapping = 1001;
  81. THREE.MirroredRepeatWrapping = 1002;
  82. // Filters
  83. THREE.NearestFilter = 1003;
  84. THREE.NearestMipMapNearestFilter = 1004;
  85. THREE.NearestMipMapLinearFilter = 1005;
  86. THREE.LinearFilter = 1006;
  87. THREE.LinearMipMapNearestFilter = 1007;
  88. THREE.LinearMipMapLinearFilter = 1008;
  89. // Data types
  90. THREE.UnsignedByteType = 1009;
  91. THREE.ByteType = 1010;
  92. THREE.ShortType = 1011;
  93. THREE.UnsignedShortType = 1012;
  94. THREE.IntType = 1013;
  95. THREE.UnsignedIntType = 1014;
  96. THREE.FloatType = 1015;
  97. // Pixel types
  98. //THREE.UnsignedByteType = 1009;
  99. THREE.UnsignedShort4444Type = 1016;
  100. THREE.UnsignedShort5551Type = 1017;
  101. THREE.UnsignedShort565Type = 1018;
  102. // Pixel formats
  103. THREE.AlphaFormat = 1019;
  104. THREE.RGBFormat = 1020;
  105. THREE.RGBAFormat = 1021;
  106. THREE.LuminanceFormat = 1022;
  107. THREE.LuminanceAlphaFormat = 1023;
  108. // Compressed texture formats
  109. THREE.RGB_S3TC_DXT1_Format = 2001;
  110. THREE.RGBA_S3TC_DXT1_Format = 2002;
  111. THREE.RGBA_S3TC_DXT3_Format = 2003;
  112. THREE.RGBA_S3TC_DXT5_Format = 2004;
  113. /*
  114. // Potential future PVRTC compressed texture formats
  115. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  116. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  117. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  118. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  119. */
  120. // File:src/math/Color.js
  121. /**
  122. * @author mrdoob / http://mrdoob.com/
  123. */
  124. THREE.Color = function ( color ) {
  125. if ( arguments.length === 3 ) {
  126. return this.setRGB( arguments[ 0 ], arguments[ 1 ], arguments[ 2 ] );
  127. }
  128. return this.set( color )
  129. };
  130. THREE.Color.prototype = {
  131. constructor: THREE.Color,
  132. r: 1, g: 1, b: 1,
  133. set: function ( value ) {
  134. if ( value instanceof THREE.Color ) {
  135. this.copy( value );
  136. } else if ( typeof value === 'number' ) {
  137. this.setHex( value );
  138. } else if ( typeof value === 'string' ) {
  139. this.setStyle( value );
  140. }
  141. return this;
  142. },
  143. setHex: function ( hex ) {
  144. hex = Math.floor( hex );
  145. this.r = ( hex >> 16 & 255 ) / 255;
  146. this.g = ( hex >> 8 & 255 ) / 255;
  147. this.b = ( hex & 255 ) / 255;
  148. return this;
  149. },
  150. setRGB: function ( r, g, b ) {
  151. this.r = r;
  152. this.g = g;
  153. this.b = b;
  154. return this;
  155. },
  156. setHSL: function ( h, s, l ) {
  157. // h,s,l ranges are in 0.0 - 1.0
  158. if ( s === 0 ) {
  159. this.r = this.g = this.b = l;
  160. } else {
  161. var hue2rgb = function ( p, q, t ) {
  162. if ( t < 0 ) t += 1;
  163. if ( t > 1 ) t -= 1;
  164. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  165. if ( t < 1 / 2 ) return q;
  166. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  167. return p;
  168. };
  169. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  170. var q = ( 2 * l ) - p;
  171. this.r = hue2rgb( q, p, h + 1 / 3 );
  172. this.g = hue2rgb( q, p, h );
  173. this.b = hue2rgb( q, p, h - 1 / 3 );
  174. }
  175. return this;
  176. },
  177. setStyle: function ( style ) {
  178. // rgb(255,0,0)
  179. if ( /^rgb\((\d+), ?(\d+), ?(\d+)\)$/i.test( style ) ) {
  180. var color = /^rgb\((\d+), ?(\d+), ?(\d+)\)$/i.exec( style );
  181. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  182. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  183. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  184. return this;
  185. }
  186. // rgb(100%,0%,0%)
  187. if ( /^rgb\((\d+)\%, ?(\d+)\%, ?(\d+)\%\)$/i.test( style ) ) {
  188. var color = /^rgb\((\d+)\%, ?(\d+)\%, ?(\d+)\%\)$/i.exec( style );
  189. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  190. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  191. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  192. return this;
  193. }
  194. // #ff0000
  195. if ( /^\#([0-9a-f]{6})$/i.test( style ) ) {
  196. var color = /^\#([0-9a-f]{6})$/i.exec( style );
  197. this.setHex( parseInt( color[ 1 ], 16 ) );
  198. return this;
  199. }
  200. // #f00
  201. if ( /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.test( style ) ) {
  202. var color = /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec( style );
  203. this.setHex( parseInt( color[ 1 ] + color[ 1 ] + color[ 2 ] + color[ 2 ] + color[ 3 ] + color[ 3 ], 16 ) );
  204. return this;
  205. }
  206. // red
  207. if ( /^(\w+)$/i.test( style ) ) {
  208. this.setHex( THREE.ColorKeywords[ style ] );
  209. return this;
  210. }
  211. },
  212. copy: function ( color ) {
  213. this.r = color.r;
  214. this.g = color.g;
  215. this.b = color.b;
  216. return this;
  217. },
  218. copyGammaToLinear: function ( color ) {
  219. this.r = color.r * color.r;
  220. this.g = color.g * color.g;
  221. this.b = color.b * color.b;
  222. return this;
  223. },
  224. copyLinearToGamma: function ( color ) {
  225. this.r = Math.sqrt( color.r );
  226. this.g = Math.sqrt( color.g );
  227. this.b = Math.sqrt( color.b );
  228. return this;
  229. },
  230. convertGammaToLinear: function () {
  231. var r = this.r, g = this.g, b = this.b;
  232. this.r = r * r;
  233. this.g = g * g;
  234. this.b = b * b;
  235. return this;
  236. },
  237. convertLinearToGamma: function () {
  238. this.r = Math.sqrt( this.r );
  239. this.g = Math.sqrt( this.g );
  240. this.b = Math.sqrt( this.b );
  241. return this;
  242. },
  243. getHex: function () {
  244. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  245. },
  246. getHexString: function () {
  247. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  248. },
  249. getHSL: function ( optionalTarget ) {
  250. // h,s,l ranges are in 0.0 - 1.0
  251. var hsl = optionalTarget || { h: 0, s: 0, l: 0 };
  252. var r = this.r, g = this.g, b = this.b;
  253. var max = Math.max( r, g, b );
  254. var min = Math.min( r, g, b );
  255. var hue, saturation;
  256. var lightness = ( min + max ) / 2.0;
  257. if ( min === max ) {
  258. hue = 0;
  259. saturation = 0;
  260. } else {
  261. var delta = max - min;
  262. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  263. switch ( max ) {
  264. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  265. case g: hue = ( b - r ) / delta + 2; break;
  266. case b: hue = ( r - g ) / delta + 4; break;
  267. }
  268. hue /= 6;
  269. }
  270. hsl.h = hue;
  271. hsl.s = saturation;
  272. hsl.l = lightness;
  273. return hsl;
  274. },
  275. getStyle: function () {
  276. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  277. },
  278. offsetHSL: function ( h, s, l ) {
  279. var hsl = this.getHSL();
  280. hsl.h += h; hsl.s += s; hsl.l += l;
  281. this.setHSL( hsl.h, hsl.s, hsl.l );
  282. return this;
  283. },
  284. add: function ( color ) {
  285. this.r += color.r;
  286. this.g += color.g;
  287. this.b += color.b;
  288. return this;
  289. },
  290. addColors: function ( color1, color2 ) {
  291. this.r = color1.r + color2.r;
  292. this.g = color1.g + color2.g;
  293. this.b = color1.b + color2.b;
  294. return this;
  295. },
  296. addScalar: function ( s ) {
  297. this.r += s;
  298. this.g += s;
  299. this.b += s;
  300. return this;
  301. },
  302. multiply: function ( color ) {
  303. this.r *= color.r;
  304. this.g *= color.g;
  305. this.b *= color.b;
  306. return this;
  307. },
  308. multiplyScalar: function ( s ) {
  309. this.r *= s;
  310. this.g *= s;
  311. this.b *= s;
  312. return this;
  313. },
  314. lerp: function ( color, alpha ) {
  315. this.r += ( color.r - this.r ) * alpha;
  316. this.g += ( color.g - this.g ) * alpha;
  317. this.b += ( color.b - this.b ) * alpha;
  318. return this;
  319. },
  320. equals: function ( c ) {
  321. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  322. },
  323. fromArray: function ( array ) {
  324. this.r = array[ 0 ];
  325. this.g = array[ 1 ];
  326. this.b = array[ 2 ];
  327. return this;
  328. },
  329. toArray: function () {
  330. return [ this.r, this.g, this.b ];
  331. },
  332. clone: function () {
  333. return new THREE.Color().setRGB( this.r, this.g, this.b );
  334. }
  335. };
  336. THREE.ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  337. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  338. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  339. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  340. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  341. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  342. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  343. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  344. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  345. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  346. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  347. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  348. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  349. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  350. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  351. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  352. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  353. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  354. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  355. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  356. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  357. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  358. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  359. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  360. // File:src/math/Quaternion.js
  361. /**
  362. * @author mikael emtinger / http://gomo.se/
  363. * @author alteredq / http://alteredqualia.com/
  364. * @author WestLangley / http://github.com/WestLangley
  365. * @author bhouston / http://exocortex.com
  366. */
  367. THREE.Quaternion = function ( x, y, z, w ) {
  368. this._x = x || 0;
  369. this._y = y || 0;
  370. this._z = z || 0;
  371. this._w = ( w !== undefined ) ? w : 1;
  372. };
  373. THREE.Quaternion.prototype = {
  374. constructor: THREE.Quaternion,
  375. _x: 0,_y: 0, _z: 0, _w: 0,
  376. get x () {
  377. return this._x;
  378. },
  379. set x ( value ) {
  380. this._x = value;
  381. this.onChangeCallback();
  382. },
  383. get y () {
  384. return this._y;
  385. },
  386. set y ( value ) {
  387. this._y = value;
  388. this.onChangeCallback();
  389. },
  390. get z () {
  391. return this._z;
  392. },
  393. set z ( value ) {
  394. this._z = value;
  395. this.onChangeCallback();
  396. },
  397. get w () {
  398. return this._w;
  399. },
  400. set w ( value ) {
  401. this._w = value;
  402. this.onChangeCallback();
  403. },
  404. set: function ( x, y, z, w ) {
  405. this._x = x;
  406. this._y = y;
  407. this._z = z;
  408. this._w = w;
  409. this.onChangeCallback();
  410. return this;
  411. },
  412. copy: function ( quaternion ) {
  413. this._x = quaternion.x;
  414. this._y = quaternion.y;
  415. this._z = quaternion.z;
  416. this._w = quaternion.w;
  417. this.onChangeCallback();
  418. return this;
  419. },
  420. setFromEuler: function ( euler, update ) {
  421. if ( euler instanceof THREE.Euler === false ) {
  422. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  423. }
  424. // http://www.mathworks.com/matlabcentral/fileexchange/
  425. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  426. // content/SpinCalc.m
  427. var c1 = Math.cos( euler._x / 2 );
  428. var c2 = Math.cos( euler._y / 2 );
  429. var c3 = Math.cos( euler._z / 2 );
  430. var s1 = Math.sin( euler._x / 2 );
  431. var s2 = Math.sin( euler._y / 2 );
  432. var s3 = Math.sin( euler._z / 2 );
  433. if ( euler.order === 'XYZ' ) {
  434. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  435. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  436. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  437. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  438. } else if ( euler.order === 'YXZ' ) {
  439. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  440. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  441. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  442. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  443. } else if ( euler.order === 'ZXY' ) {
  444. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  445. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  446. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  447. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  448. } else if ( euler.order === 'ZYX' ) {
  449. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  450. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  451. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  452. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  453. } else if ( euler.order === 'YZX' ) {
  454. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  455. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  456. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  457. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  458. } else if ( euler.order === 'XZY' ) {
  459. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  460. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  461. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  462. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  463. }
  464. if ( update !== false ) this.onChangeCallback();
  465. return this;
  466. },
  467. setFromAxisAngle: function ( axis, angle ) {
  468. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  469. // assumes axis is normalized
  470. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  471. this._x = axis.x * s;
  472. this._y = axis.y * s;
  473. this._z = axis.z * s;
  474. this._w = Math.cos( halfAngle );
  475. this.onChangeCallback();
  476. return this;
  477. },
  478. setFromRotationMatrix: function ( m ) {
  479. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  480. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  481. var te = m.elements,
  482. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  483. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  484. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  485. trace = m11 + m22 + m33,
  486. s;
  487. if ( trace > 0 ) {
  488. s = 0.5 / Math.sqrt( trace + 1.0 );
  489. this._w = 0.25 / s;
  490. this._x = ( m32 - m23 ) * s;
  491. this._y = ( m13 - m31 ) * s;
  492. this._z = ( m21 - m12 ) * s;
  493. } else if ( m11 > m22 && m11 > m33 ) {
  494. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  495. this._w = ( m32 - m23 ) / s;
  496. this._x = 0.25 * s;
  497. this._y = ( m12 + m21 ) / s;
  498. this._z = ( m13 + m31 ) / s;
  499. } else if ( m22 > m33 ) {
  500. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  501. this._w = ( m13 - m31 ) / s;
  502. this._x = ( m12 + m21 ) / s;
  503. this._y = 0.25 * s;
  504. this._z = ( m23 + m32 ) / s;
  505. } else {
  506. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  507. this._w = ( m21 - m12 ) / s;
  508. this._x = ( m13 + m31 ) / s;
  509. this._y = ( m23 + m32 ) / s;
  510. this._z = 0.25 * s;
  511. }
  512. this.onChangeCallback();
  513. return this;
  514. },
  515. setFromUnitVectors: function () {
  516. // http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final
  517. // assumes direction vectors vFrom and vTo are normalized
  518. var v1, r;
  519. var EPS = 0.000001;
  520. return function ( vFrom, vTo ) {
  521. if ( v1 === undefined ) v1 = new THREE.Vector3();
  522. r = vFrom.dot( vTo ) + 1;
  523. if ( r < EPS ) {
  524. r = 0;
  525. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  526. v1.set( - vFrom.y, vFrom.x, 0 );
  527. } else {
  528. v1.set( 0, - vFrom.z, vFrom.y );
  529. }
  530. } else {
  531. v1.crossVectors( vFrom, vTo );
  532. }
  533. this._x = v1.x;
  534. this._y = v1.y;
  535. this._z = v1.z;
  536. this._w = r;
  537. this.normalize();
  538. return this;
  539. }
  540. }(),
  541. inverse: function () {
  542. this.conjugate().normalize();
  543. return this;
  544. },
  545. conjugate: function () {
  546. this._x *= - 1;
  547. this._y *= - 1;
  548. this._z *= - 1;
  549. this.onChangeCallback();
  550. return this;
  551. },
  552. dot: function ( v ) {
  553. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  554. },
  555. lengthSq: function () {
  556. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  557. },
  558. length: function () {
  559. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  560. },
  561. normalize: function () {
  562. var l = this.length();
  563. if ( l === 0 ) {
  564. this._x = 0;
  565. this._y = 0;
  566. this._z = 0;
  567. this._w = 1;
  568. } else {
  569. l = 1 / l;
  570. this._x = this._x * l;
  571. this._y = this._y * l;
  572. this._z = this._z * l;
  573. this._w = this._w * l;
  574. }
  575. this.onChangeCallback();
  576. return this;
  577. },
  578. multiply: function ( q, p ) {
  579. if ( p !== undefined ) {
  580. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  581. return this.multiplyQuaternions( q, p );
  582. }
  583. return this.multiplyQuaternions( this, q );
  584. },
  585. multiplyQuaternions: function ( a, b ) {
  586. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  587. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  588. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  589. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  590. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  591. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  592. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  593. this.onChangeCallback();
  594. return this;
  595. },
  596. multiplyVector3: function ( vector ) {
  597. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  598. return vector.applyQuaternion( this );
  599. },
  600. slerp: function ( qb, t ) {
  601. var x = this._x, y = this._y, z = this._z, w = this._w;
  602. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  603. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  604. if ( cosHalfTheta < 0 ) {
  605. this._w = - qb._w;
  606. this._x = - qb._x;
  607. this._y = - qb._y;
  608. this._z = - qb._z;
  609. cosHalfTheta = - cosHalfTheta;
  610. } else {
  611. this.copy( qb );
  612. }
  613. if ( cosHalfTheta >= 1.0 ) {
  614. this._w = w;
  615. this._x = x;
  616. this._y = y;
  617. this._z = z;
  618. return this;
  619. }
  620. var halfTheta = Math.acos( cosHalfTheta );
  621. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  622. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  623. this._w = 0.5 * ( w + this._w );
  624. this._x = 0.5 * ( x + this._x );
  625. this._y = 0.5 * ( y + this._y );
  626. this._z = 0.5 * ( z + this._z );
  627. return this;
  628. }
  629. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  630. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  631. this._w = ( w * ratioA + this._w * ratioB );
  632. this._x = ( x * ratioA + this._x * ratioB );
  633. this._y = ( y * ratioA + this._y * ratioB );
  634. this._z = ( z * ratioA + this._z * ratioB );
  635. this.onChangeCallback();
  636. return this;
  637. },
  638. equals: function ( quaternion ) {
  639. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  640. },
  641. fromArray: function ( array ) {
  642. this._x = array[ 0 ];
  643. this._y = array[ 1 ];
  644. this._z = array[ 2 ];
  645. this._w = array[ 3 ];
  646. this.onChangeCallback();
  647. return this;
  648. },
  649. toArray: function () {
  650. return [ this._x, this._y, this._z, this._w ];
  651. },
  652. onChange: function ( callback ) {
  653. this.onChangeCallback = callback;
  654. return this;
  655. },
  656. onChangeCallback: function () {},
  657. clone: function () {
  658. return new THREE.Quaternion( this._x, this._y, this._z, this._w );
  659. }
  660. };
  661. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  662. return qm.copy( qa ).slerp( qb, t );
  663. }
  664. // File:src/math/Vector2.js
  665. /**
  666. * @author mrdoob / http://mrdoob.com/
  667. * @author philogb / http://blog.thejit.org/
  668. * @author egraether / http://egraether.com/
  669. * @author zz85 / http://www.lab4games.net/zz85/blog
  670. */
  671. THREE.Vector2 = function ( x, y ) {
  672. this.x = x || 0;
  673. this.y = y || 0;
  674. };
  675. THREE.Vector2.prototype = {
  676. constructor: THREE.Vector2,
  677. set: function ( x, y ) {
  678. this.x = x;
  679. this.y = y;
  680. return this;
  681. },
  682. setX: function ( x ) {
  683. this.x = x;
  684. return this;
  685. },
  686. setY: function ( y ) {
  687. this.y = y;
  688. return this;
  689. },
  690. setComponent: function ( index, value ) {
  691. switch ( index ) {
  692. case 0: this.x = value; break;
  693. case 1: this.y = value; break;
  694. default: throw new Error( 'index is out of range: ' + index );
  695. }
  696. },
  697. getComponent: function ( index ) {
  698. switch ( index ) {
  699. case 0: return this.x;
  700. case 1: return this.y;
  701. default: throw new Error( 'index is out of range: ' + index );
  702. }
  703. },
  704. copy: function ( v ) {
  705. this.x = v.x;
  706. this.y = v.y;
  707. return this;
  708. },
  709. add: function ( v, w ) {
  710. if ( w !== undefined ) {
  711. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  712. return this.addVectors( v, w );
  713. }
  714. this.x += v.x;
  715. this.y += v.y;
  716. return this;
  717. },
  718. addVectors: function ( a, b ) {
  719. this.x = a.x + b.x;
  720. this.y = a.y + b.y;
  721. return this;
  722. },
  723. addScalar: function ( s ) {
  724. this.x += s;
  725. this.y += s;
  726. return this;
  727. },
  728. sub: function ( v, w ) {
  729. if ( w !== undefined ) {
  730. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  731. return this.subVectors( v, w );
  732. }
  733. this.x -= v.x;
  734. this.y -= v.y;
  735. return this;
  736. },
  737. subVectors: function ( a, b ) {
  738. this.x = a.x - b.x;
  739. this.y = a.y - b.y;
  740. return this;
  741. },
  742. multiply: function ( v ) {
  743. this.x *= v.x;
  744. this.y *= v.y;
  745. return this;
  746. },
  747. multiplyScalar: function ( s ) {
  748. this.x *= s;
  749. this.y *= s;
  750. return this;
  751. },
  752. divide: function ( v ) {
  753. this.x /= v.x;
  754. this.y /= v.y;
  755. return this;
  756. },
  757. divideScalar: function ( scalar ) {
  758. if ( scalar !== 0 ) {
  759. var invScalar = 1 / scalar;
  760. this.x *= invScalar;
  761. this.y *= invScalar;
  762. } else {
  763. this.x = 0;
  764. this.y = 0;
  765. }
  766. return this;
  767. },
  768. min: function ( v ) {
  769. if ( this.x > v.x ) {
  770. this.x = v.x;
  771. }
  772. if ( this.y > v.y ) {
  773. this.y = v.y;
  774. }
  775. return this;
  776. },
  777. max: function ( v ) {
  778. if ( this.x < v.x ) {
  779. this.x = v.x;
  780. }
  781. if ( this.y < v.y ) {
  782. this.y = v.y;
  783. }
  784. return this;
  785. },
  786. clamp: function ( min, max ) {
  787. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  788. if ( this.x < min.x ) {
  789. this.x = min.x;
  790. } else if ( this.x > max.x ) {
  791. this.x = max.x;
  792. }
  793. if ( this.y < min.y ) {
  794. this.y = min.y;
  795. } else if ( this.y > max.y ) {
  796. this.y = max.y;
  797. }
  798. return this;
  799. },
  800. clampScalar: ( function () {
  801. var min, max;
  802. return function ( minVal, maxVal ) {
  803. if ( min === undefined ) {
  804. min = new THREE.Vector2();
  805. max = new THREE.Vector2();
  806. }
  807. min.set( minVal, minVal );
  808. max.set( maxVal, maxVal );
  809. return this.clamp( min, max );
  810. };
  811. } )(),
  812. floor: function () {
  813. this.x = Math.floor( this.x );
  814. this.y = Math.floor( this.y );
  815. return this;
  816. },
  817. ceil: function () {
  818. this.x = Math.ceil( this.x );
  819. this.y = Math.ceil( this.y );
  820. return this;
  821. },
  822. round: function () {
  823. this.x = Math.round( this.x );
  824. this.y = Math.round( this.y );
  825. return this;
  826. },
  827. roundToZero: function () {
  828. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  829. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  830. return this;
  831. },
  832. negate: function () {
  833. return this.multiplyScalar( - 1 );
  834. },
  835. dot: function ( v ) {
  836. return this.x * v.x + this.y * v.y;
  837. },
  838. lengthSq: function () {
  839. return this.x * this.x + this.y * this.y;
  840. },
  841. length: function () {
  842. return Math.sqrt( this.x * this.x + this.y * this.y );
  843. },
  844. normalize: function () {
  845. return this.divideScalar( this.length() );
  846. },
  847. distanceTo: function ( v ) {
  848. return Math.sqrt( this.distanceToSquared( v ) );
  849. },
  850. distanceToSquared: function ( v ) {
  851. var dx = this.x - v.x, dy = this.y - v.y;
  852. return dx * dx + dy * dy;
  853. },
  854. setLength: function ( l ) {
  855. var oldLength = this.length();
  856. if ( oldLength !== 0 && l !== oldLength ) {
  857. this.multiplyScalar( l / oldLength );
  858. }
  859. return this;
  860. },
  861. lerp: function ( v, alpha ) {
  862. this.x += ( v.x - this.x ) * alpha;
  863. this.y += ( v.y - this.y ) * alpha;
  864. return this;
  865. },
  866. equals: function ( v ) {
  867. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  868. },
  869. fromArray: function ( array ) {
  870. this.x = array[ 0 ];
  871. this.y = array[ 1 ];
  872. return this;
  873. },
  874. toArray: function () {
  875. return [ this.x, this.y ];
  876. },
  877. clone: function () {
  878. return new THREE.Vector2( this.x, this.y );
  879. }
  880. };
  881. // File:src/math/Vector3.js
  882. /**
  883. * @author mrdoob / http://mrdoob.com/
  884. * @author *kile / http://kile.stravaganza.org/
  885. * @author philogb / http://blog.thejit.org/
  886. * @author mikael emtinger / http://gomo.se/
  887. * @author egraether / http://egraether.com/
  888. * @author WestLangley / http://github.com/WestLangley
  889. */
  890. THREE.Vector3 = function ( x, y, z ) {
  891. this.x = x || 0;
  892. this.y = y || 0;
  893. this.z = z || 0;
  894. };
  895. THREE.Vector3.prototype = {
  896. constructor: THREE.Vector3,
  897. set: function ( x, y, z ) {
  898. this.x = x;
  899. this.y = y;
  900. this.z = z;
  901. return this;
  902. },
  903. setX: function ( x ) {
  904. this.x = x;
  905. return this;
  906. },
  907. setY: function ( y ) {
  908. this.y = y;
  909. return this;
  910. },
  911. setZ: function ( z ) {
  912. this.z = z;
  913. return this;
  914. },
  915. setComponent: function ( index, value ) {
  916. switch ( index ) {
  917. case 0: this.x = value; break;
  918. case 1: this.y = value; break;
  919. case 2: this.z = value; break;
  920. default: throw new Error( 'index is out of range: ' + index );
  921. }
  922. },
  923. getComponent: function ( index ) {
  924. switch ( index ) {
  925. case 0: return this.x;
  926. case 1: return this.y;
  927. case 2: return this.z;
  928. default: throw new Error( 'index is out of range: ' + index );
  929. }
  930. },
  931. copy: function ( v ) {
  932. this.x = v.x;
  933. this.y = v.y;
  934. this.z = v.z;
  935. return this;
  936. },
  937. add: function ( v, w ) {
  938. if ( w !== undefined ) {
  939. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  940. return this.addVectors( v, w );
  941. }
  942. this.x += v.x;
  943. this.y += v.y;
  944. this.z += v.z;
  945. return this;
  946. },
  947. addScalar: function ( s ) {
  948. this.x += s;
  949. this.y += s;
  950. this.z += s;
  951. return this;
  952. },
  953. addVectors: function ( a, b ) {
  954. this.x = a.x + b.x;
  955. this.y = a.y + b.y;
  956. this.z = a.z + b.z;
  957. return this;
  958. },
  959. sub: function ( v, w ) {
  960. if ( w !== undefined ) {
  961. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  962. return this.subVectors( v, w );
  963. }
  964. this.x -= v.x;
  965. this.y -= v.y;
  966. this.z -= v.z;
  967. return this;
  968. },
  969. subVectors: function ( a, b ) {
  970. this.x = a.x - b.x;
  971. this.y = a.y - b.y;
  972. this.z = a.z - b.z;
  973. return this;
  974. },
  975. multiply: function ( v, w ) {
  976. if ( w !== undefined ) {
  977. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  978. return this.multiplyVectors( v, w );
  979. }
  980. this.x *= v.x;
  981. this.y *= v.y;
  982. this.z *= v.z;
  983. return this;
  984. },
  985. multiplyScalar: function ( scalar ) {
  986. this.x *= scalar;
  987. this.y *= scalar;
  988. this.z *= scalar;
  989. return this;
  990. },
  991. multiplyVectors: function ( a, b ) {
  992. this.x = a.x * b.x;
  993. this.y = a.y * b.y;
  994. this.z = a.z * b.z;
  995. return this;
  996. },
  997. applyEuler: function () {
  998. var quaternion;
  999. return function ( euler ) {
  1000. if ( euler instanceof THREE.Euler === false ) {
  1001. console.error( 'THREE.Vector3: .applyEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  1002. }
  1003. if ( quaternion === undefined ) quaternion = new THREE.Quaternion();
  1004. this.applyQuaternion( quaternion.setFromEuler( euler ) );
  1005. return this;
  1006. };
  1007. }(),
  1008. applyAxisAngle: function () {
  1009. var quaternion;
  1010. return function ( axis, angle ) {
  1011. if ( quaternion === undefined ) quaternion = new THREE.Quaternion();
  1012. this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  1013. return this;
  1014. };
  1015. }(),
  1016. applyMatrix3: function ( m ) {
  1017. var x = this.x;
  1018. var y = this.y;
  1019. var z = this.z;
  1020. var e = m.elements;
  1021. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  1022. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  1023. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  1024. return this;
  1025. },
  1026. applyMatrix4: function ( m ) {
  1027. // input: THREE.Matrix4 affine matrix
  1028. var x = this.x, y = this.y, z = this.z;
  1029. var e = m.elements;
  1030. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ];
  1031. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ];
  1032. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ];
  1033. return this;
  1034. },
  1035. applyProjection: function ( m ) {
  1036. // input: THREE.Matrix4 projection matrix
  1037. var x = this.x, y = this.y, z = this.z;
  1038. var e = m.elements;
  1039. var d = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] ); // perspective divide
  1040. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * d;
  1041. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * d;
  1042. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * d;
  1043. return this;
  1044. },
  1045. applyQuaternion: function ( q ) {
  1046. var x = this.x;
  1047. var y = this.y;
  1048. var z = this.z;
  1049. var qx = q.x;
  1050. var qy = q.y;
  1051. var qz = q.z;
  1052. var qw = q.w;
  1053. // calculate quat * vector
  1054. var ix = qw * x + qy * z - qz * y;
  1055. var iy = qw * y + qz * x - qx * z;
  1056. var iz = qw * z + qx * y - qy * x;
  1057. var iw = - qx * x - qy * y - qz * z;
  1058. // calculate result * inverse quat
  1059. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  1060. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  1061. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  1062. return this;
  1063. },
  1064. transformDirection: function ( m ) {
  1065. // input: THREE.Matrix4 affine matrix
  1066. // vector interpreted as a direction
  1067. var x = this.x, y = this.y, z = this.z;
  1068. var e = m.elements;
  1069. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  1070. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  1071. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  1072. this.normalize();
  1073. return this;
  1074. },
  1075. divide: function ( v ) {
  1076. this.x /= v.x;
  1077. this.y /= v.y;
  1078. this.z /= v.z;
  1079. return this;
  1080. },
  1081. divideScalar: function ( scalar ) {
  1082. if ( scalar !== 0 ) {
  1083. var invScalar = 1 / scalar;
  1084. this.x *= invScalar;
  1085. this.y *= invScalar;
  1086. this.z *= invScalar;
  1087. } else {
  1088. this.x = 0;
  1089. this.y = 0;
  1090. this.z = 0;
  1091. }
  1092. return this;
  1093. },
  1094. min: function ( v ) {
  1095. if ( this.x > v.x ) {
  1096. this.x = v.x;
  1097. }
  1098. if ( this.y > v.y ) {
  1099. this.y = v.y;
  1100. }
  1101. if ( this.z > v.z ) {
  1102. this.z = v.z;
  1103. }
  1104. return this;
  1105. },
  1106. max: function ( v ) {
  1107. if ( this.x < v.x ) {
  1108. this.x = v.x;
  1109. }
  1110. if ( this.y < v.y ) {
  1111. this.y = v.y;
  1112. }
  1113. if ( this.z < v.z ) {
  1114. this.z = v.z;
  1115. }
  1116. return this;
  1117. },
  1118. clamp: function ( min, max ) {
  1119. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1120. if ( this.x < min.x ) {
  1121. this.x = min.x;
  1122. } else if ( this.x > max.x ) {
  1123. this.x = max.x;
  1124. }
  1125. if ( this.y < min.y ) {
  1126. this.y = min.y;
  1127. } else if ( this.y > max.y ) {
  1128. this.y = max.y;
  1129. }
  1130. if ( this.z < min.z ) {
  1131. this.z = min.z;
  1132. } else if ( this.z > max.z ) {
  1133. this.z = max.z;
  1134. }
  1135. return this;
  1136. },
  1137. clampScalar: ( function () {
  1138. var min, max;
  1139. return function ( minVal, maxVal ) {
  1140. if ( min === undefined ) {
  1141. min = new THREE.Vector3();
  1142. max = new THREE.Vector3();
  1143. }
  1144. min.set( minVal, minVal, minVal );
  1145. max.set( maxVal, maxVal, maxVal );
  1146. return this.clamp( min, max );
  1147. };
  1148. } )(),
  1149. floor: function () {
  1150. this.x = Math.floor( this.x );
  1151. this.y = Math.floor( this.y );
  1152. this.z = Math.floor( this.z );
  1153. return this;
  1154. },
  1155. ceil: function () {
  1156. this.x = Math.ceil( this.x );
  1157. this.y = Math.ceil( this.y );
  1158. this.z = Math.ceil( this.z );
  1159. return this;
  1160. },
  1161. round: function () {
  1162. this.x = Math.round( this.x );
  1163. this.y = Math.round( this.y );
  1164. this.z = Math.round( this.z );
  1165. return this;
  1166. },
  1167. roundToZero: function () {
  1168. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1169. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1170. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1171. return this;
  1172. },
  1173. negate: function () {
  1174. return this.multiplyScalar( - 1 );
  1175. },
  1176. dot: function ( v ) {
  1177. return this.x * v.x + this.y * v.y + this.z * v.z;
  1178. },
  1179. lengthSq: function () {
  1180. return this.x * this.x + this.y * this.y + this.z * this.z;
  1181. },
  1182. length: function () {
  1183. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1184. },
  1185. lengthManhattan: function () {
  1186. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1187. },
  1188. normalize: function () {
  1189. return this.divideScalar( this.length() );
  1190. },
  1191. setLength: function ( l ) {
  1192. var oldLength = this.length();
  1193. if ( oldLength !== 0 && l !== oldLength ) {
  1194. this.multiplyScalar( l / oldLength );
  1195. }
  1196. return this;
  1197. },
  1198. lerp: function ( v, alpha ) {
  1199. this.x += ( v.x - this.x ) * alpha;
  1200. this.y += ( v.y - this.y ) * alpha;
  1201. this.z += ( v.z - this.z ) * alpha;
  1202. return this;
  1203. },
  1204. cross: function ( v, w ) {
  1205. if ( w !== undefined ) {
  1206. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1207. return this.crossVectors( v, w );
  1208. }
  1209. var x = this.x, y = this.y, z = this.z;
  1210. this.x = y * v.z - z * v.y;
  1211. this.y = z * v.x - x * v.z;
  1212. this.z = x * v.y - y * v.x;
  1213. return this;
  1214. },
  1215. crossVectors: function ( a, b ) {
  1216. var ax = a.x, ay = a.y, az = a.z;
  1217. var bx = b.x, by = b.y, bz = b.z;
  1218. this.x = ay * bz - az * by;
  1219. this.y = az * bx - ax * bz;
  1220. this.z = ax * by - ay * bx;
  1221. return this;
  1222. },
  1223. projectOnVector: function () {
  1224. var v1, dot;
  1225. return function ( vector ) {
  1226. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1227. v1.copy( vector ).normalize();
  1228. dot = this.dot( v1 );
  1229. return this.copy( v1 ).multiplyScalar( dot );
  1230. };
  1231. }(),
  1232. projectOnPlane: function () {
  1233. var v1;
  1234. return function ( planeNormal ) {
  1235. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1236. v1.copy( this ).projectOnVector( planeNormal );
  1237. return this.sub( v1 );
  1238. }
  1239. }(),
  1240. reflect: function () {
  1241. // reflect incident vector off plane orthogonal to normal
  1242. // normal is assumed to have unit length
  1243. var v1;
  1244. return function ( normal ) {
  1245. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1246. return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  1247. }
  1248. }(),
  1249. angleTo: function ( v ) {
  1250. var theta = this.dot( v ) / ( this.length() * v.length() );
  1251. // clamp, to handle numerical problems
  1252. return Math.acos( THREE.Math.clamp( theta, - 1, 1 ) );
  1253. },
  1254. distanceTo: function ( v ) {
  1255. return Math.sqrt( this.distanceToSquared( v ) );
  1256. },
  1257. distanceToSquared: function ( v ) {
  1258. var dx = this.x - v.x;
  1259. var dy = this.y - v.y;
  1260. var dz = this.z - v.z;
  1261. return dx * dx + dy * dy + dz * dz;
  1262. },
  1263. setEulerFromRotationMatrix: function ( m, order ) {
  1264. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  1265. },
  1266. setEulerFromQuaternion: function ( q, order ) {
  1267. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  1268. },
  1269. getPositionFromMatrix: function ( m ) {
  1270. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  1271. return this.setFromMatrixPosition( m );
  1272. },
  1273. getScaleFromMatrix: function ( m ) {
  1274. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  1275. return this.setFromMatrixScale( m );
  1276. },
  1277. getColumnFromMatrix: function ( index, matrix ) {
  1278. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  1279. return this.setFromMatrixColumn( index, matrix );
  1280. },
  1281. setFromMatrixPosition: function ( m ) {
  1282. this.x = m.elements[ 12 ];
  1283. this.y = m.elements[ 13 ];
  1284. this.z = m.elements[ 14 ];
  1285. return this;
  1286. },
  1287. setFromMatrixScale: function ( m ) {
  1288. var sx = this.set( m.elements[ 0 ], m.elements[ 1 ], m.elements[ 2 ] ).length();
  1289. var sy = this.set( m.elements[ 4 ], m.elements[ 5 ], m.elements[ 6 ] ).length();
  1290. var sz = this.set( m.elements[ 8 ], m.elements[ 9 ], m.elements[ 10 ] ).length();
  1291. this.x = sx;
  1292. this.y = sy;
  1293. this.z = sz;
  1294. return this;
  1295. },
  1296. setFromMatrixColumn: function ( index, matrix ) {
  1297. var offset = index * 4;
  1298. var me = matrix.elements;
  1299. this.x = me[ offset ];
  1300. this.y = me[ offset + 1 ];
  1301. this.z = me[ offset + 2 ];
  1302. return this;
  1303. },
  1304. equals: function ( v ) {
  1305. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1306. },
  1307. fromArray: function ( array ) {
  1308. this.x = array[ 0 ];
  1309. this.y = array[ 1 ];
  1310. this.z = array[ 2 ];
  1311. return this;
  1312. },
  1313. toArray: function () {
  1314. return [ this.x, this.y, this.z ];
  1315. },
  1316. clone: function () {
  1317. return new THREE.Vector3( this.x, this.y, this.z );
  1318. }
  1319. };
  1320. // File:src/math/Vector4.js
  1321. /**
  1322. * @author supereggbert / http://www.paulbrunt.co.uk/
  1323. * @author philogb / http://blog.thejit.org/
  1324. * @author mikael emtinger / http://gomo.se/
  1325. * @author egraether / http://egraether.com/
  1326. * @author WestLangley / http://github.com/WestLangley
  1327. */
  1328. THREE.Vector4 = function ( x, y, z, w ) {
  1329. this.x = x || 0;
  1330. this.y = y || 0;
  1331. this.z = z || 0;
  1332. this.w = ( w !== undefined ) ? w : 1;
  1333. };
  1334. THREE.Vector4.prototype = {
  1335. constructor: THREE.Vector4,
  1336. set: function ( x, y, z, w ) {
  1337. this.x = x;
  1338. this.y = y;
  1339. this.z = z;
  1340. this.w = w;
  1341. return this;
  1342. },
  1343. setX: function ( x ) {
  1344. this.x = x;
  1345. return this;
  1346. },
  1347. setY: function ( y ) {
  1348. this.y = y;
  1349. return this;
  1350. },
  1351. setZ: function ( z ) {
  1352. this.z = z;
  1353. return this;
  1354. },
  1355. setW: function ( w ) {
  1356. this.w = w;
  1357. return this;
  1358. },
  1359. setComponent: function ( index, value ) {
  1360. switch ( index ) {
  1361. case 0: this.x = value; break;
  1362. case 1: this.y = value; break;
  1363. case 2: this.z = value; break;
  1364. case 3: this.w = value; break;
  1365. default: throw new Error( 'index is out of range: ' + index );
  1366. }
  1367. },
  1368. getComponent: function ( index ) {
  1369. switch ( index ) {
  1370. case 0: return this.x;
  1371. case 1: return this.y;
  1372. case 2: return this.z;
  1373. case 3: return this.w;
  1374. default: throw new Error( 'index is out of range: ' + index );
  1375. }
  1376. },
  1377. copy: function ( v ) {
  1378. this.x = v.x;
  1379. this.y = v.y;
  1380. this.z = v.z;
  1381. this.w = ( v.w !== undefined ) ? v.w : 1;
  1382. return this;
  1383. },
  1384. add: function ( v, w ) {
  1385. if ( w !== undefined ) {
  1386. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1387. return this.addVectors( v, w );
  1388. }
  1389. this.x += v.x;
  1390. this.y += v.y;
  1391. this.z += v.z;
  1392. this.w += v.w;
  1393. return this;
  1394. },
  1395. addScalar: function ( s ) {
  1396. this.x += s;
  1397. this.y += s;
  1398. this.z += s;
  1399. this.w += s;
  1400. return this;
  1401. },
  1402. addVectors: function ( a, b ) {
  1403. this.x = a.x + b.x;
  1404. this.y = a.y + b.y;
  1405. this.z = a.z + b.z;
  1406. this.w = a.w + b.w;
  1407. return this;
  1408. },
  1409. sub: function ( v, w ) {
  1410. if ( w !== undefined ) {
  1411. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1412. return this.subVectors( v, w );
  1413. }
  1414. this.x -= v.x;
  1415. this.y -= v.y;
  1416. this.z -= v.z;
  1417. this.w -= v.w;
  1418. return this;
  1419. },
  1420. subVectors: function ( a, b ) {
  1421. this.x = a.x - b.x;
  1422. this.y = a.y - b.y;
  1423. this.z = a.z - b.z;
  1424. this.w = a.w - b.w;
  1425. return this;
  1426. },
  1427. multiplyScalar: function ( scalar ) {
  1428. this.x *= scalar;
  1429. this.y *= scalar;
  1430. this.z *= scalar;
  1431. this.w *= scalar;
  1432. return this;
  1433. },
  1434. applyMatrix4: function ( m ) {
  1435. var x = this.x;
  1436. var y = this.y;
  1437. var z = this.z;
  1438. var w = this.w;
  1439. var e = m.elements;
  1440. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1441. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1442. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1443. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1444. return this;
  1445. },
  1446. divideScalar: function ( scalar ) {
  1447. if ( scalar !== 0 ) {
  1448. var invScalar = 1 / scalar;
  1449. this.x *= invScalar;
  1450. this.y *= invScalar;
  1451. this.z *= invScalar;
  1452. this.w *= invScalar;
  1453. } else {
  1454. this.x = 0;
  1455. this.y = 0;
  1456. this.z = 0;
  1457. this.w = 1;
  1458. }
  1459. return this;
  1460. },
  1461. setAxisAngleFromQuaternion: function ( q ) {
  1462. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1463. // q is assumed to be normalized
  1464. this.w = 2 * Math.acos( q.w );
  1465. var s = Math.sqrt( 1 - q.w * q.w );
  1466. if ( s < 0.0001 ) {
  1467. this.x = 1;
  1468. this.y = 0;
  1469. this.z = 0;
  1470. } else {
  1471. this.x = q.x / s;
  1472. this.y = q.y / s;
  1473. this.z = q.z / s;
  1474. }
  1475. return this;
  1476. },
  1477. setAxisAngleFromRotationMatrix: function ( m ) {
  1478. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1479. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1480. var angle, x, y, z, // variables for result
  1481. epsilon = 0.01, // margin to allow for rounding errors
  1482. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1483. te = m.elements,
  1484. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1485. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1486. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1487. if ( ( Math.abs( m12 - m21 ) < epsilon )
  1488. && ( Math.abs( m13 - m31 ) < epsilon )
  1489. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1490. // singularity found
  1491. // first check for identity matrix which must have +1 for all terms
  1492. // in leading diagonal and zero in other terms
  1493. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  1494. && ( Math.abs( m13 + m31 ) < epsilon2 )
  1495. && ( Math.abs( m23 + m32 ) < epsilon2 )
  1496. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1497. // this singularity is identity matrix so angle = 0
  1498. this.set( 1, 0, 0, 0 );
  1499. return this; // zero angle, arbitrary axis
  1500. }
  1501. // otherwise this singularity is angle = 180
  1502. angle = Math.PI;
  1503. var xx = ( m11 + 1 ) / 2;
  1504. var yy = ( m22 + 1 ) / 2;
  1505. var zz = ( m33 + 1 ) / 2;
  1506. var xy = ( m12 + m21 ) / 4;
  1507. var xz = ( m13 + m31 ) / 4;
  1508. var yz = ( m23 + m32 ) / 4;
  1509. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  1510. if ( xx < epsilon ) {
  1511. x = 0;
  1512. y = 0.707106781;
  1513. z = 0.707106781;
  1514. } else {
  1515. x = Math.sqrt( xx );
  1516. y = xy / x;
  1517. z = xz / x;
  1518. }
  1519. } else if ( yy > zz ) { // m22 is the largest diagonal term
  1520. if ( yy < epsilon ) {
  1521. x = 0.707106781;
  1522. y = 0;
  1523. z = 0.707106781;
  1524. } else {
  1525. y = Math.sqrt( yy );
  1526. x = xy / y;
  1527. z = yz / y;
  1528. }
  1529. } else { // m33 is the largest diagonal term so base result on this
  1530. if ( zz < epsilon ) {
  1531. x = 0.707106781;
  1532. y = 0.707106781;
  1533. z = 0;
  1534. } else {
  1535. z = Math.sqrt( zz );
  1536. x = xz / z;
  1537. y = yz / z;
  1538. }
  1539. }
  1540. this.set( x, y, z, angle );
  1541. return this; // return 180 deg rotation
  1542. }
  1543. // as we have reached here there are no singularities so we can handle normally
  1544. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  1545. + ( m13 - m31 ) * ( m13 - m31 )
  1546. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1547. if ( Math.abs( s ) < 0.001 ) s = 1;
  1548. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1549. // caught by singularity test above, but I've left it in just in case
  1550. this.x = ( m32 - m23 ) / s;
  1551. this.y = ( m13 - m31 ) / s;
  1552. this.z = ( m21 - m12 ) / s;
  1553. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1554. return this;
  1555. },
  1556. min: function ( v ) {
  1557. if ( this.x > v.x ) {
  1558. this.x = v.x;
  1559. }
  1560. if ( this.y > v.y ) {
  1561. this.y = v.y;
  1562. }
  1563. if ( this.z > v.z ) {
  1564. this.z = v.z;
  1565. }
  1566. if ( this.w > v.w ) {
  1567. this.w = v.w;
  1568. }
  1569. return this;
  1570. },
  1571. max: function ( v ) {
  1572. if ( this.x < v.x ) {
  1573. this.x = v.x;
  1574. }
  1575. if ( this.y < v.y ) {
  1576. this.y = v.y;
  1577. }
  1578. if ( this.z < v.z ) {
  1579. this.z = v.z;
  1580. }
  1581. if ( this.w < v.w ) {
  1582. this.w = v.w;
  1583. }
  1584. return this;
  1585. },
  1586. clamp: function ( min, max ) {
  1587. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1588. if ( this.x < min.x ) {
  1589. this.x = min.x;
  1590. } else if ( this.x > max.x ) {
  1591. this.x = max.x;
  1592. }
  1593. if ( this.y < min.y ) {
  1594. this.y = min.y;
  1595. } else if ( this.y > max.y ) {
  1596. this.y = max.y;
  1597. }
  1598. if ( this.z < min.z ) {
  1599. this.z = min.z;
  1600. } else if ( this.z > max.z ) {
  1601. this.z = max.z;
  1602. }
  1603. if ( this.w < min.w ) {
  1604. this.w = min.w;
  1605. } else if ( this.w > max.w ) {
  1606. this.w = max.w;
  1607. }
  1608. return this;
  1609. },
  1610. clampScalar: ( function () {
  1611. var min, max;
  1612. return function ( minVal, maxVal ) {
  1613. if ( min === undefined ) {
  1614. min = new THREE.Vector4();
  1615. max = new THREE.Vector4();
  1616. }
  1617. min.set( minVal, minVal, minVal, minVal );
  1618. max.set( maxVal, maxVal, maxVal, maxVal );
  1619. return this.clamp( min, max );
  1620. };
  1621. } )(),
  1622. floor: function () {
  1623. this.x = Math.floor( this.x );
  1624. this.y = Math.floor( this.y );
  1625. this.z = Math.floor( this.z );
  1626. this.w = Math.floor( this.w );
  1627. return this;
  1628. },
  1629. ceil: function () {
  1630. this.x = Math.ceil( this.x );
  1631. this.y = Math.ceil( this.y );
  1632. this.z = Math.ceil( this.z );
  1633. this.w = Math.ceil( this.w );
  1634. return this;
  1635. },
  1636. round: function () {
  1637. this.x = Math.round( this.x );
  1638. this.y = Math.round( this.y );
  1639. this.z = Math.round( this.z );
  1640. this.w = Math.round( this.w );
  1641. return this;
  1642. },
  1643. roundToZero: function () {
  1644. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1645. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1646. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1647. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1648. return this;
  1649. },
  1650. negate: function () {
  1651. return this.multiplyScalar( - 1 );
  1652. },
  1653. dot: function ( v ) {
  1654. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1655. },
  1656. lengthSq: function () {
  1657. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1658. },
  1659. length: function () {
  1660. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1661. },
  1662. lengthManhattan: function () {
  1663. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1664. },
  1665. normalize: function () {
  1666. return this.divideScalar( this.length() );
  1667. },
  1668. setLength: function ( l ) {
  1669. var oldLength = this.length();
  1670. if ( oldLength !== 0 && l !== oldLength ) {
  1671. this.multiplyScalar( l / oldLength );
  1672. }
  1673. return this;
  1674. },
  1675. lerp: function ( v, alpha ) {
  1676. this.x += ( v.x - this.x ) * alpha;
  1677. this.y += ( v.y - this.y ) * alpha;
  1678. this.z += ( v.z - this.z ) * alpha;
  1679. this.w += ( v.w - this.w ) * alpha;
  1680. return this;
  1681. },
  1682. equals: function ( v ) {
  1683. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1684. },
  1685. fromArray: function ( array ) {
  1686. this.x = array[ 0 ];
  1687. this.y = array[ 1 ];
  1688. this.z = array[ 2 ];
  1689. this.w = array[ 3 ];
  1690. return this;
  1691. },
  1692. toArray: function () {
  1693. return [ this.x, this.y, this.z, this.w ];
  1694. },
  1695. clone: function () {
  1696. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  1697. }
  1698. };
  1699. // File:src/math/Euler.js
  1700. /**
  1701. * @author mrdoob / http://mrdoob.com/
  1702. * @author WestLangley / http://github.com/WestLangley
  1703. * @author bhouston / http://exocortex.com
  1704. */
  1705. THREE.Euler = function ( x, y, z, order ) {
  1706. this._x = x || 0;
  1707. this._y = y || 0;
  1708. this._z = z || 0;
  1709. this._order = order || THREE.Euler.DefaultOrder;
  1710. };
  1711. THREE.Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  1712. THREE.Euler.DefaultOrder = 'XYZ';
  1713. THREE.Euler.prototype = {
  1714. constructor: THREE.Euler,
  1715. _x: 0, _y: 0, _z: 0, _order: THREE.Euler.DefaultOrder,
  1716. get x () {
  1717. return this._x;
  1718. },
  1719. set x ( value ) {
  1720. this._x = value;
  1721. this.onChangeCallback();
  1722. },
  1723. get y () {
  1724. return this._y;
  1725. },
  1726. set y ( value ) {
  1727. this._y = value;
  1728. this.onChangeCallback();
  1729. },
  1730. get z () {
  1731. return this._z;
  1732. },
  1733. set z ( value ) {
  1734. this._z = value;
  1735. this.onChangeCallback();
  1736. },
  1737. get order () {
  1738. return this._order;
  1739. },
  1740. set order ( value ) {
  1741. this._order = value;
  1742. this.onChangeCallback();
  1743. },
  1744. set: function ( x, y, z, order ) {
  1745. this._x = x;
  1746. this._y = y;
  1747. this._z = z;
  1748. this._order = order || this._order;
  1749. this.onChangeCallback();
  1750. return this;
  1751. },
  1752. copy: function ( euler ) {
  1753. this._x = euler._x;
  1754. this._y = euler._y;
  1755. this._z = euler._z;
  1756. this._order = euler._order;
  1757. this.onChangeCallback();
  1758. return this;
  1759. },
  1760. setFromRotationMatrix: function ( m, order ) {
  1761. var clamp = THREE.Math.clamp;
  1762. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1763. var te = m.elements;
  1764. var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  1765. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  1766. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1767. order = order || this._order;
  1768. if ( order === 'XYZ' ) {
  1769. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  1770. if ( Math.abs( m13 ) < 0.99999 ) {
  1771. this._x = Math.atan2( - m23, m33 );
  1772. this._z = Math.atan2( - m12, m11 );
  1773. } else {
  1774. this._x = Math.atan2( m32, m22 );
  1775. this._z = 0;
  1776. }
  1777. } else if ( order === 'YXZ' ) {
  1778. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  1779. if ( Math.abs( m23 ) < 0.99999 ) {
  1780. this._y = Math.atan2( m13, m33 );
  1781. this._z = Math.atan2( m21, m22 );
  1782. } else {
  1783. this._y = Math.atan2( - m31, m11 );
  1784. this._z = 0;
  1785. }
  1786. } else if ( order === 'ZXY' ) {
  1787. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  1788. if ( Math.abs( m32 ) < 0.99999 ) {
  1789. this._y = Math.atan2( - m31, m33 );
  1790. this._z = Math.atan2( - m12, m22 );
  1791. } else {
  1792. this._y = 0;
  1793. this._z = Math.atan2( m21, m11 );
  1794. }
  1795. } else if ( order === 'ZYX' ) {
  1796. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  1797. if ( Math.abs( m31 ) < 0.99999 ) {
  1798. this._x = Math.atan2( m32, m33 );
  1799. this._z = Math.atan2( m21, m11 );
  1800. } else {
  1801. this._x = 0;
  1802. this._z = Math.atan2( - m12, m22 );
  1803. }
  1804. } else if ( order === 'YZX' ) {
  1805. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  1806. if ( Math.abs( m21 ) < 0.99999 ) {
  1807. this._x = Math.atan2( - m23, m22 );
  1808. this._y = Math.atan2( - m31, m11 );
  1809. } else {
  1810. this._x = 0;
  1811. this._y = Math.atan2( m13, m33 );
  1812. }
  1813. } else if ( order === 'XZY' ) {
  1814. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  1815. if ( Math.abs( m12 ) < 0.99999 ) {
  1816. this._x = Math.atan2( m32, m22 );
  1817. this._y = Math.atan2( m13, m11 );
  1818. } else {
  1819. this._x = Math.atan2( - m23, m33 );
  1820. this._y = 0;
  1821. }
  1822. } else {
  1823. console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order )
  1824. }
  1825. this._order = order;
  1826. this.onChangeCallback();
  1827. return this;
  1828. },
  1829. setFromQuaternion: function ( q, order, update ) {
  1830. var clamp = THREE.Math.clamp;
  1831. // q is assumed to be normalized
  1832. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  1833. var sqx = q.x * q.x;
  1834. var sqy = q.y * q.y;
  1835. var sqz = q.z * q.z;
  1836. var sqw = q.w * q.w;
  1837. order = order || this._order;
  1838. if ( order === 'XYZ' ) {
  1839. this._x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  1840. this._y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ), - 1, 1 ) );
  1841. this._z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  1842. } else if ( order === 'YXZ' ) {
  1843. this._x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ), - 1, 1 ) );
  1844. this._y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  1845. this._z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  1846. } else if ( order === 'ZXY' ) {
  1847. this._x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ), - 1, 1 ) );
  1848. this._y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  1849. this._z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  1850. } else if ( order === 'ZYX' ) {
  1851. this._x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  1852. this._y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ), - 1, 1 ) );
  1853. this._z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  1854. } else if ( order === 'YZX' ) {
  1855. this._x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  1856. this._y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  1857. this._z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ), - 1, 1 ) );
  1858. } else if ( order === 'XZY' ) {
  1859. this._x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  1860. this._y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  1861. this._z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ), - 1, 1 ) );
  1862. } else {
  1863. console.warn( 'THREE.Euler: .setFromQuaternion() given unsupported order: ' + order )
  1864. }
  1865. this._order = order;
  1866. if ( update !== false ) this.onChangeCallback();
  1867. return this;
  1868. },
  1869. reorder: function () {
  1870. // WARNING: this discards revolution information -bhouston
  1871. var q = new THREE.Quaternion();
  1872. return function ( newOrder ) {
  1873. q.setFromEuler( this );
  1874. this.setFromQuaternion( q, newOrder );
  1875. };
  1876. }(),
  1877. equals: function ( euler ) {
  1878. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  1879. },
  1880. fromArray: function ( array ) {
  1881. this._x = array[ 0 ];
  1882. this._y = array[ 1 ];
  1883. this._z = array[ 2 ];
  1884. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  1885. this.onChangeCallback();
  1886. return this;
  1887. },
  1888. toArray: function () {
  1889. return [ this._x, this._y, this._z, this._order ];
  1890. },
  1891. onChange: function ( callback ) {
  1892. this.onChangeCallback = callback;
  1893. return this;
  1894. },
  1895. onChangeCallback: function () {},
  1896. clone: function () {
  1897. return new THREE.Euler( this._x, this._y, this._z, this._order );
  1898. }
  1899. };
  1900. // File:src/math/Line3.js
  1901. /**
  1902. * @author bhouston / http://exocortex.com
  1903. */
  1904. THREE.Line3 = function ( start, end ) {
  1905. this.start = ( start !== undefined ) ? start : new THREE.Vector3();
  1906. this.end = ( end !== undefined ) ? end : new THREE.Vector3();
  1907. };
  1908. THREE.Line3.prototype = {
  1909. constructor: THREE.Line3,
  1910. set: function ( start, end ) {
  1911. this.start.copy( start );
  1912. this.end.copy( end );
  1913. return this;
  1914. },
  1915. copy: function ( line ) {
  1916. this.start.copy( line.start );
  1917. this.end.copy( line.end );
  1918. return this;
  1919. },
  1920. center: function ( optionalTarget ) {
  1921. var result = optionalTarget || new THREE.Vector3();
  1922. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  1923. },
  1924. delta: function ( optionalTarget ) {
  1925. var result = optionalTarget || new THREE.Vector3();
  1926. return result.subVectors( this.end, this.start );
  1927. },
  1928. distanceSq: function () {
  1929. return this.start.distanceToSquared( this.end );
  1930. },
  1931. distance: function () {
  1932. return this.start.distanceTo( this.end );
  1933. },
  1934. at: function ( t, optionalTarget ) {
  1935. var result = optionalTarget || new THREE.Vector3();
  1936. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1937. },
  1938. closestPointToPointParameter: function () {
  1939. var startP = new THREE.Vector3();
  1940. var startEnd = new THREE.Vector3();
  1941. return function ( point, clampToLine ) {
  1942. startP.subVectors( point, this.start );
  1943. startEnd.subVectors( this.end, this.start );
  1944. var startEnd2 = startEnd.dot( startEnd );
  1945. var startEnd_startP = startEnd.dot( startP );
  1946. var t = startEnd_startP / startEnd2;
  1947. if ( clampToLine ) {
  1948. t = THREE.Math.clamp( t, 0, 1 );
  1949. }
  1950. return t;
  1951. };
  1952. }(),
  1953. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  1954. var t = this.closestPointToPointParameter( point, clampToLine );
  1955. var result = optionalTarget || new THREE.Vector3();
  1956. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1957. },
  1958. applyMatrix4: function ( matrix ) {
  1959. this.start.applyMatrix4( matrix );
  1960. this.end.applyMatrix4( matrix );
  1961. return this;
  1962. },
  1963. equals: function ( line ) {
  1964. return line.start.equals( this.start ) && line.end.equals( this.end );
  1965. },
  1966. clone: function () {
  1967. return new THREE.Line3().copy( this );
  1968. }
  1969. };
  1970. // File:src/math/Box2.js
  1971. /**
  1972. * @author bhouston / http://exocortex.com
  1973. */
  1974. THREE.Box2 = function ( min, max ) {
  1975. this.min = ( min !== undefined ) ? min : new THREE.Vector2( Infinity, Infinity );
  1976. this.max = ( max !== undefined ) ? max : new THREE.Vector2( - Infinity, - Infinity );
  1977. };
  1978. THREE.Box2.prototype = {
  1979. constructor: THREE.Box2,
  1980. set: function ( min, max ) {
  1981. this.min.copy( min );
  1982. this.max.copy( max );
  1983. return this;
  1984. },
  1985. setFromPoints: function ( points ) {
  1986. this.makeEmpty();
  1987. for ( var i = 0, il = points.length; i < il; i ++ ) {
  1988. this.expandByPoint( points[ i ] )
  1989. }
  1990. return this;
  1991. },
  1992. setFromCenterAndSize: function () {
  1993. var v1 = new THREE.Vector2();
  1994. return function ( center, size ) {
  1995. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  1996. this.min.copy( center ).sub( halfSize );
  1997. this.max.copy( center ).add( halfSize );
  1998. return this;
  1999. };
  2000. }(),
  2001. copy: function ( box ) {
  2002. this.min.copy( box.min );
  2003. this.max.copy( box.max );
  2004. return this;
  2005. },
  2006. makeEmpty: function () {
  2007. this.min.x = this.min.y = Infinity;
  2008. this.max.x = this.max.y = - Infinity;
  2009. return this;
  2010. },
  2011. empty: function () {
  2012. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2013. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  2014. },
  2015. center: function ( optionalTarget ) {
  2016. var result = optionalTarget || new THREE.Vector2();
  2017. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2018. },
  2019. size: function ( optionalTarget ) {
  2020. var result = optionalTarget || new THREE.Vector2();
  2021. return result.subVectors( this.max, this.min );
  2022. },
  2023. expandByPoint: function ( point ) {
  2024. this.min.min( point );
  2025. this.max.max( point );
  2026. return this;
  2027. },
  2028. expandByVector: function ( vector ) {
  2029. this.min.sub( vector );
  2030. this.max.add( vector );
  2031. return this;
  2032. },
  2033. expandByScalar: function ( scalar ) {
  2034. this.min.addScalar( - scalar );
  2035. this.max.addScalar( scalar );
  2036. return this;
  2037. },
  2038. containsPoint: function ( point ) {
  2039. if ( point.x < this.min.x || point.x > this.max.x ||
  2040. point.y < this.min.y || point.y > this.max.y ) {
  2041. return false;
  2042. }
  2043. return true;
  2044. },
  2045. containsBox: function ( box ) {
  2046. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2047. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  2048. return true;
  2049. }
  2050. return false;
  2051. },
  2052. getParameter: function ( point, optionalTarget ) {
  2053. // This can potentially have a divide by zero if the box
  2054. // has a size dimension of 0.
  2055. var result = optionalTarget || new THREE.Vector2();
  2056. return result.set(
  2057. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2058. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  2059. );
  2060. },
  2061. isIntersectionBox: function ( box ) {
  2062. // using 6 splitting planes to rule out intersections.
  2063. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2064. box.max.y < this.min.y || box.min.y > this.max.y ) {
  2065. return false;
  2066. }
  2067. return true;
  2068. },
  2069. clampPoint: function ( point, optionalTarget ) {
  2070. var result = optionalTarget || new THREE.Vector2();
  2071. return result.copy( point ).clamp( this.min, this.max );
  2072. },
  2073. distanceToPoint: function () {
  2074. var v1 = new THREE.Vector2();
  2075. return function ( point ) {
  2076. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2077. return clampedPoint.sub( point ).length();
  2078. };
  2079. }(),
  2080. intersect: function ( box ) {
  2081. this.min.max( box.min );
  2082. this.max.min( box.max );
  2083. return this;
  2084. },
  2085. union: function ( box ) {
  2086. this.min.min( box.min );
  2087. this.max.max( box.max );
  2088. return this;
  2089. },
  2090. translate: function ( offset ) {
  2091. this.min.add( offset );
  2092. this.max.add( offset );
  2093. return this;
  2094. },
  2095. equals: function ( box ) {
  2096. return box.min.equals( this.min ) && box.max.equals( this.max );
  2097. },
  2098. clone: function () {
  2099. return new THREE.Box2().copy( this );
  2100. }
  2101. };
  2102. // File:src/math/Box3.js
  2103. /**
  2104. * @author bhouston / http://exocortex.com
  2105. * @author WestLangley / http://github.com/WestLangley
  2106. */
  2107. THREE.Box3 = function ( min, max ) {
  2108. this.min = ( min !== undefined ) ? min : new THREE.Vector3( Infinity, Infinity, Infinity );
  2109. this.max = ( max !== undefined ) ? max : new THREE.Vector3( - Infinity, - Infinity, - Infinity );
  2110. };
  2111. THREE.Box3.prototype = {
  2112. constructor: THREE.Box3,
  2113. set: function ( min, max ) {
  2114. this.min.copy( min );
  2115. this.max.copy( max );
  2116. return this;
  2117. },
  2118. setFromPoints: function ( points ) {
  2119. this.makeEmpty();
  2120. for ( var i = 0, il = points.length; i < il; i ++ ) {
  2121. this.expandByPoint( points[ i ] )
  2122. }
  2123. return this;
  2124. },
  2125. setFromCenterAndSize: function () {
  2126. var v1 = new THREE.Vector3();
  2127. return function ( center, size ) {
  2128. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2129. this.min.copy( center ).sub( halfSize );
  2130. this.max.copy( center ).add( halfSize );
  2131. return this;
  2132. };
  2133. }(),
  2134. setFromObject: function () {
  2135. // Computes the world-axis-aligned bounding box of an object (including its children),
  2136. // accounting for both the object's, and childrens', world transforms
  2137. var v1 = new THREE.Vector3();
  2138. return function ( object ) {
  2139. var scope = this;
  2140. object.updateMatrixWorld( true );
  2141. this.makeEmpty();
  2142. object.traverse( function ( node ) {
  2143. if ( node.geometry !== undefined && node.geometry.vertices !== undefined ) {
  2144. var vertices = node.geometry.vertices;
  2145. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  2146. v1.copy( vertices[ i ] );
  2147. v1.applyMatrix4( node.matrixWorld );
  2148. scope.expandByPoint( v1 );
  2149. }
  2150. }
  2151. } );
  2152. return this;
  2153. };
  2154. }(),
  2155. copy: function ( box ) {
  2156. this.min.copy( box.min );
  2157. this.max.copy( box.max );
  2158. return this;
  2159. },
  2160. makeEmpty: function () {
  2161. this.min.x = this.min.y = this.min.z = Infinity;
  2162. this.max.x = this.max.y = this.max.z = - Infinity;
  2163. return this;
  2164. },
  2165. empty: function () {
  2166. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2167. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2168. },
  2169. center: function ( optionalTarget ) {
  2170. var result = optionalTarget || new THREE.Vector3();
  2171. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2172. },
  2173. size: function ( optionalTarget ) {
  2174. var result = optionalTarget || new THREE.Vector3();
  2175. return result.subVectors( this.max, this.min );
  2176. },
  2177. expandByPoint: function ( point ) {
  2178. this.min.min( point );
  2179. this.max.max( point );
  2180. return this;
  2181. },
  2182. expandByVector: function ( vector ) {
  2183. this.min.sub( vector );
  2184. this.max.add( vector );
  2185. return this;
  2186. },
  2187. expandByScalar: function ( scalar ) {
  2188. this.min.addScalar( - scalar );
  2189. this.max.addScalar( scalar );
  2190. return this;
  2191. },
  2192. containsPoint: function ( point ) {
  2193. if ( point.x < this.min.x || point.x > this.max.x ||
  2194. point.y < this.min.y || point.y > this.max.y ||
  2195. point.z < this.min.z || point.z > this.max.z ) {
  2196. return false;
  2197. }
  2198. return true;
  2199. },
  2200. containsBox: function ( box ) {
  2201. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2202. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  2203. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  2204. return true;
  2205. }
  2206. return false;
  2207. },
  2208. getParameter: function ( point, optionalTarget ) {
  2209. // This can potentially have a divide by zero if the box
  2210. // has a size dimension of 0.
  2211. var result = optionalTarget || new THREE.Vector3();
  2212. return result.set(
  2213. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2214. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2215. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2216. );
  2217. },
  2218. isIntersectionBox: function ( box ) {
  2219. // using 6 splitting planes to rule out intersections.
  2220. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2221. box.max.y < this.min.y || box.min.y > this.max.y ||
  2222. box.max.z < this.min.z || box.min.z > this.max.z ) {
  2223. return false;
  2224. }
  2225. return true;
  2226. },
  2227. clampPoint: function ( point, optionalTarget ) {
  2228. var result = optionalTarget || new THREE.Vector3();
  2229. return result.copy( point ).clamp( this.min, this.max );
  2230. },
  2231. distanceToPoint: function () {
  2232. var v1 = new THREE.Vector3();
  2233. return function ( point ) {
  2234. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2235. return clampedPoint.sub( point ).length();
  2236. };
  2237. }(),
  2238. getBoundingSphere: function () {
  2239. var v1 = new THREE.Vector3();
  2240. return function ( optionalTarget ) {
  2241. var result = optionalTarget || new THREE.Sphere();
  2242. result.center = this.center();
  2243. result.radius = this.size( v1 ).length() * 0.5;
  2244. return result;
  2245. };
  2246. }(),
  2247. intersect: function ( box ) {
  2248. this.min.max( box.min );
  2249. this.max.min( box.max );
  2250. return this;
  2251. },
  2252. union: function ( box ) {
  2253. this.min.min( box.min );
  2254. this.max.max( box.max );
  2255. return this;
  2256. },
  2257. applyMatrix4: function () {
  2258. var points = [
  2259. new THREE.Vector3(),
  2260. new THREE.Vector3(),
  2261. new THREE.Vector3(),
  2262. new THREE.Vector3(),
  2263. new THREE.Vector3(),
  2264. new THREE.Vector3(),
  2265. new THREE.Vector3(),
  2266. new THREE.Vector3()
  2267. ];
  2268. return function ( matrix ) {
  2269. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2270. points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2271. points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2272. points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2273. points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2274. points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2275. points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2276. points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2277. points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2278. this.makeEmpty();
  2279. this.setFromPoints( points );
  2280. return this;
  2281. };
  2282. }(),
  2283. translate: function ( offset ) {
  2284. this.min.add( offset );
  2285. this.max.add( offset );
  2286. return this;
  2287. },
  2288. equals: function ( box ) {
  2289. return box.min.equals( this.min ) && box.max.equals( this.max );
  2290. },
  2291. clone: function () {
  2292. return new THREE.Box3().copy( this );
  2293. }
  2294. };
  2295. // File:src/math/Matrix3.js
  2296. /**
  2297. * @author alteredq / http://alteredqualia.com/
  2298. * @author WestLangley / http://github.com/WestLangley
  2299. * @author bhouston / http://exocortex.com
  2300. */
  2301. THREE.Matrix3 = function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2302. this.elements = new Float32Array( 9 );
  2303. var te = this.elements;
  2304. te[ 0 ] = ( n11 !== undefined ) ? n11 : 1; te[ 3 ] = n12 || 0; te[ 6 ] = n13 || 0;
  2305. te[ 1 ] = n21 || 0; te[ 4 ] = ( n22 !== undefined ) ? n22 : 1; te[ 7 ] = n23 || 0;
  2306. te[ 2 ] = n31 || 0; te[ 5 ] = n32 || 0; te[ 8 ] = ( n33 !== undefined ) ? n33 : 1;
  2307. };
  2308. THREE.Matrix3.prototype = {
  2309. constructor: THREE.Matrix3,
  2310. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2311. var te = this.elements;
  2312. te[ 0 ] = n11; te[ 3 ] = n12; te[ 6 ] = n13;
  2313. te[ 1 ] = n21; te[ 4 ] = n22; te[ 7 ] = n23;
  2314. te[ 2 ] = n31; te[ 5 ] = n32; te[ 8 ] = n33;
  2315. return this;
  2316. },
  2317. identity: function () {
  2318. this.set(
  2319. 1, 0, 0,
  2320. 0, 1, 0,
  2321. 0, 0, 1
  2322. );
  2323. return this;
  2324. },
  2325. copy: function ( m ) {
  2326. var me = m.elements;
  2327. this.set(
  2328. me[ 0 ], me[ 3 ], me[ 6 ],
  2329. me[ 1 ], me[ 4 ], me[ 7 ],
  2330. me[ 2 ], me[ 5 ], me[ 8 ]
  2331. );
  2332. return this;
  2333. },
  2334. multiplyVector3: function ( vector ) {
  2335. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  2336. return vector.applyMatrix3( this );
  2337. },
  2338. multiplyVector3Array: function ( a ) {
  2339. console.warn( 'THREE.Matrix3: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  2340. return this.applyToVector3Array( a );
  2341. },
  2342. applyToVector3Array: function () {
  2343. var v1 = new THREE.Vector3();
  2344. return function ( array, offset, length ) {
  2345. if ( offset === undefined ) offset = 0;
  2346. if ( length === undefined ) length = array.length;
  2347. for ( var i = 0, j = offset, il; i < length; i += 3, j += 3 ) {
  2348. v1.x = array[ j ];
  2349. v1.y = array[ j + 1 ];
  2350. v1.z = array[ j + 2 ];
  2351. v1.applyMatrix3( this );
  2352. array[ j ] = v1.x;
  2353. array[ j + 1 ] = v1.y;
  2354. array[ j + 2 ] = v1.z;
  2355. }
  2356. return array;
  2357. };
  2358. }(),
  2359. multiplyScalar: function ( s ) {
  2360. var te = this.elements;
  2361. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  2362. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  2363. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  2364. return this;
  2365. },
  2366. determinant: function () {
  2367. var te = this.elements;
  2368. var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  2369. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  2370. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  2371. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  2372. },
  2373. getInverse: function ( matrix, throwOnInvertible ) {
  2374. // input: THREE.Matrix4
  2375. // ( based on http://code.google.com/p/webgl-mjs/ )
  2376. var me = matrix.elements;
  2377. var te = this.elements;
  2378. te[ 0 ] = me[ 10 ] * me[ 5 ] - me[ 6 ] * me[ 9 ];
  2379. te[ 1 ] = - me[ 10 ] * me[ 1 ] + me[ 2 ] * me[ 9 ];
  2380. te[ 2 ] = me[ 6 ] * me[ 1 ] - me[ 2 ] * me[ 5 ];
  2381. te[ 3 ] = - me[ 10 ] * me[ 4 ] + me[ 6 ] * me[ 8 ];
  2382. te[ 4 ] = me[ 10 ] * me[ 0 ] - me[ 2 ] * me[ 8 ];
  2383. te[ 5 ] = - me[ 6 ] * me[ 0 ] + me[ 2 ] * me[ 4 ];
  2384. te[ 6 ] = me[ 9 ] * me[ 4 ] - me[ 5 ] * me[ 8 ];
  2385. te[ 7 ] = - me[ 9 ] * me[ 0 ] + me[ 1 ] * me[ 8 ];
  2386. te[ 8 ] = me[ 5 ] * me[ 0 ] - me[ 1 ] * me[ 4 ];
  2387. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ];
  2388. // no inverse
  2389. if ( det === 0 ) {
  2390. var msg = "Matrix3.getInverse(): can't invert matrix, determinant is 0";
  2391. if ( throwOnInvertible || false ) {
  2392. throw new Error( msg );
  2393. } else {
  2394. console.warn( msg );
  2395. }
  2396. this.identity();
  2397. return this;
  2398. }
  2399. this.multiplyScalar( 1.0 / det );
  2400. return this;
  2401. },
  2402. transpose: function () {
  2403. var tmp, m = this.elements;
  2404. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  2405. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  2406. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  2407. return this;
  2408. },
  2409. flattenToArrayOffset: function ( array, offset ) {
  2410. var te = this.elements;
  2411. array[ offset ] = te[ 0 ];
  2412. array[ offset + 1 ] = te[ 1 ];
  2413. array[ offset + 2 ] = te[ 2 ];
  2414. array[ offset + 3 ] = te[ 3 ];
  2415. array[ offset + 4 ] = te[ 4 ];
  2416. array[ offset + 5 ] = te[ 5 ];
  2417. array[ offset + 6 ] = te[ 6 ];
  2418. array[ offset + 7 ] = te[ 7 ];
  2419. array[ offset + 8 ] = te[ 8 ];
  2420. return array;
  2421. },
  2422. getNormalMatrix: function ( m ) {
  2423. // input: THREE.Matrix4
  2424. this.getInverse( m ).transpose();
  2425. return this;
  2426. },
  2427. transposeIntoArray: function ( r ) {
  2428. var m = this.elements;
  2429. r[ 0 ] = m[ 0 ];
  2430. r[ 1 ] = m[ 3 ];
  2431. r[ 2 ] = m[ 6 ];
  2432. r[ 3 ] = m[ 1 ];
  2433. r[ 4 ] = m[ 4 ];
  2434. r[ 5 ] = m[ 7 ];
  2435. r[ 6 ] = m[ 2 ];
  2436. r[ 7 ] = m[ 5 ];
  2437. r[ 8 ] = m[ 8 ];
  2438. return this;
  2439. },
  2440. fromArray: function ( array ) {
  2441. this.elements.set( array );
  2442. return this;
  2443. },
  2444. toArray: function () {
  2445. var te = this.elements;
  2446. return [
  2447. te[ 0 ], te[ 1 ], te[ 2 ],
  2448. te[ 3 ], te[ 4 ], te[ 5 ],
  2449. te[ 6 ], te[ 7 ], te[ 8 ]
  2450. ];
  2451. },
  2452. clone: function () {
  2453. var te = this.elements;
  2454. return new THREE.Matrix3(
  2455. te[ 0 ], te[ 3 ], te[ 6 ],
  2456. te[ 1 ], te[ 4 ], te[ 7 ],
  2457. te[ 2 ], te[ 5 ], te[ 8 ]
  2458. );
  2459. }
  2460. };
  2461. // File:src/math/Matrix4.js
  2462. /**
  2463. * @author mrdoob / http://mrdoob.com/
  2464. * @author supereggbert / http://www.paulbrunt.co.uk/
  2465. * @author philogb / http://blog.thejit.org/
  2466. * @author jordi_ros / http://plattsoft.com
  2467. * @author D1plo1d / http://github.com/D1plo1d
  2468. * @author alteredq / http://alteredqualia.com/
  2469. * @author mikael emtinger / http://gomo.se/
  2470. * @author timknip / http://www.floorplanner.com/
  2471. * @author bhouston / http://exocortex.com
  2472. * @author WestLangley / http://github.com/WestLangley
  2473. */
  2474. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2475. this.elements = new Float32Array( 16 );
  2476. // TODO: if n11 is undefined, then just set to identity, otherwise copy all other values into matrix
  2477. // we should not support semi specification of Matrix4, it is just weird.
  2478. var te = this.elements;
  2479. te[ 0 ] = ( n11 !== undefined ) ? n11 : 1; te[ 4 ] = n12 || 0; te[ 8 ] = n13 || 0; te[ 12 ] = n14 || 0;
  2480. te[ 1 ] = n21 || 0; te[ 5 ] = ( n22 !== undefined ) ? n22 : 1; te[ 9 ] = n23 || 0; te[ 13 ] = n24 || 0;
  2481. te[ 2 ] = n31 || 0; te[ 6 ] = n32 || 0; te[ 10 ] = ( n33 !== undefined ) ? n33 : 1; te[ 14 ] = n34 || 0;
  2482. te[ 3 ] = n41 || 0; te[ 7 ] = n42 || 0; te[ 11 ] = n43 || 0; te[ 15 ] = ( n44 !== undefined ) ? n44 : 1;
  2483. };
  2484. THREE.Matrix4.prototype = {
  2485. constructor: THREE.Matrix4,
  2486. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2487. var te = this.elements;
  2488. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  2489. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  2490. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  2491. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  2492. return this;
  2493. },
  2494. identity: function () {
  2495. this.set(
  2496. 1, 0, 0, 0,
  2497. 0, 1, 0, 0,
  2498. 0, 0, 1, 0,
  2499. 0, 0, 0, 1
  2500. );
  2501. return this;
  2502. },
  2503. copy: function ( m ) {
  2504. this.elements.set( m.elements );
  2505. return this;
  2506. },
  2507. extractPosition: function ( m ) {
  2508. console.warn( 'THREEMatrix4: .extractPosition() has been renamed to .copyPosition().' );
  2509. return this.copyPosition( m );
  2510. },
  2511. copyPosition: function ( m ) {
  2512. var te = this.elements;
  2513. var me = m.elements;
  2514. te[ 12 ] = me[ 12 ];
  2515. te[ 13 ] = me[ 13 ];
  2516. te[ 14 ] = me[ 14 ];
  2517. return this;
  2518. },
  2519. extractRotation: function () {
  2520. var v1 = new THREE.Vector3();
  2521. return function ( m ) {
  2522. var te = this.elements;
  2523. var me = m.elements;
  2524. var scaleX = 1 / v1.set( me[ 0 ], me[ 1 ], me[ 2 ] ).length();
  2525. var scaleY = 1 / v1.set( me[ 4 ], me[ 5 ], me[ 6 ] ).length();
  2526. var scaleZ = 1 / v1.set( me[ 8 ], me[ 9 ], me[ 10 ] ).length();
  2527. te[ 0 ] = me[ 0 ] * scaleX;
  2528. te[ 1 ] = me[ 1 ] * scaleX;
  2529. te[ 2 ] = me[ 2 ] * scaleX;
  2530. te[ 4 ] = me[ 4 ] * scaleY;
  2531. te[ 5 ] = me[ 5 ] * scaleY;
  2532. te[ 6 ] = me[ 6 ] * scaleY;
  2533. te[ 8 ] = me[ 8 ] * scaleZ;
  2534. te[ 9 ] = me[ 9 ] * scaleZ;
  2535. te[ 10 ] = me[ 10 ] * scaleZ;
  2536. return this;
  2537. };
  2538. }(),
  2539. makeRotationFromEuler: function ( euler ) {
  2540. if ( euler instanceof THREE.Euler === false ) {
  2541. console.error( 'THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  2542. }
  2543. var te = this.elements;
  2544. var x = euler.x, y = euler.y, z = euler.z;
  2545. var a = Math.cos( x ), b = Math.sin( x );
  2546. var c = Math.cos( y ), d = Math.sin( y );
  2547. var e = Math.cos( z ), f = Math.sin( z );
  2548. if ( euler.order === 'XYZ' ) {
  2549. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2550. te[ 0 ] = c * e;
  2551. te[ 4 ] = - c * f;
  2552. te[ 8 ] = d;
  2553. te[ 1 ] = af + be * d;
  2554. te[ 5 ] = ae - bf * d;
  2555. te[ 9 ] = - b * c;
  2556. te[ 2 ] = bf - ae * d;
  2557. te[ 6 ] = be + af * d;
  2558. te[ 10 ] = a * c;
  2559. } else if ( euler.order === 'YXZ' ) {
  2560. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2561. te[ 0 ] = ce + df * b;
  2562. te[ 4 ] = de * b - cf;
  2563. te[ 8 ] = a * d;
  2564. te[ 1 ] = a * f;
  2565. te[ 5 ] = a * e;
  2566. te[ 9 ] = - b;
  2567. te[ 2 ] = cf * b - de;
  2568. te[ 6 ] = df + ce * b;
  2569. te[ 10 ] = a * c;
  2570. } else if ( euler.order === 'ZXY' ) {
  2571. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2572. te[ 0 ] = ce - df * b;
  2573. te[ 4 ] = - a * f;
  2574. te[ 8 ] = de + cf * b;
  2575. te[ 1 ] = cf + de * b;
  2576. te[ 5 ] = a * e;
  2577. te[ 9 ] = df - ce * b;
  2578. te[ 2 ] = - a * d;
  2579. te[ 6 ] = b;
  2580. te[ 10 ] = a * c;
  2581. } else if ( euler.order === 'ZYX' ) {
  2582. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2583. te[ 0 ] = c * e;
  2584. te[ 4 ] = be * d - af;
  2585. te[ 8 ] = ae * d + bf;
  2586. te[ 1 ] = c * f;
  2587. te[ 5 ] = bf * d + ae;
  2588. te[ 9 ] = af * d - be;
  2589. te[ 2 ] = - d;
  2590. te[ 6 ] = b * c;
  2591. te[ 10 ] = a * c;
  2592. } else if ( euler.order === 'YZX' ) {
  2593. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2594. te[ 0 ] = c * e;
  2595. te[ 4 ] = bd - ac * f;
  2596. te[ 8 ] = bc * f + ad;
  2597. te[ 1 ] = f;
  2598. te[ 5 ] = a * e;
  2599. te[ 9 ] = - b * e;
  2600. te[ 2 ] = - d * e;
  2601. te[ 6 ] = ad * f + bc;
  2602. te[ 10 ] = ac - bd * f;
  2603. } else if ( euler.order === 'XZY' ) {
  2604. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2605. te[ 0 ] = c * e;
  2606. te[ 4 ] = - f;
  2607. te[ 8 ] = d * e;
  2608. te[ 1 ] = ac * f + bd;
  2609. te[ 5 ] = a * e;
  2610. te[ 9 ] = ad * f - bc;
  2611. te[ 2 ] = bc * f - ad;
  2612. te[ 6 ] = b * e;
  2613. te[ 10 ] = bd * f + ac;
  2614. }
  2615. // last column
  2616. te[ 3 ] = 0;
  2617. te[ 7 ] = 0;
  2618. te[ 11 ] = 0;
  2619. // bottom row
  2620. te[ 12 ] = 0;
  2621. te[ 13 ] = 0;
  2622. te[ 14 ] = 0;
  2623. te[ 15 ] = 1;
  2624. return this;
  2625. },
  2626. setRotationFromQuaternion: function ( q ) {
  2627. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  2628. return this.makeRotationFromQuaternion( q );
  2629. },
  2630. makeRotationFromQuaternion: function ( q ) {
  2631. var te = this.elements;
  2632. var x = q.x, y = q.y, z = q.z, w = q.w;
  2633. var x2 = x + x, y2 = y + y, z2 = z + z;
  2634. var xx = x * x2, xy = x * y2, xz = x * z2;
  2635. var yy = y * y2, yz = y * z2, zz = z * z2;
  2636. var wx = w * x2, wy = w * y2, wz = w * z2;
  2637. te[ 0 ] = 1 - ( yy + zz );
  2638. te[ 4 ] = xy - wz;
  2639. te[ 8 ] = xz + wy;
  2640. te[ 1 ] = xy + wz;
  2641. te[ 5 ] = 1 - ( xx + zz );
  2642. te[ 9 ] = yz - wx;
  2643. te[ 2 ] = xz - wy;
  2644. te[ 6 ] = yz + wx;
  2645. te[ 10 ] = 1 - ( xx + yy );
  2646. // last column
  2647. te[ 3 ] = 0;
  2648. te[ 7 ] = 0;
  2649. te[ 11 ] = 0;
  2650. // bottom row
  2651. te[ 12 ] = 0;
  2652. te[ 13 ] = 0;
  2653. te[ 14 ] = 0;
  2654. te[ 15 ] = 1;
  2655. return this;
  2656. },
  2657. lookAt: function () {
  2658. var x = new THREE.Vector3();
  2659. var y = new THREE.Vector3();
  2660. var z = new THREE.Vector3();
  2661. return function ( eye, target, up ) {
  2662. var te = this.elements;
  2663. z.subVectors( eye, target ).normalize();
  2664. if ( z.length() === 0 ) {
  2665. z.z = 1;
  2666. }
  2667. x.crossVectors( up, z ).normalize();
  2668. if ( x.length() === 0 ) {
  2669. z.x += 0.0001;
  2670. x.crossVectors( up, z ).normalize();
  2671. }
  2672. y.crossVectors( z, x );
  2673. te[ 0 ] = x.x; te[ 4 ] = y.x; te[ 8 ] = z.x;
  2674. te[ 1 ] = x.y; te[ 5 ] = y.y; te[ 9 ] = z.y;
  2675. te[ 2 ] = x.z; te[ 6 ] = y.z; te[ 10 ] = z.z;
  2676. return this;
  2677. };
  2678. }(),
  2679. multiply: function ( m, n ) {
  2680. if ( n !== undefined ) {
  2681. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2682. return this.multiplyMatrices( m, n );
  2683. }
  2684. return this.multiplyMatrices( this, m );
  2685. },
  2686. multiplyMatrices: function ( a, b ) {
  2687. var ae = a.elements;
  2688. var be = b.elements;
  2689. var te = this.elements;
  2690. var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  2691. var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  2692. var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  2693. var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  2694. var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  2695. var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  2696. var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  2697. var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  2698. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2699. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2700. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2701. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2702. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2703. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2704. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2705. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2706. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2707. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2708. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2709. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2710. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2711. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2712. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2713. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2714. return this;
  2715. },
  2716. multiplyToArray: function ( a, b, r ) {
  2717. var te = this.elements;
  2718. this.multiplyMatrices( a, b );
  2719. r[ 0 ] = te[ 0 ]; r[ 1 ] = te[ 1 ]; r[ 2 ] = te[ 2 ]; r[ 3 ] = te[ 3 ];
  2720. r[ 4 ] = te[ 4 ]; r[ 5 ] = te[ 5 ]; r[ 6 ] = te[ 6 ]; r[ 7 ] = te[ 7 ];
  2721. r[ 8 ] = te[ 8 ]; r[ 9 ] = te[ 9 ]; r[ 10 ] = te[ 10 ]; r[ 11 ] = te[ 11 ];
  2722. r[ 12 ] = te[ 12 ]; r[ 13 ] = te[ 13 ]; r[ 14 ] = te[ 14 ]; r[ 15 ] = te[ 15 ];
  2723. return this;
  2724. },
  2725. multiplyScalar: function ( s ) {
  2726. var te = this.elements;
  2727. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  2728. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  2729. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  2730. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  2731. return this;
  2732. },
  2733. multiplyVector3: function ( vector ) {
  2734. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  2735. return vector.applyProjection( this );
  2736. },
  2737. multiplyVector4: function ( vector ) {
  2738. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2739. return vector.applyMatrix4( this );
  2740. },
  2741. multiplyVector3Array: function ( a ) {
  2742. console.warn( 'THREE.Matrix4: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  2743. return this.applyToVector3Array( a );
  2744. },
  2745. applyToVector3Array: function () {
  2746. var v1 = new THREE.Vector3();
  2747. return function ( array, offset, length ) {
  2748. if ( offset === undefined ) offset = 0;
  2749. if ( length === undefined ) length = array.length;
  2750. for ( var i = 0, j = offset, il; i < length; i += 3, j += 3 ) {
  2751. v1.x = array[ j ];
  2752. v1.y = array[ j + 1 ];
  2753. v1.z = array[ j + 2 ];
  2754. v1.applyMatrix4( this );
  2755. array[ j ] = v1.x;
  2756. array[ j + 1 ] = v1.y;
  2757. array[ j + 2 ] = v1.z;
  2758. }
  2759. return array;
  2760. };
  2761. }(),
  2762. rotateAxis: function ( v ) {
  2763. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  2764. v.transformDirection( this );
  2765. },
  2766. crossVector: function ( vector ) {
  2767. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2768. return vector.applyMatrix4( this );
  2769. },
  2770. determinant: function () {
  2771. var te = this.elements;
  2772. var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  2773. var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  2774. var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  2775. var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  2776. //TODO: make this more efficient
  2777. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2778. return (
  2779. n41 * (
  2780. + n14 * n23 * n32
  2781. - n13 * n24 * n32
  2782. - n14 * n22 * n33
  2783. + n12 * n24 * n33
  2784. + n13 * n22 * n34
  2785. - n12 * n23 * n34
  2786. ) +
  2787. n42 * (
  2788. + n11 * n23 * n34
  2789. - n11 * n24 * n33
  2790. + n14 * n21 * n33
  2791. - n13 * n21 * n34
  2792. + n13 * n24 * n31
  2793. - n14 * n23 * n31
  2794. ) +
  2795. n43 * (
  2796. + n11 * n24 * n32
  2797. - n11 * n22 * n34
  2798. - n14 * n21 * n32
  2799. + n12 * n21 * n34
  2800. + n14 * n22 * n31
  2801. - n12 * n24 * n31
  2802. ) +
  2803. n44 * (
  2804. - n13 * n22 * n31
  2805. - n11 * n23 * n32
  2806. + n11 * n22 * n33
  2807. + n13 * n21 * n32
  2808. - n12 * n21 * n33
  2809. + n12 * n23 * n31
  2810. )
  2811. );
  2812. },
  2813. transpose: function () {
  2814. var te = this.elements;
  2815. var tmp;
  2816. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  2817. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  2818. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  2819. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  2820. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  2821. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  2822. return this;
  2823. },
  2824. flattenToArrayOffset: function ( array, offset ) {
  2825. var te = this.elements;
  2826. array[ offset ] = te[ 0 ];
  2827. array[ offset + 1 ] = te[ 1 ];
  2828. array[ offset + 2 ] = te[ 2 ];
  2829. array[ offset + 3 ] = te[ 3 ];
  2830. array[ offset + 4 ] = te[ 4 ];
  2831. array[ offset + 5 ] = te[ 5 ];
  2832. array[ offset + 6 ] = te[ 6 ];
  2833. array[ offset + 7 ] = te[ 7 ];
  2834. array[ offset + 8 ] = te[ 8 ];
  2835. array[ offset + 9 ] = te[ 9 ];
  2836. array[ offset + 10 ] = te[ 10 ];
  2837. array[ offset + 11 ] = te[ 11 ];
  2838. array[ offset + 12 ] = te[ 12 ];
  2839. array[ offset + 13 ] = te[ 13 ];
  2840. array[ offset + 14 ] = te[ 14 ];
  2841. array[ offset + 15 ] = te[ 15 ];
  2842. return array;
  2843. },
  2844. getPosition: function () {
  2845. var v1 = new THREE.Vector3();
  2846. return function () {
  2847. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  2848. var te = this.elements;
  2849. return v1.set( te[ 12 ], te[ 13 ], te[ 14 ] );
  2850. };
  2851. }(),
  2852. setPosition: function ( v ) {
  2853. var te = this.elements;
  2854. te[ 12 ] = v.x;
  2855. te[ 13 ] = v.y;
  2856. te[ 14 ] = v.z;
  2857. return this;
  2858. },
  2859. getInverse: function ( m, throwOnInvertible ) {
  2860. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  2861. var te = this.elements;
  2862. var me = m.elements;
  2863. var n11 = me[ 0 ], n12 = me[ 4 ], n13 = me[ 8 ], n14 = me[ 12 ];
  2864. var n21 = me[ 1 ], n22 = me[ 5 ], n23 = me[ 9 ], n24 = me[ 13 ];
  2865. var n31 = me[ 2 ], n32 = me[ 6 ], n33 = me[ 10 ], n34 = me[ 14 ];
  2866. var n41 = me[ 3 ], n42 = me[ 7 ], n43 = me[ 11 ], n44 = me[ 15 ];
  2867. te[ 0 ] = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44;
  2868. te[ 4 ] = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44;
  2869. te[ 8 ] = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44;
  2870. te[ 12 ] = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  2871. te[ 1 ] = n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44;
  2872. te[ 5 ] = n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44;
  2873. te[ 9 ] = n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44;
  2874. te[ 13 ] = n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34;
  2875. te[ 2 ] = n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44;
  2876. te[ 6 ] = n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44;
  2877. te[ 10 ] = n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44;
  2878. te[ 14 ] = n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34;
  2879. te[ 3 ] = n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43;
  2880. te[ 7 ] = n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43;
  2881. te[ 11 ] = n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43;
  2882. te[ 15 ] = n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33;
  2883. var det = n11 * te[ 0 ] + n21 * te[ 4 ] + n31 * te[ 8 ] + n41 * te[ 12 ];
  2884. if ( det == 0 ) {
  2885. var msg = "Matrix4.getInverse(): can't invert matrix, determinant is 0";
  2886. if ( throwOnInvertible || false ) {
  2887. throw new Error( msg );
  2888. } else {
  2889. console.warn( msg );
  2890. }
  2891. this.identity();
  2892. return this;
  2893. }
  2894. this.multiplyScalar( 1 / det );
  2895. return this;
  2896. },
  2897. translate: function ( v ) {
  2898. console.warn( 'THREE.Matrix4: .translate() has been removed.' );
  2899. },
  2900. rotateX: function ( angle ) {
  2901. console.warn( 'THREE.Matrix4: .rotateX() has been removed.' );
  2902. },
  2903. rotateY: function ( angle ) {
  2904. console.warn( 'THREE.Matrix4: .rotateY() has been removed.' );
  2905. },
  2906. rotateZ: function ( angle ) {
  2907. console.warn( 'THREE.Matrix4: .rotateZ() has been removed.' );
  2908. },
  2909. rotateByAxis: function ( axis, angle ) {
  2910. console.warn( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  2911. },
  2912. scale: function ( v ) {
  2913. var te = this.elements;
  2914. var x = v.x, y = v.y, z = v.z;
  2915. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  2916. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  2917. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  2918. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  2919. return this;
  2920. },
  2921. getMaxScaleOnAxis: function () {
  2922. var te = this.elements;
  2923. var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  2924. var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  2925. var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  2926. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  2927. },
  2928. makeTranslation: function ( x, y, z ) {
  2929. this.set(
  2930. 1, 0, 0, x,
  2931. 0, 1, 0, y,
  2932. 0, 0, 1, z,
  2933. 0, 0, 0, 1
  2934. );
  2935. return this;
  2936. },
  2937. makeRotationX: function ( theta ) {
  2938. var c = Math.cos( theta ), s = Math.sin( theta );
  2939. this.set(
  2940. 1, 0, 0, 0,
  2941. 0, c, - s, 0,
  2942. 0, s, c, 0,
  2943. 0, 0, 0, 1
  2944. );
  2945. return this;
  2946. },
  2947. makeRotationY: function ( theta ) {
  2948. var c = Math.cos( theta ), s = Math.sin( theta );
  2949. this.set(
  2950. c, 0, s, 0,
  2951. 0, 1, 0, 0,
  2952. - s, 0, c, 0,
  2953. 0, 0, 0, 1
  2954. );
  2955. return this;
  2956. },
  2957. makeRotationZ: function ( theta ) {
  2958. var c = Math.cos( theta ), s = Math.sin( theta );
  2959. this.set(
  2960. c, - s, 0, 0,
  2961. s, c, 0, 0,
  2962. 0, 0, 1, 0,
  2963. 0, 0, 0, 1
  2964. );
  2965. return this;
  2966. },
  2967. makeRotationAxis: function ( axis, angle ) {
  2968. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  2969. var c = Math.cos( angle );
  2970. var s = Math.sin( angle );
  2971. var t = 1 - c;
  2972. var x = axis.x, y = axis.y, z = axis.z;
  2973. var tx = t * x, ty = t * y;
  2974. this.set(
  2975. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  2976. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  2977. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  2978. 0, 0, 0, 1
  2979. );
  2980. return this;
  2981. },
  2982. makeScale: function ( x, y, z ) {
  2983. this.set(
  2984. x, 0, 0, 0,
  2985. 0, y, 0, 0,
  2986. 0, 0, z, 0,
  2987. 0, 0, 0, 1
  2988. );
  2989. return this;
  2990. },
  2991. compose: function ( position, quaternion, scale ) {
  2992. this.makeRotationFromQuaternion( quaternion );
  2993. this.scale( scale );
  2994. this.setPosition( position );
  2995. return this;
  2996. },
  2997. decompose: function () {
  2998. var vector = new THREE.Vector3();
  2999. var matrix = new THREE.Matrix4();
  3000. return function ( position, quaternion, scale ) {
  3001. var te = this.elements;
  3002. var sx = vector.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  3003. var sy = vector.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  3004. var sz = vector.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  3005. // if determine is negative, we need to invert one scale
  3006. var det = this.determinant();
  3007. if ( det < 0 ) {
  3008. sx = - sx;
  3009. }
  3010. position.x = te[ 12 ];
  3011. position.y = te[ 13 ];
  3012. position.z = te[ 14 ];
  3013. // scale the rotation part
  3014. matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy()
  3015. var invSX = 1 / sx;
  3016. var invSY = 1 / sy;
  3017. var invSZ = 1 / sz;
  3018. matrix.elements[ 0 ] *= invSX;
  3019. matrix.elements[ 1 ] *= invSX;
  3020. matrix.elements[ 2 ] *= invSX;
  3021. matrix.elements[ 4 ] *= invSY;
  3022. matrix.elements[ 5 ] *= invSY;
  3023. matrix.elements[ 6 ] *= invSY;
  3024. matrix.elements[ 8 ] *= invSZ;
  3025. matrix.elements[ 9 ] *= invSZ;
  3026. matrix.elements[ 10 ] *= invSZ;
  3027. quaternion.setFromRotationMatrix( matrix );
  3028. scale.x = sx;
  3029. scale.y = sy;
  3030. scale.z = sz;
  3031. return this;
  3032. };
  3033. }(),
  3034. makeFrustum: function ( left, right, bottom, top, near, far ) {
  3035. var te = this.elements;
  3036. var x = 2 * near / ( right - left );
  3037. var y = 2 * near / ( top - bottom );
  3038. var a = ( right + left ) / ( right - left );
  3039. var b = ( top + bottom ) / ( top - bottom );
  3040. var c = - ( far + near ) / ( far - near );
  3041. var d = - 2 * far * near / ( far - near );
  3042. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  3043. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  3044. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  3045. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  3046. return this;
  3047. },
  3048. makePerspective: function ( fov, aspect, near, far ) {
  3049. var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) );
  3050. var ymin = - ymax;
  3051. var xmin = ymin * aspect;
  3052. var xmax = ymax * aspect;
  3053. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  3054. },
  3055. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  3056. var te = this.elements;
  3057. var w = right - left;
  3058. var h = top - bottom;
  3059. var p = far - near;
  3060. var x = ( right + left ) / w;
  3061. var y = ( top + bottom ) / h;
  3062. var z = ( far + near ) / p;
  3063. te[ 0 ] = 2 / w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  3064. te[ 1 ] = 0; te[ 5 ] = 2 / h; te[ 9 ] = 0; te[ 13 ] = - y;
  3065. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 / p; te[ 14 ] = - z;
  3066. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  3067. return this;
  3068. },
  3069. fromArray: function ( array ) {
  3070. this.elements.set( array );
  3071. return this;
  3072. },
  3073. toArray: function () {
  3074. var te = this.elements;
  3075. return [
  3076. te[ 0 ], te[ 1 ], te[ 2 ], te[ 3 ],
  3077. te[ 4 ], te[ 5 ], te[ 6 ], te[ 7 ],
  3078. te[ 8 ], te[ 9 ], te[ 10 ], te[ 11 ],
  3079. te[ 12 ], te[ 13 ], te[ 14 ], te[ 15 ]
  3080. ];
  3081. },
  3082. clone: function () {
  3083. var te = this.elements;
  3084. return new THREE.Matrix4(
  3085. te[ 0 ], te[ 4 ], te[ 8 ], te[ 12 ],
  3086. te[ 1 ], te[ 5 ], te[ 9 ], te[ 13 ],
  3087. te[ 2 ], te[ 6 ], te[ 10 ], te[ 14 ],
  3088. te[ 3 ], te[ 7 ], te[ 11 ], te[ 15 ]
  3089. );
  3090. }
  3091. };
  3092. // File:src/math/Ray.js
  3093. /**
  3094. * @author bhouston / http://exocortex.com
  3095. */
  3096. THREE.Ray = function ( origin, direction ) {
  3097. this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3();
  3098. this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3();
  3099. };
  3100. THREE.Ray.prototype = {
  3101. constructor: THREE.Ray,
  3102. set: function ( origin, direction ) {
  3103. this.origin.copy( origin );
  3104. this.direction.copy( direction );
  3105. return this;
  3106. },
  3107. copy: function ( ray ) {
  3108. this.origin.copy( ray.origin );
  3109. this.direction.copy( ray.direction );
  3110. return this;
  3111. },
  3112. at: function ( t, optionalTarget ) {
  3113. var result = optionalTarget || new THREE.Vector3();
  3114. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  3115. },
  3116. recast: function () {
  3117. var v1 = new THREE.Vector3();
  3118. return function ( t ) {
  3119. this.origin.copy( this.at( t, v1 ) );
  3120. return this;
  3121. };
  3122. }(),
  3123. closestPointToPoint: function ( point, optionalTarget ) {
  3124. var result = optionalTarget || new THREE.Vector3();
  3125. result.subVectors( point, this.origin );
  3126. var directionDistance = result.dot( this.direction );
  3127. if ( directionDistance < 0 ) {
  3128. return result.copy( this.origin );
  3129. }
  3130. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3131. },
  3132. distanceToPoint: function () {
  3133. var v1 = new THREE.Vector3();
  3134. return function ( point ) {
  3135. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  3136. // point behind the ray
  3137. if ( directionDistance < 0 ) {
  3138. return this.origin.distanceTo( point );
  3139. }
  3140. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3141. return v1.distanceTo( point );
  3142. };
  3143. }(),
  3144. distanceSqToSegment: function ( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3145. // from http://www.geometrictools.com/LibMathematics/Distance/Wm5DistRay3Segment3.cpp
  3146. // It returns the min distance between the ray and the segment
  3147. // defined by v0 and v1
  3148. // It can also set two optional targets :
  3149. // - The closest point on the ray
  3150. // - The closest point on the segment
  3151. var segCenter = v0.clone().add( v1 ).multiplyScalar( 0.5 );
  3152. var segDir = v1.clone().sub( v0 ).normalize();
  3153. var segExtent = v0.distanceTo( v1 ) * 0.5;
  3154. var diff = this.origin.clone().sub( segCenter );
  3155. var a01 = - this.direction.dot( segDir );
  3156. var b0 = diff.dot( this.direction );
  3157. var b1 = - diff.dot( segDir );
  3158. var c = diff.lengthSq();
  3159. var det = Math.abs( 1 - a01 * a01 );
  3160. var s0, s1, sqrDist, extDet;
  3161. if ( det >= 0 ) {
  3162. // The ray and segment are not parallel.
  3163. s0 = a01 * b1 - b0;
  3164. s1 = a01 * b0 - b1;
  3165. extDet = segExtent * det;
  3166. if ( s0 >= 0 ) {
  3167. if ( s1 >= - extDet ) {
  3168. if ( s1 <= extDet ) {
  3169. // region 0
  3170. // Minimum at interior points of ray and segment.
  3171. var invDet = 1 / det;
  3172. s0 *= invDet;
  3173. s1 *= invDet;
  3174. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3175. } else {
  3176. // region 1
  3177. s1 = segExtent;
  3178. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3179. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3180. }
  3181. } else {
  3182. // region 5
  3183. s1 = - segExtent;
  3184. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3185. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3186. }
  3187. } else {
  3188. if ( s1 <= - extDet ) {
  3189. // region 4
  3190. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3191. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3192. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3193. } else if ( s1 <= extDet ) {
  3194. // region 3
  3195. s0 = 0;
  3196. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3197. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3198. } else {
  3199. // region 2
  3200. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3201. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3202. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3203. }
  3204. }
  3205. } else {
  3206. // Ray and segment are parallel.
  3207. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3208. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3209. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3210. }
  3211. if ( optionalPointOnRay ) {
  3212. optionalPointOnRay.copy( this.direction.clone().multiplyScalar( s0 ).add( this.origin ) );
  3213. }
  3214. if ( optionalPointOnSegment ) {
  3215. optionalPointOnSegment.copy( segDir.clone().multiplyScalar( s1 ).add( segCenter ) );
  3216. }
  3217. return sqrDist;
  3218. },
  3219. isIntersectionSphere: function ( sphere ) {
  3220. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  3221. },
  3222. intersectSphere: function () {
  3223. // from http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-sphere-intersection/
  3224. var v1 = new THREE.Vector3();
  3225. return function ( sphere, optionalTarget ) {
  3226. v1.subVectors( sphere.center, this.origin );
  3227. var tca = v1.dot( this.direction );
  3228. var d2 = v1.dot( v1 ) - tca * tca;
  3229. var radius2 = sphere.radius * sphere.radius;
  3230. if ( d2 > radius2 ) return null;
  3231. var thc = Math.sqrt( radius2 - d2 );
  3232. // t0 = first intersect point - entrance on front of sphere
  3233. var t0 = tca - thc;
  3234. // t1 = second intersect point - exit point on back of sphere
  3235. var t1 = tca + thc;
  3236. // test to see if both t0 and t1 are behind the ray - if so, return null
  3237. if ( t0 < 0 && t1 < 0 ) return null;
  3238. // test to see if t0 is behind the ray:
  3239. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3240. // in order to always return an intersect point that is in front of the ray.
  3241. if ( t0 < 0 ) return this.at( t1, optionalTarget );
  3242. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3243. return this.at( t0, optionalTarget );
  3244. }
  3245. }(),
  3246. isIntersectionPlane: function ( plane ) {
  3247. // check if the ray lies on the plane first
  3248. var distToPoint = plane.distanceToPoint( this.origin );
  3249. if ( distToPoint === 0 ) {
  3250. return true;
  3251. }
  3252. var denominator = plane.normal.dot( this.direction );
  3253. if ( denominator * distToPoint < 0 ) {
  3254. return true;
  3255. }
  3256. // ray origin is behind the plane (and is pointing behind it)
  3257. return false;
  3258. },
  3259. distanceToPlane: function ( plane ) {
  3260. var denominator = plane.normal.dot( this.direction );
  3261. if ( denominator == 0 ) {
  3262. // line is coplanar, return origin
  3263. if ( plane.distanceToPoint( this.origin ) == 0 ) {
  3264. return 0;
  3265. }
  3266. // Null is preferable to undefined since undefined means.... it is undefined
  3267. return null;
  3268. }
  3269. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3270. // Return if the ray never intersects the plane
  3271. return t >= 0 ? t : null;
  3272. },
  3273. intersectPlane: function ( plane, optionalTarget ) {
  3274. var t = this.distanceToPlane( plane );
  3275. if ( t === null ) {
  3276. return null;
  3277. }
  3278. return this.at( t, optionalTarget );
  3279. },
  3280. isIntersectionBox: function () {
  3281. var v = new THREE.Vector3();
  3282. return function ( box ) {
  3283. return this.intersectBox( box, v ) !== null;
  3284. };
  3285. }(),
  3286. intersectBox: function ( box , optionalTarget ) {
  3287. // http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-box-intersection/
  3288. var tmin,tmax,tymin,tymax,tzmin,tzmax;
  3289. var invdirx = 1 / this.direction.x,
  3290. invdiry = 1 / this.direction.y,
  3291. invdirz = 1 / this.direction.z;
  3292. var origin = this.origin;
  3293. if ( invdirx >= 0 ) {
  3294. tmin = ( box.min.x - origin.x ) * invdirx;
  3295. tmax = ( box.max.x - origin.x ) * invdirx;
  3296. } else {
  3297. tmin = ( box.max.x - origin.x ) * invdirx;
  3298. tmax = ( box.min.x - origin.x ) * invdirx;
  3299. }
  3300. if ( invdiry >= 0 ) {
  3301. tymin = ( box.min.y - origin.y ) * invdiry;
  3302. tymax = ( box.max.y - origin.y ) * invdiry;
  3303. } else {
  3304. tymin = ( box.max.y - origin.y ) * invdiry;
  3305. tymax = ( box.min.y - origin.y ) * invdiry;
  3306. }
  3307. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3308. // These lines also handle the case where tmin or tmax is NaN
  3309. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3310. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  3311. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  3312. if ( invdirz >= 0 ) {
  3313. tzmin = ( box.min.z - origin.z ) * invdirz;
  3314. tzmax = ( box.max.z - origin.z ) * invdirz;
  3315. } else {
  3316. tzmin = ( box.max.z - origin.z ) * invdirz;
  3317. tzmax = ( box.min.z - origin.z ) * invdirz;
  3318. }
  3319. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3320. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3321. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3322. //return point closest to the ray (positive side)
  3323. if ( tmax < 0 ) return null;
  3324. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  3325. },
  3326. intersectTriangle: function () {
  3327. // Compute the offset origin, edges, and normal.
  3328. var diff = new THREE.Vector3();
  3329. var edge1 = new THREE.Vector3();
  3330. var edge2 = new THREE.Vector3();
  3331. var normal = new THREE.Vector3();
  3332. return function ( a, b, c, backfaceCulling, optionalTarget ) {
  3333. // from http://www.geometrictools.com/LibMathematics/Intersection/Wm5IntrRay3Triangle3.cpp
  3334. edge1.subVectors( b, a );
  3335. edge2.subVectors( c, a );
  3336. normal.crossVectors( edge1, edge2 );
  3337. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3338. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3339. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3340. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3341. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3342. var DdN = this.direction.dot( normal );
  3343. var sign;
  3344. if ( DdN > 0 ) {
  3345. if ( backfaceCulling ) return null;
  3346. sign = 1;
  3347. } else if ( DdN < 0 ) {
  3348. sign = - 1;
  3349. DdN = - DdN;
  3350. } else {
  3351. return null;
  3352. }
  3353. diff.subVectors( this.origin, a );
  3354. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  3355. // b1 < 0, no intersection
  3356. if ( DdQxE2 < 0 ) {
  3357. return null;
  3358. }
  3359. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  3360. // b2 < 0, no intersection
  3361. if ( DdE1xQ < 0 ) {
  3362. return null;
  3363. }
  3364. // b1+b2 > 1, no intersection
  3365. if ( DdQxE2 + DdE1xQ > DdN ) {
  3366. return null;
  3367. }
  3368. // Line intersects triangle, check if ray does.
  3369. var QdN = - sign * diff.dot( normal );
  3370. // t < 0, no intersection
  3371. if ( QdN < 0 ) {
  3372. return null;
  3373. }
  3374. // Ray intersects triangle.
  3375. return this.at( QdN / DdN, optionalTarget );
  3376. };
  3377. }(),
  3378. applyMatrix4: function ( matrix4 ) {
  3379. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  3380. this.origin.applyMatrix4( matrix4 );
  3381. this.direction.sub( this.origin );
  3382. this.direction.normalize();
  3383. return this;
  3384. },
  3385. equals: function ( ray ) {
  3386. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3387. },
  3388. clone: function () {
  3389. return new THREE.Ray().copy( this );
  3390. }
  3391. };
  3392. // File:src/math/Sphere.js
  3393. /**
  3394. * @author bhouston / http://exocortex.com
  3395. * @author mrdoob / http://mrdoob.com/
  3396. */
  3397. THREE.Sphere = function ( center, radius ) {
  3398. this.center = ( center !== undefined ) ? center : new THREE.Vector3();
  3399. this.radius = ( radius !== undefined ) ? radius : 0;
  3400. };
  3401. THREE.Sphere.prototype = {
  3402. constructor: THREE.Sphere,
  3403. set: function ( center, radius ) {
  3404. this.center.copy( center );
  3405. this.radius = radius;
  3406. return this;
  3407. },
  3408. setFromPoints: function () {
  3409. var box = new THREE.Box3();
  3410. return function ( points, optionalCenter ) {
  3411. var center = this.center;
  3412. if ( optionalCenter !== undefined ) {
  3413. center.copy( optionalCenter );
  3414. } else {
  3415. box.setFromPoints( points ).center( center );
  3416. }
  3417. var maxRadiusSq = 0;
  3418. for ( var i = 0, il = points.length; i < il; i ++ ) {
  3419. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3420. }
  3421. this.radius = Math.sqrt( maxRadiusSq );
  3422. return this;
  3423. };
  3424. }(),
  3425. copy: function ( sphere ) {
  3426. this.center.copy( sphere.center );
  3427. this.radius = sphere.radius;
  3428. return this;
  3429. },
  3430. empty: function () {
  3431. return ( this.radius <= 0 );
  3432. },
  3433. containsPoint: function ( point ) {
  3434. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3435. },
  3436. distanceToPoint: function ( point ) {
  3437. return ( point.distanceTo( this.center ) - this.radius );
  3438. },
  3439. intersectsSphere: function ( sphere ) {
  3440. var radiusSum = this.radius + sphere.radius;
  3441. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3442. },
  3443. clampPoint: function ( point, optionalTarget ) {
  3444. var deltaLengthSq = this.center.distanceToSquared( point );
  3445. var result = optionalTarget || new THREE.Vector3();
  3446. result.copy( point );
  3447. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3448. result.sub( this.center ).normalize();
  3449. result.multiplyScalar( this.radius ).add( this.center );
  3450. }
  3451. return result;
  3452. },
  3453. getBoundingBox: function ( optionalTarget ) {
  3454. var box = optionalTarget || new THREE.Box3();
  3455. box.set( this.center, this.center );
  3456. box.expandByScalar( this.radius );
  3457. return box;
  3458. },
  3459. applyMatrix4: function ( matrix ) {
  3460. this.center.applyMatrix4( matrix );
  3461. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3462. return this;
  3463. },
  3464. translate: function ( offset ) {
  3465. this.center.add( offset );
  3466. return this;
  3467. },
  3468. equals: function ( sphere ) {
  3469. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3470. },
  3471. clone: function () {
  3472. return new THREE.Sphere().copy( this );
  3473. }
  3474. };
  3475. // File:src/math/Frustum.js
  3476. /**
  3477. * @author mrdoob / http://mrdoob.com/
  3478. * @author alteredq / http://alteredqualia.com/
  3479. * @author bhouston / http://exocortex.com
  3480. */
  3481. THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) {
  3482. this.planes = [
  3483. ( p0 !== undefined ) ? p0 : new THREE.Plane(),
  3484. ( p1 !== undefined ) ? p1 : new THREE.Plane(),
  3485. ( p2 !== undefined ) ? p2 : new THREE.Plane(),
  3486. ( p3 !== undefined ) ? p3 : new THREE.Plane(),
  3487. ( p4 !== undefined ) ? p4 : new THREE.Plane(),
  3488. ( p5 !== undefined ) ? p5 : new THREE.Plane()
  3489. ];
  3490. };
  3491. THREE.Frustum.prototype = {
  3492. constructor: THREE.Frustum,
  3493. set: function ( p0, p1, p2, p3, p4, p5 ) {
  3494. var planes = this.planes;
  3495. planes[ 0 ].copy( p0 );
  3496. planes[ 1 ].copy( p1 );
  3497. planes[ 2 ].copy( p2 );
  3498. planes[ 3 ].copy( p3 );
  3499. planes[ 4 ].copy( p4 );
  3500. planes[ 5 ].copy( p5 );
  3501. return this;
  3502. },
  3503. copy: function ( frustum ) {
  3504. var planes = this.planes;
  3505. for ( var i = 0; i < 6; i ++ ) {
  3506. planes[ i ].copy( frustum.planes[ i ] );
  3507. }
  3508. return this;
  3509. },
  3510. setFromMatrix: function ( m ) {
  3511. var planes = this.planes;
  3512. var me = m.elements;
  3513. var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  3514. var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  3515. var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  3516. var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  3517. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  3518. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  3519. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  3520. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  3521. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  3522. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  3523. return this;
  3524. },
  3525. intersectsObject: function () {
  3526. var sphere = new THREE.Sphere();
  3527. return function ( object ) {
  3528. var geometry = object.geometry;
  3529. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  3530. sphere.copy( geometry.boundingSphere );
  3531. sphere.applyMatrix4( object.matrixWorld );
  3532. return this.intersectsSphere( sphere );
  3533. };
  3534. }(),
  3535. intersectsSphere: function ( sphere ) {
  3536. var planes = this.planes;
  3537. var center = sphere.center;
  3538. var negRadius = - sphere.radius;
  3539. for ( var i = 0; i < 6; i ++ ) {
  3540. var distance = planes[ i ].distanceToPoint( center );
  3541. if ( distance < negRadius ) {
  3542. return false;
  3543. }
  3544. }
  3545. return true;
  3546. },
  3547. intersectsBox: function () {
  3548. var p1 = new THREE.Vector3(),
  3549. p2 = new THREE.Vector3();
  3550. return function ( box ) {
  3551. var planes = this.planes;
  3552. for ( var i = 0; i < 6 ; i ++ ) {
  3553. var plane = planes[ i ];
  3554. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  3555. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  3556. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  3557. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  3558. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  3559. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  3560. var d1 = plane.distanceToPoint( p1 );
  3561. var d2 = plane.distanceToPoint( p2 );
  3562. // if both outside plane, no intersection
  3563. if ( d1 < 0 && d2 < 0 ) {
  3564. return false;
  3565. }
  3566. }
  3567. return true;
  3568. };
  3569. }(),
  3570. containsPoint: function ( point ) {
  3571. var planes = this.planes;
  3572. for ( var i = 0; i < 6; i ++ ) {
  3573. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  3574. return false;
  3575. }
  3576. }
  3577. return true;
  3578. },
  3579. clone: function () {
  3580. return new THREE.Frustum().copy( this );
  3581. }
  3582. };
  3583. // File:src/math/Plane.js
  3584. /**
  3585. * @author bhouston / http://exocortex.com
  3586. */
  3587. THREE.Plane = function ( normal, constant ) {
  3588. this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 );
  3589. this.constant = ( constant !== undefined ) ? constant : 0;
  3590. };
  3591. THREE.Plane.prototype = {
  3592. constructor: THREE.Plane,
  3593. set: function ( normal, constant ) {
  3594. this.normal.copy( normal );
  3595. this.constant = constant;
  3596. return this;
  3597. },
  3598. setComponents: function ( x, y, z, w ) {
  3599. this.normal.set( x, y, z );
  3600. this.constant = w;
  3601. return this;
  3602. },
  3603. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  3604. this.normal.copy( normal );
  3605. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  3606. return this;
  3607. },
  3608. setFromCoplanarPoints: function () {
  3609. var v1 = new THREE.Vector3();
  3610. var v2 = new THREE.Vector3();
  3611. return function ( a, b, c ) {
  3612. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  3613. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  3614. this.setFromNormalAndCoplanarPoint( normal, a );
  3615. return this;
  3616. };
  3617. }(),
  3618. copy: function ( plane ) {
  3619. this.normal.copy( plane.normal );
  3620. this.constant = plane.constant;
  3621. return this;
  3622. },
  3623. normalize: function () {
  3624. // Note: will lead to a divide by zero if the plane is invalid.
  3625. var inverseNormalLength = 1.0 / this.normal.length();
  3626. this.normal.multiplyScalar( inverseNormalLength );
  3627. this.constant *= inverseNormalLength;
  3628. return this;
  3629. },
  3630. negate: function () {
  3631. this.constant *= - 1;
  3632. this.normal.negate();
  3633. return this;
  3634. },
  3635. distanceToPoint: function ( point ) {
  3636. return this.normal.dot( point ) + this.constant;
  3637. },
  3638. distanceToSphere: function ( sphere ) {
  3639. return this.distanceToPoint( sphere.center ) - sphere.radius;
  3640. },
  3641. projectPoint: function ( point, optionalTarget ) {
  3642. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  3643. },
  3644. orthoPoint: function ( point, optionalTarget ) {
  3645. var perpendicularMagnitude = this.distanceToPoint( point );
  3646. var result = optionalTarget || new THREE.Vector3();
  3647. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  3648. },
  3649. isIntersectionLine: function ( line ) {
  3650. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  3651. var startSign = this.distanceToPoint( line.start );
  3652. var endSign = this.distanceToPoint( line.end );
  3653. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  3654. },
  3655. intersectLine: function () {
  3656. var v1 = new THREE.Vector3();
  3657. return function ( line, optionalTarget ) {
  3658. var result = optionalTarget || new THREE.Vector3();
  3659. var direction = line.delta( v1 );
  3660. var denominator = this.normal.dot( direction );
  3661. if ( denominator == 0 ) {
  3662. // line is coplanar, return origin
  3663. if ( this.distanceToPoint( line.start ) == 0 ) {
  3664. return result.copy( line.start );
  3665. }
  3666. // Unsure if this is the correct method to handle this case.
  3667. return undefined;
  3668. }
  3669. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  3670. if ( t < 0 || t > 1 ) {
  3671. return undefined;
  3672. }
  3673. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  3674. };
  3675. }(),
  3676. coplanarPoint: function ( optionalTarget ) {
  3677. var result = optionalTarget || new THREE.Vector3();
  3678. return result.copy( this.normal ).multiplyScalar( - this.constant );
  3679. },
  3680. applyMatrix4: function () {
  3681. var v1 = new THREE.Vector3();
  3682. var v2 = new THREE.Vector3();
  3683. var m1 = new THREE.Matrix3();
  3684. return function ( matrix, optionalNormalMatrix ) {
  3685. // compute new normal based on theory here:
  3686. // http://www.songho.ca/opengl/gl_normaltransform.html
  3687. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  3688. var newNormal = v1.copy( this.normal ).applyMatrix3( normalMatrix );
  3689. var newCoplanarPoint = this.coplanarPoint( v2 );
  3690. newCoplanarPoint.applyMatrix4( matrix );
  3691. this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint );
  3692. return this;
  3693. };
  3694. }(),
  3695. translate: function ( offset ) {
  3696. this.constant = this.constant - offset.dot( this.normal );
  3697. return this;
  3698. },
  3699. equals: function ( plane ) {
  3700. return plane.normal.equals( this.normal ) && ( plane.constant == this.constant );
  3701. },
  3702. clone: function () {
  3703. return new THREE.Plane().copy( this );
  3704. }
  3705. };
  3706. // File:src/math/Math.js
  3707. /**
  3708. * @author alteredq / http://alteredqualia.com/
  3709. * @author mrdoob / http://mrdoob.com/
  3710. */
  3711. THREE.Math = {
  3712. generateUUID: function () {
  3713. // http://www.broofa.com/Tools/Math.uuid.htm
  3714. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split( '' );
  3715. var uuid = new Array( 36 );
  3716. var rnd = 0, r;
  3717. return function () {
  3718. for ( var i = 0; i < 36; i ++ ) {
  3719. if ( i == 8 || i == 13 || i == 18 || i == 23 ) {
  3720. uuid[ i ] = '-';
  3721. } else if ( i == 14 ) {
  3722. uuid[ i ] = '4';
  3723. } else {
  3724. if ( rnd <= 0x02 ) rnd = 0x2000000 + ( Math.random() * 0x1000000 ) | 0;
  3725. r = rnd & 0xf;
  3726. rnd = rnd >> 4;
  3727. uuid[ i ] = chars[ ( i == 19 ) ? ( r & 0x3 ) | 0x8 : r ];
  3728. }
  3729. }
  3730. return uuid.join( '' );
  3731. };
  3732. }(),
  3733. // Clamp value to range <a, b>
  3734. clamp: function ( x, a, b ) {
  3735. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  3736. },
  3737. // Clamp value to range <a, inf)
  3738. clampBottom: function ( x, a ) {
  3739. return x < a ? a : x;
  3740. },
  3741. // Linear mapping from range <a1, a2> to range <b1, b2>
  3742. mapLinear: function ( x, a1, a2, b1, b2 ) {
  3743. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  3744. },
  3745. // http://en.wikipedia.org/wiki/Smoothstep
  3746. smoothstep: function ( x, min, max ) {
  3747. if ( x <= min ) return 0;
  3748. if ( x >= max ) return 1;
  3749. x = ( x - min ) / ( max - min );
  3750. return x * x * ( 3 - 2 * x );
  3751. },
  3752. smootherstep: function ( x, min, max ) {
  3753. if ( x <= min ) return 0;
  3754. if ( x >= max ) return 1;
  3755. x = ( x - min ) / ( max - min );
  3756. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  3757. },
  3758. // Random float from <0, 1> with 16 bits of randomness
  3759. // (standard Math.random() creates repetitive patterns when applied over larger space)
  3760. random16: function () {
  3761. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  3762. },
  3763. // Random integer from <low, high> interval
  3764. randInt: function ( low, high ) {
  3765. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  3766. },
  3767. // Random float from <low, high> interval
  3768. randFloat: function ( low, high ) {
  3769. return low + Math.random() * ( high - low );
  3770. },
  3771. // Random float from <-range/2, range/2> interval
  3772. randFloatSpread: function ( range ) {
  3773. return range * ( 0.5 - Math.random() );
  3774. },
  3775. sign: function ( x ) {
  3776. return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : 0;
  3777. },
  3778. degToRad: function () {
  3779. var degreeToRadiansFactor = Math.PI / 180;
  3780. return function ( degrees ) {
  3781. return degrees * degreeToRadiansFactor;
  3782. };
  3783. }(),
  3784. radToDeg: function () {
  3785. var radianToDegreesFactor = 180 / Math.PI;
  3786. return function ( radians ) {
  3787. return radians * radianToDegreesFactor;
  3788. };
  3789. }(),
  3790. isPowerOfTwo: function ( value ) {
  3791. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  3792. }
  3793. };
  3794. // File:src/math/Spline.js
  3795. /**
  3796. * Spline from Tween.js, slightly optimized (and trashed)
  3797. * http://sole.github.com/tween.js/examples/05_spline.html
  3798. *
  3799. * @author mrdoob / http://mrdoob.com/
  3800. * @author alteredq / http://alteredqualia.com/
  3801. */
  3802. THREE.Spline = function ( points ) {
  3803. this.points = points;
  3804. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3805. point, intPoint, weight, w2, w3,
  3806. pa, pb, pc, pd;
  3807. this.initFromArray = function ( a ) {
  3808. this.points = [];
  3809. for ( var i = 0; i < a.length; i ++ ) {
  3810. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3811. }
  3812. };
  3813. this.getPoint = function ( k ) {
  3814. point = ( this.points.length - 1 ) * k;
  3815. intPoint = Math.floor( point );
  3816. weight = point - intPoint;
  3817. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3818. c[ 1 ] = intPoint;
  3819. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3820. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3821. pa = this.points[ c[ 0 ] ];
  3822. pb = this.points[ c[ 1 ] ];
  3823. pc = this.points[ c[ 2 ] ];
  3824. pd = this.points[ c[ 3 ] ];
  3825. w2 = weight * weight;
  3826. w3 = weight * w2;
  3827. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3828. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3829. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3830. return v3;
  3831. };
  3832. this.getControlPointsArray = function () {
  3833. var i, p, l = this.points.length,
  3834. coords = [];
  3835. for ( i = 0; i < l; i ++ ) {
  3836. p = this.points[ i ];
  3837. coords[ i ] = [ p.x, p.y, p.z ];
  3838. }
  3839. return coords;
  3840. };
  3841. // approximate length by summing linear segments
  3842. this.getLength = function ( nSubDivisions ) {
  3843. var i, index, nSamples, position,
  3844. point = 0, intPoint = 0, oldIntPoint = 0,
  3845. oldPosition = new THREE.Vector3(),
  3846. tmpVec = new THREE.Vector3(),
  3847. chunkLengths = [],
  3848. totalLength = 0;
  3849. // first point has 0 length
  3850. chunkLengths[ 0 ] = 0;
  3851. if ( ! nSubDivisions ) nSubDivisions = 100;
  3852. nSamples = this.points.length * nSubDivisions;
  3853. oldPosition.copy( this.points[ 0 ] );
  3854. for ( i = 1; i < nSamples; i ++ ) {
  3855. index = i / nSamples;
  3856. position = this.getPoint( index );
  3857. tmpVec.copy( position );
  3858. totalLength += tmpVec.distanceTo( oldPosition );
  3859. oldPosition.copy( position );
  3860. point = ( this.points.length - 1 ) * index;
  3861. intPoint = Math.floor( point );
  3862. if ( intPoint != oldIntPoint ) {
  3863. chunkLengths[ intPoint ] = totalLength;
  3864. oldIntPoint = intPoint;
  3865. }
  3866. }
  3867. // last point ends with total length
  3868. chunkLengths[ chunkLengths.length ] = totalLength;
  3869. return { chunks: chunkLengths, total: totalLength };
  3870. };
  3871. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3872. var i, j,
  3873. index, indexCurrent, indexNext,
  3874. linearDistance, realDistance,
  3875. sampling, position,
  3876. newpoints = [],
  3877. tmpVec = new THREE.Vector3(),
  3878. sl = this.getLength();
  3879. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3880. for ( i = 1; i < this.points.length; i ++ ) {
  3881. //tmpVec.copy( this.points[ i - 1 ] );
  3882. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3883. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3884. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3885. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3886. indexNext = i / ( this.points.length - 1 );
  3887. for ( j = 1; j < sampling - 1; j ++ ) {
  3888. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  3889. position = this.getPoint( index );
  3890. newpoints.push( tmpVec.copy( position ).clone() );
  3891. }
  3892. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  3893. }
  3894. this.points = newpoints;
  3895. };
  3896. // Catmull-Rom
  3897. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  3898. var v0 = ( p2 - p0 ) * 0.5,
  3899. v1 = ( p3 - p1 ) * 0.5;
  3900. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3901. };
  3902. };
  3903. // File:src/math/Triangle.js
  3904. /**
  3905. * @author bhouston / http://exocortex.com
  3906. * @author mrdoob / http://mrdoob.com/
  3907. */
  3908. THREE.Triangle = function ( a, b, c ) {
  3909. this.a = ( a !== undefined ) ? a : new THREE.Vector3();
  3910. this.b = ( b !== undefined ) ? b : new THREE.Vector3();
  3911. this.c = ( c !== undefined ) ? c : new THREE.Vector3();
  3912. };
  3913. THREE.Triangle.normal = function () {
  3914. var v0 = new THREE.Vector3();
  3915. return function ( a, b, c, optionalTarget ) {
  3916. var result = optionalTarget || new THREE.Vector3();
  3917. result.subVectors( c, b );
  3918. v0.subVectors( a, b );
  3919. result.cross( v0 );
  3920. var resultLengthSq = result.lengthSq();
  3921. if ( resultLengthSq > 0 ) {
  3922. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  3923. }
  3924. return result.set( 0, 0, 0 );
  3925. };
  3926. }();
  3927. // static/instance method to calculate barycoordinates
  3928. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  3929. THREE.Triangle.barycoordFromPoint = function () {
  3930. var v0 = new THREE.Vector3();
  3931. var v1 = new THREE.Vector3();
  3932. var v2 = new THREE.Vector3();
  3933. return function ( point, a, b, c, optionalTarget ) {
  3934. v0.subVectors( c, a );
  3935. v1.subVectors( b, a );
  3936. v2.subVectors( point, a );
  3937. var dot00 = v0.dot( v0 );
  3938. var dot01 = v0.dot( v1 );
  3939. var dot02 = v0.dot( v2 );
  3940. var dot11 = v1.dot( v1 );
  3941. var dot12 = v1.dot( v2 );
  3942. var denom = ( dot00 * dot11 - dot01 * dot01 );
  3943. var result = optionalTarget || new THREE.Vector3();
  3944. // colinear or singular triangle
  3945. if ( denom == 0 ) {
  3946. // arbitrary location outside of triangle?
  3947. // not sure if this is the best idea, maybe should be returning undefined
  3948. return result.set( - 2, - 1, - 1 );
  3949. }
  3950. var invDenom = 1 / denom;
  3951. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  3952. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  3953. // barycoordinates must always sum to 1
  3954. return result.set( 1 - u - v, v, u );
  3955. };
  3956. }();
  3957. THREE.Triangle.containsPoint = function () {
  3958. var v1 = new THREE.Vector3();
  3959. return function ( point, a, b, c ) {
  3960. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 );
  3961. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  3962. };
  3963. }();
  3964. THREE.Triangle.prototype = {
  3965. constructor: THREE.Triangle,
  3966. set: function ( a, b, c ) {
  3967. this.a.copy( a );
  3968. this.b.copy( b );
  3969. this.c.copy( c );
  3970. return this;
  3971. },
  3972. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  3973. this.a.copy( points[ i0 ] );
  3974. this.b.copy( points[ i1 ] );
  3975. this.c.copy( points[ i2 ] );
  3976. return this;
  3977. },
  3978. copy: function ( triangle ) {
  3979. this.a.copy( triangle.a );
  3980. this.b.copy( triangle.b );
  3981. this.c.copy( triangle.c );
  3982. return this;
  3983. },
  3984. area: function () {
  3985. var v0 = new THREE.Vector3();
  3986. var v1 = new THREE.Vector3();
  3987. return function () {
  3988. v0.subVectors( this.c, this.b );
  3989. v1.subVectors( this.a, this.b );
  3990. return v0.cross( v1 ).length() * 0.5;
  3991. };
  3992. }(),
  3993. midpoint: function ( optionalTarget ) {
  3994. var result = optionalTarget || new THREE.Vector3();
  3995. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  3996. },
  3997. normal: function ( optionalTarget ) {
  3998. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  3999. },
  4000. plane: function ( optionalTarget ) {
  4001. var result = optionalTarget || new THREE.Plane();
  4002. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  4003. },
  4004. barycoordFromPoint: function ( point, optionalTarget ) {
  4005. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  4006. },
  4007. containsPoint: function ( point ) {
  4008. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  4009. },
  4010. equals: function ( triangle ) {
  4011. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  4012. },
  4013. clone: function () {
  4014. return new THREE.Triangle().copy( this );
  4015. }
  4016. };
  4017. // File:src/core/Clock.js
  4018. /**
  4019. * @author alteredq / http://alteredqualia.com/
  4020. */
  4021. THREE.Clock = function ( autoStart ) {
  4022. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  4023. this.startTime = 0;
  4024. this.oldTime = 0;
  4025. this.elapsedTime = 0;
  4026. this.running = false;
  4027. };
  4028. THREE.Clock.prototype = {
  4029. constructor: THREE.Clock,
  4030. start: function () {
  4031. this.startTime = self.performance !== undefined && self.performance.now !== undefined
  4032. ? self.performance.now()
  4033. : Date.now();
  4034. this.oldTime = this.startTime;
  4035. this.running = true;
  4036. },
  4037. stop: function () {
  4038. this.getElapsedTime();
  4039. this.running = false;
  4040. },
  4041. getElapsedTime: function () {
  4042. this.getDelta();
  4043. return this.elapsedTime;
  4044. },
  4045. getDelta: function () {
  4046. var diff = 0;
  4047. if ( this.autoStart && ! this.running ) {
  4048. this.start();
  4049. }
  4050. if ( this.running ) {
  4051. var newTime = self.performance !== undefined && self.performance.now !== undefined
  4052. ? self.performance.now()
  4053. : Date.now();
  4054. diff = 0.001 * ( newTime - this.oldTime );
  4055. this.oldTime = newTime;
  4056. this.elapsedTime += diff;
  4057. }
  4058. return diff;
  4059. }
  4060. };
  4061. // File:src/core/EventDispatcher.js
  4062. /**
  4063. * https://github.com/mrdoob/eventdispatcher.js/
  4064. */
  4065. THREE.EventDispatcher = function () {}
  4066. THREE.EventDispatcher.prototype = {
  4067. constructor: THREE.EventDispatcher,
  4068. apply: function ( object ) {
  4069. object.addEventListener = THREE.EventDispatcher.prototype.addEventListener;
  4070. object.hasEventListener = THREE.EventDispatcher.prototype.hasEventListener;
  4071. object.removeEventListener = THREE.EventDispatcher.prototype.removeEventListener;
  4072. object.dispatchEvent = THREE.EventDispatcher.prototype.dispatchEvent;
  4073. },
  4074. addEventListener: function ( type, listener ) {
  4075. if ( this._listeners === undefined ) this._listeners = {};
  4076. var listeners = this._listeners;
  4077. if ( listeners[ type ] === undefined ) {
  4078. listeners[ type ] = [];
  4079. }
  4080. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  4081. listeners[ type ].push( listener );
  4082. }
  4083. },
  4084. hasEventListener: function ( type, listener ) {
  4085. if ( this._listeners === undefined ) return false;
  4086. var listeners = this._listeners;
  4087. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  4088. return true;
  4089. }
  4090. return false;
  4091. },
  4092. removeEventListener: function ( type, listener ) {
  4093. if ( this._listeners === undefined ) return;
  4094. var listeners = this._listeners;
  4095. var listenerArray = listeners[ type ];
  4096. if ( listenerArray !== undefined ) {
  4097. var index = listenerArray.indexOf( listener );
  4098. if ( index !== - 1 ) {
  4099. listenerArray.splice( index, 1 );
  4100. }
  4101. }
  4102. },
  4103. dispatchEvent: function ( event ) {
  4104. if ( this._listeners === undefined ) return;
  4105. var listeners = this._listeners;
  4106. var listenerArray = listeners[ event.type ];
  4107. if ( listenerArray !== undefined ) {
  4108. event.target = this;
  4109. var array = [];
  4110. var length = listenerArray.length;
  4111. for ( var i = 0; i < length; i ++ ) {
  4112. array[ i ] = listenerArray[ i ];
  4113. }
  4114. for ( var i = 0; i < length; i ++ ) {
  4115. array[ i ].call( this, event );
  4116. }
  4117. }
  4118. }
  4119. };
  4120. // File:src/core/Raycaster.js
  4121. /**
  4122. * @author mrdoob / http://mrdoob.com/
  4123. * @author bhouston / http://exocortex.com/
  4124. * @author stephomi / http://stephaneginier.com/
  4125. */
  4126. ( function ( THREE ) {
  4127. THREE.Raycaster = function ( origin, direction, near, far ) {
  4128. this.ray = new THREE.Ray( origin, direction );
  4129. // direction is assumed to be normalized (for accurate distance calculations)
  4130. this.near = near || 0;
  4131. this.far = far || Infinity;
  4132. this.params = {
  4133. Sprite: {},
  4134. Mesh: {},
  4135. PointCloud: { threshold: 1 },
  4136. LOD: {},
  4137. Line: {}
  4138. };
  4139. };
  4140. var descSort = function ( a, b ) {
  4141. return a.distance - b.distance;
  4142. };
  4143. var intersectObject = function ( object, raycaster, intersects, recursive ) {
  4144. object.raycast( raycaster, intersects );
  4145. if ( recursive === true ) {
  4146. var children = object.children;
  4147. for ( var i = 0, l = children.length; i < l; i ++ ) {
  4148. intersectObject( children[ i ], raycaster, intersects, true );
  4149. }
  4150. }
  4151. };
  4152. //
  4153. THREE.Raycaster.prototype = {
  4154. constructor: THREE.Raycaster,
  4155. precision: 0.0001,
  4156. linePrecision: 1,
  4157. set: function ( origin, direction ) {
  4158. this.ray.set( origin, direction );
  4159. // direction is assumed to be normalized (for accurate distance calculations)
  4160. },
  4161. intersectObject: function ( object, recursive ) {
  4162. var intersects = [];
  4163. intersectObject( object, this, intersects, recursive );
  4164. intersects.sort( descSort );
  4165. return intersects;
  4166. },
  4167. intersectObjects: function ( objects, recursive ) {
  4168. var intersects = [];
  4169. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  4170. intersectObject( objects[ i ], this, intersects, recursive );
  4171. }
  4172. intersects.sort( descSort );
  4173. return intersects;
  4174. }
  4175. };
  4176. }( THREE ) );
  4177. // File:src/core/Object3D.js
  4178. /**
  4179. * @author mrdoob / http://mrdoob.com/
  4180. * @author mikael emtinger / http://gomo.se/
  4181. * @author alteredq / http://alteredqualia.com/
  4182. * @author WestLangley / http://github.com/WestLangley
  4183. */
  4184. THREE.Object3D = function () {
  4185. this.id = THREE.Object3DIdCount ++;
  4186. this.uuid = THREE.Math.generateUUID();
  4187. this.name = '';
  4188. this.parent = undefined;
  4189. this.children = [];
  4190. this.up = THREE.Object3D.DefaultUp.clone();
  4191. var scope = this;
  4192. var position = new THREE.Vector3();
  4193. var rotation = new THREE.Euler();
  4194. var quaternion = new THREE.Quaternion();
  4195. var scale = new THREE.Vector3( 1, 1, 1 );
  4196. rotation.onChange( function () {
  4197. quaternion.setFromEuler( rotation, false );
  4198. } );
  4199. quaternion.onChange( function () {
  4200. rotation.setFromQuaternion( quaternion, undefined, false );
  4201. } );
  4202. Object.defineProperties( this, {
  4203. position: {
  4204. enumerable: true,
  4205. value: position
  4206. },
  4207. rotation: {
  4208. enumerable: true,
  4209. value: rotation
  4210. },
  4211. quaternion: {
  4212. enumerable: true,
  4213. value: quaternion
  4214. },
  4215. scale: {
  4216. enumerable: true,
  4217. value: scale
  4218. },
  4219. } );
  4220. this.renderDepth = null;
  4221. this.rotationAutoUpdate = true;
  4222. this.matrix = new THREE.Matrix4();
  4223. this.matrixWorld = new THREE.Matrix4();
  4224. this.matrixAutoUpdate = true;
  4225. this.matrixWorldNeedsUpdate = false;
  4226. this.visible = true;
  4227. this.castShadow = false;
  4228. this.receiveShadow = false;
  4229. this.frustumCulled = true;
  4230. this.userData = {};
  4231. };
  4232. THREE.Object3D.DefaultUp = new THREE.Vector3( 0, 1, 0 );
  4233. THREE.Object3D.prototype = {
  4234. constructor: THREE.Object3D,
  4235. get eulerOrder () {
  4236. console.warn( 'THREE.Object3D: .eulerOrder has been moved to .rotation.order.' );
  4237. return this.rotation.order;
  4238. },
  4239. set eulerOrder ( value ) {
  4240. console.warn( 'THREE.Object3D: .eulerOrder has been moved to .rotation.order.' );
  4241. this.rotation.order = value;
  4242. },
  4243. get useQuaternion () {
  4244. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  4245. },
  4246. set useQuaternion ( value ) {
  4247. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  4248. },
  4249. applyMatrix: function ( matrix ) {
  4250. this.matrix.multiplyMatrices( matrix, this.matrix );
  4251. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4252. },
  4253. setRotationFromAxisAngle: function ( axis, angle ) {
  4254. // assumes axis is normalized
  4255. this.quaternion.setFromAxisAngle( axis, angle );
  4256. },
  4257. setRotationFromEuler: function ( euler ) {
  4258. this.quaternion.setFromEuler( euler, true );
  4259. },
  4260. setRotationFromMatrix: function ( m ) {
  4261. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4262. this.quaternion.setFromRotationMatrix( m );
  4263. },
  4264. setRotationFromQuaternion: function ( q ) {
  4265. // assumes q is normalized
  4266. this.quaternion.copy( q );
  4267. },
  4268. rotateOnAxis: function () {
  4269. // rotate object on axis in object space
  4270. // axis is assumed to be normalized
  4271. var q1 = new THREE.Quaternion();
  4272. return function ( axis, angle ) {
  4273. q1.setFromAxisAngle( axis, angle );
  4274. this.quaternion.multiply( q1 );
  4275. return this;
  4276. }
  4277. }(),
  4278. rotateX: function () {
  4279. var v1 = new THREE.Vector3( 1, 0, 0 );
  4280. return function ( angle ) {
  4281. return this.rotateOnAxis( v1, angle );
  4282. };
  4283. }(),
  4284. rotateY: function () {
  4285. var v1 = new THREE.Vector3( 0, 1, 0 );
  4286. return function ( angle ) {
  4287. return this.rotateOnAxis( v1, angle );
  4288. };
  4289. }(),
  4290. rotateZ: function () {
  4291. var v1 = new THREE.Vector3( 0, 0, 1 );
  4292. return function ( angle ) {
  4293. return this.rotateOnAxis( v1, angle );
  4294. };
  4295. }(),
  4296. translateOnAxis: function () {
  4297. // translate object by distance along axis in object space
  4298. // axis is assumed to be normalized
  4299. var v1 = new THREE.Vector3();
  4300. return function ( axis, distance ) {
  4301. v1.copy( axis ).applyQuaternion( this.quaternion );
  4302. this.position.add( v1.multiplyScalar( distance ) );
  4303. return this;
  4304. }
  4305. }(),
  4306. translate: function ( distance, axis ) {
  4307. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  4308. return this.translateOnAxis( axis, distance );
  4309. },
  4310. translateX: function () {
  4311. var v1 = new THREE.Vector3( 1, 0, 0 );
  4312. return function ( distance ) {
  4313. return this.translateOnAxis( v1, distance );
  4314. };
  4315. }(),
  4316. translateY: function () {
  4317. var v1 = new THREE.Vector3( 0, 1, 0 );
  4318. return function ( distance ) {
  4319. return this.translateOnAxis( v1, distance );
  4320. };
  4321. }(),
  4322. translateZ: function () {
  4323. var v1 = new THREE.Vector3( 0, 0, 1 );
  4324. return function ( distance ) {
  4325. return this.translateOnAxis( v1, distance );
  4326. };
  4327. }(),
  4328. localToWorld: function ( vector ) {
  4329. return vector.applyMatrix4( this.matrixWorld );
  4330. },
  4331. worldToLocal: function () {
  4332. var m1 = new THREE.Matrix4();
  4333. return function ( vector ) {
  4334. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  4335. };
  4336. }(),
  4337. lookAt: function () {
  4338. // This routine does not support objects with rotated and/or translated parent(s)
  4339. var m1 = new THREE.Matrix4();
  4340. return function ( vector ) {
  4341. m1.lookAt( vector, this.position, this.up );
  4342. this.quaternion.setFromRotationMatrix( m1 );
  4343. };
  4344. }(),
  4345. add: function ( object ) {
  4346. if ( arguments.length > 1 ) {
  4347. for ( var i = 0; i < arguments.length; i++ ) {
  4348. this.add( arguments[ i ] );
  4349. }
  4350. return this;
  4351. };
  4352. if ( object === this ) {
  4353. console.warn( "THREE.Object3D.add: An object can't be added as a child of itself." );
  4354. return this;
  4355. }
  4356. if ( object instanceof THREE.Object3D ) {
  4357. if ( object.parent !== undefined ) {
  4358. object.parent.remove( object );
  4359. }
  4360. object.parent = this;
  4361. object.dispatchEvent( { type: 'added' } );
  4362. this.children.push( object );
  4363. // add to scene
  4364. var scene = this;
  4365. while ( scene.parent !== undefined ) {
  4366. scene = scene.parent;
  4367. }
  4368. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  4369. scene.__addObject( object );
  4370. }
  4371. }
  4372. return this;
  4373. },
  4374. remove: function ( object ) {
  4375. if ( arguments.length > 1 ) {
  4376. for ( var i = 0; i < arguments.length; i++ ) {
  4377. this.remove( arguments[ i ] );
  4378. }
  4379. };
  4380. var index = this.children.indexOf( object );
  4381. if ( index !== - 1 ) {
  4382. object.parent = undefined;
  4383. object.dispatchEvent( { type: 'removed' } );
  4384. this.children.splice( index, 1 );
  4385. // remove from scene
  4386. var scene = this;
  4387. while ( scene.parent !== undefined ) {
  4388. scene = scene.parent;
  4389. }
  4390. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  4391. scene.__removeObject( object );
  4392. }
  4393. }
  4394. },
  4395. raycast: function () {},
  4396. traverse: function ( callback ) {
  4397. callback( this );
  4398. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4399. this.children[ i ].traverse( callback );
  4400. }
  4401. },
  4402. traverseVisible: function ( callback ) {
  4403. if ( this.visible === false ) return;
  4404. callback( this );
  4405. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4406. this.children[ i ].traverseVisible( callback );
  4407. }
  4408. },
  4409. getObjectById: function ( id, recursive ) {
  4410. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4411. var child = this.children[ i ];
  4412. if ( child.id === id ) {
  4413. return child;
  4414. }
  4415. if ( recursive === true ) {
  4416. child = child.getObjectById( id, recursive );
  4417. if ( child !== undefined ) {
  4418. return child;
  4419. }
  4420. }
  4421. }
  4422. return undefined;
  4423. },
  4424. getObjectByName: function ( name, recursive ) {
  4425. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4426. var child = this.children[ i ];
  4427. if ( child.name === name ) {
  4428. return child;
  4429. }
  4430. if ( recursive === true ) {
  4431. child = child.getObjectByName( name, recursive );
  4432. if ( child !== undefined ) {
  4433. return child;
  4434. }
  4435. }
  4436. }
  4437. return undefined;
  4438. },
  4439. getChildByName: function ( name, recursive ) {
  4440. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  4441. return this.getObjectByName( name, recursive );
  4442. },
  4443. updateMatrix: function () {
  4444. this.matrix.compose( this.position, this.quaternion, this.scale );
  4445. this.matrixWorldNeedsUpdate = true;
  4446. },
  4447. updateMatrixWorld: function ( force ) {
  4448. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  4449. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  4450. if ( this.parent === undefined ) {
  4451. this.matrixWorld.copy( this.matrix );
  4452. } else {
  4453. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4454. }
  4455. this.matrixWorldNeedsUpdate = false;
  4456. force = true;
  4457. }
  4458. // update children
  4459. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4460. this.children[ i ].updateMatrixWorld( force );
  4461. }
  4462. },
  4463. clone: function ( object, recursive ) {
  4464. if ( object === undefined ) object = new THREE.Object3D();
  4465. if ( recursive === undefined ) recursive = true;
  4466. object.name = this.name;
  4467. object.up.copy( this.up );
  4468. object.position.copy( this.position );
  4469. object.quaternion.copy( this.quaternion );
  4470. object.scale.copy( this.scale );
  4471. object.renderDepth = this.renderDepth;
  4472. object.rotationAutoUpdate = this.rotationAutoUpdate;
  4473. object.matrix.copy( this.matrix );
  4474. object.matrixWorld.copy( this.matrixWorld );
  4475. object.matrixAutoUpdate = this.matrixAutoUpdate;
  4476. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  4477. object.visible = this.visible;
  4478. object.castShadow = this.castShadow;
  4479. object.receiveShadow = this.receiveShadow;
  4480. object.frustumCulled = this.frustumCulled;
  4481. object.userData = JSON.parse( JSON.stringify( this.userData ) );
  4482. if ( recursive === true ) {
  4483. for ( var i = 0; i < this.children.length; i ++ ) {
  4484. var child = this.children[ i ];
  4485. object.add( child.clone() );
  4486. }
  4487. }
  4488. return object;
  4489. }
  4490. };
  4491. THREE.EventDispatcher.prototype.apply( THREE.Object3D.prototype );
  4492. THREE.Object3DIdCount = 0;
  4493. // File:src/core/Projector.js
  4494. /**
  4495. * @author mrdoob / http://mrdoob.com/
  4496. * @author supereggbert / http://www.paulbrunt.co.uk/
  4497. * @author julianwa / https://github.com/julianwa
  4498. */
  4499. THREE.Projector = function () {
  4500. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  4501. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  4502. _face, _faceCount, _facePool = [], _facePoolLength = 0,
  4503. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  4504. _sprite, _spriteCount, _spritePool = [], _spritePoolLength = 0,
  4505. _renderData = { objects: [], lights: [], elements: [] },
  4506. _vA = new THREE.Vector3(),
  4507. _vB = new THREE.Vector3(),
  4508. _vC = new THREE.Vector3(),
  4509. _vector3 = new THREE.Vector3(),
  4510. _vector4 = new THREE.Vector4(),
  4511. _clipBox = new THREE.Box3( new THREE.Vector3( - 1, - 1, - 1 ), new THREE.Vector3( 1, 1, 1 ) ),
  4512. _boundingBox = new THREE.Box3(),
  4513. _points3 = new Array( 3 ),
  4514. _points4 = new Array( 4 ),
  4515. _viewMatrix = new THREE.Matrix4(),
  4516. _viewProjectionMatrix = new THREE.Matrix4(),
  4517. _modelMatrix,
  4518. _modelViewProjectionMatrix = new THREE.Matrix4(),
  4519. _normalMatrix = new THREE.Matrix3(),
  4520. _frustum = new THREE.Frustum(),
  4521. _clippedVertex1PositionScreen = new THREE.Vector4(),
  4522. _clippedVertex2PositionScreen = new THREE.Vector4();
  4523. this.projectVector = function ( vector, camera ) {
  4524. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  4525. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  4526. return vector.applyProjection( _viewProjectionMatrix );
  4527. };
  4528. this.unprojectVector = function () {
  4529. var projectionMatrixInverse = new THREE.Matrix4();
  4530. return function ( vector, camera ) {
  4531. projectionMatrixInverse.getInverse( camera.projectionMatrix );
  4532. _viewProjectionMatrix.multiplyMatrices( camera.matrixWorld, projectionMatrixInverse );
  4533. return vector.applyProjection( _viewProjectionMatrix );
  4534. };
  4535. }();
  4536. this.pickingRay = function ( vector, camera ) {
  4537. // set two vectors with opposing z values
  4538. vector.z = - 1.0;
  4539. var end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  4540. this.unprojectVector( vector, camera );
  4541. this.unprojectVector( end, camera );
  4542. // find direction from vector to end
  4543. end.sub( vector ).normalize();
  4544. return new THREE.Raycaster( vector, end );
  4545. };
  4546. var RenderList = function () {
  4547. var normals = [];
  4548. var uvs = [];
  4549. var object = null;
  4550. var material = null;
  4551. var normalMatrix = new THREE.Matrix3();
  4552. var setObject = function ( value ) {
  4553. object = value;
  4554. material = object.material;
  4555. normalMatrix.getNormalMatrix( object.matrixWorld );
  4556. normals.length = 0;
  4557. uvs.length = 0;
  4558. };
  4559. var projectVertex = function ( vertex ) {
  4560. var position = vertex.position;
  4561. var positionWorld = vertex.positionWorld;
  4562. var positionScreen = vertex.positionScreen;
  4563. positionWorld.copy( position ).applyMatrix4( _modelMatrix );
  4564. positionScreen.copy( positionWorld ).applyMatrix4( _viewProjectionMatrix );
  4565. var invW = 1 / positionScreen.w;
  4566. positionScreen.x *= invW;
  4567. positionScreen.y *= invW;
  4568. positionScreen.z *= invW;
  4569. vertex.visible = positionScreen.x >= - 1 && positionScreen.x <= 1 &&
  4570. positionScreen.y >= - 1 && positionScreen.y <= 1 &&
  4571. positionScreen.z >= - 1 && positionScreen.z <= 1;
  4572. };
  4573. var pushVertex = function ( x, y, z ) {
  4574. _vertex = getNextVertexInPool();
  4575. _vertex.position.set( x, y, z );
  4576. projectVertex( _vertex );
  4577. };
  4578. var pushNormal = function ( x, y, z ) {
  4579. normals.push( x, y, z );
  4580. };
  4581. var pushUv = function ( x, y ) {
  4582. uvs.push( x, y );
  4583. };
  4584. var checkTriangleVisibility = function ( v1, v2, v3 ) {
  4585. if ( v1.visible === true || v2.visible === true || v3.visible === true ) return true;
  4586. _points3[ 0 ] = v1.positionScreen;
  4587. _points3[ 1 ] = v2.positionScreen;
  4588. _points3[ 2 ] = v3.positionScreen;
  4589. return _clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points3 ) );
  4590. };
  4591. var checkBackfaceCulling = function ( v1, v2, v3 ) {
  4592. return ( ( v3.positionScreen.x - v1.positionScreen.x ) *
  4593. ( v2.positionScreen.y - v1.positionScreen.y ) -
  4594. ( v3.positionScreen.y - v1.positionScreen.y ) *
  4595. ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  4596. };
  4597. var pushLine = function ( a, b ) {
  4598. var v1 = _vertexPool[ a ];
  4599. var v2 = _vertexPool[ b ];
  4600. _line = getNextLineInPool();
  4601. _line.id = object.id;
  4602. _line.v1.copy( v1 );
  4603. _line.v2.copy( v2 );
  4604. _line.z = ( v1.positionScreen.z + v2.positionScreen.z ) / 2;
  4605. _line.material = object.material;
  4606. _renderData.elements.push( _line );
  4607. };
  4608. var pushTriangle = function ( a, b, c ) {
  4609. var v1 = _vertexPool[ a ];
  4610. var v2 = _vertexPool[ b ];
  4611. var v3 = _vertexPool[ c ];
  4612. if ( checkTriangleVisibility( v1, v2, v3 ) === false ) return;
  4613. if ( material.side === THREE.DoubleSide || checkBackfaceCulling( v1, v2, v3 ) === true ) {
  4614. _face = getNextFaceInPool();
  4615. _face.id = object.id;
  4616. _face.v1.copy( v1 );
  4617. _face.v2.copy( v2 );
  4618. _face.v3.copy( v3 );
  4619. _face.z = ( v1.positionScreen.z + v2.positionScreen.z + v3.positionScreen.z ) / 3;
  4620. for ( var i = 0; i < 3; i ++ ) {
  4621. var offset = arguments[ i ] * 3;
  4622. var normal = _face.vertexNormalsModel[ i ];
  4623. normal.set( normals[ offset ], normals[ offset + 1 ], normals[ offset + 2 ] );
  4624. normal.applyMatrix3( normalMatrix ).normalize();
  4625. var offset2 = arguments[ i ] * 2;
  4626. var uv = _face.uvs[ i ];
  4627. uv.set( uvs[ offset2 ], uvs[ offset2 + 1 ] );
  4628. }
  4629. _face.vertexNormalsLength = 3;
  4630. _face.material = object.material;
  4631. _renderData.elements.push( _face );
  4632. }
  4633. };
  4634. return {
  4635. setObject: setObject,
  4636. projectVertex: projectVertex,
  4637. checkTriangleVisibility: checkTriangleVisibility,
  4638. checkBackfaceCulling: checkBackfaceCulling,
  4639. pushVertex: pushVertex,
  4640. pushNormal: pushNormal,
  4641. pushUv: pushUv,
  4642. pushLine: pushLine,
  4643. pushTriangle: pushTriangle
  4644. }
  4645. };
  4646. var renderList = new RenderList();
  4647. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  4648. _faceCount = 0;
  4649. _lineCount = 0;
  4650. _spriteCount = 0;
  4651. _renderData.elements.length = 0;
  4652. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  4653. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  4654. _viewMatrix.copy( camera.matrixWorldInverse.getInverse( camera.matrixWorld ) );
  4655. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, _viewMatrix );
  4656. _frustum.setFromMatrix( _viewProjectionMatrix );
  4657. //
  4658. _objectCount = 0;
  4659. _renderData.objects.length = 0;
  4660. _renderData.lights.length = 0;
  4661. scene.traverseVisible( function ( object ) {
  4662. if ( object instanceof THREE.Light ) {
  4663. _renderData.lights.push( object );
  4664. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.Sprite ) {
  4665. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  4666. _object = getNextObjectInPool();
  4667. _object.id = object.id;
  4668. _object.object = object;
  4669. if ( object.renderDepth !== null ) {
  4670. _object.z = object.renderDepth;
  4671. } else {
  4672. _vector3.setFromMatrixPosition( object.matrixWorld );
  4673. _vector3.applyProjection( _viewProjectionMatrix );
  4674. _object.z = _vector3.z;
  4675. }
  4676. _renderData.objects.push( _object );
  4677. }
  4678. }
  4679. } );
  4680. if ( sortObjects === true ) {
  4681. _renderData.objects.sort( painterSort );
  4682. }
  4683. //
  4684. for ( var o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
  4685. var object = _renderData.objects[ o ].object;
  4686. var geometry = object.geometry;
  4687. renderList.setObject( object );
  4688. _modelMatrix = object.matrixWorld;
  4689. _vertexCount = 0;
  4690. if ( object instanceof THREE.Mesh ) {
  4691. if ( geometry instanceof THREE.BufferGeometry ) {
  4692. var attributes = geometry.attributes;
  4693. var offsets = geometry.offsets;
  4694. if ( attributes.position === undefined ) continue;
  4695. var positions = attributes.position.array;
  4696. for ( var i = 0, l = positions.length; i < l; i += 3 ) {
  4697. renderList.pushVertex( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  4698. }
  4699. if ( attributes.normal !== undefined ) {
  4700. var normals = attributes.normal.array;
  4701. for ( var i = 0, l = normals.length; i < l; i += 3 ) {
  4702. renderList.pushNormal( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] );
  4703. }
  4704. }
  4705. if ( attributes.uv !== undefined ) {
  4706. var uvs = attributes.uv.array;
  4707. for ( var i = 0, l = uvs.length; i < l; i += 2 ) {
  4708. renderList.pushUv( uvs[ i ], uvs[ i + 1 ] );
  4709. }
  4710. }
  4711. if ( attributes.index !== undefined ) {
  4712. var indices = attributes.index.array;
  4713. if ( offsets.length > 0 ) {
  4714. for ( var o = 0; o < offsets.length; o ++ ) {
  4715. var offset = offsets[ o ];
  4716. var index = offset.index;
  4717. for ( var i = offset.start, l = offset.start + offset.count; i < l; i += 3 ) {
  4718. renderList.pushTriangle( indices[ i ] + index, indices[ i + 1 ] + index, indices[ i + 2 ] + index );
  4719. }
  4720. }
  4721. } else {
  4722. for ( var i = 0, l = indices.length; i < l; i += 3 ) {
  4723. renderList.pushTriangle( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  4724. }
  4725. }
  4726. } else {
  4727. for ( var i = 0, l = positions.length / 3; i < l; i += 3 ) {
  4728. renderList.pushTriangle( i, i + 1, i + 2 );
  4729. }
  4730. }
  4731. } else if ( geometry instanceof THREE.Geometry ) {
  4732. var vertices = geometry.vertices;
  4733. var faces = geometry.faces;
  4734. var faceVertexUvs = geometry.faceVertexUvs[ 0 ];
  4735. _normalMatrix.getNormalMatrix( _modelMatrix );
  4736. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  4737. var objectMaterials = isFaceMaterial === true ? object.material : null;
  4738. for ( var v = 0, vl = vertices.length; v < vl; v ++ ) {
  4739. var vertex = vertices[ v ];
  4740. renderList.pushVertex( vertex.x, vertex.y, vertex.z );
  4741. }
  4742. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  4743. var face = faces[ f ];
  4744. var material = isFaceMaterial === true
  4745. ? objectMaterials.materials[ face.materialIndex ]
  4746. : object.material;
  4747. if ( material === undefined ) continue;
  4748. var side = material.side;
  4749. var v1 = _vertexPool[ face.a ];
  4750. var v2 = _vertexPool[ face.b ];
  4751. var v3 = _vertexPool[ face.c ];
  4752. if ( material.morphTargets === true ) {
  4753. var morphTargets = geometry.morphTargets;
  4754. var morphInfluences = object.morphTargetInfluences;
  4755. var v1p = v1.position;
  4756. var v2p = v2.position;
  4757. var v3p = v3.position;
  4758. _vA.set( 0, 0, 0 );
  4759. _vB.set( 0, 0, 0 );
  4760. _vC.set( 0, 0, 0 );
  4761. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  4762. var influence = morphInfluences[ t ];
  4763. if ( influence === 0 ) continue;
  4764. var targets = morphTargets[ t ].vertices;
  4765. _vA.x += ( targets[ face.a ].x - v1p.x ) * influence;
  4766. _vA.y += ( targets[ face.a ].y - v1p.y ) * influence;
  4767. _vA.z += ( targets[ face.a ].z - v1p.z ) * influence;
  4768. _vB.x += ( targets[ face.b ].x - v2p.x ) * influence;
  4769. _vB.y += ( targets[ face.b ].y - v2p.y ) * influence;
  4770. _vB.z += ( targets[ face.b ].z - v2p.z ) * influence;
  4771. _vC.x += ( targets[ face.c ].x - v3p.x ) * influence;
  4772. _vC.y += ( targets[ face.c ].y - v3p.y ) * influence;
  4773. _vC.z += ( targets[ face.c ].z - v3p.z ) * influence;
  4774. }
  4775. v1.position.add( _vA );
  4776. v2.position.add( _vB );
  4777. v3.position.add( _vC );
  4778. renderList.projectVertex( v1 );
  4779. renderList.projectVertex( v2 );
  4780. renderList.projectVertex( v3 );
  4781. }
  4782. if ( renderList.checkTriangleVisibility( v1, v2, v3 ) === false ) continue;
  4783. var visible = renderList.checkBackfaceCulling( v1, v2, v3 );
  4784. if ( side !== THREE.DoubleSide ) {
  4785. if ( side === THREE.FrontSide && visible === false ) continue;
  4786. if ( side === THREE.BackSide && visible === true ) continue;
  4787. }
  4788. _face = getNextFaceInPool();
  4789. _face.id = object.id;
  4790. _face.v1.copy( v1 );
  4791. _face.v2.copy( v2 );
  4792. _face.v3.copy( v3 );
  4793. _face.normalModel.copy( face.normal );
  4794. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4795. _face.normalModel.negate();
  4796. }
  4797. _face.normalModel.applyMatrix3( _normalMatrix ).normalize();
  4798. var faceVertexNormals = face.vertexNormals;
  4799. for ( var n = 0, nl = Math.min( faceVertexNormals.length, 3 ); n < nl; n ++ ) {
  4800. var normalModel = _face.vertexNormalsModel[ n ];
  4801. normalModel.copy( faceVertexNormals[ n ] );
  4802. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4803. normalModel.negate();
  4804. }
  4805. normalModel.applyMatrix3( _normalMatrix ).normalize();
  4806. }
  4807. _face.vertexNormalsLength = faceVertexNormals.length;
  4808. var vertexUvs = faceVertexUvs[ f ];
  4809. if ( vertexUvs !== undefined ) {
  4810. for ( var u = 0; u < 3; u ++ ) {
  4811. _face.uvs[ u ].copy( vertexUvs[ u ] );
  4812. }
  4813. }
  4814. _face.color = face.color;
  4815. _face.material = material;
  4816. _face.z = ( v1.positionScreen.z + v2.positionScreen.z + v3.positionScreen.z ) / 3;
  4817. _renderData.elements.push( _face );
  4818. }
  4819. }
  4820. } else if ( object instanceof THREE.Line ) {
  4821. if ( geometry instanceof THREE.BufferGeometry ) {
  4822. var attributes = geometry.attributes;
  4823. if ( attributes.position !== undefined ) {
  4824. var positions = attributes.position.array;
  4825. for ( var i = 0, l = positions.length; i < l; i += 3 ) {
  4826. renderList.pushVertex( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  4827. }
  4828. if ( attributes.index !== undefined ) {
  4829. var indices = attributes.index.array;
  4830. for ( var i = 0, l = indices.length; i < l; i += 2 ) {
  4831. renderList.pushLine( indices[ i ], indices[ i + 1 ] );
  4832. }
  4833. } else {
  4834. var step = object.type === THREE.LinePieces ? 2 : 1;
  4835. for ( var i = 0, l = ( positions.length / 3 ) - 1; i < l; i += step ) {
  4836. renderList.pushLine( i, i + 1 );
  4837. }
  4838. }
  4839. }
  4840. } else if ( geometry instanceof THREE.Geometry ) {
  4841. _modelViewProjectionMatrix.multiplyMatrices( _viewProjectionMatrix, _modelMatrix );
  4842. var vertices = object.geometry.vertices;
  4843. if ( vertices.length === 0 ) continue;
  4844. v1 = getNextVertexInPool();
  4845. v1.positionScreen.copy( vertices[ 0 ] ).applyMatrix4( _modelViewProjectionMatrix );
  4846. // Handle LineStrip and LinePieces
  4847. var step = object.type === THREE.LinePieces ? 2 : 1;
  4848. for ( var v = 1, vl = vertices.length; v < vl; v ++ ) {
  4849. v1 = getNextVertexInPool();
  4850. v1.positionScreen.copy( vertices[ v ] ).applyMatrix4( _modelViewProjectionMatrix );
  4851. if ( ( v + 1 ) % step > 0 ) continue;
  4852. v2 = _vertexPool[ _vertexCount - 2 ];
  4853. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  4854. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  4855. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  4856. // Perform the perspective divide
  4857. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  4858. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  4859. _line = getNextLineInPool();
  4860. _line.id = object.id;
  4861. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  4862. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  4863. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  4864. _line.material = object.material;
  4865. if ( object.material.vertexColors === THREE.VertexColors ) {
  4866. _line.vertexColors[ 0 ].copy( object.geometry.colors[ v ] );
  4867. _line.vertexColors[ 1 ].copy( object.geometry.colors[ v - 1 ] );
  4868. }
  4869. _renderData.elements.push( _line );
  4870. }
  4871. }
  4872. }
  4873. } else if ( object instanceof THREE.Sprite ) {
  4874. _vector4.set( _modelMatrix.elements[ 12 ], _modelMatrix.elements[ 13 ], _modelMatrix.elements[ 14 ], 1 );
  4875. _vector4.applyMatrix4( _viewProjectionMatrix );
  4876. var invW = 1 / _vector4.w;
  4877. _vector4.z *= invW;
  4878. if ( _vector4.z >= - 1 && _vector4.z <= 1 ) {
  4879. _sprite = getNextSpriteInPool();
  4880. _sprite.id = object.id;
  4881. _sprite.x = _vector4.x * invW;
  4882. _sprite.y = _vector4.y * invW;
  4883. _sprite.z = _vector4.z;
  4884. _sprite.object = object;
  4885. _sprite.rotation = object.rotation;
  4886. _sprite.scale.x = object.scale.x * Math.abs( _sprite.x - ( _vector4.x + camera.projectionMatrix.elements[ 0 ] ) / ( _vector4.w + camera.projectionMatrix.elements[ 12 ] ) );
  4887. _sprite.scale.y = object.scale.y * Math.abs( _sprite.y - ( _vector4.y + camera.projectionMatrix.elements[ 5 ] ) / ( _vector4.w + camera.projectionMatrix.elements[ 13 ] ) );
  4888. _sprite.material = object.material;
  4889. _renderData.elements.push( _sprite );
  4890. }
  4891. }
  4892. }
  4893. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  4894. return _renderData;
  4895. };
  4896. // Pools
  4897. function getNextObjectInPool() {
  4898. if ( _objectCount === _objectPoolLength ) {
  4899. var object = new THREE.RenderableObject();
  4900. _objectPool.push( object );
  4901. _objectPoolLength ++;
  4902. _objectCount ++;
  4903. return object;
  4904. }
  4905. return _objectPool[ _objectCount ++ ];
  4906. }
  4907. function getNextVertexInPool() {
  4908. if ( _vertexCount === _vertexPoolLength ) {
  4909. var vertex = new THREE.RenderableVertex();
  4910. _vertexPool.push( vertex );
  4911. _vertexPoolLength ++;
  4912. _vertexCount ++;
  4913. return vertex;
  4914. }
  4915. return _vertexPool[ _vertexCount ++ ];
  4916. }
  4917. function getNextFaceInPool() {
  4918. if ( _faceCount === _facePoolLength ) {
  4919. var face = new THREE.RenderableFace();
  4920. _facePool.push( face );
  4921. _facePoolLength ++;
  4922. _faceCount ++;
  4923. return face;
  4924. }
  4925. return _facePool[ _faceCount ++ ];
  4926. }
  4927. function getNextLineInPool() {
  4928. if ( _lineCount === _linePoolLength ) {
  4929. var line = new THREE.RenderableLine();
  4930. _linePool.push( line );
  4931. _linePoolLength ++;
  4932. _lineCount ++
  4933. return line;
  4934. }
  4935. return _linePool[ _lineCount ++ ];
  4936. }
  4937. function getNextSpriteInPool() {
  4938. if ( _spriteCount === _spritePoolLength ) {
  4939. var sprite = new THREE.RenderableSprite();
  4940. _spritePool.push( sprite );
  4941. _spritePoolLength ++;
  4942. _spriteCount ++
  4943. return sprite;
  4944. }
  4945. return _spritePool[ _spriteCount ++ ];
  4946. }
  4947. //
  4948. function painterSort( a, b ) {
  4949. if ( a.z !== b.z ) {
  4950. return b.z - a.z;
  4951. } else if ( a.id !== b.id ) {
  4952. return a.id - b.id;
  4953. } else {
  4954. return 0;
  4955. }
  4956. }
  4957. function clipLine( s1, s2 ) {
  4958. var alpha1 = 0, alpha2 = 1,
  4959. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  4960. // Z = -1 and Z = +1, respectively.
  4961. bc1near = s1.z + s1.w,
  4962. bc2near = s2.z + s2.w,
  4963. bc1far = - s1.z + s1.w,
  4964. bc2far = - s2.z + s2.w;
  4965. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  4966. // Both vertices lie entirely within all clip planes.
  4967. return true;
  4968. } else if ( ( bc1near < 0 && bc2near < 0 ) || ( bc1far < 0 && bc2far < 0 ) ) {
  4969. // Both vertices lie entirely outside one of the clip planes.
  4970. return false;
  4971. } else {
  4972. // The line segment spans at least one clip plane.
  4973. if ( bc1near < 0 ) {
  4974. // v1 lies outside the near plane, v2 inside
  4975. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  4976. } else if ( bc2near < 0 ) {
  4977. // v2 lies outside the near plane, v1 inside
  4978. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  4979. }
  4980. if ( bc1far < 0 ) {
  4981. // v1 lies outside the far plane, v2 inside
  4982. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  4983. } else if ( bc2far < 0 ) {
  4984. // v2 lies outside the far plane, v2 inside
  4985. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  4986. }
  4987. if ( alpha2 < alpha1 ) {
  4988. // The line segment spans two boundaries, but is outside both of them.
  4989. // (This can't happen when we're only clipping against just near/far but good
  4990. // to leave the check here for future usage if other clip planes are added.)
  4991. return false;
  4992. } else {
  4993. // Update the s1 and s2 vertices to match the clipped line segment.
  4994. s1.lerp( s2, alpha1 );
  4995. s2.lerp( s1, 1 - alpha2 );
  4996. return true;
  4997. }
  4998. }
  4999. }
  5000. };
  5001. // File:src/core/Face3.js
  5002. /**
  5003. * @author mrdoob / http://mrdoob.com/
  5004. * @author alteredq / http://alteredqualia.com/
  5005. */
  5006. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  5007. this.a = a;
  5008. this.b = b;
  5009. this.c = c;
  5010. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  5011. this.vertexNormals = normal instanceof Array ? normal : [];
  5012. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  5013. this.vertexColors = color instanceof Array ? color : [];
  5014. this.vertexTangents = [];
  5015. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  5016. };
  5017. THREE.Face3.prototype = {
  5018. constructor: THREE.Face3,
  5019. clone: function () {
  5020. var face = new THREE.Face3( this.a, this.b, this.c );
  5021. face.normal.copy( this.normal );
  5022. face.color.copy( this.color );
  5023. face.materialIndex = this.materialIndex;
  5024. for ( var i = 0, il = this.vertexNormals.length; i < il; i ++ ) {
  5025. face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  5026. }
  5027. for ( var i = 0, il = this.vertexColors.length; i < il; i ++ ) {
  5028. face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  5029. }
  5030. for ( var i = 0, il = this.vertexTangents.length; i < il; i ++ ) {
  5031. face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  5032. }
  5033. return face;
  5034. }
  5035. };
  5036. // File:src/core/Face4.js
  5037. /**
  5038. * @author mrdoob / http://mrdoob.com/
  5039. */
  5040. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  5041. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' )
  5042. return new THREE.Face3( a, b, c, normal, color, materialIndex );
  5043. };
  5044. // File:src/core/BufferAttribute.js
  5045. /**
  5046. * @author mrdoob / http://mrdoob.com/
  5047. */
  5048. THREE.BufferAttribute = function ( array, itemSize ) {
  5049. this.array = array;
  5050. this.itemSize = itemSize;
  5051. };
  5052. THREE.BufferAttribute.prototype = {
  5053. constructor: THREE.BufferAttribute,
  5054. get length () {
  5055. return this.array.length;
  5056. },
  5057. set: function ( value ) {
  5058. this.array.set( value );
  5059. return this;
  5060. },
  5061. setX: function ( index, x ) {
  5062. this.array[ index * this.itemSize ] = x;
  5063. return this;
  5064. },
  5065. setY: function ( index, y ) {
  5066. this.array[ index * this.itemSize + 1 ] = y;
  5067. return this;
  5068. },
  5069. setZ: function ( index, z ) {
  5070. this.array[ index * this.itemSize + 2 ] = z;
  5071. return this;
  5072. },
  5073. setXY: function ( index, x, y ) {
  5074. index *= this.itemSize;
  5075. this.array[ index ] = x;
  5076. this.array[ index + 1 ] = y;
  5077. return this;
  5078. },
  5079. setXYZ: function ( index, x, y, z ) {
  5080. index *= this.itemSize;
  5081. this.array[ index ] = x;
  5082. this.array[ index + 1 ] = y;
  5083. this.array[ index + 2 ] = z;
  5084. return this;
  5085. },
  5086. setXYZW: function ( index, x, y, z, w ) {
  5087. index *= this.itemSize;
  5088. this.array[ index ] = x;
  5089. this.array[ index + 1 ] = y;
  5090. this.array[ index + 2 ] = z;
  5091. this.array[ index + 3 ] = w;
  5092. return this;
  5093. }
  5094. };
  5095. //
  5096. THREE.Int8Attribute = function ( data, itemSize ) {
  5097. console.warn( 'THREE.Int8Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  5098. return new THREE.BufferAttribute( data, itemSize );
  5099. };
  5100. THREE.Uint8Attribute = function ( data, itemSize ) {
  5101. console.warn( 'THREE.Uint8Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  5102. return new THREE.BufferAttribute( data, itemSize );
  5103. };
  5104. THREE.Uint8ClampedAttribute = function ( data, itemSize ) {
  5105. console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  5106. return new THREE.BufferAttribute( data, itemSize );
  5107. };
  5108. THREE.Int16Attribute = function ( data, itemSize ) {
  5109. console.warn( 'THREE.Int16Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  5110. return new THREE.BufferAttribute( data, itemSize );
  5111. };
  5112. THREE.Uint16Attribute = function ( data, itemSize ) {
  5113. console.warn( 'THREE.Uint16Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  5114. return new THREE.BufferAttribute( data, itemSize );
  5115. };
  5116. THREE.Int32Attribute = function ( data, itemSize ) {
  5117. console.warn( 'THREE.Int32Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  5118. return new THREE.BufferAttribute( data, itemSize );
  5119. };
  5120. THREE.Uint32Attribute = function ( data, itemSize ) {
  5121. console.warn( 'THREE.Uint32Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  5122. return new THREE.BufferAttribute( data, itemSize );
  5123. };
  5124. THREE.Float32Attribute = function ( data, itemSize ) {
  5125. console.warn( 'THREE.Float32Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  5126. return new THREE.BufferAttribute( data, itemSize );
  5127. };
  5128. THREE.Float64Attribute = function ( data, itemSize ) {
  5129. console.warn( 'THREE.Float64Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  5130. return new THREE.BufferAttribute( data, itemSize );
  5131. };
  5132. // File:src/core/BufferGeometry.js
  5133. /**
  5134. * @author alteredq / http://alteredqualia.com/
  5135. */
  5136. THREE.BufferGeometry = function () {
  5137. this.id = THREE.GeometryIdCount ++;
  5138. this.uuid = THREE.Math.generateUUID();
  5139. this.name = '';
  5140. this.attributes = {};
  5141. this.drawcalls = [];
  5142. this.offsets = this.drawcalls; // backwards compatibility
  5143. this.boundingBox = null;
  5144. this.boundingSphere = null;
  5145. };
  5146. THREE.BufferGeometry.prototype = {
  5147. constructor: THREE.BufferGeometry,
  5148. addAttribute: function ( name, attribute ) {
  5149. if ( attribute instanceof THREE.BufferAttribute === false ) {
  5150. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  5151. this.attributes[ name ] = { array: arguments[ 1 ], itemSize: arguments[ 2 ] };
  5152. return;
  5153. }
  5154. this.attributes[ name ] = attribute;
  5155. },
  5156. getAttribute: function ( name ) {
  5157. return this.attributes[ name ];
  5158. },
  5159. addDrawCall: function ( start, count, indexOffset ) {
  5160. this.drawcalls.push( {
  5161. start: start,
  5162. count: count,
  5163. index: indexOffset !== undefined ? indexOffset : 0
  5164. } );
  5165. },
  5166. applyMatrix: function ( matrix ) {
  5167. var position = this.attributes.position;
  5168. if ( position !== undefined ) {
  5169. matrix.applyToVector3Array( position.array );
  5170. position.needsUpdate = true;
  5171. }
  5172. var normal = this.attributes.normal;
  5173. if ( normal !== undefined ) {
  5174. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5175. normalMatrix.applyToVector3Array( normal.array );
  5176. normal.needsUpdate = true;
  5177. }
  5178. },
  5179. fromGeometry: function ( geometry, settings ) {
  5180. settings = settings || { 'vertexColors': THREE.NoColors };
  5181. var vertices = geometry.vertices;
  5182. var faces = geometry.faces;
  5183. var faceVertexUvs = geometry.faceVertexUvs;
  5184. var vertexColors = settings.vertexColors;
  5185. var hasFaceVertexUv = faceVertexUvs[ 0 ].length > 0;
  5186. var hasFaceVertexNormals = faces[ 0 ].vertexNormals.length == 3;
  5187. var positions = new Float32Array( faces.length * 3 * 3 );
  5188. this.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
  5189. var normals = new Float32Array( faces.length * 3 * 3 );
  5190. this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
  5191. if ( vertexColors !== THREE.NoColors ) {
  5192. var colors = new Float32Array( faces.length * 3 * 3 );
  5193. this.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) );
  5194. }
  5195. if ( hasFaceVertexUv === true ) {
  5196. var uvs = new Float32Array( faces.length * 3 * 2 );
  5197. this.addAttribute( 'uvs', new THREE.BufferAttribute( uvs, 2 ) );
  5198. }
  5199. for ( var i = 0, i2 = 0, i3 = 0; i < faces.length; i ++, i2 += 6, i3 += 9 ) {
  5200. var face = faces[ i ];
  5201. var a = vertices[ face.a ];
  5202. var b = vertices[ face.b ];
  5203. var c = vertices[ face.c ];
  5204. positions[ i3 ] = a.x;
  5205. positions[ i3 + 1 ] = a.y;
  5206. positions[ i3 + 2 ] = a.z;
  5207. positions[ i3 + 3 ] = b.x;
  5208. positions[ i3 + 4 ] = b.y;
  5209. positions[ i3 + 5 ] = b.z;
  5210. positions[ i3 + 6 ] = c.x;
  5211. positions[ i3 + 7 ] = c.y;
  5212. positions[ i3 + 8 ] = c.z;
  5213. if ( hasFaceVertexNormals === true ) {
  5214. var na = face.vertexNormals[ 0 ];
  5215. var nb = face.vertexNormals[ 1 ];
  5216. var nc = face.vertexNormals[ 2 ];
  5217. normals[ i3 ] = na.x;
  5218. normals[ i3 + 1 ] = na.y;
  5219. normals[ i3 + 2 ] = na.z;
  5220. normals[ i3 + 3 ] = nb.x;
  5221. normals[ i3 + 4 ] = nb.y;
  5222. normals[ i3 + 5 ] = nb.z;
  5223. normals[ i3 + 6 ] = nc.x;
  5224. normals[ i3 + 7 ] = nc.y;
  5225. normals[ i3 + 8 ] = nc.z;
  5226. } else {
  5227. var n = face.normal;
  5228. normals[ i3 ] = n.x;
  5229. normals[ i3 + 1 ] = n.y;
  5230. normals[ i3 + 2 ] = n.z;
  5231. normals[ i3 + 3 ] = n.x;
  5232. normals[ i3 + 4 ] = n.y;
  5233. normals[ i3 + 5 ] = n.z;
  5234. normals[ i3 + 6 ] = n.x;
  5235. normals[ i3 + 7 ] = n.y;
  5236. normals[ i3 + 8 ] = n.z;
  5237. }
  5238. if ( vertexColors === THREE.FaceColors ) {
  5239. var fc = face.color;
  5240. colors[ i3 ] = fc.r;
  5241. colors[ i3 + 1 ] = fc.g;
  5242. colors[ i3 + 2 ] = fc.b;
  5243. colors[ i3 + 3 ] = fc.r;
  5244. colors[ i3 + 4 ] = fc.g;
  5245. colors[ i3 + 5 ] = fc.b;
  5246. colors[ i3 + 6 ] = fc.r;
  5247. colors[ i3 + 7 ] = fc.g;
  5248. colors[ i3 + 8 ] = fc.b;
  5249. } else if ( vertexColors === THREE.VertexColors ) {
  5250. var vca = face.vertexColors[ 0 ];
  5251. var vcb = face.vertexColors[ 1 ];
  5252. var vcc = face.vertexColors[ 2 ];
  5253. colors[ i3 ] = vca.r;
  5254. colors[ i3 + 1 ] = vca.g;
  5255. colors[ i3 + 2 ] = vca.b;
  5256. colors[ i3 + 3 ] = vcb.r;
  5257. colors[ i3 + 4 ] = vcb.g;
  5258. colors[ i3 + 5 ] = vcb.b;
  5259. colors[ i3 + 6 ] = vcc.r;
  5260. colors[ i3 + 7 ] = vcc.g;
  5261. colors[ i3 + 8 ] = vcc.b;
  5262. }
  5263. if ( hasFaceVertexUv === true ) {
  5264. var uva = faceVertexUvs[ 0 ][ i ][ 0 ];
  5265. var uvb = faceVertexUvs[ 0 ][ i ][ 1 ];
  5266. var uvc = faceVertexUvs[ 0 ][ i ][ 2 ];
  5267. uvs[ i2 ] = uva.x;
  5268. uvs[ i2 + 1 ] = uva.y;
  5269. uvs[ i2 + 2 ] = uvb.x;
  5270. uvs[ i2 + 3 ] = uvb.y;
  5271. uvs[ i2 + 4 ] = uvc.x;
  5272. uvs[ i2 + 5 ] = uvc.y;
  5273. }
  5274. }
  5275. this.computeBoundingSphere()
  5276. return this;
  5277. },
  5278. computeBoundingBox: function () {
  5279. if ( this.boundingBox === null ) {
  5280. this.boundingBox = new THREE.Box3();
  5281. }
  5282. var positions = this.attributes[ 'position' ].array;
  5283. if ( positions ) {
  5284. var bb = this.boundingBox;
  5285. if ( positions.length >= 3 ) {
  5286. bb.min.x = bb.max.x = positions[ 0 ];
  5287. bb.min.y = bb.max.y = positions[ 1 ];
  5288. bb.min.z = bb.max.z = positions[ 2 ];
  5289. }
  5290. for ( var i = 3, il = positions.length; i < il; i += 3 ) {
  5291. var x = positions[ i ];
  5292. var y = positions[ i + 1 ];
  5293. var z = positions[ i + 2 ];
  5294. // bounding box
  5295. if ( x < bb.min.x ) {
  5296. bb.min.x = x;
  5297. } else if ( x > bb.max.x ) {
  5298. bb.max.x = x;
  5299. }
  5300. if ( y < bb.min.y ) {
  5301. bb.min.y = y;
  5302. } else if ( y > bb.max.y ) {
  5303. bb.max.y = y;
  5304. }
  5305. if ( z < bb.min.z ) {
  5306. bb.min.z = z;
  5307. } else if ( z > bb.max.z ) {
  5308. bb.max.z = z;
  5309. }
  5310. }
  5311. }
  5312. if ( positions === undefined || positions.length === 0 ) {
  5313. this.boundingBox.min.set( 0, 0, 0 );
  5314. this.boundingBox.max.set( 0, 0, 0 );
  5315. }
  5316. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  5317. console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.' );
  5318. }
  5319. },
  5320. computeBoundingSphere: function () {
  5321. var box = new THREE.Box3();
  5322. var vector = new THREE.Vector3();
  5323. return function () {
  5324. if ( this.boundingSphere === null ) {
  5325. this.boundingSphere = new THREE.Sphere();
  5326. }
  5327. var positions = this.attributes[ 'position' ].array;
  5328. if ( positions ) {
  5329. box.makeEmpty();
  5330. var center = this.boundingSphere.center;
  5331. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5332. vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5333. box.expandByPoint( vector );
  5334. }
  5335. box.center( center );
  5336. // hoping to find a boundingSphere with a radius smaller than the
  5337. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  5338. var maxRadiusSq = 0;
  5339. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5340. vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5341. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  5342. }
  5343. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  5344. if ( isNaN( this.boundingSphere.radius ) ) {
  5345. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.' );
  5346. }
  5347. }
  5348. }
  5349. }(),
  5350. computeFaceNormals: function () {
  5351. // backwards compatibility
  5352. },
  5353. computeVertexNormals: function () {
  5354. if ( this.attributes[ 'position' ] ) {
  5355. var i, il;
  5356. var j, jl;
  5357. var nVertexElements = this.attributes[ 'position' ].array.length;
  5358. if ( this.attributes[ 'normal' ] === undefined ) {
  5359. this.attributes[ 'normal' ] = {
  5360. itemSize: 3,
  5361. array: new Float32Array( nVertexElements )
  5362. };
  5363. } else {
  5364. // reset existing normals to zero
  5365. for ( i = 0, il = this.attributes[ 'normal' ].array.length; i < il; i ++ ) {
  5366. this.attributes[ 'normal' ].array[ i ] = 0;
  5367. }
  5368. }
  5369. var positions = this.attributes[ 'position' ].array;
  5370. var normals = this.attributes[ 'normal' ].array;
  5371. var vA, vB, vC, x, y, z,
  5372. pA = new THREE.Vector3(),
  5373. pB = new THREE.Vector3(),
  5374. pC = new THREE.Vector3(),
  5375. cb = new THREE.Vector3(),
  5376. ab = new THREE.Vector3();
  5377. // indexed elements
  5378. if ( this.attributes[ 'index' ] ) {
  5379. var indices = this.attributes[ 'index' ].array;
  5380. var offsets = ( this.offsets.length > 0 ? this.offsets : [ { start: 0, count: indices.length, index: 0 } ] );
  5381. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5382. var start = offsets[ j ].start;
  5383. var count = offsets[ j ].count;
  5384. var index = offsets[ j ].index;
  5385. for ( i = start, il = start + count; i < il; i += 3 ) {
  5386. vA = index + indices[ i ];
  5387. vB = index + indices[ i + 1 ];
  5388. vC = index + indices[ i + 2 ];
  5389. x = positions[ vA * 3 ];
  5390. y = positions[ vA * 3 + 1 ];
  5391. z = positions[ vA * 3 + 2 ];
  5392. pA.set( x, y, z );
  5393. x = positions[ vB * 3 ];
  5394. y = positions[ vB * 3 + 1 ];
  5395. z = positions[ vB * 3 + 2 ];
  5396. pB.set( x, y, z );
  5397. x = positions[ vC * 3 ];
  5398. y = positions[ vC * 3 + 1 ];
  5399. z = positions[ vC * 3 + 2 ];
  5400. pC.set( x, y, z );
  5401. cb.subVectors( pC, pB );
  5402. ab.subVectors( pA, pB );
  5403. cb.cross( ab );
  5404. normals[ vA * 3 ] += cb.x;
  5405. normals[ vA * 3 + 1 ] += cb.y;
  5406. normals[ vA * 3 + 2 ] += cb.z;
  5407. normals[ vB * 3 ] += cb.x;
  5408. normals[ vB * 3 + 1 ] += cb.y;
  5409. normals[ vB * 3 + 2 ] += cb.z;
  5410. normals[ vC * 3 ] += cb.x;
  5411. normals[ vC * 3 + 1 ] += cb.y;
  5412. normals[ vC * 3 + 2 ] += cb.z;
  5413. }
  5414. }
  5415. // non-indexed elements (unconnected triangle soup)
  5416. } else {
  5417. for ( i = 0, il = positions.length; i < il; i += 9 ) {
  5418. x = positions[ i ];
  5419. y = positions[ i + 1 ];
  5420. z = positions[ i + 2 ];
  5421. pA.set( x, y, z );
  5422. x = positions[ i + 3 ];
  5423. y = positions[ i + 4 ];
  5424. z = positions[ i + 5 ];
  5425. pB.set( x, y, z );
  5426. x = positions[ i + 6 ];
  5427. y = positions[ i + 7 ];
  5428. z = positions[ i + 8 ];
  5429. pC.set( x, y, z );
  5430. cb.subVectors( pC, pB );
  5431. ab.subVectors( pA, pB );
  5432. cb.cross( ab );
  5433. normals[ i ] = cb.x;
  5434. normals[ i + 1 ] = cb.y;
  5435. normals[ i + 2 ] = cb.z;
  5436. normals[ i + 3 ] = cb.x;
  5437. normals[ i + 4 ] = cb.y;
  5438. normals[ i + 5 ] = cb.z;
  5439. normals[ i + 6 ] = cb.x;
  5440. normals[ i + 7 ] = cb.y;
  5441. normals[ i + 8 ] = cb.z;
  5442. }
  5443. }
  5444. this.normalizeNormals();
  5445. this.normalsNeedUpdate = true;
  5446. }
  5447. },
  5448. computeTangents: function () {
  5449. // based on http://www.terathon.com/code/tangent.html
  5450. // (per vertex tangents)
  5451. if ( this.attributes[ 'index' ] === undefined ||
  5452. this.attributes[ 'position' ] === undefined ||
  5453. this.attributes[ 'normal' ] === undefined ||
  5454. this.attributes[ 'uv' ] === undefined ) {
  5455. console.warn( 'Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()' );
  5456. return;
  5457. }
  5458. var indices = this.attributes[ 'index' ].array;
  5459. var positions = this.attributes[ 'position' ].array;
  5460. var normals = this.attributes[ 'normal' ].array;
  5461. var uvs = this.attributes[ 'uv' ].array;
  5462. var nVertices = positions.length / 3;
  5463. if ( this.attributes[ 'tangent' ] === undefined ) {
  5464. var nTangentElements = 4 * nVertices;
  5465. this.attributes[ 'tangent' ] = {
  5466. itemSize: 4,
  5467. array: new Float32Array( nTangentElements )
  5468. };
  5469. }
  5470. var tangents = this.attributes[ 'tangent' ].array;
  5471. var tan1 = [], tan2 = [];
  5472. for ( var k = 0; k < nVertices; k ++ ) {
  5473. tan1[ k ] = new THREE.Vector3();
  5474. tan2[ k ] = new THREE.Vector3();
  5475. }
  5476. var xA, yA, zA,
  5477. xB, yB, zB,
  5478. xC, yC, zC,
  5479. uA, vA,
  5480. uB, vB,
  5481. uC, vC,
  5482. x1, x2, y1, y2, z1, z2,
  5483. s1, s2, t1, t2, r;
  5484. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  5485. function handleTriangle( a, b, c ) {
  5486. xA = positions[ a * 3 ];
  5487. yA = positions[ a * 3 + 1 ];
  5488. zA = positions[ a * 3 + 2 ];
  5489. xB = positions[ b * 3 ];
  5490. yB = positions[ b * 3 + 1 ];
  5491. zB = positions[ b * 3 + 2 ];
  5492. xC = positions[ c * 3 ];
  5493. yC = positions[ c * 3 + 1 ];
  5494. zC = positions[ c * 3 + 2 ];
  5495. uA = uvs[ a * 2 ];
  5496. vA = uvs[ a * 2 + 1 ];
  5497. uB = uvs[ b * 2 ];
  5498. vB = uvs[ b * 2 + 1 ];
  5499. uC = uvs[ c * 2 ];
  5500. vC = uvs[ c * 2 + 1 ];
  5501. x1 = xB - xA;
  5502. x2 = xC - xA;
  5503. y1 = yB - yA;
  5504. y2 = yC - yA;
  5505. z1 = zB - zA;
  5506. z2 = zC - zA;
  5507. s1 = uB - uA;
  5508. s2 = uC - uA;
  5509. t1 = vB - vA;
  5510. t2 = vC - vA;
  5511. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5512. sdir.set(
  5513. ( t2 * x1 - t1 * x2 ) * r,
  5514. ( t2 * y1 - t1 * y2 ) * r,
  5515. ( t2 * z1 - t1 * z2 ) * r
  5516. );
  5517. tdir.set(
  5518. ( s1 * x2 - s2 * x1 ) * r,
  5519. ( s1 * y2 - s2 * y1 ) * r,
  5520. ( s1 * z2 - s2 * z1 ) * r
  5521. );
  5522. tan1[ a ].add( sdir );
  5523. tan1[ b ].add( sdir );
  5524. tan1[ c ].add( sdir );
  5525. tan2[ a ].add( tdir );
  5526. tan2[ b ].add( tdir );
  5527. tan2[ c ].add( tdir );
  5528. }
  5529. var i, il;
  5530. var j, jl;
  5531. var iA, iB, iC;
  5532. var offsets = this.offsets;
  5533. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5534. var start = offsets[ j ].start;
  5535. var count = offsets[ j ].count;
  5536. var index = offsets[ j ].index;
  5537. for ( i = start, il = start + count; i < il; i += 3 ) {
  5538. iA = index + indices[ i ];
  5539. iB = index + indices[ i + 1 ];
  5540. iC = index + indices[ i + 2 ];
  5541. handleTriangle( iA, iB, iC );
  5542. }
  5543. }
  5544. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  5545. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  5546. var w, t, test;
  5547. function handleVertex( v ) {
  5548. n.x = normals[ v * 3 ];
  5549. n.y = normals[ v * 3 + 1 ];
  5550. n.z = normals[ v * 3 + 2 ];
  5551. n2.copy( n );
  5552. t = tan1[ v ];
  5553. // Gram-Schmidt orthogonalize
  5554. tmp.copy( t );
  5555. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5556. // Calculate handedness
  5557. tmp2.crossVectors( n2, t );
  5558. test = tmp2.dot( tan2[ v ] );
  5559. w = ( test < 0.0 ) ? - 1.0 : 1.0;
  5560. tangents[ v * 4 ] = tmp.x;
  5561. tangents[ v * 4 + 1 ] = tmp.y;
  5562. tangents[ v * 4 + 2 ] = tmp.z;
  5563. tangents[ v * 4 + 3 ] = w;
  5564. }
  5565. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5566. var start = offsets[ j ].start;
  5567. var count = offsets[ j ].count;
  5568. var index = offsets[ j ].index;
  5569. for ( i = start, il = start + count; i < il; i += 3 ) {
  5570. iA = index + indices[ i ];
  5571. iB = index + indices[ i + 1 ];
  5572. iC = index + indices[ i + 2 ];
  5573. handleVertex( iA );
  5574. handleVertex( iB );
  5575. handleVertex( iC );
  5576. }
  5577. }
  5578. },
  5579. /*
  5580. computeOffsets
  5581. Compute the draw offset for large models by chunking the index buffer into chunks of 65k addressable vertices.
  5582. This method will effectively rewrite the index buffer and remap all attributes to match the new indices.
  5583. WARNING: This method will also expand the vertex count to prevent sprawled triangles across draw offsets.
  5584. indexBufferSize - Defaults to 65535, but allows for larger or smaller chunks.
  5585. */
  5586. computeOffsets: function ( indexBufferSize ) {
  5587. var size = indexBufferSize;
  5588. if ( indexBufferSize === undefined )
  5589. size = 65535; //WebGL limits type of index buffer values to 16-bit.
  5590. var s = Date.now();
  5591. var indices = this.attributes[ 'index' ].array;
  5592. var vertices = this.attributes[ 'position' ].array;
  5593. var verticesCount = ( vertices.length / 3 );
  5594. var facesCount = ( indices.length / 3 );
  5595. /*
  5596. console.log("Computing buffers in offsets of "+size+" -> indices:"+indices.length+" vertices:"+vertices.length);
  5597. console.log("Faces to process: "+(indices.length/3));
  5598. console.log("Reordering "+verticesCount+" vertices.");
  5599. */
  5600. var sortedIndices = new Uint16Array( indices.length ); //16-bit buffers
  5601. var indexPtr = 0;
  5602. var vertexPtr = 0;
  5603. var offsets = [ { start:0, count:0, index:0 } ];
  5604. var offset = offsets[ 0 ];
  5605. var duplicatedVertices = 0;
  5606. var newVerticeMaps = 0;
  5607. var faceVertices = new Int32Array( 6 );
  5608. var vertexMap = new Int32Array( vertices.length );
  5609. var revVertexMap = new Int32Array( vertices.length );
  5610. for ( var j = 0; j < vertices.length; j ++ ) { vertexMap[ j ] = - 1; revVertexMap[ j ] = - 1; }
  5611. /*
  5612. Traverse every face and reorder vertices in the proper offsets of 65k.
  5613. We can have more than 65k entries in the index buffer per offset, but only reference 65k values.
  5614. */
  5615. for ( var findex = 0; findex < facesCount; findex ++ ) {
  5616. newVerticeMaps = 0;
  5617. for ( var vo = 0; vo < 3; vo ++ ) {
  5618. var vid = indices[ findex * 3 + vo ];
  5619. if ( vertexMap[ vid ] == - 1 ) {
  5620. //Unmapped vertice
  5621. faceVertices[ vo * 2 ] = vid;
  5622. faceVertices[ vo * 2 + 1 ] = - 1;
  5623. newVerticeMaps ++;
  5624. } else if ( vertexMap[ vid ] < offset.index ) {
  5625. //Reused vertices from previous block (duplicate)
  5626. faceVertices[ vo * 2 ] = vid;
  5627. faceVertices[ vo * 2 + 1 ] = - 1;
  5628. duplicatedVertices ++;
  5629. } else {
  5630. //Reused vertice in the current block
  5631. faceVertices[ vo * 2 ] = vid;
  5632. faceVertices[ vo * 2 + 1 ] = vertexMap[ vid ];
  5633. }
  5634. }
  5635. var faceMax = vertexPtr + newVerticeMaps;
  5636. if ( faceMax > ( offset.index + size ) ) {
  5637. var new_offset = { start:indexPtr, count:0, index:vertexPtr };
  5638. offsets.push( new_offset );
  5639. offset = new_offset;
  5640. //Re-evaluate reused vertices in light of new offset.
  5641. for ( var v = 0; v < 6; v += 2 ) {
  5642. var new_vid = faceVertices[ v + 1 ];
  5643. if ( new_vid > - 1 && new_vid < offset.index )
  5644. faceVertices[ v + 1 ] = - 1;
  5645. }
  5646. }
  5647. //Reindex the face.
  5648. for ( var v = 0; v < 6; v += 2 ) {
  5649. var vid = faceVertices[ v ];
  5650. var new_vid = faceVertices[ v + 1 ];
  5651. if ( new_vid === - 1 )
  5652. new_vid = vertexPtr ++;
  5653. vertexMap[ vid ] = new_vid;
  5654. revVertexMap[ new_vid ] = vid;
  5655. sortedIndices[ indexPtr ++ ] = new_vid - offset.index; //XXX overflows at 16bit
  5656. offset.count ++;
  5657. }
  5658. }
  5659. /* Move all attribute values to map to the new computed indices , also expand the vertice stack to match our new vertexPtr. */
  5660. this.reorderBuffers( sortedIndices, revVertexMap, vertexPtr );
  5661. this.offsets = offsets;
  5662. /*
  5663. var orderTime = Date.now();
  5664. console.log("Reorder time: "+(orderTime-s)+"ms");
  5665. console.log("Duplicated "+duplicatedVertices+" vertices.");
  5666. console.log("Compute Buffers time: "+(Date.now()-s)+"ms");
  5667. console.log("Draw offsets: "+offsets.length);
  5668. */
  5669. return offsets;
  5670. },
  5671. merge: function () {
  5672. console.log( 'BufferGeometry.merge(): TODO' );
  5673. },
  5674. normalizeNormals: function () {
  5675. var normals = this.attributes[ 'normal' ].array;
  5676. var x, y, z, n;
  5677. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  5678. x = normals[ i ];
  5679. y = normals[ i + 1 ];
  5680. z = normals[ i + 2 ];
  5681. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  5682. normals[ i ] *= n;
  5683. normals[ i + 1 ] *= n;
  5684. normals[ i + 2 ] *= n;
  5685. }
  5686. },
  5687. /*
  5688. reoderBuffers:
  5689. Reorder attributes based on a new indexBuffer and indexMap.
  5690. indexBuffer - Uint16Array of the new ordered indices.
  5691. indexMap - Int32Array where the position is the new vertex ID and the value the old vertex ID for each vertex.
  5692. vertexCount - Amount of total vertices considered in this reordering (in case you want to grow the vertice stack).
  5693. */
  5694. reorderBuffers: function ( indexBuffer, indexMap, vertexCount ) {
  5695. /* Create a copy of all attributes for reordering. */
  5696. var sortedAttributes = {};
  5697. var types = [ Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array ];
  5698. for ( var attr in this.attributes ) {
  5699. if ( attr == 'index' )
  5700. continue;
  5701. var sourceArray = this.attributes[ attr ].array;
  5702. for ( var i = 0, il = types.length; i < il; i ++ ) {
  5703. var type = types[ i ];
  5704. if ( sourceArray instanceof type ) {
  5705. sortedAttributes[ attr ] = new type( this.attributes[ attr ].itemSize * vertexCount );
  5706. break;
  5707. }
  5708. }
  5709. }
  5710. /* Move attribute positions based on the new index map */
  5711. for ( var new_vid = 0; new_vid < vertexCount; new_vid ++ ) {
  5712. var vid = indexMap[ new_vid ];
  5713. for ( var attr in this.attributes ) {
  5714. if ( attr == 'index' )
  5715. continue;
  5716. var attrArray = this.attributes[ attr ].array;
  5717. var attrSize = this.attributes[ attr ].itemSize;
  5718. var sortedAttr = sortedAttributes[ attr ];
  5719. for ( var k = 0; k < attrSize; k ++ )
  5720. sortedAttr[ new_vid * attrSize + k ] = attrArray[ vid * attrSize + k ];
  5721. }
  5722. }
  5723. /* Carry the new sorted buffers locally */
  5724. this.attributes[ 'index' ].array = indexBuffer;
  5725. for ( var attr in this.attributes ) {
  5726. if ( attr == 'index' )
  5727. continue;
  5728. this.attributes[ attr ].array = sortedAttributes[ attr ];
  5729. this.attributes[ attr ].numItems = this.attributes[ attr ].itemSize * vertexCount;
  5730. }
  5731. },
  5732. clone: function () {
  5733. var geometry = new THREE.BufferGeometry();
  5734. var types = [ Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array ];
  5735. for ( var attr in this.attributes ) {
  5736. var sourceAttr = this.attributes[ attr ];
  5737. var sourceArray = sourceAttr.array;
  5738. var attribute = {
  5739. itemSize: sourceAttr.itemSize,
  5740. array: null
  5741. };
  5742. for ( var i = 0, il = types.length; i < il; i ++ ) {
  5743. var type = types[ i ];
  5744. if ( sourceArray instanceof type ) {
  5745. attribute.array = new type( sourceArray );
  5746. break;
  5747. }
  5748. }
  5749. geometry.attributes[ attr ] = attribute;
  5750. }
  5751. for ( var i = 0, il = this.offsets.length; i < il; i ++ ) {
  5752. var offset = this.offsets[ i ];
  5753. geometry.offsets.push( {
  5754. start: offset.start,
  5755. index: offset.index,
  5756. count: offset.count
  5757. } );
  5758. }
  5759. return geometry;
  5760. },
  5761. dispose: function () {
  5762. this.dispatchEvent( { type: 'dispose' } );
  5763. }
  5764. };
  5765. THREE.EventDispatcher.prototype.apply( THREE.BufferGeometry.prototype );
  5766. // File:src/core/Geometry.js
  5767. /**
  5768. * @author mrdoob / http://mrdoob.com/
  5769. * @author kile / http://kile.stravaganza.org/
  5770. * @author alteredq / http://alteredqualia.com/
  5771. * @author mikael emtinger / http://gomo.se/
  5772. * @author zz85 / http://www.lab4games.net/zz85/blog
  5773. * @author bhouston / http://exocortex.com
  5774. */
  5775. THREE.Geometry = function () {
  5776. this.id = THREE.GeometryIdCount ++;
  5777. this.uuid = THREE.Math.generateUUID();
  5778. this.name = '';
  5779. this.vertices = [];
  5780. this.colors = []; // one-to-one vertex colors, used in Points and Line
  5781. this.faces = [];
  5782. this.faceVertexUvs = [ [] ];
  5783. this.morphTargets = [];
  5784. this.morphColors = [];
  5785. this.morphNormals = [];
  5786. this.skinWeights = [];
  5787. this.skinIndices = [];
  5788. this.lineDistances = [];
  5789. this.boundingBox = null;
  5790. this.boundingSphere = null;
  5791. this.hasTangents = false;
  5792. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  5793. // update flags
  5794. this.verticesNeedUpdate = false;
  5795. this.elementsNeedUpdate = false;
  5796. this.uvsNeedUpdate = false;
  5797. this.normalsNeedUpdate = false;
  5798. this.tangentsNeedUpdate = false;
  5799. this.colorsNeedUpdate = false;
  5800. this.lineDistancesNeedUpdate = false;
  5801. this.buffersNeedUpdate = false;
  5802. this.groupsNeedUpdate = false;
  5803. };
  5804. THREE.Geometry.prototype = {
  5805. constructor: THREE.Geometry,
  5806. applyMatrix: function ( matrix ) {
  5807. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5808. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  5809. var vertex = this.vertices[ i ];
  5810. vertex.applyMatrix4( matrix );
  5811. }
  5812. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  5813. var face = this.faces[ i ];
  5814. face.normal.applyMatrix3( normalMatrix ).normalize();
  5815. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  5816. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  5817. }
  5818. }
  5819. if ( this.boundingBox instanceof THREE.Box3 ) {
  5820. this.computeBoundingBox();
  5821. }
  5822. if ( this.boundingSphere instanceof THREE.Sphere ) {
  5823. this.computeBoundingSphere();
  5824. }
  5825. },
  5826. center: function () {
  5827. this.computeBoundingBox();
  5828. var offset = new THREE.Vector3();
  5829. offset.addVectors( this.boundingBox.min, this.boundingBox.max );
  5830. offset.multiplyScalar( - 0.5 );
  5831. this.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  5832. this.computeBoundingBox();
  5833. return offset;
  5834. },
  5835. computeFaceNormals: function () {
  5836. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  5837. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5838. var face = this.faces[ f ];
  5839. var vA = this.vertices[ face.a ];
  5840. var vB = this.vertices[ face.b ];
  5841. var vC = this.vertices[ face.c ];
  5842. cb.subVectors( vC, vB );
  5843. ab.subVectors( vA, vB );
  5844. cb.cross( ab );
  5845. cb.normalize();
  5846. face.normal.copy( cb );
  5847. }
  5848. },
  5849. computeVertexNormals: function ( areaWeighted ) {
  5850. var v, vl, f, fl, face, vertices;
  5851. vertices = new Array( this.vertices.length );
  5852. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5853. vertices[ v ] = new THREE.Vector3();
  5854. }
  5855. if ( areaWeighted ) {
  5856. // vertex normals weighted by triangle areas
  5857. // http://www.iquilezles.org/www/articles/normals/normals.htm
  5858. var vA, vB, vC, vD;
  5859. var cb = new THREE.Vector3(), ab = new THREE.Vector3(),
  5860. db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3();
  5861. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5862. face = this.faces[ f ];
  5863. vA = this.vertices[ face.a ];
  5864. vB = this.vertices[ face.b ];
  5865. vC = this.vertices[ face.c ];
  5866. cb.subVectors( vC, vB );
  5867. ab.subVectors( vA, vB );
  5868. cb.cross( ab );
  5869. vertices[ face.a ].add( cb );
  5870. vertices[ face.b ].add( cb );
  5871. vertices[ face.c ].add( cb );
  5872. }
  5873. } else {
  5874. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5875. face = this.faces[ f ];
  5876. vertices[ face.a ].add( face.normal );
  5877. vertices[ face.b ].add( face.normal );
  5878. vertices[ face.c ].add( face.normal );
  5879. }
  5880. }
  5881. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5882. vertices[ v ].normalize();
  5883. }
  5884. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5885. face = this.faces[ f ];
  5886. face.vertexNormals[ 0 ] = vertices[ face.a ].clone();
  5887. face.vertexNormals[ 1 ] = vertices[ face.b ].clone();
  5888. face.vertexNormals[ 2 ] = vertices[ face.c ].clone();
  5889. }
  5890. },
  5891. computeMorphNormals: function () {
  5892. var i, il, f, fl, face;
  5893. // save original normals
  5894. // - create temp variables on first access
  5895. // otherwise just copy (for faster repeated calls)
  5896. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5897. face = this.faces[ f ];
  5898. if ( ! face.__originalFaceNormal ) {
  5899. face.__originalFaceNormal = face.normal.clone();
  5900. } else {
  5901. face.__originalFaceNormal.copy( face.normal );
  5902. }
  5903. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  5904. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  5905. if ( ! face.__originalVertexNormals[ i ] ) {
  5906. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  5907. } else {
  5908. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  5909. }
  5910. }
  5911. }
  5912. // use temp geometry to compute face and vertex normals for each morph
  5913. var tmpGeo = new THREE.Geometry();
  5914. tmpGeo.faces = this.faces;
  5915. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  5916. // create on first access
  5917. if ( ! this.morphNormals[ i ] ) {
  5918. this.morphNormals[ i ] = {};
  5919. this.morphNormals[ i ].faceNormals = [];
  5920. this.morphNormals[ i ].vertexNormals = [];
  5921. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  5922. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  5923. var faceNormal, vertexNormals;
  5924. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5925. faceNormal = new THREE.Vector3();
  5926. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  5927. dstNormalsFace.push( faceNormal );
  5928. dstNormalsVertex.push( vertexNormals );
  5929. }
  5930. }
  5931. var morphNormals = this.morphNormals[ i ];
  5932. // set vertices to morph target
  5933. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  5934. // compute morph normals
  5935. tmpGeo.computeFaceNormals();
  5936. tmpGeo.computeVertexNormals();
  5937. // store morph normals
  5938. var faceNormal, vertexNormals;
  5939. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5940. face = this.faces[ f ];
  5941. faceNormal = morphNormals.faceNormals[ f ];
  5942. vertexNormals = morphNormals.vertexNormals[ f ];
  5943. faceNormal.copy( face.normal );
  5944. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  5945. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  5946. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  5947. }
  5948. }
  5949. // restore original normals
  5950. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5951. face = this.faces[ f ];
  5952. face.normal = face.__originalFaceNormal;
  5953. face.vertexNormals = face.__originalVertexNormals;
  5954. }
  5955. },
  5956. computeTangents: function () {
  5957. // based on http://www.terathon.com/code/tangent.html
  5958. // tangents go to vertices
  5959. var f, fl, v, vl, i, il, vertexIndex,
  5960. face, uv, vA, vB, vC, uvA, uvB, uvC,
  5961. x1, x2, y1, y2, z1, z2,
  5962. s1, s2, t1, t2, r, t, test,
  5963. tan1 = [], tan2 = [],
  5964. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  5965. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  5966. n = new THREE.Vector3(), w;
  5967. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5968. tan1[ v ] = new THREE.Vector3();
  5969. tan2[ v ] = new THREE.Vector3();
  5970. }
  5971. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  5972. vA = context.vertices[ a ];
  5973. vB = context.vertices[ b ];
  5974. vC = context.vertices[ c ];
  5975. uvA = uv[ ua ];
  5976. uvB = uv[ ub ];
  5977. uvC = uv[ uc ];
  5978. x1 = vB.x - vA.x;
  5979. x2 = vC.x - vA.x;
  5980. y1 = vB.y - vA.y;
  5981. y2 = vC.y - vA.y;
  5982. z1 = vB.z - vA.z;
  5983. z2 = vC.z - vA.z;
  5984. s1 = uvB.x - uvA.x;
  5985. s2 = uvC.x - uvA.x;
  5986. t1 = uvB.y - uvA.y;
  5987. t2 = uvC.y - uvA.y;
  5988. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5989. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  5990. ( t2 * y1 - t1 * y2 ) * r,
  5991. ( t2 * z1 - t1 * z2 ) * r );
  5992. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  5993. ( s1 * y2 - s2 * y1 ) * r,
  5994. ( s1 * z2 - s2 * z1 ) * r );
  5995. tan1[ a ].add( sdir );
  5996. tan1[ b ].add( sdir );
  5997. tan1[ c ].add( sdir );
  5998. tan2[ a ].add( tdir );
  5999. tan2[ b ].add( tdir );
  6000. tan2[ c ].add( tdir );
  6001. }
  6002. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6003. face = this.faces[ f ];
  6004. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  6005. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  6006. }
  6007. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  6008. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6009. face = this.faces[ f ];
  6010. for ( i = 0; i < Math.min( face.vertexNormals.length, 3 ); i ++ ) {
  6011. n.copy( face.vertexNormals[ i ] );
  6012. vertexIndex = face[ faceIndex[ i ] ];
  6013. t = tan1[ vertexIndex ];
  6014. // Gram-Schmidt orthogonalize
  6015. tmp.copy( t );
  6016. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6017. // Calculate handedness
  6018. tmp2.crossVectors( face.vertexNormals[ i ], t );
  6019. test = tmp2.dot( tan2[ vertexIndex ] );
  6020. w = ( test < 0.0 ) ? - 1.0 : 1.0;
  6021. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  6022. }
  6023. }
  6024. this.hasTangents = true;
  6025. },
  6026. computeLineDistances: function () {
  6027. var d = 0;
  6028. var vertices = this.vertices;
  6029. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  6030. if ( i > 0 ) {
  6031. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  6032. }
  6033. this.lineDistances[ i ] = d;
  6034. }
  6035. },
  6036. computeBoundingBox: function () {
  6037. if ( this.boundingBox === null ) {
  6038. this.boundingBox = new THREE.Box3();
  6039. }
  6040. this.boundingBox.setFromPoints( this.vertices );
  6041. },
  6042. computeBoundingSphere: function () {
  6043. if ( this.boundingSphere === null ) {
  6044. this.boundingSphere = new THREE.Sphere();
  6045. }
  6046. this.boundingSphere.setFromPoints( this.vertices );
  6047. },
  6048. merge: function ( geometry, matrix, materialIndexOffset ) {
  6049. if ( geometry instanceof THREE.Geometry === false ) {
  6050. console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  6051. return;
  6052. }
  6053. var normalMatrix,
  6054. vertexOffset = this.vertices.length,
  6055. uvPosition = this.faceVertexUvs[ 0 ].length,
  6056. vertices1 = this.vertices,
  6057. vertices2 = geometry.vertices,
  6058. faces1 = this.faces,
  6059. faces2 = geometry.faces,
  6060. uvs1 = this.faceVertexUvs[ 0 ],
  6061. uvs2 = geometry.faceVertexUvs[ 0 ];
  6062. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  6063. if ( matrix !== undefined ) {
  6064. normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  6065. }
  6066. // vertices
  6067. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  6068. var vertex = vertices2[ i ];
  6069. var vertexCopy = vertex.clone();
  6070. if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
  6071. vertices1.push( vertexCopy );
  6072. }
  6073. // faces
  6074. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  6075. var face = faces2[ i ], faceCopy, normal, color,
  6076. faceVertexNormals = face.vertexNormals,
  6077. faceVertexColors = face.vertexColors;
  6078. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  6079. faceCopy.normal.copy( face.normal );
  6080. if ( normalMatrix !== undefined ) {
  6081. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  6082. }
  6083. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  6084. normal = faceVertexNormals[ j ].clone();
  6085. if ( normalMatrix !== undefined ) {
  6086. normal.applyMatrix3( normalMatrix ).normalize();
  6087. }
  6088. faceCopy.vertexNormals.push( normal );
  6089. }
  6090. faceCopy.color.copy( face.color );
  6091. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  6092. color = faceVertexColors[ j ];
  6093. faceCopy.vertexColors.push( color.clone() );
  6094. }
  6095. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  6096. faces1.push( faceCopy );
  6097. }
  6098. // uvs
  6099. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  6100. var uv = uvs2[ i ], uvCopy = [];
  6101. if ( uv === undefined ) {
  6102. continue;
  6103. }
  6104. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  6105. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  6106. }
  6107. uvs1.push( uvCopy );
  6108. }
  6109. },
  6110. /*
  6111. * Checks for duplicate vertices with hashmap.
  6112. * Duplicated vertices are removed
  6113. * and faces' vertices are updated.
  6114. */
  6115. mergeVertices: function () {
  6116. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  6117. var unique = [], changes = [];
  6118. var v, key;
  6119. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  6120. var precision = Math.pow( 10, precisionPoints );
  6121. var i,il, face;
  6122. var indices, k, j, jl, u;
  6123. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  6124. v = this.vertices[ i ];
  6125. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  6126. if ( verticesMap[ key ] === undefined ) {
  6127. verticesMap[ key ] = i;
  6128. unique.push( this.vertices[ i ] );
  6129. changes[ i ] = unique.length - 1;
  6130. } else {
  6131. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  6132. changes[ i ] = changes[ verticesMap[ key ] ];
  6133. }
  6134. };
  6135. // if faces are completely degenerate after merging vertices, we
  6136. // have to remove them from the geometry.
  6137. var faceIndicesToRemove = [];
  6138. for ( i = 0, il = this.faces.length; i < il; i ++ ) {
  6139. face = this.faces[ i ];
  6140. face.a = changes[ face.a ];
  6141. face.b = changes[ face.b ];
  6142. face.c = changes[ face.c ];
  6143. indices = [ face.a, face.b, face.c ];
  6144. var dupIndex = - 1;
  6145. // if any duplicate vertices are found in a Face3
  6146. // we have to remove the face as nothing can be saved
  6147. for ( var n = 0; n < 3; n ++ ) {
  6148. if ( indices[ n ] == indices[ ( n + 1 ) % 3 ] ) {
  6149. dupIndex = n;
  6150. faceIndicesToRemove.push( i );
  6151. break;
  6152. }
  6153. }
  6154. }
  6155. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  6156. var idx = faceIndicesToRemove[ i ];
  6157. this.faces.splice( idx, 1 );
  6158. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  6159. this.faceVertexUvs[ j ].splice( idx, 1 );
  6160. }
  6161. }
  6162. // Use unique set of vertices
  6163. var diff = this.vertices.length - unique.length;
  6164. this.vertices = unique;
  6165. return diff;
  6166. },
  6167. // Geometry splitting
  6168. makeGroups: ( function () {
  6169. var geometryGroupCounter = 0;
  6170. return function ( usesFaceMaterial, maxVerticesInGroup ) {
  6171. var f, fl, face, materialIndex,
  6172. groupHash, hash_map = {},geometryGroup;
  6173. var numMorphTargets = this.morphTargets.length;
  6174. var numMorphNormals = this.morphNormals.length;
  6175. this.geometryGroups = {};
  6176. this.geometryGroupsList = [];
  6177. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6178. face = this.faces[ f ];
  6179. materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  6180. if ( ! ( materialIndex in hash_map ) ) {
  6181. hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
  6182. }
  6183. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  6184. if ( ! ( groupHash in this.geometryGroups ) ) {
  6185. geometryGroup = { 'id': geometryGroupCounter++, 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  6186. this.geometryGroups[ groupHash ] = geometryGroup;
  6187. this.geometryGroupsList.push(geometryGroup);
  6188. }
  6189. if ( this.geometryGroups[ groupHash ].vertices + 3 > maxVerticesInGroup ) {
  6190. hash_map[ materialIndex ].counter += 1;
  6191. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  6192. if ( ! ( groupHash in this.geometryGroups ) ) {
  6193. geometryGroup = { 'id': geometryGroupCounter++, 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  6194. this.geometryGroups[ groupHash ] = geometryGroup;
  6195. this.geometryGroupsList.push(geometryGroup);
  6196. }
  6197. }
  6198. this.geometryGroups[ groupHash ].faces3.push( f );
  6199. this.geometryGroups[ groupHash ].vertices += 3;
  6200. }
  6201. };
  6202. } )(),
  6203. clone: function () {
  6204. var geometry = new THREE.Geometry();
  6205. var vertices = this.vertices;
  6206. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  6207. geometry.vertices.push( vertices[ i ].clone() );
  6208. }
  6209. var faces = this.faces;
  6210. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  6211. geometry.faces.push( faces[ i ].clone() );
  6212. }
  6213. var uvs = this.faceVertexUvs[ 0 ];
  6214. for ( var i = 0, il = uvs.length; i < il; i ++ ) {
  6215. var uv = uvs[ i ], uvCopy = [];
  6216. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  6217. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  6218. }
  6219. geometry.faceVertexUvs[ 0 ].push( uvCopy );
  6220. }
  6221. return geometry;
  6222. },
  6223. dispose: function () {
  6224. this.dispatchEvent( { type: 'dispose' } );
  6225. }
  6226. };
  6227. THREE.EventDispatcher.prototype.apply( THREE.Geometry.prototype );
  6228. THREE.GeometryIdCount = 0;
  6229. // File:src/cameras/Camera.js
  6230. /**
  6231. * @author mrdoob / http://mrdoob.com/
  6232. * @author mikael emtinger / http://gomo.se/
  6233. * @author WestLangley / http://github.com/WestLangley
  6234. */
  6235. THREE.Camera = function () {
  6236. THREE.Object3D.call( this );
  6237. this.matrixWorldInverse = new THREE.Matrix4();
  6238. this.projectionMatrix = new THREE.Matrix4();
  6239. };
  6240. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  6241. THREE.Camera.prototype.lookAt = function () {
  6242. // This routine does not support cameras with rotated and/or translated parent(s)
  6243. var m1 = new THREE.Matrix4();
  6244. return function ( vector ) {
  6245. m1.lookAt( this.position, vector, this.up );
  6246. this.quaternion.setFromRotationMatrix( m1 );
  6247. };
  6248. }();
  6249. THREE.Camera.prototype.clone = function ( camera ) {
  6250. if ( camera === undefined ) camera = new THREE.Camera();
  6251. THREE.Object3D.prototype.clone.call( this, camera );
  6252. camera.matrixWorldInverse.copy( this.matrixWorldInverse );
  6253. camera.projectionMatrix.copy( this.projectionMatrix );
  6254. return camera;
  6255. };
  6256. // File:src/cameras/CubeCamera.js
  6257. /**
  6258. * Camera for rendering cube maps
  6259. * - renders scene into axis-aligned cube
  6260. *
  6261. * @author alteredq / http://alteredqualia.com/
  6262. */
  6263. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  6264. THREE.Object3D.call( this );
  6265. var fov = 90, aspect = 1;
  6266. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  6267. cameraPX.up.set( 0, - 1, 0 );
  6268. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  6269. this.add( cameraPX );
  6270. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  6271. cameraNX.up.set( 0, - 1, 0 );
  6272. cameraNX.lookAt( new THREE.Vector3( - 1, 0, 0 ) );
  6273. this.add( cameraNX );
  6274. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  6275. cameraPY.up.set( 0, 0, 1 );
  6276. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  6277. this.add( cameraPY );
  6278. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  6279. cameraNY.up.set( 0, 0, - 1 );
  6280. cameraNY.lookAt( new THREE.Vector3( 0, - 1, 0 ) );
  6281. this.add( cameraNY );
  6282. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  6283. cameraPZ.up.set( 0, - 1, 0 );
  6284. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  6285. this.add( cameraPZ );
  6286. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  6287. cameraNZ.up.set( 0, - 1, 0 );
  6288. cameraNZ.lookAt( new THREE.Vector3( 0, 0, - 1 ) );
  6289. this.add( cameraNZ );
  6290. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  6291. this.updateCubeMap = function ( renderer, scene ) {
  6292. var renderTarget = this.renderTarget;
  6293. var generateMipmaps = renderTarget.generateMipmaps;
  6294. renderTarget.generateMipmaps = false;
  6295. renderTarget.activeCubeFace = 0;
  6296. renderer.render( scene, cameraPX, renderTarget );
  6297. renderTarget.activeCubeFace = 1;
  6298. renderer.render( scene, cameraNX, renderTarget );
  6299. renderTarget.activeCubeFace = 2;
  6300. renderer.render( scene, cameraPY, renderTarget );
  6301. renderTarget.activeCubeFace = 3;
  6302. renderer.render( scene, cameraNY, renderTarget );
  6303. renderTarget.activeCubeFace = 4;
  6304. renderer.render( scene, cameraPZ, renderTarget );
  6305. renderTarget.generateMipmaps = generateMipmaps;
  6306. renderTarget.activeCubeFace = 5;
  6307. renderer.render( scene, cameraNZ, renderTarget );
  6308. };
  6309. };
  6310. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  6311. // File:src/cameras/OrthographicCamera.js
  6312. /**
  6313. * @author alteredq / http://alteredqualia.com/
  6314. */
  6315. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  6316. THREE.Camera.call( this );
  6317. this.left = left;
  6318. this.right = right;
  6319. this.top = top;
  6320. this.bottom = bottom;
  6321. this.near = ( near !== undefined ) ? near : 0.1;
  6322. this.far = ( far !== undefined ) ? far : 2000;
  6323. this.updateProjectionMatrix();
  6324. };
  6325. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  6326. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  6327. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  6328. };
  6329. THREE.OrthographicCamera.prototype.clone = function () {
  6330. var camera = new THREE.OrthographicCamera();
  6331. THREE.Camera.prototype.clone.call( this, camera );
  6332. camera.left = this.left;
  6333. camera.right = this.right;
  6334. camera.top = this.top;
  6335. camera.bottom = this.bottom;
  6336. camera.near = this.near;
  6337. camera.far = this.far;
  6338. return camera;
  6339. };
  6340. // File:src/cameras/PerspectiveCamera.js
  6341. /**
  6342. * @author mrdoob / http://mrdoob.com/
  6343. * @author greggman / http://games.greggman.com/
  6344. * @author zz85 / http://www.lab4games.net/zz85/blog
  6345. */
  6346. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  6347. THREE.Camera.call( this );
  6348. this.fov = fov !== undefined ? fov : 50;
  6349. this.aspect = aspect !== undefined ? aspect : 1;
  6350. this.near = near !== undefined ? near : 0.1;
  6351. this.far = far !== undefined ? far : 2000;
  6352. this.updateProjectionMatrix();
  6353. };
  6354. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  6355. /**
  6356. * Uses Focal Length (in mm) to estimate and set FOV
  6357. * 35mm (fullframe) camera is used if frame size is not specified;
  6358. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  6359. */
  6360. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  6361. if ( frameHeight === undefined ) frameHeight = 24;
  6362. this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  6363. this.updateProjectionMatrix();
  6364. }
  6365. /**
  6366. * Sets an offset in a larger frustum. This is useful for multi-window or
  6367. * multi-monitor/multi-machine setups.
  6368. *
  6369. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  6370. * the monitors are in grid like this
  6371. *
  6372. * +---+---+---+
  6373. * | A | B | C |
  6374. * +---+---+---+
  6375. * | D | E | F |
  6376. * +---+---+---+
  6377. *
  6378. * then for each monitor you would call it like this
  6379. *
  6380. * var w = 1920;
  6381. * var h = 1080;
  6382. * var fullWidth = w * 3;
  6383. * var fullHeight = h * 2;
  6384. *
  6385. * --A--
  6386. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  6387. * --B--
  6388. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  6389. * --C--
  6390. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  6391. * --D--
  6392. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  6393. * --E--
  6394. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  6395. * --F--
  6396. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  6397. *
  6398. * Note there is no reason monitors have to be the same size or in a grid.
  6399. */
  6400. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  6401. this.fullWidth = fullWidth;
  6402. this.fullHeight = fullHeight;
  6403. this.x = x;
  6404. this.y = y;
  6405. this.width = width;
  6406. this.height = height;
  6407. this.updateProjectionMatrix();
  6408. };
  6409. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  6410. if ( this.fullWidth ) {
  6411. var aspect = this.fullWidth / this.fullHeight;
  6412. var top = Math.tan( THREE.Math.degToRad( this.fov * 0.5 ) ) * this.near;
  6413. var bottom = - top;
  6414. var left = aspect * bottom;
  6415. var right = aspect * top;
  6416. var width = Math.abs( right - left );
  6417. var height = Math.abs( top - bottom );
  6418. this.projectionMatrix.makeFrustum(
  6419. left + this.x * width / this.fullWidth,
  6420. left + ( this.x + this.width ) * width / this.fullWidth,
  6421. top - ( this.y + this.height ) * height / this.fullHeight,
  6422. top - this.y * height / this.fullHeight,
  6423. this.near,
  6424. this.far
  6425. );
  6426. } else {
  6427. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  6428. }
  6429. };
  6430. THREE.PerspectiveCamera.prototype.clone = function () {
  6431. var camera = new THREE.PerspectiveCamera();
  6432. THREE.Camera.prototype.clone.call( this, camera );
  6433. camera.fov = this.fov;
  6434. camera.aspect = this.aspect;
  6435. camera.near = this.near;
  6436. camera.far = this.far;
  6437. return camera;
  6438. };
  6439. // File:src/lights/Light.js
  6440. /**
  6441. * @author mrdoob / http://mrdoob.com/
  6442. * @author alteredq / http://alteredqualia.com/
  6443. */
  6444. THREE.Light = function ( color ) {
  6445. THREE.Object3D.call( this );
  6446. this.color = new THREE.Color( color );
  6447. };
  6448. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  6449. THREE.Light.prototype.clone = function ( light ) {
  6450. if ( light === undefined ) light = new THREE.Light();
  6451. THREE.Object3D.prototype.clone.call( this, light );
  6452. light.color.copy( this.color );
  6453. return light;
  6454. };
  6455. // File:src/lights/AmbientLight.js
  6456. /**
  6457. * @author mrdoob / http://mrdoob.com/
  6458. */
  6459. THREE.AmbientLight = function ( color ) {
  6460. THREE.Light.call( this, color );
  6461. };
  6462. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  6463. THREE.AmbientLight.prototype.clone = function () {
  6464. var light = new THREE.AmbientLight();
  6465. THREE.Light.prototype.clone.call( this, light );
  6466. return light;
  6467. };
  6468. // File:src/lights/AreaLight.js
  6469. /**
  6470. * @author MPanknin / http://www.redplant.de/
  6471. * @author alteredq / http://alteredqualia.com/
  6472. */
  6473. THREE.AreaLight = function ( color, intensity ) {
  6474. THREE.Light.call( this, color );
  6475. this.normal = new THREE.Vector3( 0, - 1, 0 );
  6476. this.right = new THREE.Vector3( 1, 0, 0 );
  6477. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6478. this.width = 1.0;
  6479. this.height = 1.0;
  6480. this.constantAttenuation = 1.5;
  6481. this.linearAttenuation = 0.5;
  6482. this.quadraticAttenuation = 0.1;
  6483. };
  6484. THREE.AreaLight.prototype = Object.create( THREE.Light.prototype );
  6485. // File:src/lights/DirectionalLight.js
  6486. /**
  6487. * @author mrdoob / http://mrdoob.com/
  6488. * @author alteredq / http://alteredqualia.com/
  6489. */
  6490. THREE.DirectionalLight = function ( color, intensity ) {
  6491. THREE.Light.call( this, color );
  6492. this.position.set( 0, 1, 0 );
  6493. this.target = new THREE.Object3D();
  6494. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6495. this.castShadow = false;
  6496. this.onlyShadow = false;
  6497. //
  6498. this.shadowCameraNear = 50;
  6499. this.shadowCameraFar = 5000;
  6500. this.shadowCameraLeft = - 500;
  6501. this.shadowCameraRight = 500;
  6502. this.shadowCameraTop = 500;
  6503. this.shadowCameraBottom = - 500;
  6504. this.shadowCameraVisible = false;
  6505. this.shadowBias = 0;
  6506. this.shadowDarkness = 0.5;
  6507. this.shadowMapWidth = 512;
  6508. this.shadowMapHeight = 512;
  6509. //
  6510. this.shadowCascade = false;
  6511. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, - 1000 );
  6512. this.shadowCascadeCount = 2;
  6513. this.shadowCascadeBias = [ 0, 0, 0 ];
  6514. this.shadowCascadeWidth = [ 512, 512, 512 ];
  6515. this.shadowCascadeHeight = [ 512, 512, 512 ];
  6516. this.shadowCascadeNearZ = [ - 1.000, 0.990, 0.998 ];
  6517. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  6518. this.shadowCascadeArray = [];
  6519. //
  6520. this.shadowMap = null;
  6521. this.shadowMapSize = null;
  6522. this.shadowCamera = null;
  6523. this.shadowMatrix = null;
  6524. };
  6525. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  6526. THREE.DirectionalLight.prototype.clone = function () {
  6527. var light = new THREE.DirectionalLight();
  6528. THREE.Light.prototype.clone.call( this, light );
  6529. light.target = this.target.clone();
  6530. light.intensity = this.intensity;
  6531. light.castShadow = this.castShadow;
  6532. light.onlyShadow = this.onlyShadow;
  6533. //
  6534. light.shadowCameraNear = this.shadowCameraNear;
  6535. light.shadowCameraFar = this.shadowCameraFar;
  6536. light.shadowCameraLeft = this.shadowCameraLeft;
  6537. light.shadowCameraRight = this.shadowCameraRight;
  6538. light.shadowCameraTop = this.shadowCameraTop;
  6539. light.shadowCameraBottom = this.shadowCameraBottom;
  6540. light.shadowCameraVisible = this.shadowCameraVisible;
  6541. light.shadowBias = this.shadowBias;
  6542. light.shadowDarkness = this.shadowDarkness;
  6543. light.shadowMapWidth = this.shadowMapWidth;
  6544. light.shadowMapHeight = this.shadowMapHeight;
  6545. //
  6546. light.shadowCascade = this.shadowCascade;
  6547. light.shadowCascadeOffset.copy( this.shadowCascadeOffset );
  6548. light.shadowCascadeCount = this.shadowCascadeCount;
  6549. light.shadowCascadeBias = this.shadowCascadeBias.slice( 0 );
  6550. light.shadowCascadeWidth = this.shadowCascadeWidth.slice( 0 );
  6551. light.shadowCascadeHeight = this.shadowCascadeHeight.slice( 0 );
  6552. light.shadowCascadeNearZ = this.shadowCascadeNearZ.slice( 0 );
  6553. light.shadowCascadeFarZ = this.shadowCascadeFarZ.slice( 0 );
  6554. return light;
  6555. };
  6556. // File:src/lights/HemisphereLight.js
  6557. /**
  6558. * @author alteredq / http://alteredqualia.com/
  6559. */
  6560. THREE.HemisphereLight = function ( skyColor, groundColor, intensity ) {
  6561. THREE.Light.call( this, skyColor );
  6562. this.position.set( 0, 100, 0 );
  6563. this.groundColor = new THREE.Color( groundColor );
  6564. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6565. };
  6566. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  6567. THREE.HemisphereLight.prototype.clone = function () {
  6568. var light = new THREE.HemisphereLight();
  6569. THREE.Light.prototype.clone.call( this, light );
  6570. light.groundColor.copy( this.groundColor );
  6571. light.intensity = this.intensity;
  6572. return light;
  6573. };
  6574. // File:src/lights/PointLight.js
  6575. /**
  6576. * @author mrdoob / http://mrdoob.com/
  6577. */
  6578. THREE.PointLight = function ( color, intensity, distance ) {
  6579. THREE.Light.call( this, color );
  6580. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6581. this.distance = ( distance !== undefined ) ? distance : 0;
  6582. };
  6583. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  6584. THREE.PointLight.prototype.clone = function () {
  6585. var light = new THREE.PointLight();
  6586. THREE.Light.prototype.clone.call( this, light );
  6587. light.intensity = this.intensity;
  6588. light.distance = this.distance;
  6589. return light;
  6590. };
  6591. // File:src/lights/SpotLight.js
  6592. /**
  6593. * @author alteredq / http://alteredqualia.com/
  6594. */
  6595. THREE.SpotLight = function ( color, intensity, distance, angle, exponent ) {
  6596. THREE.Light.call( this, color );
  6597. this.position.set( 0, 1, 0 );
  6598. this.target = new THREE.Object3D();
  6599. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6600. this.distance = ( distance !== undefined ) ? distance : 0;
  6601. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  6602. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  6603. this.castShadow = false;
  6604. this.onlyShadow = false;
  6605. //
  6606. this.shadowCameraNear = 50;
  6607. this.shadowCameraFar = 5000;
  6608. this.shadowCameraFov = 50;
  6609. this.shadowCameraVisible = false;
  6610. this.shadowBias = 0;
  6611. this.shadowDarkness = 0.5;
  6612. this.shadowMapWidth = 512;
  6613. this.shadowMapHeight = 512;
  6614. //
  6615. this.shadowMap = null;
  6616. this.shadowMapSize = null;
  6617. this.shadowCamera = null;
  6618. this.shadowMatrix = null;
  6619. };
  6620. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  6621. THREE.SpotLight.prototype.clone = function () {
  6622. var light = new THREE.SpotLight();
  6623. THREE.Light.prototype.clone.call( this, light );
  6624. light.target = this.target.clone();
  6625. light.intensity = this.intensity;
  6626. light.distance = this.distance;
  6627. light.angle = this.angle;
  6628. light.exponent = this.exponent;
  6629. light.castShadow = this.castShadow;
  6630. light.onlyShadow = this.onlyShadow;
  6631. //
  6632. light.shadowCameraNear = this.shadowCameraNear;
  6633. light.shadowCameraFar = this.shadowCameraFar;
  6634. light.shadowCameraFov = this.shadowCameraFov;
  6635. light.shadowCameraVisible = this.shadowCameraVisible;
  6636. light.shadowBias = this.shadowBias;
  6637. light.shadowDarkness = this.shadowDarkness;
  6638. light.shadowMapWidth = this.shadowMapWidth;
  6639. light.shadowMapHeight = this.shadowMapHeight;
  6640. return light;
  6641. };
  6642. // File:src/loaders/Cache.js
  6643. /**
  6644. * @author mrdoob / http://mrdoob.com/
  6645. */
  6646. THREE.Cache = function () {
  6647. this.files = {};
  6648. };
  6649. THREE.Cache.prototype = {
  6650. constructor: THREE.Cache,
  6651. add: function ( key, file ) {
  6652. // console.log( 'THREE.Cache', 'Adding key:', key );
  6653. this.files[ key ] = file;
  6654. },
  6655. get: function ( key ) {
  6656. // console.log( 'THREE.Cache', 'Checking key:', key );
  6657. return this.files[ key ];
  6658. },
  6659. remove: function ( key ) {
  6660. delete this.files[ key ];
  6661. },
  6662. clear: function () {
  6663. this.files = {}
  6664. }
  6665. };
  6666. // File:src/loaders/Loader.js
  6667. /**
  6668. * @author alteredq / http://alteredqualia.com/
  6669. */
  6670. THREE.Loader = function ( showStatus ) {
  6671. this.showStatus = showStatus;
  6672. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  6673. this.imageLoader = new THREE.ImageLoader();
  6674. this.onLoadStart = function () {};
  6675. this.onLoadProgress = function () {};
  6676. this.onLoadComplete = function () {};
  6677. };
  6678. THREE.Loader.prototype = {
  6679. constructor: THREE.Loader,
  6680. crossOrigin: undefined,
  6681. addStatusElement: function () {
  6682. var e = document.createElement( 'div' );
  6683. e.style.position = 'absolute';
  6684. e.style.right = '0px';
  6685. e.style.top = '0px';
  6686. e.style.fontSize = '0.8em';
  6687. e.style.textAlign = 'left';
  6688. e.style.background = 'rgba(0,0,0,0.25)';
  6689. e.style.color = '#fff';
  6690. e.style.width = '120px';
  6691. e.style.padding = '0.5em 0.5em 0.5em 0.5em';
  6692. e.style.zIndex = 1000;
  6693. e.innerHTML = 'Loading ...';
  6694. return e;
  6695. },
  6696. updateProgress: function ( progress ) {
  6697. var message = 'Loaded ';
  6698. if ( progress.total ) {
  6699. message += ( 100 * progress.loaded / progress.total ).toFixed( 0 ) + '%';
  6700. } else {
  6701. message += ( progress.loaded / 1024 ).toFixed( 2 ) + ' KB';
  6702. }
  6703. this.statusDomElement.innerHTML = message;
  6704. },
  6705. extractUrlBase: function ( url ) {
  6706. var parts = url.split( '/' );
  6707. if ( parts.length === 1 ) return './';
  6708. parts.pop();
  6709. return parts.join( '/' ) + '/';
  6710. },
  6711. initMaterials: function ( materials, texturePath ) {
  6712. var array = [];
  6713. for ( var i = 0; i < materials.length; ++ i ) {
  6714. array[ i ] = this.createMaterial( materials[ i ], texturePath );
  6715. }
  6716. return array;
  6717. },
  6718. needsTangents: function ( materials ) {
  6719. for ( var i = 0, il = materials.length; i < il; i ++ ) {
  6720. var m = materials[ i ];
  6721. if ( m instanceof THREE.ShaderMaterial ) return true;
  6722. }
  6723. return false;
  6724. },
  6725. createMaterial: function ( m, texturePath ) {
  6726. var scope = this;
  6727. function nearest_pow2( n ) {
  6728. var l = Math.log( n ) / Math.LN2;
  6729. return Math.pow( 2, Math.round( l ) );
  6730. }
  6731. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  6732. var fullPath = texturePath + sourceFile;
  6733. var texture;
  6734. var loader = THREE.Loader.Handlers.get( fullPath );
  6735. if ( loader !== null ) {
  6736. texture = loader.load( fullPath );
  6737. } else {
  6738. texture = new THREE.Texture();
  6739. loader = scope.imageLoader;
  6740. loader.crossOrigin = scope.crossOrigin;
  6741. loader.load( fullPath, function ( image ) {
  6742. if ( THREE.Math.isPowerOfTwo( image.width ) === false ||
  6743. THREE.Math.isPowerOfTwo( image.height ) === false ) {
  6744. var width = nearest_pow2( image.width );
  6745. var height = nearest_pow2( image.height );
  6746. var canvas = document.createElement( 'canvas' );
  6747. canvas.width = width;
  6748. canvas.height = height;
  6749. var context = canvas.getContext( '2d' );
  6750. context.drawImage( image, 0, 0, width, height );
  6751. texture.image = canvas;
  6752. } else {
  6753. texture.image = image;
  6754. }
  6755. texture.needsUpdate = true;
  6756. } );
  6757. }
  6758. texture.sourceFile = sourceFile;
  6759. if ( repeat ) {
  6760. texture.repeat.set( repeat[ 0 ], repeat[ 1 ] );
  6761. if ( repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  6762. if ( repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  6763. }
  6764. if ( offset ) {
  6765. texture.offset.set( offset[ 0 ], offset[ 1 ] );
  6766. }
  6767. if ( wrap ) {
  6768. var wrapMap = {
  6769. 'repeat': THREE.RepeatWrapping,
  6770. 'mirror': THREE.MirroredRepeatWrapping
  6771. }
  6772. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ wrap[ 0 ] ];
  6773. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ wrap[ 1 ] ];
  6774. }
  6775. if ( anisotropy ) {
  6776. texture.anisotropy = anisotropy;
  6777. }
  6778. where[ name ] = texture;
  6779. }
  6780. function rgb2hex( rgb ) {
  6781. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  6782. }
  6783. // defaults
  6784. var mtype = 'MeshLambertMaterial';
  6785. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  6786. // parameters from model file
  6787. if ( m.shading ) {
  6788. var shading = m.shading.toLowerCase();
  6789. if ( shading === 'phong' ) mtype = 'MeshPhongMaterial';
  6790. else if ( shading === 'basic' ) mtype = 'MeshBasicMaterial';
  6791. }
  6792. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  6793. mpars.blending = THREE[ m.blending ];
  6794. }
  6795. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  6796. mpars.transparent = m.transparent;
  6797. }
  6798. if ( m.depthTest !== undefined ) {
  6799. mpars.depthTest = m.depthTest;
  6800. }
  6801. if ( m.depthWrite !== undefined ) {
  6802. mpars.depthWrite = m.depthWrite;
  6803. }
  6804. if ( m.visible !== undefined ) {
  6805. mpars.visible = m.visible;
  6806. }
  6807. if ( m.flipSided !== undefined ) {
  6808. mpars.side = THREE.BackSide;
  6809. }
  6810. if ( m.doubleSided !== undefined ) {
  6811. mpars.side = THREE.DoubleSide;
  6812. }
  6813. if ( m.wireframe !== undefined ) {
  6814. mpars.wireframe = m.wireframe;
  6815. }
  6816. if ( m.vertexColors !== undefined ) {
  6817. if ( m.vertexColors === 'face' ) {
  6818. mpars.vertexColors = THREE.FaceColors;
  6819. } else if ( m.vertexColors ) {
  6820. mpars.vertexColors = THREE.VertexColors;
  6821. }
  6822. }
  6823. // colors
  6824. if ( m.colorDiffuse ) {
  6825. mpars.color = rgb2hex( m.colorDiffuse );
  6826. } else if ( m.DbgColor ) {
  6827. mpars.color = m.DbgColor;
  6828. }
  6829. if ( m.colorSpecular ) {
  6830. mpars.specular = rgb2hex( m.colorSpecular );
  6831. }
  6832. if ( m.colorAmbient ) {
  6833. mpars.ambient = rgb2hex( m.colorAmbient );
  6834. }
  6835. if ( m.colorEmissive ) {
  6836. mpars.emissive = rgb2hex( m.colorEmissive );
  6837. }
  6838. // modifiers
  6839. if ( m.transparency ) {
  6840. mpars.opacity = m.transparency;
  6841. }
  6842. if ( m.specularCoef ) {
  6843. mpars.shininess = m.specularCoef;
  6844. }
  6845. // textures
  6846. if ( m.mapDiffuse && texturePath ) {
  6847. create_texture( mpars, 'map', m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  6848. }
  6849. if ( m.mapLight && texturePath ) {
  6850. create_texture( mpars, 'lightMap', m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  6851. }
  6852. if ( m.mapBump && texturePath ) {
  6853. create_texture( mpars, 'bumpMap', m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  6854. }
  6855. if ( m.mapNormal && texturePath ) {
  6856. create_texture( mpars, 'normalMap', m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  6857. }
  6858. if ( m.mapSpecular && texturePath ) {
  6859. create_texture( mpars, 'specularMap', m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  6860. }
  6861. //
  6862. if ( m.mapBumpScale ) {
  6863. mpars.bumpScale = m.mapBumpScale;
  6864. }
  6865. // special case for normal mapped material
  6866. if ( m.mapNormal ) {
  6867. var shader = THREE.ShaderLib[ 'normalmap' ];
  6868. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  6869. uniforms[ 'tNormal' ].value = mpars.normalMap;
  6870. if ( m.mapNormalFactor ) {
  6871. uniforms[ 'uNormalScale' ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  6872. }
  6873. if ( mpars.map ) {
  6874. uniforms[ 'tDiffuse' ].value = mpars.map;
  6875. uniforms[ 'enableDiffuse' ].value = true;
  6876. }
  6877. if ( mpars.specularMap ) {
  6878. uniforms[ 'tSpecular' ].value = mpars.specularMap;
  6879. uniforms[ 'enableSpecular' ].value = true;
  6880. }
  6881. if ( mpars.lightMap ) {
  6882. uniforms[ 'tAO' ].value = mpars.lightMap;
  6883. uniforms[ 'enableAO' ].value = true;
  6884. }
  6885. // for the moment don't handle displacement texture
  6886. uniforms[ 'diffuse' ].value.setHex( mpars.color );
  6887. uniforms[ 'specular' ].value.setHex( mpars.specular );
  6888. uniforms[ 'ambient' ].value.setHex( mpars.ambient );
  6889. uniforms[ 'shininess' ].value = mpars.shininess;
  6890. if ( mpars.opacity !== undefined ) {
  6891. uniforms[ 'opacity' ].value = mpars.opacity;
  6892. }
  6893. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  6894. var material = new THREE.ShaderMaterial( parameters );
  6895. if ( mpars.transparent ) {
  6896. material.transparent = true;
  6897. }
  6898. } else {
  6899. var material = new THREE[ mtype ]( mpars );
  6900. }
  6901. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  6902. return material;
  6903. }
  6904. };
  6905. THREE.Loader.Handlers = {
  6906. handlers: [],
  6907. add: function ( regex, loader ) {
  6908. this.handlers.push( regex, loader );
  6909. },
  6910. get: function ( file ) {
  6911. for ( var i = 0, l = this.handlers.length; i < l; i += 2 ) {
  6912. var regex = this.handlers[ i ];
  6913. var loader = this.handlers[ i + 1 ];
  6914. if ( regex.test( file ) ) {
  6915. return loader;
  6916. }
  6917. }
  6918. return null;
  6919. }
  6920. };
  6921. // File:src/loaders/XHRLoader.js
  6922. /**
  6923. * @author mrdoob / http://mrdoob.com/
  6924. */
  6925. THREE.XHRLoader = function ( manager ) {
  6926. this.cache = new THREE.Cache();
  6927. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6928. };
  6929. THREE.XHRLoader.prototype = {
  6930. constructor: THREE.XHRLoader,
  6931. load: function ( url, onLoad, onProgress, onError ) {
  6932. var scope = this;
  6933. var cached = scope.cache.get( url );
  6934. if ( cached !== undefined ) {
  6935. if ( onLoad ) onLoad( cached );
  6936. return;
  6937. }
  6938. var request = new XMLHttpRequest();
  6939. request.open( 'GET', url, true );
  6940. request.addEventListener( 'load', function ( event ) {
  6941. scope.cache.add( url, this.response );
  6942. if ( onLoad ) onLoad( this.response );
  6943. scope.manager.itemEnd( url );
  6944. }, false );
  6945. if ( onProgress !== undefined ) {
  6946. request.addEventListener( 'progress', function ( event ) {
  6947. onProgress( event );
  6948. }, false );
  6949. }
  6950. if ( onError !== undefined ) {
  6951. request.addEventListener( 'error', function ( event ) {
  6952. onError( event );
  6953. }, false );
  6954. }
  6955. if ( this.crossOrigin !== undefined ) request.crossOrigin = this.crossOrigin;
  6956. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  6957. request.send( null );
  6958. scope.manager.itemStart( url );
  6959. },
  6960. setResponseType: function ( value ) {
  6961. this.responseType = value;
  6962. },
  6963. setCrossOrigin: function ( value ) {
  6964. this.crossOrigin = value;
  6965. }
  6966. };
  6967. // File:src/loaders/ImageLoader.js
  6968. /**
  6969. * @author mrdoob / http://mrdoob.com/
  6970. */
  6971. THREE.ImageLoader = function ( manager ) {
  6972. this.cache = new THREE.Cache();
  6973. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6974. };
  6975. THREE.ImageLoader.prototype = {
  6976. constructor: THREE.ImageLoader,
  6977. load: function ( url, onLoad, onProgress, onError ) {
  6978. var scope = this;
  6979. var cached = scope.cache.get( url );
  6980. if ( cached !== undefined ) {
  6981. onLoad( cached );
  6982. return;
  6983. }
  6984. var image = document.createElement( 'img' );
  6985. if ( onLoad !== undefined ) {
  6986. image.addEventListener( 'load', function ( event ) {
  6987. scope.cache.add( url, this );
  6988. onLoad( this );
  6989. scope.manager.itemEnd( url );
  6990. }, false );
  6991. }
  6992. if ( onProgress !== undefined ) {
  6993. image.addEventListener( 'progress', function ( event ) {
  6994. onProgress( event );
  6995. }, false );
  6996. }
  6997. if ( onError !== undefined ) {
  6998. image.addEventListener( 'error', function ( event ) {
  6999. onError( event );
  7000. }, false );
  7001. }
  7002. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  7003. image.src = url;
  7004. scope.manager.itemStart( url );
  7005. return image;
  7006. },
  7007. setCrossOrigin: function ( value ) {
  7008. this.crossOrigin = value;
  7009. }
  7010. }
  7011. // File:src/loaders/JSONLoader.js
  7012. /**
  7013. * @author mrdoob / http://mrdoob.com/
  7014. * @author alteredq / http://alteredqualia.com/
  7015. */
  7016. THREE.JSONLoader = function ( showStatus ) {
  7017. THREE.Loader.call( this, showStatus );
  7018. this.withCredentials = false;
  7019. };
  7020. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  7021. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  7022. var scope = this;
  7023. // todo: unify load API to for easier SceneLoader use
  7024. texturePath = texturePath && ( typeof texturePath === 'string' ) ? texturePath : this.extractUrlBase( url );
  7025. this.onLoadStart();
  7026. this.loadAjaxJSON( this, url, callback, texturePath );
  7027. };
  7028. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  7029. var xhr = new XMLHttpRequest();
  7030. var length = 0;
  7031. xhr.onreadystatechange = function () {
  7032. if ( xhr.readyState === xhr.DONE ) {
  7033. if ( xhr.status === 200 || xhr.status === 0 ) {
  7034. if ( xhr.responseText ) {
  7035. var json = JSON.parse( xhr.responseText );
  7036. if ( json.metadata !== undefined && json.metadata.type === 'scene' ) {
  7037. console.error( 'THREE.JSONLoader: "' + url + '" seems to be a Scene. Use THREE.SceneLoader instead.' );
  7038. return;
  7039. }
  7040. var result = context.parse( json, texturePath );
  7041. callback( result.geometry, result.materials );
  7042. } else {
  7043. console.error( 'THREE.JSONLoader: "' + url + '" seems to be unreachable or the file is empty.' );
  7044. }
  7045. // in context of more complex asset initialization
  7046. // do not block on single failed file
  7047. // maybe should go even one more level up
  7048. context.onLoadComplete();
  7049. } else {
  7050. console.error( 'THREE.JSONLoader: Couldn\'t load "' + url + '" (' + xhr.status + ')' );
  7051. }
  7052. } else if ( xhr.readyState === xhr.LOADING ) {
  7053. if ( callbackProgress ) {
  7054. if ( length === 0 ) {
  7055. length = xhr.getResponseHeader( 'Content-Length' );
  7056. }
  7057. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  7058. }
  7059. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  7060. if ( callbackProgress !== undefined ) {
  7061. length = xhr.getResponseHeader( 'Content-Length' );
  7062. }
  7063. }
  7064. };
  7065. xhr.open( 'GET', url, true );
  7066. xhr.withCredentials = this.withCredentials;
  7067. xhr.send( null );
  7068. };
  7069. THREE.JSONLoader.prototype.parse = function ( json, texturePath ) {
  7070. var scope = this,
  7071. geometry = new THREE.Geometry(),
  7072. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  7073. parseModel( scale );
  7074. parseSkin();
  7075. parseMorphing( scale );
  7076. geometry.computeFaceNormals();
  7077. geometry.computeBoundingSphere();
  7078. function parseModel( scale ) {
  7079. function isBitSet( value, position ) {
  7080. return value & ( 1 << position );
  7081. }
  7082. var i, j, fi,
  7083. offset, zLength,
  7084. colorIndex, normalIndex, uvIndex, materialIndex,
  7085. type,
  7086. isQuad,
  7087. hasMaterial,
  7088. hasFaceVertexUv,
  7089. hasFaceNormal, hasFaceVertexNormal,
  7090. hasFaceColor, hasFaceVertexColor,
  7091. vertex, face, faceA, faceB, color, hex, normal,
  7092. uvLayer, uv, u, v,
  7093. faces = json.faces,
  7094. vertices = json.vertices,
  7095. normals = json.normals,
  7096. colors = json.colors,
  7097. nUvLayers = 0;
  7098. if ( json.uvs !== undefined ) {
  7099. // disregard empty arrays
  7100. for ( i = 0; i < json.uvs.length; i ++ ) {
  7101. if ( json.uvs[ i ].length ) nUvLayers ++;
  7102. }
  7103. for ( i = 0; i < nUvLayers; i ++ ) {
  7104. geometry.faceVertexUvs[ i ] = [];
  7105. }
  7106. }
  7107. offset = 0;
  7108. zLength = vertices.length;
  7109. while ( offset < zLength ) {
  7110. vertex = new THREE.Vector3();
  7111. vertex.x = vertices[ offset ++ ] * scale;
  7112. vertex.y = vertices[ offset ++ ] * scale;
  7113. vertex.z = vertices[ offset ++ ] * scale;
  7114. geometry.vertices.push( vertex );
  7115. }
  7116. offset = 0;
  7117. zLength = faces.length;
  7118. while ( offset < zLength ) {
  7119. type = faces[ offset ++ ];
  7120. isQuad = isBitSet( type, 0 );
  7121. hasMaterial = isBitSet( type, 1 );
  7122. hasFaceVertexUv = isBitSet( type, 3 );
  7123. hasFaceNormal = isBitSet( type, 4 );
  7124. hasFaceVertexNormal = isBitSet( type, 5 );
  7125. hasFaceColor = isBitSet( type, 6 );
  7126. hasFaceVertexColor = isBitSet( type, 7 );
  7127. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  7128. if ( isQuad ) {
  7129. faceA = new THREE.Face3();
  7130. faceA.a = faces[ offset ];
  7131. faceA.b = faces[ offset + 1 ];
  7132. faceA.c = faces[ offset + 3 ];
  7133. faceB = new THREE.Face3();
  7134. faceB.a = faces[ offset + 1 ];
  7135. faceB.b = faces[ offset + 2 ];
  7136. faceB.c = faces[ offset + 3 ];
  7137. offset += 4;
  7138. if ( hasMaterial ) {
  7139. materialIndex = faces[ offset ++ ];
  7140. faceA.materialIndex = materialIndex;
  7141. faceB.materialIndex = materialIndex;
  7142. }
  7143. // to get face <=> uv index correspondence
  7144. fi = geometry.faces.length;
  7145. if ( hasFaceVertexUv ) {
  7146. for ( i = 0; i < nUvLayers; i ++ ) {
  7147. uvLayer = json.uvs[ i ];
  7148. geometry.faceVertexUvs[ i ][ fi ] = [];
  7149. geometry.faceVertexUvs[ i ][ fi + 1 ] = []
  7150. for ( j = 0; j < 4; j ++ ) {
  7151. uvIndex = faces[ offset ++ ];
  7152. u = uvLayer[ uvIndex * 2 ];
  7153. v = uvLayer[ uvIndex * 2 + 1 ];
  7154. uv = new THREE.Vector2( u, v );
  7155. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  7156. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  7157. }
  7158. }
  7159. }
  7160. if ( hasFaceNormal ) {
  7161. normalIndex = faces[ offset ++ ] * 3;
  7162. faceA.normal.set(
  7163. normals[ normalIndex ++ ],
  7164. normals[ normalIndex ++ ],
  7165. normals[ normalIndex ]
  7166. );
  7167. faceB.normal.copy( faceA.normal );
  7168. }
  7169. if ( hasFaceVertexNormal ) {
  7170. for ( i = 0; i < 4; i ++ ) {
  7171. normalIndex = faces[ offset ++ ] * 3;
  7172. normal = new THREE.Vector3(
  7173. normals[ normalIndex ++ ],
  7174. normals[ normalIndex ++ ],
  7175. normals[ normalIndex ]
  7176. );
  7177. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  7178. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  7179. }
  7180. }
  7181. if ( hasFaceColor ) {
  7182. colorIndex = faces[ offset ++ ];
  7183. hex = colors[ colorIndex ];
  7184. faceA.color.setHex( hex );
  7185. faceB.color.setHex( hex );
  7186. }
  7187. if ( hasFaceVertexColor ) {
  7188. for ( i = 0; i < 4; i ++ ) {
  7189. colorIndex = faces[ offset ++ ];
  7190. hex = colors[ colorIndex ];
  7191. if ( i !== 2 ) faceA.vertexColors.push( new THREE.Color( hex ) );
  7192. if ( i !== 0 ) faceB.vertexColors.push( new THREE.Color( hex ) );
  7193. }
  7194. }
  7195. geometry.faces.push( faceA );
  7196. geometry.faces.push( faceB );
  7197. } else {
  7198. face = new THREE.Face3();
  7199. face.a = faces[ offset ++ ];
  7200. face.b = faces[ offset ++ ];
  7201. face.c = faces[ offset ++ ];
  7202. if ( hasMaterial ) {
  7203. materialIndex = faces[ offset ++ ];
  7204. face.materialIndex = materialIndex;
  7205. }
  7206. // to get face <=> uv index correspondence
  7207. fi = geometry.faces.length;
  7208. if ( hasFaceVertexUv ) {
  7209. for ( i = 0; i < nUvLayers; i ++ ) {
  7210. uvLayer = json.uvs[ i ];
  7211. geometry.faceVertexUvs[ i ][ fi ] = [];
  7212. for ( j = 0; j < 3; j ++ ) {
  7213. uvIndex = faces[ offset ++ ];
  7214. u = uvLayer[ uvIndex * 2 ];
  7215. v = uvLayer[ uvIndex * 2 + 1 ];
  7216. uv = new THREE.Vector2( u, v );
  7217. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  7218. }
  7219. }
  7220. }
  7221. if ( hasFaceNormal ) {
  7222. normalIndex = faces[ offset ++ ] * 3;
  7223. face.normal.set(
  7224. normals[ normalIndex ++ ],
  7225. normals[ normalIndex ++ ],
  7226. normals[ normalIndex ]
  7227. );
  7228. }
  7229. if ( hasFaceVertexNormal ) {
  7230. for ( i = 0; i < 3; i ++ ) {
  7231. normalIndex = faces[ offset ++ ] * 3;
  7232. normal = new THREE.Vector3(
  7233. normals[ normalIndex ++ ],
  7234. normals[ normalIndex ++ ],
  7235. normals[ normalIndex ]
  7236. );
  7237. face.vertexNormals.push( normal );
  7238. }
  7239. }
  7240. if ( hasFaceColor ) {
  7241. colorIndex = faces[ offset ++ ];
  7242. face.color.setHex( colors[ colorIndex ] );
  7243. }
  7244. if ( hasFaceVertexColor ) {
  7245. for ( i = 0; i < 3; i ++ ) {
  7246. colorIndex = faces[ offset ++ ];
  7247. face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) );
  7248. }
  7249. }
  7250. geometry.faces.push( face );
  7251. }
  7252. }
  7253. };
  7254. function parseSkin() {
  7255. var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2;
  7256. if ( json.skinWeights ) {
  7257. for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {
  7258. var x = json.skinWeights[ i ];
  7259. var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
  7260. var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
  7261. var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;
  7262. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  7263. }
  7264. }
  7265. if ( json.skinIndices ) {
  7266. for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {
  7267. var a = json.skinIndices[ i ];
  7268. var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
  7269. var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
  7270. var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;
  7271. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  7272. }
  7273. }
  7274. geometry.bones = json.bones;
  7275. if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {
  7276. console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
  7277. geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );
  7278. }
  7279. // could change this to json.animations[0] or remove completely
  7280. geometry.animation = json.animation;
  7281. geometry.animations = json.animations;
  7282. };
  7283. function parseMorphing( scale ) {
  7284. if ( json.morphTargets !== undefined ) {
  7285. var i, l, v, vl, dstVertices, srcVertices;
  7286. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  7287. geometry.morphTargets[ i ] = {};
  7288. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  7289. geometry.morphTargets[ i ].vertices = [];
  7290. dstVertices = geometry.morphTargets[ i ].vertices;
  7291. srcVertices = json.morphTargets [ i ].vertices;
  7292. for ( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  7293. var vertex = new THREE.Vector3();
  7294. vertex.x = srcVertices[ v ] * scale;
  7295. vertex.y = srcVertices[ v + 1 ] * scale;
  7296. vertex.z = srcVertices[ v + 2 ] * scale;
  7297. dstVertices.push( vertex );
  7298. }
  7299. }
  7300. }
  7301. if ( json.morphColors !== undefined ) {
  7302. var i, l, c, cl, dstColors, srcColors, color;
  7303. for ( i = 0, l = json.morphColors.length; i < l; i ++ ) {
  7304. geometry.morphColors[ i ] = {};
  7305. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  7306. geometry.morphColors[ i ].colors = [];
  7307. dstColors = geometry.morphColors[ i ].colors;
  7308. srcColors = json.morphColors [ i ].colors;
  7309. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  7310. color = new THREE.Color( 0xffaa00 );
  7311. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  7312. dstColors.push( color );
  7313. }
  7314. }
  7315. }
  7316. };
  7317. if ( json.materials === undefined || json.materials.length === 0 ) {
  7318. return { geometry: geometry };
  7319. } else {
  7320. var materials = this.initMaterials( json.materials, texturePath );
  7321. if ( this.needsTangents( materials ) ) {
  7322. geometry.computeTangents();
  7323. }
  7324. return { geometry: geometry, materials: materials };
  7325. }
  7326. };
  7327. // File:src/loaders/LoadingManager.js
  7328. /**
  7329. * @author mrdoob / http://mrdoob.com/
  7330. */
  7331. THREE.LoadingManager = function ( onLoad, onProgress, onError ) {
  7332. var scope = this;
  7333. var loaded = 0, total = 0;
  7334. this.onLoad = onLoad;
  7335. this.onProgress = onProgress;
  7336. this.onError = onError;
  7337. this.itemStart = function ( url ) {
  7338. total ++;
  7339. };
  7340. this.itemEnd = function ( url ) {
  7341. loaded ++;
  7342. if ( scope.onProgress !== undefined ) {
  7343. scope.onProgress( url, loaded, total );
  7344. }
  7345. if ( loaded === total && scope.onLoad !== undefined ) {
  7346. scope.onLoad();
  7347. }
  7348. };
  7349. };
  7350. THREE.DefaultLoadingManager = new THREE.LoadingManager();
  7351. // File:src/loaders/BufferGeometryLoader.js
  7352. /**
  7353. * @author mrdoob / http://mrdoob.com/
  7354. */
  7355. THREE.BufferGeometryLoader = function ( manager ) {
  7356. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7357. };
  7358. THREE.BufferGeometryLoader.prototype = {
  7359. constructor: THREE.BufferGeometryLoader,
  7360. load: function ( url, onLoad, onProgress, onError ) {
  7361. var scope = this;
  7362. var loader = new THREE.XHRLoader();
  7363. loader.setCrossOrigin( this.crossOrigin );
  7364. loader.load( url, function ( text ) {
  7365. onLoad( scope.parse( JSON.parse( text ) ) );
  7366. }, onProgress, onError );
  7367. },
  7368. setCrossOrigin: function ( value ) {
  7369. this.crossOrigin = value;
  7370. },
  7371. parse: function ( json ) {
  7372. var geometry = new THREE.BufferGeometry();
  7373. var attributes = json.attributes;
  7374. for ( var key in attributes ) {
  7375. var attribute = attributes[ key ];
  7376. geometry.attributes[ key ] = {
  7377. itemSize: attribute.itemSize,
  7378. array: new self[ attribute.type ]( attribute.array )
  7379. }
  7380. }
  7381. var offsets = json.offsets;
  7382. if ( offsets !== undefined ) {
  7383. geometry.offsets = JSON.parse( JSON.stringify( offsets ) );
  7384. }
  7385. var boundingSphere = json.boundingSphere;
  7386. if ( boundingSphere !== undefined ) {
  7387. geometry.boundingSphere = new THREE.Sphere(
  7388. new THREE.Vector3().fromArray( boundingSphere.center !== undefined ? boundingSphere.center : [ 0, 0, 0 ] ),
  7389. boundingSphere.radius
  7390. );
  7391. }
  7392. return geometry;
  7393. }
  7394. };
  7395. // File:src/loaders/MaterialLoader.js
  7396. /**
  7397. * @author mrdoob / http://mrdoob.com/
  7398. */
  7399. THREE.MaterialLoader = function ( manager ) {
  7400. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7401. };
  7402. THREE.MaterialLoader.prototype = {
  7403. constructor: THREE.MaterialLoader,
  7404. load: function ( url, onLoad, onProgress, onError ) {
  7405. var scope = this;
  7406. var loader = new THREE.XHRLoader();
  7407. loader.setCrossOrigin( this.crossOrigin );
  7408. loader.load( url, function ( text ) {
  7409. onLoad( scope.parse( JSON.parse( text ) ) );
  7410. }, onProgress, onError );
  7411. },
  7412. setCrossOrigin: function ( value ) {
  7413. this.crossOrigin = value;
  7414. },
  7415. parse: function ( json ) {
  7416. var material = new THREE[ json.type ];
  7417. if ( json.color !== undefined ) material.color.setHex( json.color );
  7418. if ( json.ambient !== undefined ) material.ambient.setHex( json.ambient );
  7419. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  7420. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  7421. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  7422. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  7423. if ( json.blending !== undefined ) material.blending = json.blending;
  7424. if ( json.side !== undefined ) material.side = json.side;
  7425. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  7426. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  7427. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  7428. if ( json.materials !== undefined ) {
  7429. for ( var i = 0, l = json.materials.length; i < l; i ++ ) {
  7430. material.materials.push( this.parse( json.materials[ i ] ) );
  7431. }
  7432. }
  7433. return material;
  7434. }
  7435. };
  7436. // File:src/loaders/ObjectLoader.js
  7437. /**
  7438. * @author mrdoob / http://mrdoob.com/
  7439. */
  7440. THREE.ObjectLoader = function ( manager ) {
  7441. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7442. };
  7443. THREE.ObjectLoader.prototype = {
  7444. constructor: THREE.ObjectLoader,
  7445. load: function ( url, onLoad, onProgress, onError ) {
  7446. var scope = this;
  7447. var loader = new THREE.XHRLoader( scope.manager );
  7448. loader.setCrossOrigin( this.crossOrigin );
  7449. loader.load( url, function ( text ) {
  7450. onLoad( scope.parse( JSON.parse( text ) ) );
  7451. }, onProgress, onError );
  7452. },
  7453. setCrossOrigin: function ( value ) {
  7454. this.crossOrigin = value;
  7455. },
  7456. parse: function ( json ) {
  7457. var geometries = this.parseGeometries( json.geometries );
  7458. var materials = this.parseMaterials( json.materials );
  7459. var object = this.parseObject( json.object, geometries, materials );
  7460. return object;
  7461. },
  7462. parseGeometries: function ( json ) {
  7463. var geometries = {};
  7464. if ( json !== undefined ) {
  7465. var geometryLoader = new THREE.JSONLoader();
  7466. var bufferGeometryLoader = new THREE.BufferGeometryLoader();
  7467. for ( var i = 0, l = json.length; i < l; i ++ ) {
  7468. var geometry;
  7469. var data = json[ i ];
  7470. switch ( data.type ) {
  7471. case 'PlaneGeometry':
  7472. geometry = new THREE.PlaneGeometry(
  7473. data.width,
  7474. data.height,
  7475. data.widthSegments,
  7476. data.heightSegments
  7477. );
  7478. break;
  7479. case 'BoxGeometry':
  7480. case 'CubeGeometry': // backwards compatible
  7481. geometry = new THREE.BoxGeometry(
  7482. data.width,
  7483. data.height,
  7484. data.depth,
  7485. data.widthSegments,
  7486. data.heightSegments,
  7487. data.depthSegments
  7488. );
  7489. break;
  7490. case 'CircleGeometry':
  7491. geometry = new THREE.CircleGeometry(
  7492. data.radius,
  7493. data.segments
  7494. );
  7495. break;
  7496. case 'CylinderGeometry':
  7497. geometry = new THREE.CylinderGeometry(
  7498. data.radiusTop,
  7499. data.radiusBottom,
  7500. data.height,
  7501. data.radialSegments,
  7502. data.heightSegments,
  7503. data.openEnded
  7504. );
  7505. break;
  7506. case 'SphereGeometry':
  7507. geometry = new THREE.SphereGeometry(
  7508. data.radius,
  7509. data.widthSegments,
  7510. data.heightSegments,
  7511. data.phiStart,
  7512. data.phiLength,
  7513. data.thetaStart,
  7514. data.thetaLength
  7515. );
  7516. break;
  7517. case 'IcosahedronGeometry':
  7518. geometry = new THREE.IcosahedronGeometry(
  7519. data.radius,
  7520. data.detail
  7521. );
  7522. break;
  7523. case 'TorusGeometry':
  7524. geometry = new THREE.TorusGeometry(
  7525. data.radius,
  7526. data.tube,
  7527. data.radialSegments,
  7528. data.tubularSegments,
  7529. data.arc
  7530. );
  7531. break;
  7532. case 'TorusKnotGeometry':
  7533. geometry = new THREE.TorusKnotGeometry(
  7534. data.radius,
  7535. data.tube,
  7536. data.radialSegments,
  7537. data.tubularSegments,
  7538. data.p,
  7539. data.q,
  7540. data.heightScale
  7541. );
  7542. break;
  7543. case 'BufferGeometry':
  7544. geometry = bufferGeometryLoader.parse( data.data );
  7545. break;
  7546. case 'Geometry':
  7547. geometry = geometryLoader.parse( data.data ).geometry;
  7548. break;
  7549. }
  7550. geometry.uuid = data.uuid;
  7551. if ( data.name !== undefined ) geometry.name = data.name;
  7552. geometries[ data.uuid ] = geometry;
  7553. }
  7554. }
  7555. return geometries;
  7556. },
  7557. parseMaterials: function ( json ) {
  7558. var materials = {};
  7559. if ( json !== undefined ) {
  7560. var loader = new THREE.MaterialLoader();
  7561. for ( var i = 0, l = json.length; i < l; i ++ ) {
  7562. var data = json[ i ];
  7563. var material = loader.parse( data );
  7564. material.uuid = data.uuid;
  7565. if ( data.name !== undefined ) material.name = data.name;
  7566. materials[ data.uuid ] = material;
  7567. }
  7568. }
  7569. return materials;
  7570. },
  7571. parseObject: function () {
  7572. var matrix = new THREE.Matrix4();
  7573. return function ( data, geometries, materials ) {
  7574. var object;
  7575. switch ( data.type ) {
  7576. case 'Scene':
  7577. object = new THREE.Scene();
  7578. break;
  7579. case 'PerspectiveCamera':
  7580. object = new THREE.PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  7581. break;
  7582. case 'OrthographicCamera':
  7583. object = new THREE.OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  7584. break;
  7585. case 'AmbientLight':
  7586. object = new THREE.AmbientLight( data.color );
  7587. break;
  7588. case 'DirectionalLight':
  7589. object = new THREE.DirectionalLight( data.color, data.intensity );
  7590. break;
  7591. case 'PointLight':
  7592. object = new THREE.PointLight( data.color, data.intensity, data.distance );
  7593. break;
  7594. case 'SpotLight':
  7595. object = new THREE.SpotLight( data.color, data.intensity, data.distance, data.angle, data.exponent );
  7596. break;
  7597. case 'HemisphereLight':
  7598. object = new THREE.HemisphereLight( data.color, data.groundColor, data.intensity );
  7599. break;
  7600. case 'Mesh':
  7601. var geometry = geometries[ data.geometry ];
  7602. var material = materials[ data.material ];
  7603. if ( geometry === undefined ) {
  7604. console.error( 'THREE.ObjectLoader: Undefined geometry ' + data.geometry );
  7605. }
  7606. if ( material === undefined ) {
  7607. console.error( 'THREE.ObjectLoader: Undefined material ' + data.material );
  7608. }
  7609. object = new THREE.Mesh( geometry, material );
  7610. break;
  7611. case 'Sprite':
  7612. var material = materials[ data.material ];
  7613. if ( material === undefined ) {
  7614. console.error( 'THREE.ObjectLoader: Undefined material ' + data.material );
  7615. }
  7616. object = new THREE.Sprite( material );
  7617. break;
  7618. default:
  7619. object = new THREE.Object3D();
  7620. }
  7621. object.uuid = data.uuid;
  7622. if ( data.name !== undefined ) object.name = data.name;
  7623. if ( data.matrix !== undefined ) {
  7624. matrix.fromArray( data.matrix );
  7625. matrix.decompose( object.position, object.quaternion, object.scale );
  7626. } else {
  7627. if ( data.position !== undefined ) object.position.fromArray( data.position );
  7628. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  7629. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  7630. }
  7631. if ( data.visible !== undefined ) object.visible = data.visible;
  7632. if ( data.userData !== undefined ) object.userData = data.userData;
  7633. if ( data.children !== undefined ) {
  7634. for ( var child in data.children ) {
  7635. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  7636. }
  7637. }
  7638. return object;
  7639. }
  7640. }()
  7641. };
  7642. // File:src/loaders/TextureLoader.js
  7643. /**
  7644. * @author mrdoob / http://mrdoob.com/
  7645. */
  7646. THREE.TextureLoader = function ( manager ) {
  7647. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7648. };
  7649. THREE.TextureLoader.prototype = {
  7650. constructor: THREE.TextureLoader,
  7651. load: function ( url, onLoad, onProgress, onError ) {
  7652. var scope = this;
  7653. var loader = new THREE.ImageLoader( scope.manager );
  7654. loader.setCrossOrigin( this.crossOrigin );
  7655. loader.load( url, function ( image ) {
  7656. var texture = new THREE.Texture( image );
  7657. texture.needsUpdate = true;
  7658. if ( onLoad !== undefined ) {
  7659. onLoad( texture );
  7660. }
  7661. }, onProgress, onError );
  7662. },
  7663. setCrossOrigin: function ( value ) {
  7664. this.crossOrigin = value;
  7665. }
  7666. };
  7667. // File:src/materials/Material.js
  7668. /**
  7669. * @author mrdoob / http://mrdoob.com/
  7670. * @author alteredq / http://alteredqualia.com/
  7671. */
  7672. THREE.Material = function () {
  7673. this.id = THREE.MaterialIdCount ++;
  7674. this.uuid = THREE.Math.generateUUID();
  7675. this.name = '';
  7676. this.side = THREE.FrontSide;
  7677. this.opacity = 1;
  7678. this.transparent = false;
  7679. this.blending = THREE.NormalBlending;
  7680. this.blendSrc = THREE.SrcAlphaFactor;
  7681. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  7682. this.blendEquation = THREE.AddEquation;
  7683. this.depthTest = true;
  7684. this.depthWrite = true;
  7685. this.polygonOffset = false;
  7686. this.polygonOffsetFactor = 0;
  7687. this.polygonOffsetUnits = 0;
  7688. this.alphaTest = 0;
  7689. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  7690. this.visible = true;
  7691. this.needsUpdate = true;
  7692. };
  7693. THREE.Material.prototype = {
  7694. constructor: THREE.Material,
  7695. setValues: function ( values ) {
  7696. if ( values === undefined ) return;
  7697. for ( var key in values ) {
  7698. var newValue = values[ key ];
  7699. if ( newValue === undefined ) {
  7700. console.warn( "THREE.Material: '" + key + "' parameter is undefined." );
  7701. continue;
  7702. }
  7703. if ( key in this ) {
  7704. var currentValue = this[ key ];
  7705. if ( currentValue instanceof THREE.Color ) {
  7706. currentValue.set( newValue );
  7707. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  7708. currentValue.copy( newValue );
  7709. } else if ( key == 'overdraw' ) {
  7710. // ensure overdraw is backwards-compatable with legacy boolean type
  7711. this[ key ] = Number( newValue );
  7712. } else {
  7713. this[ key ] = newValue;
  7714. }
  7715. }
  7716. }
  7717. },
  7718. clone: function ( material ) {
  7719. if ( material === undefined ) material = new THREE.Material();
  7720. material.name = this.name;
  7721. material.side = this.side;
  7722. material.opacity = this.opacity;
  7723. material.transparent = this.transparent;
  7724. material.blending = this.blending;
  7725. material.blendSrc = this.blendSrc;
  7726. material.blendDst = this.blendDst;
  7727. material.blendEquation = this.blendEquation;
  7728. material.depthTest = this.depthTest;
  7729. material.depthWrite = this.depthWrite;
  7730. material.polygonOffset = this.polygonOffset;
  7731. material.polygonOffsetFactor = this.polygonOffsetFactor;
  7732. material.polygonOffsetUnits = this.polygonOffsetUnits;
  7733. material.alphaTest = this.alphaTest;
  7734. material.overdraw = this.overdraw;
  7735. material.visible = this.visible;
  7736. return material;
  7737. },
  7738. dispose: function () {
  7739. this.dispatchEvent( { type: 'dispose' } );
  7740. }
  7741. };
  7742. THREE.EventDispatcher.prototype.apply( THREE.Material.prototype );
  7743. THREE.MaterialIdCount = 0;
  7744. // File:src/materials/LineBasicMaterial.js
  7745. /**
  7746. * @author mrdoob / http://mrdoob.com/
  7747. * @author alteredq / http://alteredqualia.com/
  7748. *
  7749. * parameters = {
  7750. * color: <hex>,
  7751. * opacity: <float>,
  7752. *
  7753. * blending: THREE.NormalBlending,
  7754. * depthTest: <bool>,
  7755. * depthWrite: <bool>,
  7756. *
  7757. * linewidth: <float>,
  7758. * linecap: "round",
  7759. * linejoin: "round",
  7760. *
  7761. * vertexColors: <bool>
  7762. *
  7763. * fog: <bool>
  7764. * }
  7765. */
  7766. THREE.LineBasicMaterial = function ( parameters ) {
  7767. THREE.Material.call( this );
  7768. this.color = new THREE.Color( 0xffffff );
  7769. this.linewidth = 1;
  7770. this.linecap = 'round';
  7771. this.linejoin = 'round';
  7772. this.vertexColors = THREE.NoColors;
  7773. this.fog = true;
  7774. this.setValues( parameters );
  7775. };
  7776. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7777. THREE.LineBasicMaterial.prototype.clone = function () {
  7778. var material = new THREE.LineBasicMaterial();
  7779. THREE.Material.prototype.clone.call( this, material );
  7780. material.color.copy( this.color );
  7781. material.linewidth = this.linewidth;
  7782. material.linecap = this.linecap;
  7783. material.linejoin = this.linejoin;
  7784. material.vertexColors = this.vertexColors;
  7785. material.fog = this.fog;
  7786. return material;
  7787. };
  7788. // File:src/materials/LineDashedMaterial.js
  7789. /**
  7790. * @author alteredq / http://alteredqualia.com/
  7791. *
  7792. * parameters = {
  7793. * color: <hex>,
  7794. * opacity: <float>,
  7795. *
  7796. * blending: THREE.NormalBlending,
  7797. * depthTest: <bool>,
  7798. * depthWrite: <bool>,
  7799. *
  7800. * linewidth: <float>,
  7801. *
  7802. * scale: <float>,
  7803. * dashSize: <float>,
  7804. * gapSize: <float>,
  7805. *
  7806. * vertexColors: <bool>
  7807. *
  7808. * fog: <bool>
  7809. * }
  7810. */
  7811. THREE.LineDashedMaterial = function ( parameters ) {
  7812. THREE.Material.call( this );
  7813. this.color = new THREE.Color( 0xffffff );
  7814. this.linewidth = 1;
  7815. this.scale = 1;
  7816. this.dashSize = 3;
  7817. this.gapSize = 1;
  7818. this.vertexColors = false;
  7819. this.fog = true;
  7820. this.setValues( parameters );
  7821. };
  7822. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  7823. THREE.LineDashedMaterial.prototype.clone = function () {
  7824. var material = new THREE.LineDashedMaterial();
  7825. THREE.Material.prototype.clone.call( this, material );
  7826. material.color.copy( this.color );
  7827. material.linewidth = this.linewidth;
  7828. material.scale = this.scale;
  7829. material.dashSize = this.dashSize;
  7830. material.gapSize = this.gapSize;
  7831. material.vertexColors = this.vertexColors;
  7832. material.fog = this.fog;
  7833. return material;
  7834. };
  7835. // File:src/materials/MeshBasicMaterial.js
  7836. /**
  7837. * @author mrdoob / http://mrdoob.com/
  7838. * @author alteredq / http://alteredqualia.com/
  7839. *
  7840. * parameters = {
  7841. * color: <hex>,
  7842. * opacity: <float>,
  7843. * map: new THREE.Texture( <Image> ),
  7844. *
  7845. * lightMap: new THREE.Texture( <Image> ),
  7846. *
  7847. * specularMap: new THREE.Texture( <Image> ),
  7848. *
  7849. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7850. * combine: THREE.Multiply,
  7851. * reflectivity: <float>,
  7852. * refractionRatio: <float>,
  7853. *
  7854. * shading: THREE.SmoothShading,
  7855. * blending: THREE.NormalBlending,
  7856. * depthTest: <bool>,
  7857. * depthWrite: <bool>,
  7858. *
  7859. * wireframe: <boolean>,
  7860. * wireframeLinewidth: <float>,
  7861. *
  7862. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7863. *
  7864. * skinning: <bool>,
  7865. * morphTargets: <bool>,
  7866. *
  7867. * fog: <bool>
  7868. * }
  7869. */
  7870. THREE.MeshBasicMaterial = function ( parameters ) {
  7871. THREE.Material.call( this );
  7872. this.color = new THREE.Color( 0xffffff ); // emissive
  7873. this.map = null;
  7874. this.lightMap = null;
  7875. this.specularMap = null;
  7876. this.envMap = null;
  7877. this.combine = THREE.MultiplyOperation;
  7878. this.reflectivity = 1;
  7879. this.refractionRatio = 0.98;
  7880. this.fog = true;
  7881. this.shading = THREE.SmoothShading;
  7882. this.wireframe = false;
  7883. this.wireframeLinewidth = 1;
  7884. this.wireframeLinecap = 'round';
  7885. this.wireframeLinejoin = 'round';
  7886. this.vertexColors = THREE.NoColors;
  7887. this.skinning = false;
  7888. this.morphTargets = false;
  7889. this.setValues( parameters );
  7890. };
  7891. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7892. THREE.MeshBasicMaterial.prototype.clone = function () {
  7893. var material = new THREE.MeshBasicMaterial();
  7894. THREE.Material.prototype.clone.call( this, material );
  7895. material.color.copy( this.color );
  7896. material.map = this.map;
  7897. material.lightMap = this.lightMap;
  7898. material.specularMap = this.specularMap;
  7899. material.envMap = this.envMap;
  7900. material.combine = this.combine;
  7901. material.reflectivity = this.reflectivity;
  7902. material.refractionRatio = this.refractionRatio;
  7903. material.fog = this.fog;
  7904. material.shading = this.shading;
  7905. material.wireframe = this.wireframe;
  7906. material.wireframeLinewidth = this.wireframeLinewidth;
  7907. material.wireframeLinecap = this.wireframeLinecap;
  7908. material.wireframeLinejoin = this.wireframeLinejoin;
  7909. material.vertexColors = this.vertexColors;
  7910. material.skinning = this.skinning;
  7911. material.morphTargets = this.morphTargets;
  7912. return material;
  7913. };
  7914. // File:src/materials/MeshLambertMaterial.js
  7915. /**
  7916. * @author mrdoob / http://mrdoob.com/
  7917. * @author alteredq / http://alteredqualia.com/
  7918. *
  7919. * parameters = {
  7920. * color: <hex>,
  7921. * ambient: <hex>,
  7922. * emissive: <hex>,
  7923. * opacity: <float>,
  7924. *
  7925. * map: new THREE.Texture( <Image> ),
  7926. *
  7927. * lightMap: new THREE.Texture( <Image> ),
  7928. *
  7929. * specularMap: new THREE.Texture( <Image> ),
  7930. *
  7931. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7932. * combine: THREE.Multiply,
  7933. * reflectivity: <float>,
  7934. * refractionRatio: <float>,
  7935. *
  7936. * shading: THREE.SmoothShading,
  7937. * blending: THREE.NormalBlending,
  7938. * depthTest: <bool>,
  7939. * depthWrite: <bool>,
  7940. *
  7941. * wireframe: <boolean>,
  7942. * wireframeLinewidth: <float>,
  7943. *
  7944. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7945. *
  7946. * skinning: <bool>,
  7947. * morphTargets: <bool>,
  7948. * morphNormals: <bool>,
  7949. *
  7950. * fog: <bool>
  7951. * }
  7952. */
  7953. THREE.MeshLambertMaterial = function ( parameters ) {
  7954. THREE.Material.call( this );
  7955. this.color = new THREE.Color( 0xffffff ); // diffuse
  7956. this.ambient = new THREE.Color( 0xffffff );
  7957. this.emissive = new THREE.Color( 0x000000 );
  7958. this.wrapAround = false;
  7959. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  7960. this.map = null;
  7961. this.lightMap = null;
  7962. this.specularMap = null;
  7963. this.envMap = null;
  7964. this.combine = THREE.MultiplyOperation;
  7965. this.reflectivity = 1;
  7966. this.refractionRatio = 0.98;
  7967. this.fog = true;
  7968. this.shading = THREE.SmoothShading;
  7969. this.wireframe = false;
  7970. this.wireframeLinewidth = 1;
  7971. this.wireframeLinecap = 'round';
  7972. this.wireframeLinejoin = 'round';
  7973. this.vertexColors = THREE.NoColors;
  7974. this.skinning = false;
  7975. this.morphTargets = false;
  7976. this.morphNormals = false;
  7977. this.setValues( parameters );
  7978. };
  7979. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  7980. THREE.MeshLambertMaterial.prototype.clone = function () {
  7981. var material = new THREE.MeshLambertMaterial();
  7982. THREE.Material.prototype.clone.call( this, material );
  7983. material.color.copy( this.color );
  7984. material.ambient.copy( this.ambient );
  7985. material.emissive.copy( this.emissive );
  7986. material.wrapAround = this.wrapAround;
  7987. material.wrapRGB.copy( this.wrapRGB );
  7988. material.map = this.map;
  7989. material.lightMap = this.lightMap;
  7990. material.specularMap = this.specularMap;
  7991. material.envMap = this.envMap;
  7992. material.combine = this.combine;
  7993. material.reflectivity = this.reflectivity;
  7994. material.refractionRatio = this.refractionRatio;
  7995. material.fog = this.fog;
  7996. material.shading = this.shading;
  7997. material.wireframe = this.wireframe;
  7998. material.wireframeLinewidth = this.wireframeLinewidth;
  7999. material.wireframeLinecap = this.wireframeLinecap;
  8000. material.wireframeLinejoin = this.wireframeLinejoin;
  8001. material.vertexColors = this.vertexColors;
  8002. material.skinning = this.skinning;
  8003. material.morphTargets = this.morphTargets;
  8004. material.morphNormals = this.morphNormals;
  8005. return material;
  8006. };
  8007. // File:src/materials/MeshPhongMaterial.js
  8008. /**
  8009. * @author mrdoob / http://mrdoob.com/
  8010. * @author alteredq / http://alteredqualia.com/
  8011. *
  8012. * parameters = {
  8013. * color: <hex>,
  8014. * ambient: <hex>,
  8015. * emissive: <hex>,
  8016. * specular: <hex>,
  8017. * shininess: <float>,
  8018. * opacity: <float>,
  8019. *
  8020. * map: new THREE.Texture( <Image> ),
  8021. *
  8022. * lightMap: new THREE.Texture( <Image> ),
  8023. *
  8024. * bumpMap: new THREE.Texture( <Image> ),
  8025. * bumpScale: <float>,
  8026. *
  8027. * normalMap: new THREE.Texture( <Image> ),
  8028. * normalScale: <Vector2>,
  8029. *
  8030. * specularMap: new THREE.Texture( <Image> ),
  8031. *
  8032. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8033. * combine: THREE.Multiply,
  8034. * reflectivity: <float>,
  8035. * refractionRatio: <float>,
  8036. *
  8037. * shading: THREE.SmoothShading,
  8038. * blending: THREE.NormalBlending,
  8039. * depthTest: <bool>,
  8040. * depthWrite: <bool>,
  8041. *
  8042. * wireframe: <boolean>,
  8043. * wireframeLinewidth: <float>,
  8044. *
  8045. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8046. *
  8047. * skinning: <bool>,
  8048. * morphTargets: <bool>,
  8049. * morphNormals: <bool>,
  8050. *
  8051. * fog: <bool>
  8052. * }
  8053. */
  8054. THREE.MeshPhongMaterial = function ( parameters ) {
  8055. THREE.Material.call( this );
  8056. this.color = new THREE.Color( 0xffffff ); // diffuse
  8057. this.ambient = new THREE.Color( 0xffffff );
  8058. this.emissive = new THREE.Color( 0x000000 );
  8059. this.specular = new THREE.Color( 0x111111 );
  8060. this.shininess = 30;
  8061. this.metal = false;
  8062. this.wrapAround = false;
  8063. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  8064. this.map = null;
  8065. this.lightMap = null;
  8066. this.bumpMap = null;
  8067. this.bumpScale = 1;
  8068. this.normalMap = null;
  8069. this.normalScale = new THREE.Vector2( 1, 1 );
  8070. this.specularMap = null;
  8071. this.envMap = null;
  8072. this.combine = THREE.MultiplyOperation;
  8073. this.reflectivity = 1;
  8074. this.refractionRatio = 0.98;
  8075. this.fog = true;
  8076. this.shading = THREE.SmoothShading;
  8077. this.wireframe = false;
  8078. this.wireframeLinewidth = 1;
  8079. this.wireframeLinecap = 'round';
  8080. this.wireframeLinejoin = 'round';
  8081. this.vertexColors = THREE.NoColors;
  8082. this.skinning = false;
  8083. this.morphTargets = false;
  8084. this.morphNormals = false;
  8085. this.setValues( parameters );
  8086. };
  8087. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  8088. THREE.MeshPhongMaterial.prototype.clone = function () {
  8089. var material = new THREE.MeshPhongMaterial();
  8090. THREE.Material.prototype.clone.call( this, material );
  8091. material.color.copy( this.color );
  8092. material.ambient.copy( this.ambient );
  8093. material.emissive.copy( this.emissive );
  8094. material.specular.copy( this.specular );
  8095. material.shininess = this.shininess;
  8096. material.metal = this.metal;
  8097. material.wrapAround = this.wrapAround;
  8098. material.wrapRGB.copy( this.wrapRGB );
  8099. material.map = this.map;
  8100. material.lightMap = this.lightMap;
  8101. material.bumpMap = this.bumpMap;
  8102. material.bumpScale = this.bumpScale;
  8103. material.normalMap = this.normalMap;
  8104. material.normalScale.copy( this.normalScale );
  8105. material.specularMap = this.specularMap;
  8106. material.envMap = this.envMap;
  8107. material.combine = this.combine;
  8108. material.reflectivity = this.reflectivity;
  8109. material.refractionRatio = this.refractionRatio;
  8110. material.fog = this.fog;
  8111. material.shading = this.shading;
  8112. material.wireframe = this.wireframe;
  8113. material.wireframeLinewidth = this.wireframeLinewidth;
  8114. material.wireframeLinecap = this.wireframeLinecap;
  8115. material.wireframeLinejoin = this.wireframeLinejoin;
  8116. material.vertexColors = this.vertexColors;
  8117. material.skinning = this.skinning;
  8118. material.morphTargets = this.morphTargets;
  8119. material.morphNormals = this.morphNormals;
  8120. return material;
  8121. };
  8122. // File:src/materials/MeshDepthMaterial.js
  8123. /**
  8124. * @author mrdoob / http://mrdoob.com/
  8125. * @author alteredq / http://alteredqualia.com/
  8126. *
  8127. * parameters = {
  8128. * opacity: <float>,
  8129. *
  8130. * blending: THREE.NormalBlending,
  8131. * depthTest: <bool>,
  8132. * depthWrite: <bool>,
  8133. *
  8134. * wireframe: <boolean>,
  8135. * wireframeLinewidth: <float>
  8136. * }
  8137. */
  8138. THREE.MeshDepthMaterial = function ( parameters ) {
  8139. THREE.Material.call( this );
  8140. this.morphTargets = false;
  8141. this.wireframe = false;
  8142. this.wireframeLinewidth = 1;
  8143. this.setValues( parameters );
  8144. };
  8145. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  8146. THREE.MeshDepthMaterial.prototype.clone = function () {
  8147. var material = new THREE.MeshDepthMaterial();
  8148. THREE.Material.prototype.clone.call( this, material );
  8149. material.wireframe = this.wireframe;
  8150. material.wireframeLinewidth = this.wireframeLinewidth;
  8151. return material;
  8152. };
  8153. // File:src/materials/MeshNormalMaterial.js
  8154. /**
  8155. * @author mrdoob / http://mrdoob.com/
  8156. *
  8157. * parameters = {
  8158. * opacity: <float>,
  8159. *
  8160. * shading: THREE.FlatShading,
  8161. * blending: THREE.NormalBlending,
  8162. * depthTest: <bool>,
  8163. * depthWrite: <bool>,
  8164. *
  8165. * wireframe: <boolean>,
  8166. * wireframeLinewidth: <float>
  8167. * }
  8168. */
  8169. THREE.MeshNormalMaterial = function ( parameters ) {
  8170. THREE.Material.call( this, parameters );
  8171. this.shading = THREE.FlatShading;
  8172. this.wireframe = false;
  8173. this.wireframeLinewidth = 1;
  8174. this.morphTargets = false;
  8175. this.setValues( parameters );
  8176. };
  8177. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  8178. THREE.MeshNormalMaterial.prototype.clone = function () {
  8179. var material = new THREE.MeshNormalMaterial();
  8180. THREE.Material.prototype.clone.call( this, material );
  8181. material.shading = this.shading;
  8182. material.wireframe = this.wireframe;
  8183. material.wireframeLinewidth = this.wireframeLinewidth;
  8184. return material;
  8185. };
  8186. // File:src/materials/MeshFaceMaterial.js
  8187. /**
  8188. * @author mrdoob / http://mrdoob.com/
  8189. */
  8190. THREE.MeshFaceMaterial = function ( materials ) {
  8191. this.materials = materials instanceof Array ? materials : [];
  8192. };
  8193. THREE.MeshFaceMaterial.prototype.clone = function () {
  8194. var material = new THREE.MeshFaceMaterial();
  8195. for ( var i = 0; i < this.materials.length; i ++ ) {
  8196. material.materials.push( this.materials[ i ].clone() );
  8197. }
  8198. return material;
  8199. };
  8200. // File:src/materials/PointCloudMaterial.js
  8201. /**
  8202. * @author mrdoob / http://mrdoob.com/
  8203. * @author alteredq / http://alteredqualia.com/
  8204. *
  8205. * parameters = {
  8206. * color: <hex>,
  8207. * opacity: <float>,
  8208. * map: new THREE.Texture( <Image> ),
  8209. *
  8210. * size: <float>,
  8211. *
  8212. * blending: THREE.NormalBlending,
  8213. * depthTest: <bool>,
  8214. * depthWrite: <bool>,
  8215. *
  8216. * vertexColors: <bool>,
  8217. *
  8218. * fog: <bool>
  8219. * }
  8220. */
  8221. THREE.PointCloudMaterial = function ( parameters ) {
  8222. THREE.Material.call( this );
  8223. this.color = new THREE.Color( 0xffffff );
  8224. this.map = null;
  8225. this.size = 1;
  8226. this.sizeAttenuation = true;
  8227. this.vertexColors = THREE.NoColors;
  8228. this.fog = true;
  8229. this.setValues( parameters );
  8230. };
  8231. THREE.PointCloudMaterial.prototype = Object.create( THREE.Material.prototype );
  8232. THREE.PointCloudMaterial.prototype.clone = function () {
  8233. var material = new THREE.PointCloudMaterial();
  8234. THREE.Material.prototype.clone.call( this, material );
  8235. material.color.copy( this.color );
  8236. material.map = this.map;
  8237. material.size = this.size;
  8238. material.sizeAttenuation = this.sizeAttenuation;
  8239. material.vertexColors = this.vertexColors;
  8240. material.fog = this.fog;
  8241. return material;
  8242. };
  8243. // backwards compatibility
  8244. THREE.ParticleSystemMaterial = function ( parameters ) {
  8245. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointCloudMaterial.' );
  8246. return new THREE.PointCloudMaterial( parameters );
  8247. }
  8248. // File:src/materials/ShaderMaterial.js
  8249. /**
  8250. * @author alteredq / http://alteredqualia.com/
  8251. *
  8252. * parameters = {
  8253. * fragmentShader: <string>,
  8254. * vertexShader: <string>,
  8255. *
  8256. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  8257. *
  8258. * defines: { "label" : "value" },
  8259. *
  8260. * shading: THREE.SmoothShading,
  8261. * blending: THREE.NormalBlending,
  8262. * depthTest: <bool>,
  8263. * depthWrite: <bool>,
  8264. *
  8265. * wireframe: <boolean>,
  8266. * wireframeLinewidth: <float>,
  8267. *
  8268. * lights: <bool>,
  8269. *
  8270. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8271. *
  8272. * skinning: <bool>,
  8273. * morphTargets: <bool>,
  8274. * morphNormals: <bool>,
  8275. *
  8276. * fog: <bool>
  8277. * }
  8278. */
  8279. THREE.ShaderMaterial = function ( parameters ) {
  8280. THREE.Material.call( this );
  8281. this.fragmentShader = 'void main() {}';
  8282. this.vertexShader = 'void main() {}';
  8283. this.uniforms = {};
  8284. this.defines = {};
  8285. this.attributes = null;
  8286. this.shading = THREE.SmoothShading;
  8287. this.linewidth = 1;
  8288. this.wireframe = false;
  8289. this.wireframeLinewidth = 1;
  8290. this.fog = false; // set to use scene fog
  8291. this.lights = false; // set to use scene lights
  8292. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  8293. this.skinning = false; // set to use skinning attribute streams
  8294. this.morphTargets = false; // set to use morph targets
  8295. this.morphNormals = false; // set to use morph normals
  8296. // When rendered geometry doesn't include these attributes but the material does,
  8297. // use these default values in WebGL. This avoids errors when buffer data is missing.
  8298. this.defaultAttributeValues = {
  8299. 'color': [ 1, 1, 1 ],
  8300. 'uv': [ 0, 0 ],
  8301. 'uv2': [ 0, 0 ]
  8302. };
  8303. this.index0AttributeName = undefined;
  8304. this.setValues( parameters );
  8305. };
  8306. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  8307. THREE.ShaderMaterial.prototype.clone = function () {
  8308. var material = new THREE.ShaderMaterial();
  8309. THREE.Material.prototype.clone.call( this, material );
  8310. material.fragmentShader = this.fragmentShader;
  8311. material.vertexShader = this.vertexShader;
  8312. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  8313. material.attributes = this.attributes;
  8314. material.defines = this.defines;
  8315. material.shading = this.shading;
  8316. material.wireframe = this.wireframe;
  8317. material.wireframeLinewidth = this.wireframeLinewidth;
  8318. material.fog = this.fog;
  8319. material.lights = this.lights;
  8320. material.vertexColors = this.vertexColors;
  8321. material.skinning = this.skinning;
  8322. material.morphTargets = this.morphTargets;
  8323. material.morphNormals = this.morphNormals;
  8324. return material;
  8325. };
  8326. // File:src/materials/RawShaderMaterial.js
  8327. /**
  8328. * @author mrdoob / http://mrdoob.com/
  8329. */
  8330. THREE.RawShaderMaterial = function ( parameters ) {
  8331. THREE.ShaderMaterial.call( this, parameters );
  8332. };
  8333. THREE.RawShaderMaterial.prototype = Object.create( THREE.ShaderMaterial.prototype );
  8334. THREE.RawShaderMaterial.prototype.clone = function () {
  8335. var material = new THREE.RawShaderMaterial();
  8336. THREE.ShaderMaterial.prototype.clone.call( this, material );
  8337. return material;
  8338. };
  8339. // File:src/materials/SpriteMaterial.js
  8340. /**
  8341. * @author alteredq / http://alteredqualia.com/
  8342. *
  8343. * parameters = {
  8344. * color: <hex>,
  8345. * opacity: <float>,
  8346. * map: new THREE.Texture( <Image> ),
  8347. *
  8348. * blending: THREE.NormalBlending,
  8349. * depthTest: <bool>,
  8350. * depthWrite: <bool>,
  8351. *
  8352. * uvOffset: new THREE.Vector2(),
  8353. * uvScale: new THREE.Vector2(),
  8354. *
  8355. * fog: <bool>
  8356. * }
  8357. */
  8358. THREE.SpriteMaterial = function ( parameters ) {
  8359. THREE.Material.call( this );
  8360. // defaults
  8361. this.color = new THREE.Color( 0xffffff );
  8362. this.map = null;
  8363. this.rotation = 0;
  8364. this.fog = false;
  8365. // set parameters
  8366. this.setValues( parameters );
  8367. };
  8368. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  8369. THREE.SpriteMaterial.prototype.clone = function () {
  8370. var material = new THREE.SpriteMaterial();
  8371. THREE.Material.prototype.clone.call( this, material );
  8372. material.color.copy( this.color );
  8373. material.map = this.map;
  8374. material.rotation = this.rotation;
  8375. material.fog = this.fog;
  8376. return material;
  8377. };
  8378. // File:src/materials/SpriteCanvasMaterial.js
  8379. /**
  8380. * @author mrdoob / http://mrdoob.com/
  8381. *
  8382. * parameters = {
  8383. * color: <hex>,
  8384. * program: <function>,
  8385. * opacity: <float>,
  8386. * blending: THREE.NormalBlending
  8387. * }
  8388. */
  8389. THREE.SpriteCanvasMaterial = function ( parameters ) {
  8390. THREE.Material.call( this );
  8391. this.color = new THREE.Color( 0xffffff );
  8392. this.program = function ( context, color ) {};
  8393. this.setValues( parameters );
  8394. };
  8395. THREE.SpriteCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  8396. THREE.SpriteCanvasMaterial.prototype.clone = function () {
  8397. var material = new THREE.SpriteCanvasMaterial();
  8398. THREE.Material.prototype.clone.call( this, material );
  8399. material.color.copy( this.color );
  8400. material.program = this.program;
  8401. return material;
  8402. };
  8403. // backwards compatibility
  8404. THREE.ParticleCanvasMaterial = THREE.SpriteCanvasMaterial;
  8405. // File:src/textures/Texture.js
  8406. /**
  8407. * @author mrdoob / http://mrdoob.com/
  8408. * @author alteredq / http://alteredqualia.com/
  8409. * @author szimek / https://github.com/szimek/
  8410. */
  8411. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  8412. this.id = THREE.TextureIdCount ++;
  8413. this.uuid = THREE.Math.generateUUID();
  8414. this.name = '';
  8415. this.image = image !== undefined ? image : THREE.Texture.DEFAULT_IMAGE;
  8416. this.mipmaps = [];
  8417. this.mapping = mapping !== undefined ? mapping : THREE.Texture.DEFAULT_MAPPING;
  8418. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  8419. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  8420. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  8421. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  8422. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  8423. this.format = format !== undefined ? format : THREE.RGBAFormat;
  8424. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  8425. this.offset = new THREE.Vector2( 0, 0 );
  8426. this.repeat = new THREE.Vector2( 1, 1 );
  8427. this.generateMipmaps = true;
  8428. this.premultiplyAlpha = false;
  8429. this.flipY = true;
  8430. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  8431. this._needsUpdate = false;
  8432. this.onUpdate = null;
  8433. };
  8434. THREE.Texture.DEFAULT_IMAGE = undefined;
  8435. THREE.Texture.DEFAULT_MAPPING = new THREE.UVMapping();
  8436. THREE.Texture.prototype = {
  8437. constructor: THREE.Texture,
  8438. get needsUpdate () {
  8439. return this._needsUpdate;
  8440. },
  8441. set needsUpdate ( value ) {
  8442. if ( value === true ) this.update();
  8443. this._needsUpdate = value;
  8444. },
  8445. clone: function ( texture ) {
  8446. if ( texture === undefined ) texture = new THREE.Texture();
  8447. texture.image = this.image;
  8448. texture.mipmaps = this.mipmaps.slice( 0 );
  8449. texture.mapping = this.mapping;
  8450. texture.wrapS = this.wrapS;
  8451. texture.wrapT = this.wrapT;
  8452. texture.magFilter = this.magFilter;
  8453. texture.minFilter = this.minFilter;
  8454. texture.anisotropy = this.anisotropy;
  8455. texture.format = this.format;
  8456. texture.type = this.type;
  8457. texture.offset.copy( this.offset );
  8458. texture.repeat.copy( this.repeat );
  8459. texture.generateMipmaps = this.generateMipmaps;
  8460. texture.premultiplyAlpha = this.premultiplyAlpha;
  8461. texture.flipY = this.flipY;
  8462. texture.unpackAlignment = this.unpackAlignment;
  8463. return texture;
  8464. },
  8465. update: function () {
  8466. this.dispatchEvent( { type: 'update' } );
  8467. },
  8468. dispose: function () {
  8469. this.dispatchEvent( { type: 'dispose' } );
  8470. }
  8471. };
  8472. THREE.EventDispatcher.prototype.apply( THREE.Texture.prototype );
  8473. THREE.TextureIdCount = 0;
  8474. // File:src/textures/CubeTexture.js
  8475. /**
  8476. * @author mrdoob / http://mrdoob.com/
  8477. */
  8478. THREE.CubeTexture = function ( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  8479. THREE.Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8480. this.images = images;
  8481. };
  8482. THREE.CubeTexture.prototype = Object.create( THREE.Texture.prototype );
  8483. THREE.CubeTexture.clone = function ( texture ) {
  8484. if ( texture === undefined ) texture = new THREE.CubeTexture();
  8485. THREE.Texture.prototype.clone.call( this, texture );
  8486. texture.images = this.images;
  8487. return texture;
  8488. };
  8489. // File:src/textures/CompressedTexture.js
  8490. /**
  8491. * @author alteredq / http://alteredqualia.com/
  8492. */
  8493. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  8494. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8495. this.image = { width: width, height: height };
  8496. this.mipmaps = mipmaps;
  8497. this.generateMipmaps = false; // WebGL currently can't generate mipmaps for compressed textures, they must be embedded in DDS file
  8498. };
  8499. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  8500. THREE.CompressedTexture.prototype.clone = function () {
  8501. var texture = new THREE.CompressedTexture();
  8502. THREE.Texture.prototype.clone.call( this, texture );
  8503. return texture;
  8504. };
  8505. // File:src/textures/DataTexture.js
  8506. /**
  8507. * @author alteredq / http://alteredqualia.com/
  8508. */
  8509. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  8510. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8511. this.image = { data: data, width: width, height: height };
  8512. };
  8513. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  8514. THREE.DataTexture.prototype.clone = function () {
  8515. var texture = new THREE.DataTexture();
  8516. THREE.Texture.prototype.clone.call( this, texture );
  8517. return texture;
  8518. };
  8519. // File:src/objects/PointCloud.js
  8520. /**
  8521. * @author alteredq / http://alteredqualia.com/
  8522. */
  8523. THREE.PointCloud = function ( geometry, material ) {
  8524. THREE.Object3D.call( this );
  8525. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  8526. this.material = material !== undefined ? material : new THREE.PointCloudMaterial( { color: Math.random() * 0xffffff } );
  8527. this.sortParticles = false;
  8528. };
  8529. THREE.PointCloud.prototype = Object.create( THREE.Object3D.prototype );
  8530. THREE.PointCloud.prototype.raycast = ( function () {
  8531. var inverseMatrix = new THREE.Matrix4();
  8532. var ray = new THREE.Ray();
  8533. return function ( raycaster, intersects ) {
  8534. var object = this;
  8535. var geometry = object.geometry;
  8536. var threshold = raycaster.params.PointCloud.threshold;
  8537. inverseMatrix.getInverse( this.matrixWorld );
  8538. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  8539. if ( geometry.boundingBox !== null ) {
  8540. if ( ray.isIntersectionBox( geometry.boundingBox ) === false ) {
  8541. return;
  8542. }
  8543. }
  8544. var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  8545. var position = new THREE.Vector3();
  8546. var testPoint = function ( point, index ) {
  8547. var rayPointDistance = ray.distanceToPoint( point );
  8548. if ( rayPointDistance < localThreshold ) {
  8549. var intersectPoint = ray.closestPointToPoint( point );
  8550. intersectPoint.applyMatrix4( object.matrixWorld );
  8551. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  8552. intersects.push( {
  8553. distance: distance,
  8554. distanceToRay: rayPointDistance,
  8555. point: intersectPoint.clone(),
  8556. index: index,
  8557. face: null,
  8558. object: object
  8559. } );
  8560. }
  8561. };
  8562. if ( geometry instanceof THREE.BufferGeometry ) {
  8563. var attributes = geometry.attributes;
  8564. var positions = attributes.position.array;
  8565. if ( attributes.index !== undefined ) {
  8566. var indices = attributes.index.array;
  8567. var offsets = geometry.offsets;
  8568. if ( offsets.length === 0 ) {
  8569. var offset = {
  8570. start: 0,
  8571. count: indices.length,
  8572. index: 0
  8573. };
  8574. offsets = [ offset ];
  8575. }
  8576. for ( var oi = 0, ol = offsets.length; oi < ol; ++oi ) {
  8577. var start = offsets[ oi ].start;
  8578. var count = offsets[ oi ].count;
  8579. var index = offsets[ oi ].index;
  8580. for ( var i = start, il = start + count; i < il; i ++ ) {
  8581. var a = index + indices[ i ];
  8582. position.set(
  8583. positions[ a * 3 ],
  8584. positions[ a * 3 + 1 ],
  8585. positions[ a * 3 + 2 ]
  8586. );
  8587. testPoint( position, a );
  8588. }
  8589. }
  8590. } else {
  8591. var pointCount = positions.length / 3;
  8592. for ( var i = 0; i < pointCount; i ++ ) {
  8593. position.set(
  8594. positions[ 3 * i ],
  8595. positions[ 3 * i + 1 ],
  8596. positions[ 3 * i + 2 ]
  8597. );
  8598. testPoint( position, i );
  8599. }
  8600. }
  8601. } else {
  8602. var vertices = this.geometry.vertices;
  8603. for ( var i = 0; i < vertices.length; i ++ ) {
  8604. testPoint( vertices[ i ], i );
  8605. }
  8606. }
  8607. };
  8608. }() );
  8609. THREE.PointCloud.prototype.clone = function ( object ) {
  8610. if ( object === undefined ) object = new THREE.PointCloud( this.geometry, this.material );
  8611. object.sortParticles = this.sortParticles;
  8612. THREE.Object3D.prototype.clone.call( this, object );
  8613. return object;
  8614. };
  8615. // Backwards compatibility
  8616. THREE.ParticleSystem = function ( geometry, material ) {
  8617. console.warn( 'THREE.ParticleSystem has been renamed to THREE.PointCloud.' );
  8618. return new THREE.PointCloud( geometry, material );
  8619. };
  8620. // File:src/objects/Line.js
  8621. /**
  8622. * @author mrdoob / http://mrdoob.com/
  8623. */
  8624. THREE.Line = function ( geometry, material, type ) {
  8625. THREE.Object3D.call( this );
  8626. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  8627. this.material = material !== undefined ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  8628. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  8629. };
  8630. THREE.LineStrip = 0;
  8631. THREE.LinePieces = 1;
  8632. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  8633. THREE.Line.prototype.raycast = ( function () {
  8634. var inverseMatrix = new THREE.Matrix4();
  8635. var ray = new THREE.Ray();
  8636. var sphere = new THREE.Sphere();
  8637. return function ( raycaster, intersects ) {
  8638. var precision = raycaster.linePrecision;
  8639. var precisionSq = precision * precision;
  8640. var geometry = this.geometry;
  8641. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  8642. // Checking boundingSphere distance to ray
  8643. sphere.copy( geometry.boundingSphere );
  8644. sphere.applyMatrix4( this.matrixWorld );
  8645. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  8646. return;
  8647. }
  8648. inverseMatrix.getInverse( this.matrixWorld );
  8649. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  8650. /* if ( geometry instanceof THREE.BufferGeometry ) {
  8651. } else */ if ( geometry instanceof THREE.Geometry ) {
  8652. var vertices = geometry.vertices;
  8653. var nbVertices = vertices.length;
  8654. var interSegment = new THREE.Vector3();
  8655. var interRay = new THREE.Vector3();
  8656. var step = this.type === THREE.LineStrip ? 1 : 2;
  8657. for ( var i = 0; i < nbVertices - 1; i = i + step ) {
  8658. var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  8659. if ( distSq > precisionSq ) continue;
  8660. var distance = ray.origin.distanceTo( interRay );
  8661. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  8662. intersects.push( {
  8663. distance: distance,
  8664. // What do we want? intersection point on the ray or on the segment??
  8665. // point: raycaster.ray.at( distance ),
  8666. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  8667. face: null,
  8668. faceIndex: null,
  8669. object: this
  8670. } );
  8671. }
  8672. }
  8673. };
  8674. }() );
  8675. THREE.Line.prototype.clone = function ( object ) {
  8676. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  8677. THREE.Object3D.prototype.clone.call( this, object );
  8678. return object;
  8679. };
  8680. // File:src/objects/Mesh.js
  8681. /**
  8682. * @author mrdoob / http://mrdoob.com/
  8683. * @author alteredq / http://alteredqualia.com/
  8684. * @author mikael emtinger / http://gomo.se/
  8685. * @author jonobr1 / http://jonobr1.com/
  8686. */
  8687. THREE.Mesh = function ( geometry, material ) {
  8688. THREE.Object3D.call( this );
  8689. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  8690. this.material = material !== undefined ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  8691. this.updateMorphTargets();
  8692. };
  8693. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  8694. THREE.Mesh.prototype.updateMorphTargets = function () {
  8695. if ( this.geometry.morphTargets !== undefined && this.geometry.morphTargets.length > 0 ) {
  8696. this.morphTargetBase = - 1;
  8697. this.morphTargetForcedOrder = [];
  8698. this.morphTargetInfluences = [];
  8699. this.morphTargetDictionary = {};
  8700. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  8701. this.morphTargetInfluences.push( 0 );
  8702. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  8703. }
  8704. }
  8705. };
  8706. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  8707. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  8708. return this.morphTargetDictionary[ name ];
  8709. }
  8710. console.log( 'THREE.Mesh.getMorphTargetIndexByName: morph target ' + name + ' does not exist. Returning 0.' );
  8711. return 0;
  8712. };
  8713. THREE.Mesh.prototype.raycast = ( function () {
  8714. var inverseMatrix = new THREE.Matrix4();
  8715. var ray = new THREE.Ray();
  8716. var sphere = new THREE.Sphere();
  8717. var vA = new THREE.Vector3();
  8718. var vB = new THREE.Vector3();
  8719. var vC = new THREE.Vector3();
  8720. return function ( raycaster, intersects ) {
  8721. var geometry = this.geometry;
  8722. // Checking boundingSphere distance to ray
  8723. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  8724. sphere.copy( geometry.boundingSphere );
  8725. sphere.applyMatrix4( this.matrixWorld );
  8726. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  8727. return;
  8728. }
  8729. // Check boundingBox before continuing
  8730. inverseMatrix.getInverse( this.matrixWorld );
  8731. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  8732. if ( geometry.boundingBox !== null ) {
  8733. if ( ray.isIntersectionBox( geometry.boundingBox ) === false ) {
  8734. return;
  8735. }
  8736. }
  8737. if ( geometry instanceof THREE.BufferGeometry ) {
  8738. var material = this.material;
  8739. if ( material === undefined ) return;
  8740. var attributes = geometry.attributes;
  8741. var a, b, c;
  8742. var precision = raycaster.precision;
  8743. if ( attributes.index !== undefined ) {
  8744. var indices = attributes.index.array;
  8745. var positions = attributes.position.array;
  8746. var offsets = geometry.offsets;
  8747. if ( offsets.length === 0 ) {
  8748. offsets = [ { start: 0, count: indices.length, index: 0 } ];
  8749. }
  8750. for ( var oi = 0, ol = offsets.length; oi < ol; ++oi ) {
  8751. var start = offsets[ oi ].start;
  8752. var count = offsets[ oi ].count;
  8753. var index = offsets[ oi ].index;
  8754. for ( var i = start, il = start + count; i < il; i += 3 ) {
  8755. a = index + indices[ i ];
  8756. b = index + indices[ i + 1 ];
  8757. c = index + indices[ i + 2 ];
  8758. vA.set(
  8759. positions[ a * 3 ],
  8760. positions[ a * 3 + 1 ],
  8761. positions[ a * 3 + 2 ]
  8762. );
  8763. vB.set(
  8764. positions[ b * 3 ],
  8765. positions[ b * 3 + 1 ],
  8766. positions[ b * 3 + 2 ]
  8767. );
  8768. vC.set(
  8769. positions[ c * 3 ],
  8770. positions[ c * 3 + 1 ],
  8771. positions[ c * 3 + 2 ]
  8772. );
  8773. if ( material.side === THREE.BackSide ) {
  8774. var intersectionPoint = ray.intersectTriangle( vC, vB, vA, true );
  8775. } else {
  8776. var intersectionPoint = ray.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );
  8777. }
  8778. if ( intersectionPoint === null ) continue;
  8779. intersectionPoint.applyMatrix4( this.matrixWorld );
  8780. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  8781. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  8782. intersects.push( {
  8783. distance: distance,
  8784. point: intersectionPoint,
  8785. indices: [ a, b, c ],
  8786. face: null,
  8787. faceIndex: null,
  8788. object: this
  8789. } );
  8790. }
  8791. }
  8792. } else {
  8793. var positions = attributes.position.array;
  8794. for ( var i = 0, j = 0, il = positions.length; i < il; i += 3, j += 9 ) {
  8795. a = i;
  8796. b = i + 1;
  8797. c = i + 2;
  8798. vA.set(
  8799. positions[ j ],
  8800. positions[ j + 1 ],
  8801. positions[ j + 2 ]
  8802. );
  8803. vB.set(
  8804. positions[ j + 3 ],
  8805. positions[ j + 4 ],
  8806. positions[ j + 5 ]
  8807. );
  8808. vC.set(
  8809. positions[ j + 6 ],
  8810. positions[ j + 7 ],
  8811. positions[ j + 8 ]
  8812. );
  8813. if ( material.side === THREE.BackSide ) {
  8814. var intersectionPoint = ray.intersectTriangle( vC, vB, vA, true );
  8815. } else {
  8816. var intersectionPoint = ray.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );
  8817. }
  8818. if ( intersectionPoint === null ) continue;
  8819. intersectionPoint.applyMatrix4( this.matrixWorld );
  8820. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  8821. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  8822. intersects.push( {
  8823. distance: distance,
  8824. point: intersectionPoint,
  8825. indices: [ a, b, c ],
  8826. face: null,
  8827. faceIndex: null,
  8828. object: this
  8829. } );
  8830. }
  8831. }
  8832. } else if ( geometry instanceof THREE.Geometry ) {
  8833. var isFaceMaterial = this.material instanceof THREE.MeshFaceMaterial;
  8834. var objectMaterials = isFaceMaterial === true ? this.material.materials : null;
  8835. var a, b, c, d;
  8836. var precision = raycaster.precision;
  8837. var vertices = geometry.vertices;
  8838. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  8839. var face = geometry.faces[ f ];
  8840. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : this.material;
  8841. if ( material === undefined ) continue;
  8842. a = vertices[ face.a ];
  8843. b = vertices[ face.b ];
  8844. c = vertices[ face.c ];
  8845. if ( material.morphTargets === true ) {
  8846. var morphTargets = geometry.morphTargets;
  8847. var morphInfluences = this.morphTargetInfluences;
  8848. vA.set( 0, 0, 0 );
  8849. vB.set( 0, 0, 0 );
  8850. vC.set( 0, 0, 0 );
  8851. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  8852. var influence = morphInfluences[ t ];
  8853. if ( influence === 0 ) continue;
  8854. var targets = morphTargets[ t ].vertices;
  8855. vA.x += ( targets[ face.a ].x - a.x ) * influence;
  8856. vA.y += ( targets[ face.a ].y - a.y ) * influence;
  8857. vA.z += ( targets[ face.a ].z - a.z ) * influence;
  8858. vB.x += ( targets[ face.b ].x - b.x ) * influence;
  8859. vB.y += ( targets[ face.b ].y - b.y ) * influence;
  8860. vB.z += ( targets[ face.b ].z - b.z ) * influence;
  8861. vC.x += ( targets[ face.c ].x - c.x ) * influence;
  8862. vC.y += ( targets[ face.c ].y - c.y ) * influence;
  8863. vC.z += ( targets[ face.c ].z - c.z ) * influence;
  8864. }
  8865. vA.add( a );
  8866. vB.add( b );
  8867. vC.add( c );
  8868. a = vA;
  8869. b = vB;
  8870. c = vC;
  8871. }
  8872. if ( material.side === THREE.BackSide ) {
  8873. var intersectionPoint = ray.intersectTriangle( c, b, a, true );
  8874. } else {
  8875. var intersectionPoint = ray.intersectTriangle( a, b, c, material.side !== THREE.DoubleSide );
  8876. }
  8877. if ( intersectionPoint === null ) continue;
  8878. intersectionPoint.applyMatrix4( this.matrixWorld );
  8879. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  8880. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  8881. intersects.push( {
  8882. distance: distance,
  8883. point: intersectionPoint,
  8884. face: face,
  8885. faceIndex: f,
  8886. object: this
  8887. } );
  8888. }
  8889. }
  8890. };
  8891. }() );
  8892. THREE.Mesh.prototype.clone = function ( object, recursive ) {
  8893. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  8894. THREE.Object3D.prototype.clone.call( this, object, recursive );
  8895. return object;
  8896. };
  8897. // File:src/objects/Bone.js
  8898. /**
  8899. * @author mikael emtinger / http://gomo.se/
  8900. * @author alteredq / http://alteredqualia.com/
  8901. */
  8902. THREE.Bone = function ( belongsToSkin ) {
  8903. THREE.Object3D.call( this );
  8904. this.skin = belongsToSkin;
  8905. this.skinMatrix = new THREE.Matrix4();
  8906. this.accumulatedRotWeight = 0;
  8907. this.accumulatedPosWeight = 0;
  8908. this.accumulatedSclWeight = 0;
  8909. };
  8910. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  8911. THREE.Bone.prototype.update = function ( parentSkinMatrix, forceUpdate ) {
  8912. // update local
  8913. if ( this.matrixAutoUpdate ) {
  8914. forceUpdate |= this.updateMatrix();
  8915. }
  8916. // update skin matrix
  8917. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  8918. if ( parentSkinMatrix ) {
  8919. this.skinMatrix.multiplyMatrices( parentSkinMatrix, this.matrix );
  8920. } else {
  8921. this.skinMatrix.copy( this.matrix );
  8922. }
  8923. this.matrixWorldNeedsUpdate = false;
  8924. forceUpdate = true;
  8925. // Reset weights to be re-accumulated in the next frame
  8926. this.accumulatedRotWeight = 0;
  8927. this.accumulatedPosWeight = 0;
  8928. this.accumulatedSclWeight = 0;
  8929. }
  8930. // update children
  8931. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  8932. this.children[ i ].update( this.skinMatrix, forceUpdate );
  8933. }
  8934. };
  8935. // File:src/objects/Skeleton.js
  8936. /**
  8937. * @author mikael emtinger / http://gomo.se/
  8938. * @author alteredq / http://alteredqualia.com/
  8939. * @author michael guerrero / http://realitymeltdown.com
  8940. */
  8941. THREE.Skeleton = function ( boneList, useVertexTexture ) {
  8942. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  8943. // init bones
  8944. this.bones = [];
  8945. this.boneMatrices = [];
  8946. var bone, gbone, p, q, s;
  8947. if ( boneList !== undefined ) {
  8948. for ( var b = 0; b < boneList.length; ++b ) {
  8949. gbone = boneList[ b ];
  8950. p = gbone.pos;
  8951. q = gbone.rotq;
  8952. s = gbone.scl;
  8953. bone = this.addBone();
  8954. bone.name = gbone.name;
  8955. bone.position.set( p[ 0 ], p[ 1 ], p[ 2 ] );
  8956. bone.quaternion.set( q[ 0 ], q[ 1 ], q[ 2 ], q[ 3 ] );
  8957. if ( s !== undefined ) {
  8958. bone.scale.set( s[ 0 ], s[ 1 ], s[ 2 ] );
  8959. } else {
  8960. bone.scale.set( 1, 1, 1 );
  8961. }
  8962. }
  8963. for ( var b = 0; b < boneList.length; ++b ) {
  8964. gbone = boneList[ b ];
  8965. if ( gbone.parent !== - 1 ) {
  8966. this.bones[ gbone.parent ].add( this.bones[ b ] );
  8967. }
  8968. }
  8969. //
  8970. var nBones = this.bones.length;
  8971. if ( this.useVertexTexture ) {
  8972. // layout (1 matrix = 4 pixels)
  8973. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  8974. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  8975. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  8976. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  8977. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  8978. var size;
  8979. if ( nBones > 256 )
  8980. size = 64;
  8981. else if ( nBones > 64 )
  8982. size = 32;
  8983. else if ( nBones > 16 )
  8984. size = 16;
  8985. else
  8986. size = 8;
  8987. this.boneTextureWidth = size;
  8988. this.boneTextureHeight = size;
  8989. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  8990. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  8991. this.boneTexture.minFilter = THREE.NearestFilter;
  8992. this.boneTexture.magFilter = THREE.NearestFilter;
  8993. this.boneTexture.generateMipmaps = false;
  8994. this.boneTexture.flipY = false;
  8995. } else {
  8996. this.boneMatrices = new Float32Array( 16 * nBones );
  8997. }
  8998. }
  8999. };
  9000. THREE.Skeleton.prototype = Object.create( THREE.Mesh.prototype );
  9001. THREE.Skeleton.prototype.addBone = function ( bone ) {
  9002. if ( bone === undefined ) {
  9003. bone = new THREE.Bone( this );
  9004. }
  9005. this.bones.push( bone );
  9006. return bone;
  9007. };
  9008. THREE.Skeleton.prototype.calculateInverses = function ( bone ) {
  9009. this.boneInverses = [];
  9010. for ( var b = 0, bl = this.bones.length; b < bl; ++b ) {
  9011. var inverse = new THREE.Matrix4();
  9012. inverse.getInverse( this.bones[ b ].skinMatrix );
  9013. this.boneInverses.push( inverse );
  9014. }
  9015. };
  9016. // File:src/objects/SkinnedMesh.js
  9017. /**
  9018. * @author mikael emtinger / http://gomo.se/
  9019. * @author alteredq / http://alteredqualia.com/
  9020. */
  9021. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  9022. THREE.Mesh.call( this, geometry, material );
  9023. this.skeleton = new THREE.Skeleton( this.geometry && this.geometry.bones, useVertexTexture );
  9024. // Add root level bones as children of the mesh
  9025. for ( var b = 0; b < this.skeleton.bones.length; ++b ) {
  9026. var bone = this.skeleton.bones[ b ];
  9027. if ( bone.parent === undefined ) {
  9028. this.add( bone );
  9029. }
  9030. }
  9031. this.identityMatrix = new THREE.Matrix4();
  9032. this.pose();
  9033. };
  9034. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  9035. THREE.SkinnedMesh.prototype.updateMatrixWorld = function () {
  9036. var offsetMatrix = new THREE.Matrix4();
  9037. return function ( force ) {
  9038. this.matrixAutoUpdate && this.updateMatrix();
  9039. // update matrixWorld
  9040. if ( this.matrixWorldNeedsUpdate || force ) {
  9041. if ( this.parent ) {
  9042. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  9043. } else {
  9044. this.matrixWorld.copy( this.matrix );
  9045. }
  9046. this.matrixWorldNeedsUpdate = false;
  9047. force = true;
  9048. }
  9049. // update children
  9050. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  9051. var child = this.children[ i ];
  9052. if ( child instanceof THREE.Bone ) {
  9053. child.update( this.identityMatrix, false );
  9054. } else {
  9055. child.updateMatrixWorld( true );
  9056. }
  9057. }
  9058. // make a snapshot of the bones' rest position
  9059. if ( this.skeleton.boneInverses === undefined ) {
  9060. this.skeleton.calculateInverses();
  9061. }
  9062. // flatten bone matrices to array
  9063. for ( var b = 0, bl = this.skeleton.bones.length; b < bl; b ++ ) {
  9064. // compute the offset between the current and the original transform;
  9065. // TODO: we could get rid of this multiplication step if the skinMatrix
  9066. // was already representing the offset; however, this requires some
  9067. // major changes to the animation system
  9068. offsetMatrix.multiplyMatrices( this.skeleton.bones[ b ].skinMatrix, this.skeleton.boneInverses[ b ] );
  9069. offsetMatrix.flattenToArrayOffset( this.skeleton.boneMatrices, b * 16 );
  9070. }
  9071. if ( this.skeleton.useVertexTexture ) {
  9072. this.skeleton.boneTexture.needsUpdate = true;
  9073. }
  9074. };
  9075. }();
  9076. THREE.SkinnedMesh.prototype.pose = function () {
  9077. this.updateMatrixWorld( true );
  9078. this.normalizeSkinWeights();
  9079. };
  9080. THREE.SkinnedMesh.prototype.normalizeSkinWeights = function () {
  9081. if ( this.geometry instanceof THREE.Geometry ) {
  9082. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  9083. var sw = this.geometry.skinWeights[ i ];
  9084. var scale = 1.0 / sw.lengthManhattan();
  9085. if ( scale !== Infinity ) {
  9086. sw.multiplyScalar( scale );
  9087. } else {
  9088. sw.set( 1 ); // this will be normalized by the shader anyway
  9089. }
  9090. }
  9091. } else {
  9092. // skinning weights assumed to be normalized for THREE.BufferGeometry
  9093. }
  9094. };
  9095. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  9096. if ( object === undefined ) {
  9097. object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  9098. }
  9099. THREE.Mesh.prototype.clone.call( this, object );
  9100. return object;
  9101. };
  9102. // File:src/objects/MorphAnimMesh.js
  9103. /**
  9104. * @author alteredq / http://alteredqualia.com/
  9105. */
  9106. THREE.MorphAnimMesh = function ( geometry, material ) {
  9107. THREE.Mesh.call( this, geometry, material );
  9108. // API
  9109. this.duration = 1000; // milliseconds
  9110. this.mirroredLoop = false;
  9111. this.time = 0;
  9112. // internals
  9113. this.lastKeyframe = 0;
  9114. this.currentKeyframe = 0;
  9115. this.direction = 1;
  9116. this.directionBackwards = false;
  9117. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  9118. };
  9119. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  9120. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  9121. this.startKeyframe = start;
  9122. this.endKeyframe = end;
  9123. this.length = this.endKeyframe - this.startKeyframe + 1;
  9124. };
  9125. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  9126. this.direction = 1;
  9127. this.directionBackwards = false;
  9128. };
  9129. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  9130. this.direction = - 1;
  9131. this.directionBackwards = true;
  9132. };
  9133. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  9134. var geometry = this.geometry;
  9135. if ( ! geometry.animations ) geometry.animations = {};
  9136. var firstAnimation, animations = geometry.animations;
  9137. var pattern = /([a-z]+)_?(\d+)/;
  9138. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  9139. var morph = geometry.morphTargets[ i ];
  9140. var parts = morph.name.match( pattern );
  9141. if ( parts && parts.length > 1 ) {
  9142. var label = parts[ 1 ];
  9143. var num = parts[ 2 ];
  9144. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: - Infinity };
  9145. var animation = animations[ label ];
  9146. if ( i < animation.start ) animation.start = i;
  9147. if ( i > animation.end ) animation.end = i;
  9148. if ( ! firstAnimation ) firstAnimation = label;
  9149. }
  9150. }
  9151. geometry.firstAnimation = firstAnimation;
  9152. };
  9153. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  9154. if ( ! this.geometry.animations ) this.geometry.animations = {};
  9155. this.geometry.animations[ label ] = { start: start, end: end };
  9156. };
  9157. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  9158. var animation = this.geometry.animations[ label ];
  9159. if ( animation ) {
  9160. this.setFrameRange( animation.start, animation.end );
  9161. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  9162. this.time = 0;
  9163. } else {
  9164. console.warn( 'animation[' + label + '] undefined' );
  9165. }
  9166. };
  9167. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  9168. var frameTime = this.duration / this.length;
  9169. this.time += this.direction * delta;
  9170. if ( this.mirroredLoop ) {
  9171. if ( this.time > this.duration || this.time < 0 ) {
  9172. this.direction *= - 1;
  9173. if ( this.time > this.duration ) {
  9174. this.time = this.duration;
  9175. this.directionBackwards = true;
  9176. }
  9177. if ( this.time < 0 ) {
  9178. this.time = 0;
  9179. this.directionBackwards = false;
  9180. }
  9181. }
  9182. } else {
  9183. this.time = this.time % this.duration;
  9184. if ( this.time < 0 ) this.time += this.duration;
  9185. }
  9186. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  9187. if ( keyframe !== this.currentKeyframe ) {
  9188. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  9189. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  9190. this.morphTargetInfluences[ keyframe ] = 0;
  9191. this.lastKeyframe = this.currentKeyframe;
  9192. this.currentKeyframe = keyframe;
  9193. }
  9194. var mix = ( this.time % frameTime ) / frameTime;
  9195. if ( this.directionBackwards ) {
  9196. mix = 1 - mix;
  9197. }
  9198. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  9199. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  9200. };
  9201. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  9202. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  9203. object.duration = this.duration;
  9204. object.mirroredLoop = this.mirroredLoop;
  9205. object.time = this.time;
  9206. object.lastKeyframe = this.lastKeyframe;
  9207. object.currentKeyframe = this.currentKeyframe;
  9208. object.direction = this.direction;
  9209. object.directionBackwards = this.directionBackwards;
  9210. THREE.Mesh.prototype.clone.call( this, object );
  9211. return object;
  9212. };
  9213. // File:src/objects/LOD.js
  9214. /**
  9215. * @author mikael emtinger / http://gomo.se/
  9216. * @author alteredq / http://alteredqualia.com/
  9217. * @author mrdoob / http://mrdoob.com/
  9218. */
  9219. THREE.LOD = function () {
  9220. THREE.Object3D.call( this );
  9221. this.objects = [];
  9222. };
  9223. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  9224. THREE.LOD.prototype.addLevel = function ( object, distance ) {
  9225. if ( distance === undefined ) distance = 0;
  9226. distance = Math.abs( distance );
  9227. for ( var l = 0; l < this.objects.length; l ++ ) {
  9228. if ( distance < this.objects[ l ].distance ) {
  9229. break;
  9230. }
  9231. }
  9232. this.objects.splice( l, 0, { distance: distance, object: object } );
  9233. this.add( object );
  9234. };
  9235. THREE.LOD.prototype.getObjectForDistance = function ( distance ) {
  9236. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  9237. if ( distance < this.objects[ i ].distance ) {
  9238. break;
  9239. }
  9240. }
  9241. return this.objects[ i - 1 ].object;
  9242. };
  9243. THREE.LOD.prototype.raycast = ( function () {
  9244. var matrixPosition = new THREE.Vector3();
  9245. return function ( raycaster, intersects ) {
  9246. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  9247. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  9248. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  9249. };
  9250. }() );
  9251. THREE.LOD.prototype.update = function () {
  9252. var v1 = new THREE.Vector3();
  9253. var v2 = new THREE.Vector3();
  9254. return function ( camera ) {
  9255. if ( this.objects.length > 1 ) {
  9256. v1.setFromMatrixPosition( camera.matrixWorld );
  9257. v2.setFromMatrixPosition( this.matrixWorld );
  9258. var distance = v1.distanceTo( v2 );
  9259. this.objects[ 0 ].object.visible = true;
  9260. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  9261. if ( distance >= this.objects[ i ].distance ) {
  9262. this.objects[ i - 1 ].object.visible = false;
  9263. this.objects[ i ].object.visible = true;
  9264. } else {
  9265. break;
  9266. }
  9267. }
  9268. for ( ; i < l; i ++ ) {
  9269. this.objects[ i ].object.visible = false;
  9270. }
  9271. }
  9272. };
  9273. }();
  9274. THREE.LOD.prototype.clone = function ( object ) {
  9275. if ( object === undefined ) object = new THREE.LOD();
  9276. THREE.Object3D.prototype.clone.call( this, object );
  9277. for ( var i = 0, l = this.objects.length; i < l; i ++ ) {
  9278. var x = this.objects[ i ].object.clone();
  9279. x.visible = i === 0;
  9280. object.addLevel( x, this.objects[ i ].distance );
  9281. }
  9282. return object;
  9283. };
  9284. // File:src/objects/Sprite.js
  9285. /**
  9286. * @author mikael emtinger / http://gomo.se/
  9287. * @author alteredq / http://alteredqualia.com/
  9288. */
  9289. THREE.Sprite = ( function () {
  9290. var vertices = new Float32Array( [ - 0.5, - 0.5, 0, 0.5, - 0.5, 0, 0.5, 0.5, 0 ] );
  9291. var geometry = new THREE.BufferGeometry();
  9292. geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  9293. return function ( material ) {
  9294. THREE.Object3D.call( this );
  9295. this.geometry = geometry;
  9296. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  9297. };
  9298. } )();
  9299. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  9300. THREE.Sprite.prototype.raycast = ( function () {
  9301. var matrixPosition = new THREE.Vector3();
  9302. return function ( raycaster, intersects ) {
  9303. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  9304. var distance = raycaster.ray.distanceToPoint( matrixPosition );
  9305. if ( distance > this.scale.x ) {
  9306. return;
  9307. }
  9308. intersects.push( {
  9309. distance: distance,
  9310. point: this.position,
  9311. face: null,
  9312. object: this
  9313. } );
  9314. };
  9315. }() );
  9316. THREE.Sprite.prototype.updateMatrix = function () {
  9317. this.matrix.compose( this.position, this.quaternion, this.scale );
  9318. this.matrixWorldNeedsUpdate = true;
  9319. };
  9320. THREE.Sprite.prototype.clone = function ( object ) {
  9321. if ( object === undefined ) object = new THREE.Sprite( this.material );
  9322. THREE.Object3D.prototype.clone.call( this, object );
  9323. return object;
  9324. };
  9325. // Backwards compatibility
  9326. THREE.Particle = THREE.Sprite;
  9327. // File:src/scenes/Scene.js
  9328. /**
  9329. * @author mrdoob / http://mrdoob.com/
  9330. */
  9331. THREE.Scene = function () {
  9332. THREE.Object3D.call( this );
  9333. this.fog = null;
  9334. this.overrideMaterial = null;
  9335. this.autoUpdate = true; // checked by the renderer
  9336. this.matrixAutoUpdate = false;
  9337. this.__lights = [];
  9338. this.__objectsAdded = [];
  9339. this.__objectsRemoved = [];
  9340. };
  9341. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  9342. THREE.Scene.prototype.__addObject = function ( object ) {
  9343. if ( object instanceof THREE.Light ) {
  9344. if ( this.__lights.indexOf( object ) === - 1 ) {
  9345. this.__lights.push( object );
  9346. }
  9347. if ( object.target && object.target.parent === undefined ) {
  9348. this.add( object.target );
  9349. }
  9350. } else if ( ! ( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  9351. this.__objectsAdded.push( object );
  9352. // check if previously removed
  9353. var i = this.__objectsRemoved.indexOf( object );
  9354. if ( i !== - 1 ) {
  9355. this.__objectsRemoved.splice( i, 1 );
  9356. }
  9357. }
  9358. this.dispatchEvent( { type: 'objectAdded', object: object } );
  9359. object.dispatchEvent( { type: 'addedToScene', scene: this } );
  9360. for ( var c = 0; c < object.children.length; c ++ ) {
  9361. this.__addObject( object.children[ c ] );
  9362. }
  9363. };
  9364. THREE.Scene.prototype.__removeObject = function ( object ) {
  9365. if ( object instanceof THREE.Light ) {
  9366. var i = this.__lights.indexOf( object );
  9367. if ( i !== - 1 ) {
  9368. this.__lights.splice( i, 1 );
  9369. }
  9370. if ( object.shadowCascadeArray ) {
  9371. for ( var x = 0; x < object.shadowCascadeArray.length; x ++ ) {
  9372. this.__removeObject( object.shadowCascadeArray[ x ] );
  9373. }
  9374. }
  9375. } else if ( ! ( object instanceof THREE.Camera ) ) {
  9376. this.__objectsRemoved.push( object );
  9377. // check if previously added
  9378. var i = this.__objectsAdded.indexOf( object );
  9379. if ( i !== - 1 ) {
  9380. this.__objectsAdded.splice( i, 1 );
  9381. }
  9382. }
  9383. this.dispatchEvent( { type: 'objectRemoved', object: object } );
  9384. object.dispatchEvent( { type: 'removedFromScene', scene: this } );
  9385. for ( var c = 0; c < object.children.length; c ++ ) {
  9386. this.__removeObject( object.children[ c ] );
  9387. }
  9388. };
  9389. THREE.Scene.prototype.clone = function ( object ) {
  9390. if ( object === undefined ) object = new THREE.Scene();
  9391. THREE.Object3D.prototype.clone.call( this, object );
  9392. if ( this.fog !== null ) object.fog = this.fog.clone();
  9393. if ( this.overrideMaterial !== null ) object.overrideMaterial = this.overrideMaterial.clone();
  9394. object.autoUpdate = this.autoUpdate;
  9395. object.matrixAutoUpdate = this.matrixAutoUpdate;
  9396. return object;
  9397. };
  9398. // File:src/scenes/Fog.js
  9399. /**
  9400. * @author mrdoob / http://mrdoob.com/
  9401. * @author alteredq / http://alteredqualia.com/
  9402. */
  9403. THREE.Fog = function ( color, near, far ) {
  9404. this.name = '';
  9405. this.color = new THREE.Color( color );
  9406. this.near = ( near !== undefined ) ? near : 1;
  9407. this.far = ( far !== undefined ) ? far : 1000;
  9408. };
  9409. THREE.Fog.prototype.clone = function () {
  9410. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  9411. };
  9412. // File:src/scenes/FogExp2.js
  9413. /**
  9414. * @author mrdoob / http://mrdoob.com/
  9415. * @author alteredq / http://alteredqualia.com/
  9416. */
  9417. THREE.FogExp2 = function ( color, density ) {
  9418. this.name = '';
  9419. this.color = new THREE.Color( color );
  9420. this.density = ( density !== undefined ) ? density : 0.00025;
  9421. };
  9422. THREE.FogExp2.prototype.clone = function () {
  9423. return new THREE.FogExp2( this.color.getHex(), this.density );
  9424. };
  9425. // File:src/renderers/CanvasRenderer.js
  9426. /**
  9427. * @author mrdoob / http://mrdoob.com/
  9428. */
  9429. THREE.CanvasRenderer = function ( parameters ) {
  9430. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  9431. var smoothstep = THREE.Math.smoothstep;
  9432. parameters = parameters || {};
  9433. var _this = this,
  9434. _renderData, _elements, _lights,
  9435. _projector = new THREE.Projector(),
  9436. _canvas = parameters.canvas !== undefined
  9437. ? parameters.canvas
  9438. : document.createElement( 'canvas' ),
  9439. _canvasWidth = _canvas.width,
  9440. _canvasHeight = _canvas.height,
  9441. _canvasWidthHalf = Math.floor( _canvasWidth / 2 ),
  9442. _canvasHeightHalf = Math.floor( _canvasHeight / 2 ),
  9443. _context = _canvas.getContext( '2d', {
  9444. alpha: parameters.alpha === true
  9445. } ),
  9446. _clearColor = new THREE.Color( 0x000000 ),
  9447. _clearAlpha = 0,
  9448. _contextGlobalAlpha = 1,
  9449. _contextGlobalCompositeOperation = 0,
  9450. _contextStrokeStyle = null,
  9451. _contextFillStyle = null,
  9452. _contextLineWidth = null,
  9453. _contextLineCap = null,
  9454. _contextLineJoin = null,
  9455. _contextLineDash = [],
  9456. _camera,
  9457. _v1, _v2, _v3, _v4,
  9458. _v5 = new THREE.RenderableVertex(),
  9459. _v6 = new THREE.RenderableVertex(),
  9460. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  9461. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  9462. _color = new THREE.Color(),
  9463. _color1 = new THREE.Color(),
  9464. _color2 = new THREE.Color(),
  9465. _color3 = new THREE.Color(),
  9466. _color4 = new THREE.Color(),
  9467. _diffuseColor = new THREE.Color(),
  9468. _emissiveColor = new THREE.Color(),
  9469. _lightColor = new THREE.Color(),
  9470. _patterns = {},
  9471. _image, _uvs,
  9472. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  9473. _clipBox = new THREE.Box2(),
  9474. _clearBox = new THREE.Box2(),
  9475. _elemBox = new THREE.Box2(),
  9476. _ambientLight = new THREE.Color(),
  9477. _directionalLights = new THREE.Color(),
  9478. _pointLights = new THREE.Color(),
  9479. _vector3 = new THREE.Vector3(), // Needed for PointLight
  9480. _centroid = new THREE.Vector3(),
  9481. _normal = new THREE.Vector3(),
  9482. _normalViewMatrix = new THREE.Matrix3();
  9483. // dash+gap fallbacks for Firefox and everything else
  9484. if ( _context.setLineDash === undefined ) {
  9485. _context.setLineDash = function () {}
  9486. }
  9487. this.domElement = _canvas;
  9488. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  9489. ? parameters.devicePixelRatio
  9490. : self.devicePixelRatio !== undefined
  9491. ? self.devicePixelRatio
  9492. : 1;
  9493. this.autoClear = true;
  9494. this.sortObjects = true;
  9495. this.sortElements = true;
  9496. this.info = {
  9497. render: {
  9498. vertices: 0,
  9499. faces: 0
  9500. }
  9501. }
  9502. // WebGLRenderer compatibility
  9503. this.supportsVertexTextures = function () {};
  9504. this.setFaceCulling = function () {};
  9505. this.setSize = function ( width, height, updateStyle ) {
  9506. _canvasWidth = width * this.devicePixelRatio;
  9507. _canvasHeight = height * this.devicePixelRatio;
  9508. _canvas.width = _canvasWidth;
  9509. _canvas.height = _canvasHeight;
  9510. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  9511. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  9512. if ( updateStyle !== false ) {
  9513. _canvas.style.width = width + 'px';
  9514. _canvas.style.height = height + 'px';
  9515. }
  9516. _clipBox.min.set( -_canvasWidthHalf, -_canvasHeightHalf ),
  9517. _clipBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  9518. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  9519. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  9520. _contextGlobalAlpha = 1;
  9521. _contextGlobalCompositeOperation = 0;
  9522. _contextStrokeStyle = null;
  9523. _contextFillStyle = null;
  9524. _contextLineWidth = null;
  9525. _contextLineCap = null;
  9526. _contextLineJoin = null;
  9527. this.setViewport( 0, 0, width, height );
  9528. };
  9529. this.setViewport = function ( x, y, width, height ) {
  9530. var viewportX = x * this.devicePixelRatio;
  9531. var viewportY = y * this.devicePixelRatio;
  9532. var viewportWidth = width * this.devicePixelRatio;
  9533. var viewportHeight = height * this.devicePixelRatio;
  9534. _context.setTransform( viewportWidth / _canvasWidth, 0, 0, - viewportHeight / _canvasHeight, viewportX, _canvasHeight - viewportY );
  9535. _context.translate( _canvasWidthHalf, _canvasHeightHalf );
  9536. };
  9537. this.setScissor = function () {};
  9538. this.enableScissorTest = function () {};
  9539. this.setClearColor = function ( color, alpha ) {
  9540. _clearColor.set( color );
  9541. _clearAlpha = alpha !== undefined ? alpha : 1;
  9542. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  9543. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  9544. };
  9545. this.setClearColorHex = function ( hex, alpha ) {
  9546. console.warn( 'THREE.CanvasRenderer: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  9547. this.setClearColor( hex, alpha );
  9548. };
  9549. this.getMaxAnisotropy = function () {
  9550. return 0;
  9551. };
  9552. this.clear = function () {
  9553. if ( _clearBox.empty() === false ) {
  9554. _clearBox.intersect( _clipBox );
  9555. _clearBox.expandByScalar( 2 );
  9556. if ( _clearAlpha < 1 ) {
  9557. _context.clearRect(
  9558. _clearBox.min.x | 0,
  9559. _clearBox.min.y | 0,
  9560. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  9561. ( _clearBox.max.y - _clearBox.min.y ) | 0
  9562. );
  9563. }
  9564. if ( _clearAlpha > 0 ) {
  9565. setBlending( THREE.NormalBlending );
  9566. setOpacity( 1 );
  9567. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearAlpha + ')' );
  9568. _context.fillRect(
  9569. _clearBox.min.x | 0,
  9570. _clearBox.min.y | 0,
  9571. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  9572. ( _clearBox.max.y - _clearBox.min.y ) | 0
  9573. );
  9574. }
  9575. _clearBox.makeEmpty();
  9576. }
  9577. };
  9578. // compatibility
  9579. this.clearColor = function () {};
  9580. this.clearDepth = function () {};
  9581. this.clearStencil = function () {};
  9582. this.render = function ( scene, camera ) {
  9583. if ( camera instanceof THREE.Camera === false ) {
  9584. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  9585. return;
  9586. }
  9587. if ( this.autoClear === true ) this.clear();
  9588. _this.info.render.vertices = 0;
  9589. _this.info.render.faces = 0;
  9590. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  9591. _elements = _renderData.elements;
  9592. _lights = _renderData.lights;
  9593. _camera = camera;
  9594. _normalViewMatrix.getNormalMatrix( camera.matrixWorldInverse );
  9595. /* DEBUG
  9596. setFillStyle( 'rgba( 0, 255, 255, 0.5 )' );
  9597. _context.fillRect( _clipBox.min.x, _clipBox.min.y, _clipBox.max.x - _clipBox.min.x, _clipBox.max.y - _clipBox.min.y );
  9598. */
  9599. calculateLights();
  9600. for ( var e = 0, el = _elements.length; e < el; e ++ ) {
  9601. var element = _elements[ e ];
  9602. var material = element.material;
  9603. if ( material === undefined || material.opacity === 0 ) continue;
  9604. _elemBox.makeEmpty();
  9605. if ( element instanceof THREE.RenderableSprite ) {
  9606. _v1 = element;
  9607. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  9608. renderSprite( _v1, element, material );
  9609. } else if ( element instanceof THREE.RenderableLine ) {
  9610. _v1 = element.v1; _v2 = element.v2;
  9611. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  9612. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  9613. _elemBox.setFromPoints( [
  9614. _v1.positionScreen,
  9615. _v2.positionScreen
  9616. ] );
  9617. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  9618. renderLine( _v1, _v2, element, material );
  9619. }
  9620. } else if ( element instanceof THREE.RenderableFace ) {
  9621. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  9622. if ( _v1.positionScreen.z < - 1 || _v1.positionScreen.z > 1 ) continue;
  9623. if ( _v2.positionScreen.z < - 1 || _v2.positionScreen.z > 1 ) continue;
  9624. if ( _v3.positionScreen.z < - 1 || _v3.positionScreen.z > 1 ) continue;
  9625. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  9626. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  9627. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  9628. if ( material.overdraw > 0 ) {
  9629. expand( _v1.positionScreen, _v2.positionScreen, material.overdraw );
  9630. expand( _v2.positionScreen, _v3.positionScreen, material.overdraw );
  9631. expand( _v3.positionScreen, _v1.positionScreen, material.overdraw );
  9632. }
  9633. _elemBox.setFromPoints( [
  9634. _v1.positionScreen,
  9635. _v2.positionScreen,
  9636. _v3.positionScreen
  9637. ] );
  9638. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  9639. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material );
  9640. }
  9641. }
  9642. /* DEBUG
  9643. setLineWidth( 1 );
  9644. setStrokeStyle( 'rgba( 0, 255, 0, 0.5 )' );
  9645. _context.strokeRect( _elemBox.min.x, _elemBox.min.y, _elemBox.max.x - _elemBox.min.x, _elemBox.max.y - _elemBox.min.y );
  9646. */
  9647. _clearBox.union( _elemBox );
  9648. }
  9649. /* DEBUG
  9650. setLineWidth( 1 );
  9651. setStrokeStyle( 'rgba( 255, 0, 0, 0.5 )' );
  9652. _context.strokeRect( _clearBox.min.x, _clearBox.min.y, _clearBox.max.x - _clearBox.min.x, _clearBox.max.y - _clearBox.min.y );
  9653. */
  9654. // _context.setTransform( 1, 0, 0, 1, 0, 0 );
  9655. };
  9656. //
  9657. function calculateLights() {
  9658. _ambientLight.setRGB( 0, 0, 0 );
  9659. _directionalLights.setRGB( 0, 0, 0 );
  9660. _pointLights.setRGB( 0, 0, 0 );
  9661. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  9662. var light = _lights[ l ];
  9663. var lightColor = light.color;
  9664. if ( light instanceof THREE.AmbientLight ) {
  9665. _ambientLight.add( lightColor );
  9666. } else if ( light instanceof THREE.DirectionalLight ) {
  9667. // for sprites
  9668. _directionalLights.add( lightColor );
  9669. } else if ( light instanceof THREE.PointLight ) {
  9670. // for sprites
  9671. _pointLights.add( lightColor );
  9672. }
  9673. }
  9674. }
  9675. function calculateLight( position, normal, color ) {
  9676. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  9677. var light = _lights[ l ];
  9678. _lightColor.copy( light.color );
  9679. if ( light instanceof THREE.DirectionalLight ) {
  9680. var lightPosition = _vector3.setFromMatrixPosition( light.matrixWorld ).normalize();
  9681. var amount = normal.dot( lightPosition );
  9682. if ( amount <= 0 ) continue;
  9683. amount *= light.intensity;
  9684. color.add( _lightColor.multiplyScalar( amount ) );
  9685. } else if ( light instanceof THREE.PointLight ) {
  9686. var lightPosition = _vector3.setFromMatrixPosition( light.matrixWorld );
  9687. var amount = normal.dot( _vector3.subVectors( lightPosition, position ).normalize() );
  9688. if ( amount <= 0 ) continue;
  9689. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  9690. if ( amount == 0 ) continue;
  9691. amount *= light.intensity;
  9692. color.add( _lightColor.multiplyScalar( amount ) );
  9693. }
  9694. }
  9695. }
  9696. function renderSprite( v1, element, material ) {
  9697. setOpacity( material.opacity );
  9698. setBlending( material.blending );
  9699. var scaleX = element.scale.x * _canvasWidthHalf;
  9700. var scaleY = element.scale.y * _canvasHeightHalf;
  9701. var dist = 0.5 * Math.sqrt( scaleX * scaleX + scaleY * scaleY ); // allow for rotated sprite
  9702. _elemBox.min.set( v1.x - dist, v1.y - dist );
  9703. _elemBox.max.set( v1.x + dist, v1.y + dist );
  9704. if ( material instanceof THREE.SpriteMaterial ) {
  9705. var texture = material.map;
  9706. if ( texture !== null && texture.image !== undefined ) {
  9707. if ( texture.hasEventListener( 'update', onTextureUpdate ) === false ) {
  9708. if ( texture.image.width > 0 ) {
  9709. textureToPattern( texture );
  9710. }
  9711. texture.addEventListener( 'update', onTextureUpdate );
  9712. }
  9713. var pattern = _patterns[ texture.id ];
  9714. if ( pattern !== undefined ) {
  9715. setFillStyle( pattern );
  9716. } else {
  9717. setFillStyle( 'rgba( 0, 0, 0, 1 )' );
  9718. }
  9719. //
  9720. var bitmap = texture.image;
  9721. var ox = bitmap.width * texture.offset.x;
  9722. var oy = bitmap.height * texture.offset.y;
  9723. var sx = bitmap.width * texture.repeat.x;
  9724. var sy = bitmap.height * texture.repeat.y;
  9725. var cx = scaleX / sx;
  9726. var cy = scaleY / sy;
  9727. _context.save();
  9728. _context.translate( v1.x, v1.y );
  9729. if ( material.rotation !== 0 ) _context.rotate( material.rotation );
  9730. _context.translate( - scaleX / 2, - scaleY / 2 );
  9731. _context.scale( cx, cy );
  9732. _context.translate( - ox, - oy );
  9733. _context.fillRect( ox, oy, sx, sy );
  9734. _context.restore();
  9735. } else {
  9736. // no texture
  9737. setFillStyle( material.color.getStyle() );
  9738. _context.save();
  9739. _context.translate( v1.x, v1.y );
  9740. if ( material.rotation !== 0 ) _context.rotate( material.rotation );
  9741. _context.scale( scaleX, - scaleY );
  9742. _context.fillRect( - 0.5, - 0.5, 1, 1 );
  9743. _context.restore();
  9744. }
  9745. } else if ( material instanceof THREE.SpriteCanvasMaterial ) {
  9746. setStrokeStyle( material.color.getStyle() );
  9747. setFillStyle( material.color.getStyle() );
  9748. _context.save();
  9749. _context.translate( v1.x, v1.y );
  9750. if ( material.rotation !== 0 ) _context.rotate( material.rotation );
  9751. _context.scale( scaleX, scaleY );
  9752. material.program( _context );
  9753. _context.restore();
  9754. }
  9755. /* DEBUG
  9756. setStrokeStyle( 'rgb(255,255,0)' );
  9757. _context.beginPath();
  9758. _context.moveTo( v1.x - 10, v1.y );
  9759. _context.lineTo( v1.x + 10, v1.y );
  9760. _context.moveTo( v1.x, v1.y - 10 );
  9761. _context.lineTo( v1.x, v1.y + 10 );
  9762. _context.stroke();
  9763. */
  9764. }
  9765. function renderLine( v1, v2, element, material ) {
  9766. setOpacity( material.opacity );
  9767. setBlending( material.blending );
  9768. _context.beginPath();
  9769. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  9770. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  9771. if ( material instanceof THREE.LineBasicMaterial ) {
  9772. setLineWidth( material.linewidth );
  9773. setLineCap( material.linecap );
  9774. setLineJoin( material.linejoin );
  9775. if ( material.vertexColors !== THREE.VertexColors ) {
  9776. setStrokeStyle( material.color.getStyle() );
  9777. } else {
  9778. var colorStyle1 = element.vertexColors[ 0 ].getStyle();
  9779. var colorStyle2 = element.vertexColors[ 1 ].getStyle();
  9780. if ( colorStyle1 === colorStyle2 ) {
  9781. setStrokeStyle( colorStyle1 );
  9782. } else {
  9783. try {
  9784. var grad = _context.createLinearGradient(
  9785. v1.positionScreen.x,
  9786. v1.positionScreen.y,
  9787. v2.positionScreen.x,
  9788. v2.positionScreen.y
  9789. );
  9790. grad.addColorStop( 0, colorStyle1 );
  9791. grad.addColorStop( 1, colorStyle2 );
  9792. } catch ( exception ) {
  9793. grad = colorStyle1;
  9794. }
  9795. setStrokeStyle( grad );
  9796. }
  9797. }
  9798. _context.stroke();
  9799. _elemBox.expandByScalar( material.linewidth * 2 );
  9800. } else if ( material instanceof THREE.LineDashedMaterial ) {
  9801. setLineWidth( material.linewidth );
  9802. setLineCap( material.linecap );
  9803. setLineJoin( material.linejoin );
  9804. setStrokeStyle( material.color.getStyle() );
  9805. setLineDash( [ material.dashSize, material.gapSize ] );
  9806. _context.stroke();
  9807. _elemBox.expandByScalar( material.linewidth * 2 );
  9808. setLineDash( [] );
  9809. }
  9810. }
  9811. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material ) {
  9812. _this.info.render.vertices += 3;
  9813. _this.info.render.faces ++;
  9814. setOpacity( material.opacity );
  9815. setBlending( material.blending );
  9816. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  9817. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  9818. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  9819. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  9820. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null ) {
  9821. _diffuseColor.copy( material.color );
  9822. _emissiveColor.copy( material.emissive );
  9823. if ( material.vertexColors === THREE.FaceColors ) {
  9824. _diffuseColor.multiply( element.color );
  9825. }
  9826. _color.copy( _ambientLight );
  9827. _centroid.copy( v1.positionWorld ).add( v2.positionWorld ).add( v3.positionWorld ).divideScalar( 3 );
  9828. calculateLight( _centroid, element.normalModel, _color );
  9829. _color.multiply( _diffuseColor ).add( _emissiveColor );
  9830. material.wireframe === true
  9831. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9832. : fillPath( _color );
  9833. } else if ( material instanceof THREE.MeshBasicMaterial ||
  9834. material instanceof THREE.MeshLambertMaterial ||
  9835. material instanceof THREE.MeshPhongMaterial ) {
  9836. if ( material.map !== null ) {
  9837. if ( material.map.mapping instanceof THREE.UVMapping ) {
  9838. _uvs = element.uvs;
  9839. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uvs[ uv1 ].x, _uvs[ uv1 ].y, _uvs[ uv2 ].x, _uvs[ uv2 ].y, _uvs[ uv3 ].x, _uvs[ uv3 ].y, material.map );
  9840. }
  9841. } else if ( material.envMap !== null ) {
  9842. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  9843. _normal.copy( element.vertexNormalsModel[ uv1 ] ).applyMatrix3( _normalViewMatrix );
  9844. _uv1x = 0.5 * _normal.x + 0.5;
  9845. _uv1y = 0.5 * _normal.y + 0.5;
  9846. _normal.copy( element.vertexNormalsModel[ uv2 ] ).applyMatrix3( _normalViewMatrix );
  9847. _uv2x = 0.5 * _normal.x + 0.5;
  9848. _uv2y = 0.5 * _normal.y + 0.5;
  9849. _normal.copy( element.vertexNormalsModel[ uv3 ] ).applyMatrix3( _normalViewMatrix );
  9850. _uv3x = 0.5 * _normal.x + 0.5;
  9851. _uv3y = 0.5 * _normal.y + 0.5;
  9852. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  9853. } else if ( material.envMap.mapping instanceof THREE.SphericalRefractionMapping ) {
  9854. _normal.copy( element.vertexNormalsModel[ uv1 ] ).applyMatrix3( _normalViewMatrix );
  9855. _uv1x = - 0.5 * _normal.x + 0.5;
  9856. _uv1y = - 0.5 * _normal.y + 0.5;
  9857. _normal.copy( element.vertexNormalsModel[ uv2 ] ).applyMatrix3( _normalViewMatrix );
  9858. _uv2x = - 0.5 * _normal.x + 0.5;
  9859. _uv2y = - 0.5 * _normal.y + 0.5;
  9860. _normal.copy( element.vertexNormalsModel[ uv3 ] ).applyMatrix3( _normalViewMatrix );
  9861. _uv3x = - 0.5 * _normal.x + 0.5;
  9862. _uv3y = - 0.5 * _normal.y + 0.5;
  9863. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  9864. }
  9865. } else {
  9866. _color.copy( material.color );
  9867. if ( material.vertexColors === THREE.FaceColors ) {
  9868. _color.multiply( element.color );
  9869. }
  9870. material.wireframe === true
  9871. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9872. : fillPath( _color );
  9873. }
  9874. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  9875. _color.r = _color.g = _color.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _camera.near, _camera.far );
  9876. material.wireframe === true
  9877. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9878. : fillPath( _color );
  9879. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  9880. _normal.copy( element.normalModel ).applyMatrix3( _normalViewMatrix );
  9881. _color.setRGB( _normal.x, _normal.y, _normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9882. material.wireframe === true
  9883. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9884. : fillPath( _color );
  9885. } else {
  9886. _color.setRGB( 1, 1, 1 );
  9887. material.wireframe === true
  9888. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9889. : fillPath( _color );
  9890. }
  9891. }
  9892. //
  9893. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  9894. _context.beginPath();
  9895. _context.moveTo( x0, y0 );
  9896. _context.lineTo( x1, y1 );
  9897. _context.lineTo( x2, y2 );
  9898. _context.closePath();
  9899. }
  9900. function strokePath( color, linewidth, linecap, linejoin ) {
  9901. setLineWidth( linewidth );
  9902. setLineCap( linecap );
  9903. setLineJoin( linejoin );
  9904. setStrokeStyle( color.getStyle() );
  9905. _context.stroke();
  9906. _elemBox.expandByScalar( linewidth * 2 );
  9907. }
  9908. function fillPath( color ) {
  9909. setFillStyle( color.getStyle() );
  9910. _context.fill();
  9911. }
  9912. function onTextureUpdate ( event ) {
  9913. textureToPattern( event.target );
  9914. }
  9915. function textureToPattern( texture ) {
  9916. if ( texture instanceof THREE.CompressedTexture ) return;
  9917. var repeatX = texture.wrapS === THREE.RepeatWrapping;
  9918. var repeatY = texture.wrapT === THREE.RepeatWrapping;
  9919. var image = texture.image;
  9920. var canvas = document.createElement( 'canvas' );
  9921. canvas.width = image.width;
  9922. canvas.height = image.height;
  9923. var context = canvas.getContext( '2d' );
  9924. context.setTransform( 1, 0, 0, - 1, 0, image.height );
  9925. context.drawImage( image, 0, 0 );
  9926. _patterns[ texture.id ] = _context.createPattern(
  9927. canvas, repeatX === true && repeatY === true
  9928. ? 'repeat'
  9929. : repeatX === true && repeatY === false
  9930. ? 'repeat-x'
  9931. : repeatX === false && repeatY === true
  9932. ? 'repeat-y'
  9933. : 'no-repeat'
  9934. );
  9935. }
  9936. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  9937. if ( texture instanceof THREE.DataTexture ) return;
  9938. if ( texture.hasEventListener( 'update', onTextureUpdate ) === false ) {
  9939. if ( texture.image !== undefined && texture.image.width > 0 ) {
  9940. textureToPattern( texture );
  9941. }
  9942. texture.addEventListener( 'update', onTextureUpdate );
  9943. }
  9944. var pattern = _patterns[ texture.id ];
  9945. if ( pattern !== undefined ) {
  9946. setFillStyle( pattern );
  9947. } else {
  9948. setFillStyle( 'rgba(0,0,0,1)' );
  9949. _context.fill();
  9950. return;
  9951. }
  9952. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  9953. var a, b, c, d, e, f, det, idet,
  9954. offsetX = texture.offset.x / texture.repeat.x,
  9955. offsetY = texture.offset.y / texture.repeat.y,
  9956. width = texture.image.width * texture.repeat.x,
  9957. height = texture.image.height * texture.repeat.y;
  9958. u0 = ( u0 + offsetX ) * width;
  9959. v0 = ( v0 + offsetY ) * height;
  9960. u1 = ( u1 + offsetX ) * width;
  9961. v1 = ( v1 + offsetY ) * height;
  9962. u2 = ( u2 + offsetX ) * width;
  9963. v2 = ( v2 + offsetY ) * height;
  9964. x1 -= x0; y1 -= y0;
  9965. x2 -= x0; y2 -= y0;
  9966. u1 -= u0; v1 -= v0;
  9967. u2 -= u0; v2 -= v0;
  9968. det = u1 * v2 - u2 * v1;
  9969. if ( det === 0 ) return;
  9970. idet = 1 / det;
  9971. a = ( v2 * x1 - v1 * x2 ) * idet;
  9972. b = ( v2 * y1 - v1 * y2 ) * idet;
  9973. c = ( u1 * x2 - u2 * x1 ) * idet;
  9974. d = ( u1 * y2 - u2 * y1 ) * idet;
  9975. e = x0 - a * u0 - c * v0;
  9976. f = y0 - b * u0 - d * v0;
  9977. _context.save();
  9978. _context.transform( a, b, c, d, e, f );
  9979. _context.fill();
  9980. _context.restore();
  9981. }
  9982. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  9983. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  9984. var a, b, c, d, e, f, det, idet,
  9985. width = image.width - 1,
  9986. height = image.height - 1;
  9987. u0 *= width; v0 *= height;
  9988. u1 *= width; v1 *= height;
  9989. u2 *= width; v2 *= height;
  9990. x1 -= x0; y1 -= y0;
  9991. x2 -= x0; y2 -= y0;
  9992. u1 -= u0; v1 -= v0;
  9993. u2 -= u0; v2 -= v0;
  9994. det = u1 * v2 - u2 * v1;
  9995. idet = 1 / det;
  9996. a = ( v2 * x1 - v1 * x2 ) * idet;
  9997. b = ( v2 * y1 - v1 * y2 ) * idet;
  9998. c = ( u1 * x2 - u2 * x1 ) * idet;
  9999. d = ( u1 * y2 - u2 * y1 ) * idet;
  10000. e = x0 - a * u0 - c * v0;
  10001. f = y0 - b * u0 - d * v0;
  10002. _context.save();
  10003. _context.transform( a, b, c, d, e, f );
  10004. _context.clip();
  10005. _context.drawImage( image, 0, 0 );
  10006. _context.restore();
  10007. }
  10008. // Hide anti-alias gaps
  10009. function expand( v1, v2, pixels ) {
  10010. var x = v2.x - v1.x, y = v2.y - v1.y,
  10011. det = x * x + y * y, idet;
  10012. if ( det === 0 ) return;
  10013. idet = pixels / Math.sqrt( det );
  10014. x *= idet; y *= idet;
  10015. v2.x += x; v2.y += y;
  10016. v1.x -= x; v1.y -= y;
  10017. }
  10018. // Context cached methods.
  10019. function setOpacity( value ) {
  10020. if ( _contextGlobalAlpha !== value ) {
  10021. _context.globalAlpha = value;
  10022. _contextGlobalAlpha = value;
  10023. }
  10024. }
  10025. function setBlending( value ) {
  10026. if ( _contextGlobalCompositeOperation !== value ) {
  10027. if ( value === THREE.NormalBlending ) {
  10028. _context.globalCompositeOperation = 'source-over';
  10029. } else if ( value === THREE.AdditiveBlending ) {
  10030. _context.globalCompositeOperation = 'lighter';
  10031. } else if ( value === THREE.SubtractiveBlending ) {
  10032. _context.globalCompositeOperation = 'darker';
  10033. }
  10034. _contextGlobalCompositeOperation = value;
  10035. }
  10036. }
  10037. function setLineWidth( value ) {
  10038. if ( _contextLineWidth !== value ) {
  10039. _context.lineWidth = value;
  10040. _contextLineWidth = value;
  10041. }
  10042. }
  10043. function setLineCap( value ) {
  10044. // "butt", "round", "square"
  10045. if ( _contextLineCap !== value ) {
  10046. _context.lineCap = value;
  10047. _contextLineCap = value;
  10048. }
  10049. }
  10050. function setLineJoin( value ) {
  10051. // "round", "bevel", "miter"
  10052. if ( _contextLineJoin !== value ) {
  10053. _context.lineJoin = value;
  10054. _contextLineJoin = value;
  10055. }
  10056. }
  10057. function setStrokeStyle( value ) {
  10058. if ( _contextStrokeStyle !== value ) {
  10059. _context.strokeStyle = value;
  10060. _contextStrokeStyle = value;
  10061. }
  10062. }
  10063. function setFillStyle( value ) {
  10064. if ( _contextFillStyle !== value ) {
  10065. _context.fillStyle = value;
  10066. _contextFillStyle = value;
  10067. }
  10068. }
  10069. function setLineDash( value ) {
  10070. if ( _contextLineDash.length !== value.length ) {
  10071. _context.setLineDash( value );
  10072. _contextLineDash = value;
  10073. }
  10074. }
  10075. };
  10076. // File:src/renderers/shaders/ShaderChunk.js
  10077. /**
  10078. * Shader chunks for WebLG Shader library
  10079. *
  10080. * @author alteredq / http://alteredqualia.com/
  10081. * @author mrdoob / http://mrdoob.com/
  10082. * @author mikael emtinger / http://gomo.se/
  10083. */
  10084. THREE.ShaderChunk = {
  10085. // FOG
  10086. fog_pars_fragment: [
  10087. "#ifdef USE_FOG",
  10088. " uniform vec3 fogColor;",
  10089. " #ifdef FOG_EXP2",
  10090. " uniform float fogDensity;",
  10091. " #else",
  10092. " uniform float fogNear;",
  10093. " uniform float fogFar;",
  10094. " #endif",
  10095. "#endif"
  10096. ].join("\n"),
  10097. fog_fragment: [
  10098. "#ifdef USE_FOG",
  10099. " #ifdef USE_LOGDEPTHBUF_EXT",
  10100. " float depth = gl_FragDepthEXT / gl_FragCoord.w;",
  10101. " #else",
  10102. " float depth = gl_FragCoord.z / gl_FragCoord.w;",
  10103. " #endif",
  10104. " #ifdef FOG_EXP2",
  10105. " const float LOG2 = 1.442695;",
  10106. " float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  10107. " fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  10108. " #else",
  10109. " float fogFactor = smoothstep( fogNear, fogFar, depth );",
  10110. " #endif",
  10111. " gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  10112. "#endif"
  10113. ].join("\n"),
  10114. // ENVIRONMENT MAP
  10115. envmap_pars_fragment: [
  10116. "#ifdef USE_ENVMAP",
  10117. " uniform float reflectivity;",
  10118. " uniform samplerCube envMap;",
  10119. " uniform float flipEnvMap;",
  10120. " uniform int combine;",
  10121. " #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  10122. " uniform bool useRefract;",
  10123. " uniform float refractionRatio;",
  10124. " #else",
  10125. " varying vec3 vReflect;",
  10126. " #endif",
  10127. "#endif"
  10128. ].join("\n"),
  10129. envmap_fragment: [
  10130. "#ifdef USE_ENVMAP",
  10131. " vec3 reflectVec;",
  10132. " #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  10133. " vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  10134. // http://en.wikibooks.org/wiki/GLSL_Programming/Applying_Matrix_Transformations
  10135. // "Transforming Normal Vectors with the Inverse Transformation"
  10136. " vec3 worldNormal = normalize( vec3( vec4( normal, 0.0 ) * viewMatrix ) );",
  10137. " if ( useRefract ) {",
  10138. " reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );",
  10139. " } else { ",
  10140. " reflectVec = reflect( cameraToVertex, worldNormal );",
  10141. " }",
  10142. " #else",
  10143. " reflectVec = vReflect;",
  10144. " #endif",
  10145. " #ifdef DOUBLE_SIDED",
  10146. " float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  10147. " vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  10148. " #else",
  10149. " vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  10150. " #endif",
  10151. " #ifdef GAMMA_INPUT",
  10152. " cubeColor.xyz *= cubeColor.xyz;",
  10153. " #endif",
  10154. " if ( combine == 1 ) {",
  10155. " gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  10156. " } else if ( combine == 2 ) {",
  10157. " gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
  10158. " } else {",
  10159. " gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  10160. " }",
  10161. "#endif"
  10162. ].join("\n"),
  10163. envmap_pars_vertex: [
  10164. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  10165. " varying vec3 vReflect;",
  10166. " uniform float refractionRatio;",
  10167. " uniform bool useRefract;",
  10168. "#endif"
  10169. ].join("\n"),
  10170. worldpos_vertex : [
  10171. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  10172. " #ifdef USE_SKINNING",
  10173. " vec4 worldPosition = modelMatrix * skinned;",
  10174. " #endif",
  10175. " #if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  10176. " vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
  10177. " #endif",
  10178. " #if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  10179. " vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  10180. " #endif",
  10181. "#endif"
  10182. ].join("\n"),
  10183. envmap_vertex : [
  10184. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  10185. " vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  10186. " worldNormal = normalize( worldNormal );",
  10187. " vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
  10188. " if ( useRefract ) {",
  10189. " vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
  10190. " } else {",
  10191. " vReflect = reflect( cameraToVertex, worldNormal );",
  10192. " }",
  10193. "#endif"
  10194. ].join("\n"),
  10195. // COLOR MAP (particles)
  10196. map_particle_pars_fragment: [
  10197. "#ifdef USE_MAP",
  10198. " uniform sampler2D map;",
  10199. "#endif"
  10200. ].join("\n"),
  10201. map_particle_fragment: [
  10202. "#ifdef USE_MAP",
  10203. " gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  10204. "#endif"
  10205. ].join("\n"),
  10206. // COLOR MAP (triangles)
  10207. map_pars_vertex: [
  10208. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  10209. " varying vec2 vUv;",
  10210. " uniform vec4 offsetRepeat;",
  10211. "#endif"
  10212. ].join("\n"),
  10213. map_pars_fragment: [
  10214. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  10215. " varying vec2 vUv;",
  10216. "#endif",
  10217. "#ifdef USE_MAP",
  10218. " uniform sampler2D map;",
  10219. "#endif"
  10220. ].join("\n"),
  10221. map_vertex: [
  10222. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  10223. " vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  10224. "#endif"
  10225. ].join("\n"),
  10226. map_fragment: [
  10227. "#ifdef USE_MAP",
  10228. " vec4 texelColor = texture2D( map, vUv );",
  10229. " #ifdef GAMMA_INPUT",
  10230. " texelColor.xyz *= texelColor.xyz;",
  10231. " #endif",
  10232. " gl_FragColor = gl_FragColor * texelColor;",
  10233. "#endif"
  10234. ].join("\n"),
  10235. // LIGHT MAP
  10236. lightmap_pars_fragment: [
  10237. "#ifdef USE_LIGHTMAP",
  10238. " varying vec2 vUv2;",
  10239. " uniform sampler2D lightMap;",
  10240. "#endif"
  10241. ].join("\n"),
  10242. lightmap_pars_vertex: [
  10243. "#ifdef USE_LIGHTMAP",
  10244. " varying vec2 vUv2;",
  10245. "#endif"
  10246. ].join("\n"),
  10247. lightmap_fragment: [
  10248. "#ifdef USE_LIGHTMAP",
  10249. " gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  10250. "#endif"
  10251. ].join("\n"),
  10252. lightmap_vertex: [
  10253. "#ifdef USE_LIGHTMAP",
  10254. " vUv2 = uv2;",
  10255. "#endif"
  10256. ].join("\n"),
  10257. // BUMP MAP
  10258. bumpmap_pars_fragment: [
  10259. "#ifdef USE_BUMPMAP",
  10260. " uniform sampler2D bumpMap;",
  10261. " uniform float bumpScale;",
  10262. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  10263. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  10264. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  10265. " vec2 dHdxy_fwd() {",
  10266. " vec2 dSTdx = dFdx( vUv );",
  10267. " vec2 dSTdy = dFdy( vUv );",
  10268. " float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  10269. " float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  10270. " float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  10271. " return vec2( dBx, dBy );",
  10272. " }",
  10273. " vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  10274. " vec3 vSigmaX = dFdx( surf_pos );",
  10275. " vec3 vSigmaY = dFdy( surf_pos );",
  10276. " vec3 vN = surf_norm;", // normalized
  10277. " vec3 R1 = cross( vSigmaY, vN );",
  10278. " vec3 R2 = cross( vN, vSigmaX );",
  10279. " float fDet = dot( vSigmaX, R1 );",
  10280. " vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  10281. " return normalize( abs( fDet ) * surf_norm - vGrad );",
  10282. " }",
  10283. "#endif"
  10284. ].join("\n"),
  10285. // NORMAL MAP
  10286. normalmap_pars_fragment: [
  10287. "#ifdef USE_NORMALMAP",
  10288. " uniform sampler2D normalMap;",
  10289. " uniform vec2 normalScale;",
  10290. // Per-Pixel Tangent Space Normal Mapping
  10291. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  10292. " vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  10293. " vec3 q0 = dFdx( eye_pos.xyz );",
  10294. " vec3 q1 = dFdy( eye_pos.xyz );",
  10295. " vec2 st0 = dFdx( vUv.st );",
  10296. " vec2 st1 = dFdy( vUv.st );",
  10297. " vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  10298. " vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  10299. " vec3 N = normalize( surf_norm );",
  10300. " vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  10301. " mapN.xy = normalScale * mapN.xy;",
  10302. " mat3 tsn = mat3( S, T, N );",
  10303. " return normalize( tsn * mapN );",
  10304. " }",
  10305. "#endif"
  10306. ].join("\n"),
  10307. // SPECULAR MAP
  10308. specularmap_pars_fragment: [
  10309. "#ifdef USE_SPECULARMAP",
  10310. " uniform sampler2D specularMap;",
  10311. "#endif"
  10312. ].join("\n"),
  10313. specularmap_fragment: [
  10314. "float specularStrength;",
  10315. "#ifdef USE_SPECULARMAP",
  10316. " vec4 texelSpecular = texture2D( specularMap, vUv );",
  10317. " specularStrength = texelSpecular.r;",
  10318. "#else",
  10319. " specularStrength = 1.0;",
  10320. "#endif"
  10321. ].join("\n"),
  10322. // LIGHTS LAMBERT
  10323. lights_lambert_pars_vertex: [
  10324. "uniform vec3 ambient;",
  10325. "uniform vec3 diffuse;",
  10326. "uniform vec3 emissive;",
  10327. "uniform vec3 ambientLightColor;",
  10328. "#if MAX_DIR_LIGHTS > 0",
  10329. " uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  10330. " uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  10331. "#endif",
  10332. "#if MAX_HEMI_LIGHTS > 0",
  10333. " uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  10334. " uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  10335. " uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  10336. "#endif",
  10337. "#if MAX_POINT_LIGHTS > 0",
  10338. " uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  10339. " uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10340. " uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10341. "#endif",
  10342. "#if MAX_SPOT_LIGHTS > 0",
  10343. " uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  10344. " uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10345. " uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  10346. " uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10347. " uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  10348. " uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  10349. "#endif",
  10350. "#ifdef WRAP_AROUND",
  10351. " uniform vec3 wrapRGB;",
  10352. "#endif"
  10353. ].join("\n"),
  10354. lights_lambert_vertex: [
  10355. "vLightFront = vec3( 0.0 );",
  10356. "#ifdef DOUBLE_SIDED",
  10357. " vLightBack = vec3( 0.0 );",
  10358. "#endif",
  10359. "transformedNormal = normalize( transformedNormal );",
  10360. "#if MAX_DIR_LIGHTS > 0",
  10361. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  10362. " vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  10363. " vec3 dirVector = normalize( lDirection.xyz );",
  10364. " float dotProduct = dot( transformedNormal, dirVector );",
  10365. " vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  10366. " #ifdef DOUBLE_SIDED",
  10367. " vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  10368. " #ifdef WRAP_AROUND",
  10369. " vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  10370. " #endif",
  10371. " #endif",
  10372. " #ifdef WRAP_AROUND",
  10373. " vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10374. " directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  10375. " #ifdef DOUBLE_SIDED",
  10376. " directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  10377. " #endif",
  10378. " #endif",
  10379. " vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  10380. " #ifdef DOUBLE_SIDED",
  10381. " vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  10382. " #endif",
  10383. "}",
  10384. "#endif",
  10385. "#if MAX_POINT_LIGHTS > 0",
  10386. " for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10387. " vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10388. " vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  10389. " float lDistance = 1.0;",
  10390. " if ( pointLightDistance[ i ] > 0.0 )",
  10391. " lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  10392. " lVector = normalize( lVector );",
  10393. " float dotProduct = dot( transformedNormal, lVector );",
  10394. " vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  10395. " #ifdef DOUBLE_SIDED",
  10396. " vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  10397. " #ifdef WRAP_AROUND",
  10398. " vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  10399. " #endif",
  10400. " #endif",
  10401. " #ifdef WRAP_AROUND",
  10402. " vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10403. " pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  10404. " #ifdef DOUBLE_SIDED",
  10405. " pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  10406. " #endif",
  10407. " #endif",
  10408. " vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  10409. " #ifdef DOUBLE_SIDED",
  10410. " vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  10411. " #endif",
  10412. " }",
  10413. "#endif",
  10414. "#if MAX_SPOT_LIGHTS > 0",
  10415. " for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10416. " vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10417. " vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  10418. " float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
  10419. " if ( spotEffect > spotLightAngleCos[ i ] ) {",
  10420. " spotEffect = max( pow( max( spotEffect, 0.0 ), spotLightExponent[ i ] ), 0.0 );",
  10421. " float lDistance = 1.0;",
  10422. " if ( spotLightDistance[ i ] > 0.0 )",
  10423. " lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  10424. " lVector = normalize( lVector );",
  10425. " float dotProduct = dot( transformedNormal, lVector );",
  10426. " vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  10427. " #ifdef DOUBLE_SIDED",
  10428. " vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  10429. " #ifdef WRAP_AROUND",
  10430. " vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  10431. " #endif",
  10432. " #endif",
  10433. " #ifdef WRAP_AROUND",
  10434. " vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10435. " spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  10436. " #ifdef DOUBLE_SIDED",
  10437. " spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  10438. " #endif",
  10439. " #endif",
  10440. " vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  10441. " #ifdef DOUBLE_SIDED",
  10442. " vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  10443. " #endif",
  10444. " }",
  10445. " }",
  10446. "#endif",
  10447. "#if MAX_HEMI_LIGHTS > 0",
  10448. " for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  10449. " vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  10450. " vec3 lVector = normalize( lDirection.xyz );",
  10451. " float dotProduct = dot( transformedNormal, lVector );",
  10452. " float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  10453. " float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  10454. " vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  10455. " #ifdef DOUBLE_SIDED",
  10456. " vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  10457. " #endif",
  10458. " }",
  10459. "#endif",
  10460. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  10461. "#ifdef DOUBLE_SIDED",
  10462. " vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  10463. "#endif"
  10464. ].join("\n"),
  10465. // LIGHTS PHONG
  10466. lights_phong_pars_vertex: [
  10467. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP ) || defined( USE_ENVMAP )",
  10468. " varying vec3 vWorldPosition;",
  10469. "#endif"
  10470. ].join("\n"),
  10471. lights_phong_vertex: [
  10472. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP ) || defined( USE_ENVMAP )",
  10473. " vWorldPosition = worldPosition.xyz;",
  10474. "#endif"
  10475. ].join("\n"),
  10476. lights_phong_pars_fragment: [
  10477. "uniform vec3 ambientLightColor;",
  10478. "#if MAX_DIR_LIGHTS > 0",
  10479. " uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  10480. " uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  10481. "#endif",
  10482. "#if MAX_HEMI_LIGHTS > 0",
  10483. " uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  10484. " uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  10485. " uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  10486. "#endif",
  10487. "#if MAX_POINT_LIGHTS > 0",
  10488. " uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  10489. " uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10490. " uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10491. "#endif",
  10492. "#if MAX_SPOT_LIGHTS > 0",
  10493. " uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  10494. " uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10495. " uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  10496. " uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  10497. " uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  10498. " uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10499. "#endif",
  10500. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP ) || defined( USE_ENVMAP )",
  10501. " varying vec3 vWorldPosition;",
  10502. "#endif",
  10503. "#ifdef WRAP_AROUND",
  10504. " uniform vec3 wrapRGB;",
  10505. "#endif",
  10506. "varying vec3 vViewPosition;",
  10507. "varying vec3 vNormal;"
  10508. ].join("\n"),
  10509. lights_phong_fragment: [
  10510. "vec3 normal = normalize( vNormal );",
  10511. "vec3 viewPosition = normalize( vViewPosition );",
  10512. "#ifdef DOUBLE_SIDED",
  10513. " normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  10514. "#endif",
  10515. "#ifdef USE_NORMALMAP",
  10516. " normal = perturbNormal2Arb( -vViewPosition, normal );",
  10517. "#elif defined( USE_BUMPMAP )",
  10518. " normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  10519. "#endif",
  10520. "#if MAX_POINT_LIGHTS > 0",
  10521. " vec3 pointDiffuse = vec3( 0.0 );",
  10522. " vec3 pointSpecular = vec3( 0.0 );",
  10523. " for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10524. " vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10525. " vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  10526. " float lDistance = 1.0;",
  10527. " if ( pointLightDistance[ i ] > 0.0 )",
  10528. " lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  10529. " lVector = normalize( lVector );",
  10530. // diffuse
  10531. " float dotProduct = dot( normal, lVector );",
  10532. " #ifdef WRAP_AROUND",
  10533. " float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  10534. " float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10535. " vec3 pointDiffuseWeight = mix( vec3( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  10536. " #else",
  10537. " float pointDiffuseWeight = max( dotProduct, 0.0 );",
  10538. " #endif",
  10539. " pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  10540. // specular
  10541. " vec3 pointHalfVector = normalize( lVector + viewPosition );",
  10542. " float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  10543. " float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  10544. " float specularNormalization = ( shininess + 2.0 ) / 8.0;",
  10545. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, pointHalfVector ), 0.0 ), 5.0 );",
  10546. " pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  10547. " }",
  10548. "#endif",
  10549. "#if MAX_SPOT_LIGHTS > 0",
  10550. " vec3 spotDiffuse = vec3( 0.0 );",
  10551. " vec3 spotSpecular = vec3( 0.0 );",
  10552. " for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10553. " vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10554. " vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  10555. " float lDistance = 1.0;",
  10556. " if ( spotLightDistance[ i ] > 0.0 )",
  10557. " lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  10558. " lVector = normalize( lVector );",
  10559. " float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  10560. " if ( spotEffect > spotLightAngleCos[ i ] ) {",
  10561. " spotEffect = max( pow( max( spotEffect, 0.0 ), spotLightExponent[ i ] ), 0.0 );",
  10562. // diffuse
  10563. " float dotProduct = dot( normal, lVector );",
  10564. " #ifdef WRAP_AROUND",
  10565. " float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  10566. " float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10567. " vec3 spotDiffuseWeight = mix( vec3( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  10568. " #else",
  10569. " float spotDiffuseWeight = max( dotProduct, 0.0 );",
  10570. " #endif",
  10571. " spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  10572. // specular
  10573. " vec3 spotHalfVector = normalize( lVector + viewPosition );",
  10574. " float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  10575. " float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  10576. " float specularNormalization = ( shininess + 2.0 ) / 8.0;",
  10577. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, spotHalfVector ), 0.0 ), 5.0 );",
  10578. " spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  10579. " }",
  10580. " }",
  10581. "#endif",
  10582. "#if MAX_DIR_LIGHTS > 0",
  10583. " vec3 dirDiffuse = vec3( 0.0 );",
  10584. " vec3 dirSpecular = vec3( 0.0 );" ,
  10585. " for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  10586. " vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  10587. " vec3 dirVector = normalize( lDirection.xyz );",
  10588. // diffuse
  10589. " float dotProduct = dot( normal, dirVector );",
  10590. " #ifdef WRAP_AROUND",
  10591. " float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  10592. " float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10593. " vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  10594. " #else",
  10595. " float dirDiffuseWeight = max( dotProduct, 0.0 );",
  10596. " #endif",
  10597. " dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  10598. // specular
  10599. " vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  10600. " float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  10601. " float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  10602. /*
  10603. // fresnel term from skin shader
  10604. " const float F0 = 0.128;",
  10605. " float base = 1.0 - dot( viewPosition, dirHalfVector );",
  10606. " float exponential = pow( base, 5.0 );",
  10607. " float fresnel = exponential + F0 * ( 1.0 - exponential );",
  10608. */
  10609. /*
  10610. // fresnel term from fresnel shader
  10611. " const float mFresnelBias = 0.08;",
  10612. " const float mFresnelScale = 0.3;",
  10613. " const float mFresnelPower = 5.0;",
  10614. " float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  10615. */
  10616. " float specularNormalization = ( shininess + 2.0 ) / 8.0;",
  10617. // " dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  10618. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( dirVector, dirHalfVector ), 0.0 ), 5.0 );",
  10619. " dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  10620. " }",
  10621. "#endif",
  10622. "#if MAX_HEMI_LIGHTS > 0",
  10623. " vec3 hemiDiffuse = vec3( 0.0 );",
  10624. " vec3 hemiSpecular = vec3( 0.0 );" ,
  10625. " for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  10626. " vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  10627. " vec3 lVector = normalize( lDirection.xyz );",
  10628. // diffuse
  10629. " float dotProduct = dot( normal, lVector );",
  10630. " float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  10631. " vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  10632. " hemiDiffuse += diffuse * hemiColor;",
  10633. // specular (sky light)
  10634. " vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  10635. " float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  10636. " float hemiSpecularWeightSky = specularStrength * max( pow( max( hemiDotNormalHalfSky, 0.0 ), shininess ), 0.0 );",
  10637. // specular (ground light)
  10638. " vec3 lVectorGround = -lVector;",
  10639. " vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  10640. " float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  10641. " float hemiSpecularWeightGround = specularStrength * max( pow( max( hemiDotNormalHalfGround, 0.0 ), shininess ), 0.0 );",
  10642. " float dotProductGround = dot( normal, lVectorGround );",
  10643. " float specularNormalization = ( shininess + 2.0 ) / 8.0;",
  10644. " vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, hemiHalfVectorSky ), 0.0 ), 5.0 );",
  10645. " vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 0.0 ), 5.0 );",
  10646. " hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  10647. " }",
  10648. "#endif",
  10649. "vec3 totalDiffuse = vec3( 0.0 );",
  10650. "vec3 totalSpecular = vec3( 0.0 );",
  10651. "#if MAX_DIR_LIGHTS > 0",
  10652. " totalDiffuse += dirDiffuse;",
  10653. " totalSpecular += dirSpecular;",
  10654. "#endif",
  10655. "#if MAX_HEMI_LIGHTS > 0",
  10656. " totalDiffuse += hemiDiffuse;",
  10657. " totalSpecular += hemiSpecular;",
  10658. "#endif",
  10659. "#if MAX_POINT_LIGHTS > 0",
  10660. " totalDiffuse += pointDiffuse;",
  10661. " totalSpecular += pointSpecular;",
  10662. "#endif",
  10663. "#if MAX_SPOT_LIGHTS > 0",
  10664. " totalDiffuse += spotDiffuse;",
  10665. " totalSpecular += spotSpecular;",
  10666. "#endif",
  10667. "#ifdef METAL",
  10668. " gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  10669. "#else",
  10670. " gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  10671. "#endif"
  10672. ].join("\n"),
  10673. // VERTEX COLORS
  10674. color_pars_fragment: [
  10675. "#ifdef USE_COLOR",
  10676. " varying vec3 vColor;",
  10677. "#endif"
  10678. ].join("\n"),
  10679. color_fragment: [
  10680. "#ifdef USE_COLOR",
  10681. " gl_FragColor = gl_FragColor * vec4( vColor, 1.0 );",
  10682. "#endif"
  10683. ].join("\n"),
  10684. color_pars_vertex: [
  10685. "#ifdef USE_COLOR",
  10686. " varying vec3 vColor;",
  10687. "#endif"
  10688. ].join("\n"),
  10689. color_vertex: [
  10690. "#ifdef USE_COLOR",
  10691. " #ifdef GAMMA_INPUT",
  10692. " vColor = color * color;",
  10693. " #else",
  10694. " vColor = color;",
  10695. " #endif",
  10696. "#endif"
  10697. ].join("\n"),
  10698. // SKINNING
  10699. skinning_pars_vertex: [
  10700. "#ifdef USE_SKINNING",
  10701. " #ifdef BONE_TEXTURE",
  10702. " uniform sampler2D boneTexture;",
  10703. " uniform int boneTextureWidth;",
  10704. " uniform int boneTextureHeight;",
  10705. " mat4 getBoneMatrix( const in float i ) {",
  10706. " float j = i * 4.0;",
  10707. " float x = mod( j, float( boneTextureWidth ) );",
  10708. " float y = floor( j / float( boneTextureWidth ) );",
  10709. " float dx = 1.0 / float( boneTextureWidth );",
  10710. " float dy = 1.0 / float( boneTextureHeight );",
  10711. " y = dy * ( y + 0.5 );",
  10712. " vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  10713. " vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  10714. " vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  10715. " vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  10716. " mat4 bone = mat4( v1, v2, v3, v4 );",
  10717. " return bone;",
  10718. " }",
  10719. " #else",
  10720. " uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  10721. " mat4 getBoneMatrix( const in float i ) {",
  10722. " mat4 bone = boneGlobalMatrices[ int(i) ];",
  10723. " return bone;",
  10724. " }",
  10725. " #endif",
  10726. "#endif"
  10727. ].join("\n"),
  10728. skinbase_vertex: [
  10729. "#ifdef USE_SKINNING",
  10730. " mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  10731. " mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  10732. " mat4 boneMatZ = getBoneMatrix( skinIndex.z );",
  10733. " mat4 boneMatW = getBoneMatrix( skinIndex.w );",
  10734. "#endif"
  10735. ].join("\n"),
  10736. skinning_vertex: [
  10737. "#ifdef USE_SKINNING",
  10738. " #ifdef USE_MORPHTARGETS",
  10739. " vec4 skinVertex = vec4( morphed, 1.0 );",
  10740. " #else",
  10741. " vec4 skinVertex = vec4( position, 1.0 );",
  10742. " #endif",
  10743. " vec4 skinned = vec4( 0.0 );",
  10744. " skinned += boneMatX * skinVertex * skinWeight.x;",
  10745. " skinned += boneMatY * skinVertex * skinWeight.y;",
  10746. " skinned += boneMatZ * skinVertex * skinWeight.z;",
  10747. " skinned += boneMatW * skinVertex * skinWeight.w;",
  10748. "#endif"
  10749. ].join("\n"),
  10750. // MORPHING
  10751. morphtarget_pars_vertex: [
  10752. "#ifdef USE_MORPHTARGETS",
  10753. " #ifndef USE_MORPHNORMALS",
  10754. " uniform float morphTargetInfluences[ 8 ];",
  10755. " #else",
  10756. " uniform float morphTargetInfluences[ 4 ];",
  10757. " #endif",
  10758. "#endif"
  10759. ].join("\n"),
  10760. morphtarget_vertex: [
  10761. "#ifdef USE_MORPHTARGETS",
  10762. " vec3 morphed = vec3( 0.0 );",
  10763. " morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  10764. " morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  10765. " morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  10766. " morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  10767. " #ifndef USE_MORPHNORMALS",
  10768. " morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  10769. " morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  10770. " morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  10771. " morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  10772. " #endif",
  10773. " morphed += position;",
  10774. "#endif"
  10775. ].join("\n"),
  10776. default_vertex : [
  10777. "vec4 mvPosition;",
  10778. "#ifdef USE_SKINNING",
  10779. " mvPosition = modelViewMatrix * skinned;",
  10780. "#endif",
  10781. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  10782. " mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  10783. "#endif",
  10784. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  10785. " mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10786. "#endif",
  10787. "gl_Position = projectionMatrix * mvPosition;"
  10788. ].join("\n"),
  10789. morphnormal_vertex: [
  10790. "#ifdef USE_MORPHNORMALS",
  10791. " vec3 morphedNormal = vec3( 0.0 );",
  10792. " morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  10793. " morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  10794. " morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  10795. " morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  10796. " morphedNormal += normal;",
  10797. "#endif"
  10798. ].join("\n"),
  10799. skinnormal_vertex: [
  10800. "#ifdef USE_SKINNING",
  10801. " mat4 skinMatrix = mat4( 0.0 );",
  10802. " skinMatrix += skinWeight.x * boneMatX;",
  10803. " skinMatrix += skinWeight.y * boneMatY;",
  10804. " skinMatrix += skinWeight.z * boneMatZ;",
  10805. " skinMatrix += skinWeight.w * boneMatW;",
  10806. " #ifdef USE_MORPHNORMALS",
  10807. " vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  10808. " #else",
  10809. " vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  10810. " #endif",
  10811. "#endif"
  10812. ].join("\n"),
  10813. defaultnormal_vertex: [
  10814. "vec3 objectNormal;",
  10815. "#ifdef USE_SKINNING",
  10816. " objectNormal = skinnedNormal.xyz;",
  10817. "#endif",
  10818. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  10819. " objectNormal = morphedNormal;",
  10820. "#endif",
  10821. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  10822. " objectNormal = normal;",
  10823. "#endif",
  10824. "#ifdef FLIP_SIDED",
  10825. " objectNormal = -objectNormal;",
  10826. "#endif",
  10827. "vec3 transformedNormal = normalMatrix * objectNormal;"
  10828. ].join("\n"),
  10829. // SHADOW MAP
  10830. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  10831. // http://spidergl.org/example.php?id=6
  10832. // http://fabiensanglard.net/shadowmapping
  10833. shadowmap_pars_fragment: [
  10834. "#ifdef USE_SHADOWMAP",
  10835. " uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  10836. " uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  10837. " uniform float shadowDarkness[ MAX_SHADOWS ];",
  10838. " uniform float shadowBias[ MAX_SHADOWS ];",
  10839. " varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  10840. " float unpackDepth( const in vec4 rgba_depth ) {",
  10841. " 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 );",
  10842. " float depth = dot( rgba_depth, bit_shift );",
  10843. " return depth;",
  10844. " }",
  10845. "#endif"
  10846. ].join("\n"),
  10847. shadowmap_fragment: [
  10848. "#ifdef USE_SHADOWMAP",
  10849. " #ifdef SHADOWMAP_DEBUG",
  10850. " vec3 frustumColors[3];",
  10851. " frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  10852. " frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  10853. " frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  10854. " #endif",
  10855. " #ifdef SHADOWMAP_CASCADE",
  10856. " int inFrustumCount = 0;",
  10857. " #endif",
  10858. " float fDepth;",
  10859. " vec3 shadowColor = vec3( 1.0 );",
  10860. " for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10861. " vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  10862. // "if ( something && something )" breaks ATI OpenGL shader compiler
  10863. // "if ( all( something, something ) )" using this instead
  10864. " bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  10865. " bool inFrustum = all( inFrustumVec );",
  10866. // don't shadow pixels outside of light frustum
  10867. // use just first frustum (for cascades)
  10868. // don't shadow pixels behind far plane of light frustum
  10869. " #ifdef SHADOWMAP_CASCADE",
  10870. " inFrustumCount += int( inFrustum );",
  10871. " bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  10872. " #else",
  10873. " bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  10874. " #endif",
  10875. " bool frustumTest = all( frustumTestVec );",
  10876. " if ( frustumTest ) {",
  10877. " shadowCoord.z += shadowBias[ i ];",
  10878. " #if defined( SHADOWMAP_TYPE_PCF )",
  10879. // Percentage-close filtering
  10880. // (9 pixel kernel)
  10881. // http://fabiensanglard.net/shadowmappingPCF/
  10882. " float shadow = 0.0;",
  10883. /*
  10884. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  10885. // must enroll loop manually
  10886. " for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  10887. " for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  10888. " vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  10889. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  10890. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  10891. " float fDepth = unpackDepth( rgbaDepth );",
  10892. " if ( fDepth < shadowCoord.z )",
  10893. " shadow += 1.0;",
  10894. " }",
  10895. " shadow /= 9.0;",
  10896. */
  10897. " const float shadowDelta = 1.0 / 9.0;",
  10898. " float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  10899. " float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  10900. " float dx0 = -1.25 * xPixelOffset;",
  10901. " float dy0 = -1.25 * yPixelOffset;",
  10902. " float dx1 = 1.25 * xPixelOffset;",
  10903. " float dy1 = 1.25 * yPixelOffset;",
  10904. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  10905. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10906. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  10907. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10908. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  10909. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10910. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  10911. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10912. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  10913. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10914. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  10915. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10916. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  10917. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10918. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  10919. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10920. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  10921. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10922. " shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  10923. " #elif defined( SHADOWMAP_TYPE_PCF_SOFT )",
  10924. // Percentage-close filtering
  10925. // (9 pixel kernel)
  10926. // http://fabiensanglard.net/shadowmappingPCF/
  10927. " float shadow = 0.0;",
  10928. " float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  10929. " float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  10930. " float dx0 = -1.0 * xPixelOffset;",
  10931. " float dy0 = -1.0 * yPixelOffset;",
  10932. " float dx1 = 1.0 * xPixelOffset;",
  10933. " float dy1 = 1.0 * yPixelOffset;",
  10934. " mat3 shadowKernel;",
  10935. " mat3 depthKernel;",
  10936. " depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  10937. " depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  10938. " depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  10939. " depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  10940. " depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  10941. " depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  10942. " depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  10943. " depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  10944. " depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  10945. " vec3 shadowZ = vec3( shadowCoord.z );",
  10946. " shadowKernel[0] = vec3(lessThan(depthKernel[0], shadowZ ));",
  10947. " shadowKernel[0] *= vec3(0.25);",
  10948. " shadowKernel[1] = vec3(lessThan(depthKernel[1], shadowZ ));",
  10949. " shadowKernel[1] *= vec3(0.25);",
  10950. " shadowKernel[2] = vec3(lessThan(depthKernel[2], shadowZ ));",
  10951. " shadowKernel[2] *= vec3(0.25);",
  10952. " vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );",
  10953. " shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );",
  10954. " shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );",
  10955. " vec4 shadowValues;",
  10956. " shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );",
  10957. " shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );",
  10958. " shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );",
  10959. " shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );",
  10960. " shadow = dot( shadowValues, vec4( 1.0 ) );",
  10961. " shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  10962. " #else",
  10963. " vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  10964. " float fDepth = unpackDepth( rgbaDepth );",
  10965. " if ( fDepth < shadowCoord.z )",
  10966. // spot with multiple shadows is darker
  10967. " shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  10968. // spot with multiple shadows has the same color as single shadow spot
  10969. // " shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  10970. " #endif",
  10971. " }",
  10972. " #ifdef SHADOWMAP_DEBUG",
  10973. " #ifdef SHADOWMAP_CASCADE",
  10974. " if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  10975. " #else",
  10976. " if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  10977. " #endif",
  10978. " #endif",
  10979. " }",
  10980. " #ifdef GAMMA_OUTPUT",
  10981. " shadowColor *= shadowColor;",
  10982. " #endif",
  10983. " gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  10984. "#endif"
  10985. ].join("\n"),
  10986. shadowmap_pars_vertex: [
  10987. "#ifdef USE_SHADOWMAP",
  10988. " varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  10989. " uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  10990. "#endif"
  10991. ].join("\n"),
  10992. shadowmap_vertex: [
  10993. "#ifdef USE_SHADOWMAP",
  10994. " for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10995. " vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  10996. " }",
  10997. "#endif"
  10998. ].join("\n"),
  10999. // ALPHATEST
  11000. alphatest_fragment: [
  11001. "#ifdef ALPHATEST",
  11002. " if ( gl_FragColor.a < ALPHATEST ) discard;",
  11003. "#endif"
  11004. ].join("\n"),
  11005. // LINEAR SPACE
  11006. linear_to_gamma_fragment: [
  11007. "#ifdef GAMMA_OUTPUT",
  11008. " gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  11009. "#endif"
  11010. ].join("\n"),
  11011. // LOGARITHMIC DEPTH BUFFER
  11012. // http://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html
  11013. // WebGL doesn't support gl_FragDepth out of the box, unless the EXT_frag_depth extension is available. On platforms
  11014. // without EXT_frag_depth, we have to fall back on linear z-buffer in the fragment shader, which means that some long
  11015. // faces close to the camera may have issues. This can be worked around by tesselating the model more finely when
  11016. // the camera is near the surface.
  11017. logdepthbuf_pars_vertex: [
  11018. "#ifdef USE_LOGDEPTHBUF",
  11019. " #ifdef USE_LOGDEPTHBUF_EXT",
  11020. " varying float vFragDepth;",
  11021. " #endif",
  11022. " uniform float logDepthBufFC;",
  11023. "#endif",
  11024. ].join('\n'),
  11025. logdepthbuf_vertex: [
  11026. "#ifdef USE_LOGDEPTHBUF",
  11027. " gl_Position.z = log2(max(1e-6, gl_Position.w + 1.0)) * logDepthBufFC;",
  11028. " #ifdef USE_LOGDEPTHBUF_EXT",
  11029. " vFragDepth = 1.0 + gl_Position.w;",
  11030. "#else",
  11031. " gl_Position.z = (gl_Position.z - 1.0) * gl_Position.w;",
  11032. " #endif",
  11033. "#endif"
  11034. ].join("\n"),
  11035. logdepthbuf_pars_fragment: [
  11036. "#ifdef USE_LOGDEPTHBUF",
  11037. " uniform float logDepthBufFC;",
  11038. " #ifdef USE_LOGDEPTHBUF_EXT",
  11039. " #extension GL_EXT_frag_depth : enable",
  11040. " varying float vFragDepth;",
  11041. " #endif",
  11042. "#endif"
  11043. ].join('\n'),
  11044. logdepthbuf_fragment: [
  11045. "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)",
  11046. " gl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;",
  11047. "#endif"
  11048. ].join("\n")
  11049. };
  11050. // File:src/renderers/shaders/UniformsUtils.js
  11051. /**
  11052. * Uniform Utilities
  11053. */
  11054. THREE.UniformsUtils = {
  11055. merge: function ( uniforms ) {
  11056. var u, p, tmp, merged = {};
  11057. for ( u = 0; u < uniforms.length; u ++ ) {
  11058. tmp = this.clone( uniforms[ u ] );
  11059. for ( p in tmp ) {
  11060. merged[ p ] = tmp[ p ];
  11061. }
  11062. }
  11063. return merged;
  11064. },
  11065. clone: function ( uniforms_src ) {
  11066. var u, p, parameter, parameter_src, uniforms_dst = {};
  11067. for ( u in uniforms_src ) {
  11068. uniforms_dst[ u ] = {};
  11069. for ( p in uniforms_src[ u ] ) {
  11070. parameter_src = uniforms_src[ u ][ p ];
  11071. if ( parameter_src instanceof THREE.Color ||
  11072. parameter_src instanceof THREE.Vector2 ||
  11073. parameter_src instanceof THREE.Vector3 ||
  11074. parameter_src instanceof THREE.Vector4 ||
  11075. parameter_src instanceof THREE.Matrix4 ||
  11076. parameter_src instanceof THREE.Texture ) {
  11077. uniforms_dst[ u ][ p ] = parameter_src.clone();
  11078. } else if ( parameter_src instanceof Array ) {
  11079. uniforms_dst[ u ][ p ] = parameter_src.slice();
  11080. } else {
  11081. uniforms_dst[ u ][ p ] = parameter_src;
  11082. }
  11083. }
  11084. }
  11085. return uniforms_dst;
  11086. }
  11087. };
  11088. // File:src/renderers/shaders/UniformsLib.js
  11089. /**
  11090. * Uniforms library for shared webgl shaders
  11091. */
  11092. THREE.UniformsLib = {
  11093. common: {
  11094. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  11095. "opacity" : { type: "f", value: 1.0 },
  11096. "map" : { type: "t", value: null },
  11097. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  11098. "lightMap" : { type: "t", value: null },
  11099. "specularMap" : { type: "t", value: null },
  11100. "envMap" : { type: "t", value: null },
  11101. "flipEnvMap" : { type: "f", value: - 1 },
  11102. "useRefract" : { type: "i", value: 0 },
  11103. "reflectivity" : { type: "f", value: 1.0 },
  11104. "refractionRatio" : { type: "f", value: 0.98 },
  11105. "combine" : { type: "i", value: 0 },
  11106. "morphTargetInfluences" : { type: "f", value: 0 }
  11107. },
  11108. bump: {
  11109. "bumpMap" : { type: "t", value: null },
  11110. "bumpScale" : { type: "f", value: 1 }
  11111. },
  11112. normalmap: {
  11113. "normalMap" : { type: "t", value: null },
  11114. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  11115. },
  11116. fog : {
  11117. "fogDensity" : { type: "f", value: 0.00025 },
  11118. "fogNear" : { type: "f", value: 1 },
  11119. "fogFar" : { type: "f", value: 2000 },
  11120. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  11121. },
  11122. lights: {
  11123. "ambientLightColor" : { type: "fv", value: [] },
  11124. "directionalLightDirection" : { type: "fv", value: [] },
  11125. "directionalLightColor" : { type: "fv", value: [] },
  11126. "hemisphereLightDirection" : { type: "fv", value: [] },
  11127. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  11128. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  11129. "pointLightColor" : { type: "fv", value: [] },
  11130. "pointLightPosition" : { type: "fv", value: [] },
  11131. "pointLightDistance" : { type: "fv1", value: [] },
  11132. "spotLightColor" : { type: "fv", value: [] },
  11133. "spotLightPosition" : { type: "fv", value: [] },
  11134. "spotLightDirection" : { type: "fv", value: [] },
  11135. "spotLightDistance" : { type: "fv1", value: [] },
  11136. "spotLightAngleCos" : { type: "fv1", value: [] },
  11137. "spotLightExponent" : { type: "fv1", value: [] }
  11138. },
  11139. particle: {
  11140. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  11141. "opacity" : { type: "f", value: 1.0 },
  11142. "size" : { type: "f", value: 1.0 },
  11143. "scale" : { type: "f", value: 1.0 },
  11144. "map" : { type: "t", value: null },
  11145. "fogDensity" : { type: "f", value: 0.00025 },
  11146. "fogNear" : { type: "f", value: 1 },
  11147. "fogFar" : { type: "f", value: 2000 },
  11148. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  11149. },
  11150. shadowmap: {
  11151. "shadowMap": { type: "tv", value: [] },
  11152. "shadowMapSize": { type: "v2v", value: [] },
  11153. "shadowBias" : { type: "fv1", value: [] },
  11154. "shadowDarkness": { type: "fv1", value: [] },
  11155. "shadowMatrix" : { type: "m4v", value: [] }
  11156. }
  11157. };
  11158. // File:src/renderers/shaders/ShaderLib.js
  11159. /**
  11160. * Webgl Shader Library for three.js
  11161. *
  11162. * @author alteredq / http://alteredqualia.com/
  11163. * @author mrdoob / http://mrdoob.com/
  11164. * @author mikael emtinger / http://gomo.se/
  11165. */
  11166. THREE.ShaderLib = {
  11167. 'basic': {
  11168. uniforms: THREE.UniformsUtils.merge( [
  11169. THREE.UniformsLib[ "common" ],
  11170. THREE.UniformsLib[ "fog" ],
  11171. THREE.UniformsLib[ "shadowmap" ]
  11172. ] ),
  11173. vertexShader: [
  11174. THREE.ShaderChunk[ "map_pars_vertex" ],
  11175. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  11176. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  11177. THREE.ShaderChunk[ "color_pars_vertex" ],
  11178. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11179. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11180. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11181. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11182. "void main() {",
  11183. THREE.ShaderChunk[ "map_vertex" ],
  11184. THREE.ShaderChunk[ "lightmap_vertex" ],
  11185. THREE.ShaderChunk[ "color_vertex" ],
  11186. THREE.ShaderChunk[ "skinbase_vertex" ],
  11187. " #ifdef USE_ENVMAP",
  11188. THREE.ShaderChunk[ "morphnormal_vertex" ],
  11189. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11190. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  11191. " #endif",
  11192. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11193. THREE.ShaderChunk[ "skinning_vertex" ],
  11194. THREE.ShaderChunk[ "default_vertex" ],
  11195. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11196. THREE.ShaderChunk[ "worldpos_vertex" ],
  11197. THREE.ShaderChunk[ "envmap_vertex" ],
  11198. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11199. "}"
  11200. ].join("\n"),
  11201. fragmentShader: [
  11202. "uniform vec3 diffuse;",
  11203. "uniform float opacity;",
  11204. THREE.ShaderChunk[ "color_pars_fragment" ],
  11205. THREE.ShaderChunk[ "map_pars_fragment" ],
  11206. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  11207. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  11208. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11209. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11210. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  11211. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11212. "void main() {",
  11213. " gl_FragColor = vec4( diffuse, opacity );",
  11214. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11215. THREE.ShaderChunk[ "map_fragment" ],
  11216. THREE.ShaderChunk[ "alphatest_fragment" ],
  11217. THREE.ShaderChunk[ "specularmap_fragment" ],
  11218. THREE.ShaderChunk[ "lightmap_fragment" ],
  11219. THREE.ShaderChunk[ "color_fragment" ],
  11220. THREE.ShaderChunk[ "envmap_fragment" ],
  11221. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11222. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11223. THREE.ShaderChunk[ "fog_fragment" ],
  11224. "}"
  11225. ].join("\n")
  11226. },
  11227. 'lambert': {
  11228. uniforms: THREE.UniformsUtils.merge( [
  11229. THREE.UniformsLib[ "common" ],
  11230. THREE.UniformsLib[ "fog" ],
  11231. THREE.UniformsLib[ "lights" ],
  11232. THREE.UniformsLib[ "shadowmap" ],
  11233. {
  11234. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  11235. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  11236. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  11237. }
  11238. ] ),
  11239. vertexShader: [
  11240. "#define LAMBERT",
  11241. "varying vec3 vLightFront;",
  11242. "#ifdef DOUBLE_SIDED",
  11243. " varying vec3 vLightBack;",
  11244. "#endif",
  11245. THREE.ShaderChunk[ "map_pars_vertex" ],
  11246. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  11247. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  11248. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  11249. THREE.ShaderChunk[ "color_pars_vertex" ],
  11250. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11251. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11252. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11253. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11254. "void main() {",
  11255. THREE.ShaderChunk[ "map_vertex" ],
  11256. THREE.ShaderChunk[ "lightmap_vertex" ],
  11257. THREE.ShaderChunk[ "color_vertex" ],
  11258. THREE.ShaderChunk[ "morphnormal_vertex" ],
  11259. THREE.ShaderChunk[ "skinbase_vertex" ],
  11260. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11261. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  11262. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11263. THREE.ShaderChunk[ "skinning_vertex" ],
  11264. THREE.ShaderChunk[ "default_vertex" ],
  11265. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11266. THREE.ShaderChunk[ "worldpos_vertex" ],
  11267. THREE.ShaderChunk[ "envmap_vertex" ],
  11268. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  11269. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11270. "}"
  11271. ].join("\n"),
  11272. fragmentShader: [
  11273. "uniform float opacity;",
  11274. "varying vec3 vLightFront;",
  11275. "#ifdef DOUBLE_SIDED",
  11276. " varying vec3 vLightBack;",
  11277. "#endif",
  11278. THREE.ShaderChunk[ "color_pars_fragment" ],
  11279. THREE.ShaderChunk[ "map_pars_fragment" ],
  11280. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  11281. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  11282. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11283. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11284. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  11285. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11286. "void main() {",
  11287. " gl_FragColor = vec4( vec3( 1.0 ), opacity );",
  11288. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11289. THREE.ShaderChunk[ "map_fragment" ],
  11290. THREE.ShaderChunk[ "alphatest_fragment" ],
  11291. THREE.ShaderChunk[ "specularmap_fragment" ],
  11292. " #ifdef DOUBLE_SIDED",
  11293. //"float isFront = float( gl_FrontFacing );",
  11294. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  11295. " if ( gl_FrontFacing )",
  11296. " gl_FragColor.xyz *= vLightFront;",
  11297. " else",
  11298. " gl_FragColor.xyz *= vLightBack;",
  11299. " #else",
  11300. " gl_FragColor.xyz *= vLightFront;",
  11301. " #endif",
  11302. THREE.ShaderChunk[ "lightmap_fragment" ],
  11303. THREE.ShaderChunk[ "color_fragment" ],
  11304. THREE.ShaderChunk[ "envmap_fragment" ],
  11305. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11306. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11307. THREE.ShaderChunk[ "fog_fragment" ],
  11308. "}"
  11309. ].join("\n")
  11310. },
  11311. 'phong': {
  11312. uniforms: THREE.UniformsUtils.merge( [
  11313. THREE.UniformsLib[ "common" ],
  11314. THREE.UniformsLib[ "bump" ],
  11315. THREE.UniformsLib[ "normalmap" ],
  11316. THREE.UniformsLib[ "fog" ],
  11317. THREE.UniformsLib[ "lights" ],
  11318. THREE.UniformsLib[ "shadowmap" ],
  11319. {
  11320. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  11321. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  11322. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  11323. "shininess": { type: "f", value: 30 },
  11324. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  11325. }
  11326. ] ),
  11327. vertexShader: [
  11328. "#define PHONG",
  11329. "varying vec3 vViewPosition;",
  11330. "varying vec3 vNormal;",
  11331. THREE.ShaderChunk[ "map_pars_vertex" ],
  11332. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  11333. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  11334. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  11335. THREE.ShaderChunk[ "color_pars_vertex" ],
  11336. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11337. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11338. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11339. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11340. "void main() {",
  11341. THREE.ShaderChunk[ "map_vertex" ],
  11342. THREE.ShaderChunk[ "lightmap_vertex" ],
  11343. THREE.ShaderChunk[ "color_vertex" ],
  11344. THREE.ShaderChunk[ "morphnormal_vertex" ],
  11345. THREE.ShaderChunk[ "skinbase_vertex" ],
  11346. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11347. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  11348. " vNormal = normalize( transformedNormal );",
  11349. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11350. THREE.ShaderChunk[ "skinning_vertex" ],
  11351. THREE.ShaderChunk[ "default_vertex" ],
  11352. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11353. " vViewPosition = -mvPosition.xyz;",
  11354. THREE.ShaderChunk[ "worldpos_vertex" ],
  11355. THREE.ShaderChunk[ "envmap_vertex" ],
  11356. THREE.ShaderChunk[ "lights_phong_vertex" ],
  11357. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11358. "}"
  11359. ].join("\n"),
  11360. fragmentShader: [
  11361. "uniform vec3 diffuse;",
  11362. "uniform float opacity;",
  11363. "uniform vec3 ambient;",
  11364. "uniform vec3 emissive;",
  11365. "uniform vec3 specular;",
  11366. "uniform float shininess;",
  11367. THREE.ShaderChunk[ "color_pars_fragment" ],
  11368. THREE.ShaderChunk[ "map_pars_fragment" ],
  11369. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  11370. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  11371. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11372. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  11373. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11374. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  11375. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  11376. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  11377. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11378. "void main() {",
  11379. " gl_FragColor = vec4( vec3( 1.0 ), opacity );",
  11380. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11381. THREE.ShaderChunk[ "map_fragment" ],
  11382. THREE.ShaderChunk[ "alphatest_fragment" ],
  11383. THREE.ShaderChunk[ "specularmap_fragment" ],
  11384. THREE.ShaderChunk[ "lights_phong_fragment" ],
  11385. THREE.ShaderChunk[ "lightmap_fragment" ],
  11386. THREE.ShaderChunk[ "color_fragment" ],
  11387. THREE.ShaderChunk[ "envmap_fragment" ],
  11388. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11389. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11390. THREE.ShaderChunk[ "fog_fragment" ],
  11391. "}"
  11392. ].join("\n")
  11393. },
  11394. 'particle_basic': {
  11395. uniforms: THREE.UniformsUtils.merge( [
  11396. THREE.UniformsLib[ "particle" ],
  11397. THREE.UniformsLib[ "shadowmap" ]
  11398. ] ),
  11399. vertexShader: [
  11400. "uniform float size;",
  11401. "uniform float scale;",
  11402. THREE.ShaderChunk[ "color_pars_vertex" ],
  11403. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11404. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11405. "void main() {",
  11406. THREE.ShaderChunk[ "color_vertex" ],
  11407. " vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  11408. " #ifdef USE_SIZEATTENUATION",
  11409. " gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  11410. " #else",
  11411. " gl_PointSize = size;",
  11412. " #endif",
  11413. " gl_Position = projectionMatrix * mvPosition;",
  11414. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11415. THREE.ShaderChunk[ "worldpos_vertex" ],
  11416. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11417. "}"
  11418. ].join("\n"),
  11419. fragmentShader: [
  11420. "uniform vec3 psColor;",
  11421. "uniform float opacity;",
  11422. THREE.ShaderChunk[ "color_pars_fragment" ],
  11423. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  11424. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11425. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11426. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11427. "void main() {",
  11428. " gl_FragColor = vec4( psColor, opacity );",
  11429. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11430. THREE.ShaderChunk[ "map_particle_fragment" ],
  11431. THREE.ShaderChunk[ "alphatest_fragment" ],
  11432. THREE.ShaderChunk[ "color_fragment" ],
  11433. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11434. THREE.ShaderChunk[ "fog_fragment" ],
  11435. "}"
  11436. ].join("\n")
  11437. },
  11438. 'dashed': {
  11439. uniforms: THREE.UniformsUtils.merge( [
  11440. THREE.UniformsLib[ "common" ],
  11441. THREE.UniformsLib[ "fog" ],
  11442. {
  11443. "scale" : { type: "f", value: 1 },
  11444. "dashSize" : { type: "f", value: 1 },
  11445. "totalSize": { type: "f", value: 2 }
  11446. }
  11447. ] ),
  11448. vertexShader: [
  11449. "uniform float scale;",
  11450. "attribute float lineDistance;",
  11451. "varying float vLineDistance;",
  11452. THREE.ShaderChunk[ "color_pars_vertex" ],
  11453. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11454. "void main() {",
  11455. THREE.ShaderChunk[ "color_vertex" ],
  11456. " vLineDistance = scale * lineDistance;",
  11457. " vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  11458. " gl_Position = projectionMatrix * mvPosition;",
  11459. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11460. "}"
  11461. ].join("\n"),
  11462. fragmentShader: [
  11463. "uniform vec3 diffuse;",
  11464. "uniform float opacity;",
  11465. "uniform float dashSize;",
  11466. "uniform float totalSize;",
  11467. "varying float vLineDistance;",
  11468. THREE.ShaderChunk[ "color_pars_fragment" ],
  11469. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11470. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11471. "void main() {",
  11472. " if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  11473. " discard;",
  11474. " }",
  11475. " gl_FragColor = vec4( diffuse, opacity );",
  11476. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11477. THREE.ShaderChunk[ "color_fragment" ],
  11478. THREE.ShaderChunk[ "fog_fragment" ],
  11479. "}"
  11480. ].join("\n")
  11481. },
  11482. 'depth': {
  11483. uniforms: {
  11484. "mNear": { type: "f", value: 1.0 },
  11485. "mFar" : { type: "f", value: 2000.0 },
  11486. "opacity" : { type: "f", value: 1.0 }
  11487. },
  11488. vertexShader: [
  11489. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11490. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11491. "void main() {",
  11492. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11493. THREE.ShaderChunk[ "default_vertex" ],
  11494. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11495. "}"
  11496. ].join("\n"),
  11497. fragmentShader: [
  11498. "uniform float mNear;",
  11499. "uniform float mFar;",
  11500. "uniform float opacity;",
  11501. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11502. "void main() {",
  11503. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11504. " #ifdef USE_LOGDEPTHBUF_EXT",
  11505. " float depth = gl_FragDepthEXT / gl_FragCoord.w;",
  11506. " #else",
  11507. " float depth = gl_FragCoord.z / gl_FragCoord.w;",
  11508. " #endif",
  11509. " float color = 1.0 - smoothstep( mNear, mFar, depth );",
  11510. " gl_FragColor = vec4( vec3( color ), opacity );",
  11511. "}"
  11512. ].join("\n")
  11513. },
  11514. 'normal': {
  11515. uniforms: {
  11516. "opacity" : { type: "f", value: 1.0 }
  11517. },
  11518. vertexShader: [
  11519. "varying vec3 vNormal;",
  11520. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11521. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11522. "void main() {",
  11523. " vNormal = normalize( normalMatrix * normal );",
  11524. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11525. THREE.ShaderChunk[ "default_vertex" ],
  11526. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11527. "}"
  11528. ].join("\n"),
  11529. fragmentShader: [
  11530. "uniform float opacity;",
  11531. "varying vec3 vNormal;",
  11532. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11533. "void main() {",
  11534. " gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  11535. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11536. "}"
  11537. ].join("\n")
  11538. },
  11539. /* -------------------------------------------------------------------------
  11540. // Normal map shader
  11541. // - Blinn-Phong
  11542. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  11543. // - point and directional lights (use with "lights: true" material option)
  11544. ------------------------------------------------------------------------- */
  11545. 'normalmap' : {
  11546. uniforms: THREE.UniformsUtils.merge( [
  11547. THREE.UniformsLib[ "fog" ],
  11548. THREE.UniformsLib[ "lights" ],
  11549. THREE.UniformsLib[ "shadowmap" ],
  11550. {
  11551. "enableAO" : { type: "i", value: 0 },
  11552. "enableDiffuse" : { type: "i", value: 0 },
  11553. "enableSpecular" : { type: "i", value: 0 },
  11554. "enableReflection" : { type: "i", value: 0 },
  11555. "enableDisplacement": { type: "i", value: 0 },
  11556. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  11557. "tDiffuse" : { type: "t", value: null },
  11558. "tCube" : { type: "t", value: null },
  11559. "tNormal" : { type: "t", value: null },
  11560. "tSpecular" : { type: "t", value: null },
  11561. "tAO" : { type: "t", value: null },
  11562. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  11563. "uDisplacementBias": { type: "f", value: 0.0 },
  11564. "uDisplacementScale": { type: "f", value: 1.0 },
  11565. "diffuse": { type: "c", value: new THREE.Color( 0xffffff ) },
  11566. "specular": { type: "c", value: new THREE.Color( 0x111111 ) },
  11567. "ambient": { type: "c", value: new THREE.Color( 0xffffff ) },
  11568. "shininess": { type: "f", value: 30 },
  11569. "opacity": { type: "f", value: 1 },
  11570. "useRefract": { type: "i", value: 0 },
  11571. "refractionRatio": { type: "f", value: 0.98 },
  11572. "reflectivity": { type: "f", value: 0.5 },
  11573. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  11574. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  11575. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  11576. }
  11577. ] ),
  11578. fragmentShader: [
  11579. "uniform vec3 ambient;",
  11580. "uniform vec3 diffuse;",
  11581. "uniform vec3 specular;",
  11582. "uniform float shininess;",
  11583. "uniform float opacity;",
  11584. "uniform bool enableDiffuse;",
  11585. "uniform bool enableSpecular;",
  11586. "uniform bool enableAO;",
  11587. "uniform bool enableReflection;",
  11588. "uniform sampler2D tDiffuse;",
  11589. "uniform sampler2D tNormal;",
  11590. "uniform sampler2D tSpecular;",
  11591. "uniform sampler2D tAO;",
  11592. "uniform samplerCube tCube;",
  11593. "uniform vec2 uNormalScale;",
  11594. "uniform bool useRefract;",
  11595. "uniform float refractionRatio;",
  11596. "uniform float reflectivity;",
  11597. "varying vec3 vTangent;",
  11598. "varying vec3 vBinormal;",
  11599. "varying vec3 vNormal;",
  11600. "varying vec2 vUv;",
  11601. "uniform vec3 ambientLightColor;",
  11602. "#if MAX_DIR_LIGHTS > 0",
  11603. " uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  11604. " uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  11605. "#endif",
  11606. "#if MAX_HEMI_LIGHTS > 0",
  11607. " uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  11608. " uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  11609. " uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  11610. "#endif",
  11611. "#if MAX_POINT_LIGHTS > 0",
  11612. " uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  11613. " uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  11614. " uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  11615. "#endif",
  11616. "#if MAX_SPOT_LIGHTS > 0",
  11617. " uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  11618. " uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  11619. " uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  11620. " uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  11621. " uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  11622. " uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  11623. "#endif",
  11624. "#ifdef WRAP_AROUND",
  11625. " uniform vec3 wrapRGB;",
  11626. "#endif",
  11627. "varying vec3 vWorldPosition;",
  11628. "varying vec3 vViewPosition;",
  11629. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11630. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11631. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11632. "void main() {",
  11633. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11634. " gl_FragColor = vec4( vec3( 1.0 ), opacity );",
  11635. " vec3 specularTex = vec3( 1.0 );",
  11636. " vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  11637. " normalTex.xy *= uNormalScale;",
  11638. " normalTex = normalize( normalTex );",
  11639. " if( enableDiffuse ) {",
  11640. " #ifdef GAMMA_INPUT",
  11641. " vec4 texelColor = texture2D( tDiffuse, vUv );",
  11642. " texelColor.xyz *= texelColor.xyz;",
  11643. " gl_FragColor = gl_FragColor * texelColor;",
  11644. " #else",
  11645. " gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  11646. " #endif",
  11647. " }",
  11648. " if( enableAO ) {",
  11649. " #ifdef GAMMA_INPUT",
  11650. " vec4 aoColor = texture2D( tAO, vUv );",
  11651. " aoColor.xyz *= aoColor.xyz;",
  11652. " gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  11653. " #else",
  11654. " gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  11655. " #endif",
  11656. " }",
  11657. " if( enableSpecular )",
  11658. " specularTex = texture2D( tSpecular, vUv ).xyz;",
  11659. " mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  11660. " vec3 finalNormal = tsb * normalTex;",
  11661. " #ifdef FLIP_SIDED",
  11662. " finalNormal = -finalNormal;",
  11663. " #endif",
  11664. " vec3 normal = normalize( finalNormal );",
  11665. " vec3 viewPosition = normalize( vViewPosition );",
  11666. // point lights
  11667. " #if MAX_POINT_LIGHTS > 0",
  11668. " vec3 pointDiffuse = vec3( 0.0 );",
  11669. " vec3 pointSpecular = vec3( 0.0 );",
  11670. " for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  11671. " vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  11672. " vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  11673. " float pointDistance = 1.0;",
  11674. " if ( pointLightDistance[ i ] > 0.0 )",
  11675. " pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  11676. " pointVector = normalize( pointVector );",
  11677. // diffuse
  11678. " #ifdef WRAP_AROUND",
  11679. " float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  11680. " float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  11681. " vec3 pointDiffuseWeight = mix( vec3( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  11682. " #else",
  11683. " float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  11684. " #endif",
  11685. " pointDiffuse += pointDistance * pointLightColor[ i ] * diffuse * pointDiffuseWeight;",
  11686. // specular
  11687. " vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  11688. " float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  11689. " float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  11690. " float specularNormalization = ( shininess + 2.0 ) / 8.0;",
  11691. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( pointVector, pointHalfVector ), 0.0 ), 5.0 );",
  11692. " pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  11693. " }",
  11694. " #endif",
  11695. // spot lights
  11696. " #if MAX_SPOT_LIGHTS > 0",
  11697. " vec3 spotDiffuse = vec3( 0.0 );",
  11698. " vec3 spotSpecular = vec3( 0.0 );",
  11699. " for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  11700. " vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  11701. " vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  11702. " float spotDistance = 1.0;",
  11703. " if ( spotLightDistance[ i ] > 0.0 )",
  11704. " spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  11705. " spotVector = normalize( spotVector );",
  11706. " float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  11707. " if ( spotEffect > spotLightAngleCos[ i ] ) {",
  11708. " spotEffect = max( pow( max( spotEffect, 0.0 ), spotLightExponent[ i ] ), 0.0 );",
  11709. // diffuse
  11710. " #ifdef WRAP_AROUND",
  11711. " float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  11712. " float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  11713. " vec3 spotDiffuseWeight = mix( vec3( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  11714. " #else",
  11715. " float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  11716. " #endif",
  11717. " spotDiffuse += spotDistance * spotLightColor[ i ] * diffuse * spotDiffuseWeight * spotEffect;",
  11718. // specular
  11719. " vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  11720. " float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  11721. " float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  11722. " float specularNormalization = ( shininess + 2.0 ) / 8.0;",
  11723. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( spotVector, spotHalfVector ), 0.0 ), 5.0 );",
  11724. " spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  11725. " }",
  11726. " }",
  11727. " #endif",
  11728. // directional lights
  11729. " #if MAX_DIR_LIGHTS > 0",
  11730. " vec3 dirDiffuse = vec3( 0.0 );",
  11731. " vec3 dirSpecular = vec3( 0.0 );",
  11732. " for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  11733. " vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  11734. " vec3 dirVector = normalize( lDirection.xyz );",
  11735. // diffuse
  11736. " #ifdef WRAP_AROUND",
  11737. " float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  11738. " float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  11739. " vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  11740. " #else",
  11741. " float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  11742. " #endif",
  11743. " dirDiffuse += directionalLightColor[ i ] * diffuse * dirDiffuseWeight;",
  11744. // specular
  11745. " vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  11746. " float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  11747. " float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  11748. " float specularNormalization = ( shininess + 2.0 ) / 8.0;",
  11749. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( dirVector, dirHalfVector ), 0.0 ), 5.0 );",
  11750. " dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  11751. " }",
  11752. " #endif",
  11753. // hemisphere lights
  11754. " #if MAX_HEMI_LIGHTS > 0",
  11755. " vec3 hemiDiffuse = vec3( 0.0 );",
  11756. " vec3 hemiSpecular = vec3( 0.0 );" ,
  11757. " for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  11758. " vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  11759. " vec3 lVector = normalize( lDirection.xyz );",
  11760. // diffuse
  11761. " float dotProduct = dot( normal, lVector );",
  11762. " float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  11763. " vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  11764. " hemiDiffuse += diffuse * hemiColor;",
  11765. // specular (sky light)
  11766. " vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  11767. " float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  11768. " float hemiSpecularWeightSky = specularTex.r * max( pow( max( hemiDotNormalHalfSky, 0.0 ), shininess ), 0.0 );",
  11769. // specular (ground light)
  11770. " vec3 lVectorGround = -lVector;",
  11771. " vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  11772. " float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  11773. " float hemiSpecularWeightGround = specularTex.r * max( pow( max( hemiDotNormalHalfGround, 0.0 ), shininess ), 0.0 );",
  11774. " float dotProductGround = dot( normal, lVectorGround );",
  11775. " float specularNormalization = ( shininess + 2.0 ) / 8.0;",
  11776. " vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, hemiHalfVectorSky ), 0.0 ), 5.0 );",
  11777. " vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 0.0 ), 5.0 );",
  11778. " hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  11779. " }",
  11780. " #endif",
  11781. // all lights contribution summation
  11782. " vec3 totalDiffuse = vec3( 0.0 );",
  11783. " vec3 totalSpecular = vec3( 0.0 );",
  11784. " #if MAX_DIR_LIGHTS > 0",
  11785. " totalDiffuse += dirDiffuse;",
  11786. " totalSpecular += dirSpecular;",
  11787. " #endif",
  11788. " #if MAX_HEMI_LIGHTS > 0",
  11789. " totalDiffuse += hemiDiffuse;",
  11790. " totalSpecular += hemiSpecular;",
  11791. " #endif",
  11792. " #if MAX_POINT_LIGHTS > 0",
  11793. " totalDiffuse += pointDiffuse;",
  11794. " totalSpecular += pointSpecular;",
  11795. " #endif",
  11796. " #if MAX_SPOT_LIGHTS > 0",
  11797. " totalDiffuse += spotDiffuse;",
  11798. " totalSpecular += spotSpecular;",
  11799. " #endif",
  11800. " #ifdef METAL",
  11801. " gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  11802. " #else",
  11803. " gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  11804. " #endif",
  11805. " if ( enableReflection ) {",
  11806. " vec3 vReflect;",
  11807. " vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  11808. " if ( useRefract ) {",
  11809. " vReflect = refract( cameraToVertex, normal, refractionRatio );",
  11810. " } else {",
  11811. " vReflect = reflect( cameraToVertex, normal );",
  11812. " }",
  11813. " vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  11814. " #ifdef GAMMA_INPUT",
  11815. " cubeColor.xyz *= cubeColor.xyz;",
  11816. " #endif",
  11817. " gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * reflectivity );",
  11818. " }",
  11819. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11820. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11821. THREE.ShaderChunk[ "fog_fragment" ],
  11822. "}"
  11823. ].join("\n"),
  11824. vertexShader: [
  11825. "attribute vec4 tangent;",
  11826. "uniform vec2 uOffset;",
  11827. "uniform vec2 uRepeat;",
  11828. "uniform bool enableDisplacement;",
  11829. "#ifdef VERTEX_TEXTURES",
  11830. " uniform sampler2D tDisplacement;",
  11831. " uniform float uDisplacementScale;",
  11832. " uniform float uDisplacementBias;",
  11833. "#endif",
  11834. "varying vec3 vTangent;",
  11835. "varying vec3 vBinormal;",
  11836. "varying vec3 vNormal;",
  11837. "varying vec2 vUv;",
  11838. "varying vec3 vWorldPosition;",
  11839. "varying vec3 vViewPosition;",
  11840. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11841. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11842. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11843. "void main() {",
  11844. THREE.ShaderChunk[ "skinbase_vertex" ],
  11845. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11846. // normal, tangent and binormal vectors
  11847. " #ifdef USE_SKINNING",
  11848. " vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
  11849. " vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  11850. " vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
  11851. " #else",
  11852. " vNormal = normalize( normalMatrix * normal );",
  11853. " vTangent = normalize( normalMatrix * tangent.xyz );",
  11854. " #endif",
  11855. " vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
  11856. " vUv = uv * uRepeat + uOffset;",
  11857. // displacement mapping
  11858. " vec3 displacedPosition;",
  11859. " #ifdef VERTEX_TEXTURES",
  11860. " if ( enableDisplacement ) {",
  11861. " vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  11862. " float df = uDisplacementScale * dv.x + uDisplacementBias;",
  11863. " displacedPosition = position + normalize( normal ) * df;",
  11864. " } else {",
  11865. " #ifdef USE_SKINNING",
  11866. " vec4 skinVertex = vec4( position, 1.0 );",
  11867. " vec4 skinned = vec4( 0.0 );",
  11868. " skinned += boneMatX * skinVertex * skinWeight.x;",
  11869. " skinned += boneMatY * skinVertex * skinWeight.y;",
  11870. " skinned += boneMatZ * skinVertex * skinWeight.z;",
  11871. " skinned += boneMatW * skinVertex * skinWeight.w;",
  11872. " displacedPosition = skinned.xyz;",
  11873. " #else",
  11874. " displacedPosition = position;",
  11875. " #endif",
  11876. " }",
  11877. " #else",
  11878. " #ifdef USE_SKINNING",
  11879. " vec4 skinVertex = vec4( position, 1.0 );",
  11880. " vec4 skinned = vec4( 0.0 );",
  11881. " skinned += boneMatX * skinVertex * skinWeight.x;",
  11882. " skinned += boneMatY * skinVertex * skinWeight.y;",
  11883. " skinned += boneMatZ * skinVertex * skinWeight.z;",
  11884. " skinned += boneMatW * skinVertex * skinWeight.w;",
  11885. " displacedPosition = skinned.xyz;",
  11886. " #else",
  11887. " displacedPosition = position;",
  11888. " #endif",
  11889. " #endif",
  11890. //
  11891. " vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  11892. " vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  11893. " gl_Position = projectionMatrix * mvPosition;",
  11894. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11895. //
  11896. " vWorldPosition = worldPosition.xyz;",
  11897. " vViewPosition = -mvPosition.xyz;",
  11898. // shadows
  11899. " #ifdef USE_SHADOWMAP",
  11900. " for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  11901. " vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  11902. " }",
  11903. " #endif",
  11904. "}"
  11905. ].join("\n")
  11906. },
  11907. /* -------------------------------------------------------------------------
  11908. // Cube map shader
  11909. ------------------------------------------------------------------------- */
  11910. 'cube': {
  11911. uniforms: { "tCube": { type: "t", value: null },
  11912. "tFlip": { type: "f", value: - 1 } },
  11913. vertexShader: [
  11914. "varying vec3 vWorldPosition;",
  11915. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11916. "void main() {",
  11917. " vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  11918. " vWorldPosition = worldPosition.xyz;",
  11919. " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  11920. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11921. "}"
  11922. ].join("\n"),
  11923. fragmentShader: [
  11924. "uniform samplerCube tCube;",
  11925. "uniform float tFlip;",
  11926. "varying vec3 vWorldPosition;",
  11927. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11928. "void main() {",
  11929. " gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  11930. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11931. "}"
  11932. ].join("\n")
  11933. },
  11934. /* Depth encoding into RGBA texture
  11935. *
  11936. * based on SpiderGL shadow map example
  11937. * http://spidergl.org/example.php?id=6
  11938. *
  11939. * originally from
  11940. * http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  11941. *
  11942. * see also
  11943. * http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  11944. */
  11945. 'depthRGBA': {
  11946. uniforms: {},
  11947. vertexShader: [
  11948. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11949. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11950. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11951. "void main() {",
  11952. THREE.ShaderChunk[ "skinbase_vertex" ],
  11953. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11954. THREE.ShaderChunk[ "skinning_vertex" ],
  11955. THREE.ShaderChunk[ "default_vertex" ],
  11956. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11957. "}"
  11958. ].join("\n"),
  11959. fragmentShader: [
  11960. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11961. "vec4 pack_depth( const in float depth ) {",
  11962. " const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  11963. " const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  11964. " vec4 res = mod( depth * bit_shift * vec4( 255 ), vec4( 256 ) ) / vec4( 255 );", // " vec4 res = fract( depth * bit_shift );",
  11965. " res -= res.xxyz * bit_mask;",
  11966. " return res;",
  11967. "}",
  11968. "void main() {",
  11969. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11970. " #ifdef USE_LOGDEPTHBUF_EXT",
  11971. " gl_FragData[ 0 ] = pack_depth( gl_FragDepthEXT );",
  11972. " #else",
  11973. " gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  11974. " #endif",
  11975. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  11976. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  11977. //"gl_FragData[ 0 ] = pack_depth( z );",
  11978. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  11979. "}"
  11980. ].join("\n")
  11981. }
  11982. };
  11983. // File:src/renderers/WebGLRenderer.js
  11984. /**
  11985. * @author supereggbert / http://www.paulbrunt.co.uk/
  11986. * @author mrdoob / http://mrdoob.com/
  11987. * @author alteredq / http://alteredqualia.com/
  11988. * @author szimek / https://github.com/szimek/
  11989. */
  11990. THREE.WebGLRenderer = function ( parameters ) {
  11991. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  11992. parameters = parameters || {};
  11993. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  11994. _context = parameters.context !== undefined ? parameters.context : null,
  11995. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  11996. _buffers = {},
  11997. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  11998. _depth = parameters.depth !== undefined ? parameters.depth : true,
  11999. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  12000. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  12001. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  12002. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  12003. _logarithmicDepthBuffer = parameters.logarithmicDepthBuffer !== undefined ? parameters.logarithmicDepthBuffer : false,
  12004. _clearColor = new THREE.Color( 0x000000 ),
  12005. _clearAlpha = 0;
  12006. var opaqueObjects = [];
  12007. var transparentObjects = [];
  12008. var _sortObjects = true;
  12009. // public properties
  12010. this.domElement = _canvas;
  12011. this.context = null;
  12012. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  12013. ? parameters.devicePixelRatio
  12014. : self.devicePixelRatio !== undefined
  12015. ? self.devicePixelRatio
  12016. : 1;
  12017. // clearing
  12018. this.autoClear = true;
  12019. this.autoClearColor = true;
  12020. this.autoClearDepth = true;
  12021. this.autoClearStencil = true;
  12022. // scene graph
  12023. this.sortObjects = true;
  12024. // physically based shading
  12025. this.gammaInput = false;
  12026. this.gammaOutput = false;
  12027. // shadow map
  12028. this.shadowMapEnabled = false;
  12029. this.shadowMapAutoUpdate = true;
  12030. this.shadowMapType = THREE.PCFShadowMap;
  12031. this.shadowMapCullFace = THREE.CullFaceFront;
  12032. this.shadowMapDebug = false;
  12033. this.shadowMapCascade = false;
  12034. // morphs
  12035. this.maxMorphTargets = 8;
  12036. this.maxMorphNormals = 4;
  12037. // flags
  12038. this.autoScaleCubemaps = true;
  12039. // custom render plugins
  12040. this.renderPluginsPre = [];
  12041. this.renderPluginsPost = [];
  12042. // info
  12043. this.info = {
  12044. memory: {
  12045. programs: 0,
  12046. geometries: 0,
  12047. textures: 0
  12048. },
  12049. render: {
  12050. calls: 0,
  12051. vertices: 0,
  12052. faces: 0,
  12053. points: 0
  12054. }
  12055. };
  12056. // internal properties
  12057. var _this = this,
  12058. _programs = [],
  12059. // internal state cache
  12060. _currentProgram = null,
  12061. _currentFramebuffer = null,
  12062. _currentMaterialId = - 1,
  12063. _currentGeometryGroupHash = null,
  12064. _currentCamera = null,
  12065. _usedTextureUnits = 0,
  12066. // GL state cache
  12067. _oldDoubleSided = - 1,
  12068. _oldFlipSided = - 1,
  12069. _oldBlending = - 1,
  12070. _oldBlendEquation = - 1,
  12071. _oldBlendSrc = - 1,
  12072. _oldBlendDst = - 1,
  12073. _oldDepthTest = - 1,
  12074. _oldDepthWrite = - 1,
  12075. _oldPolygonOffset = null,
  12076. _oldPolygonOffsetFactor = null,
  12077. _oldPolygonOffsetUnits = null,
  12078. _oldLineWidth = null,
  12079. _viewportX = 0,
  12080. _viewportY = 0,
  12081. _viewportWidth = _canvas.width,
  12082. _viewportHeight = _canvas.height,
  12083. _currentWidth = 0,
  12084. _currentHeight = 0,
  12085. _newAttributes = new Uint8Array( 16 ),
  12086. _enabledAttributes = new Uint8Array( 16 ),
  12087. // frustum
  12088. _frustum = new THREE.Frustum(),
  12089. // camera matrices cache
  12090. _projScreenMatrix = new THREE.Matrix4(),
  12091. _projScreenMatrixPS = new THREE.Matrix4(),
  12092. _vector3 = new THREE.Vector3(),
  12093. // light arrays cache
  12094. _direction = new THREE.Vector3(),
  12095. _lightsNeedUpdate = true,
  12096. _lights = {
  12097. ambient: [ 0, 0, 0 ],
  12098. directional: { length: 0, colors: new Array(), positions: new Array() },
  12099. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  12100. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  12101. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  12102. };
  12103. // initialize
  12104. var _gl;
  12105. var _glExtensionTextureFloat;
  12106. var _glExtensionTextureFloatLinear;
  12107. var _glExtensionStandardDerivatives;
  12108. var _glExtensionTextureFilterAnisotropic;
  12109. var _glExtensionCompressedTextureS3TC;
  12110. var _glExtensionElementIndexUint;
  12111. var _glExtensionFragDepth;
  12112. initGL();
  12113. setDefaultGLState();
  12114. this.context = _gl;
  12115. // GPU capabilities
  12116. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  12117. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  12118. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  12119. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  12120. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  12121. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  12122. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  12123. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  12124. //
  12125. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  12126. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  12127. var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT );
  12128. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  12129. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  12130. var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT );
  12131. // clamp precision to maximum available
  12132. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  12133. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  12134. if ( _precision === 'highp' && ! highpAvailable ) {
  12135. if ( mediumpAvailable ) {
  12136. _precision = 'mediump';
  12137. console.warn( 'THREE.WebGLRenderer: highp not supported, using mediump.' );
  12138. } else {
  12139. _precision = 'lowp';
  12140. console.warn( 'THREE.WebGLRenderer: highp and mediump not supported, using lowp.' );
  12141. }
  12142. }
  12143. if ( _precision === 'mediump' && ! mediumpAvailable ) {
  12144. _precision = 'lowp';
  12145. console.warn( 'THREE.WebGLRenderer: mediump not supported, using lowp.' );
  12146. }
  12147. // API
  12148. this.getContext = function () {
  12149. return _gl;
  12150. };
  12151. this.supportsVertexTextures = function () {
  12152. return _supportsVertexTextures;
  12153. };
  12154. this.supportsFloatTextures = function () {
  12155. return _glExtensionTextureFloat;
  12156. };
  12157. this.supportsStandardDerivatives = function () {
  12158. return _glExtensionStandardDerivatives;
  12159. };
  12160. this.supportsCompressedTextureS3TC = function () {
  12161. return _glExtensionCompressedTextureS3TC;
  12162. };
  12163. this.getMaxAnisotropy = function () {
  12164. return _maxAnisotropy;
  12165. };
  12166. this.getPrecision = function () {
  12167. return _precision;
  12168. };
  12169. this.setSize = function ( width, height, updateStyle ) {
  12170. _canvas.width = width * this.devicePixelRatio;
  12171. _canvas.height = height * this.devicePixelRatio;
  12172. if ( updateStyle !== false ) {
  12173. _canvas.style.width = width + 'px';
  12174. _canvas.style.height = height + 'px';
  12175. }
  12176. this.setViewport( 0, 0, width, height );
  12177. };
  12178. this.setViewport = function ( x, y, width, height ) {
  12179. _viewportX = x * this.devicePixelRatio;
  12180. _viewportY = y * this.devicePixelRatio;
  12181. _viewportWidth = width * this.devicePixelRatio;
  12182. _viewportHeight = height * this.devicePixelRatio;
  12183. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  12184. };
  12185. this.setScissor = function ( x, y, width, height ) {
  12186. _gl.scissor(
  12187. x * this.devicePixelRatio,
  12188. y * this.devicePixelRatio,
  12189. width * this.devicePixelRatio,
  12190. height * this.devicePixelRatio
  12191. );
  12192. };
  12193. this.enableScissorTest = function ( enable ) {
  12194. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  12195. };
  12196. // Clearing
  12197. this.setClearColor = function ( color, alpha ) {
  12198. _clearColor.set( color );
  12199. _clearAlpha = alpha !== undefined ? alpha : 1;
  12200. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  12201. };
  12202. this.setClearColorHex = function ( hex, alpha ) {
  12203. console.warn( 'THREE.WebGLRenderer: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  12204. this.setClearColor( hex, alpha );
  12205. };
  12206. this.getClearColor = function () {
  12207. return _clearColor;
  12208. };
  12209. this.getClearAlpha = function () {
  12210. return _clearAlpha;
  12211. };
  12212. this.clear = function ( color, depth, stencil ) {
  12213. var bits = 0;
  12214. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  12215. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  12216. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  12217. _gl.clear( bits );
  12218. };
  12219. this.clearColor = function () {
  12220. _gl.clear( _gl.COLOR_BUFFER_BIT );
  12221. };
  12222. this.clearDepth = function () {
  12223. _gl.clear( _gl.DEPTH_BUFFER_BIT );
  12224. };
  12225. this.clearStencil = function () {
  12226. _gl.clear( _gl.STENCIL_BUFFER_BIT );
  12227. };
  12228. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  12229. this.setRenderTarget( renderTarget );
  12230. this.clear( color, depth, stencil );
  12231. };
  12232. // Plugins
  12233. this.addPostPlugin = function ( plugin ) {
  12234. plugin.init( this );
  12235. this.renderPluginsPost.push( plugin );
  12236. };
  12237. this.addPrePlugin = function ( plugin ) {
  12238. plugin.init( this );
  12239. this.renderPluginsPre.push( plugin );
  12240. };
  12241. // Rendering
  12242. this.updateShadowMap = function ( scene, camera ) {
  12243. _currentProgram = null;
  12244. _oldBlending = - 1;
  12245. _oldDepthTest = - 1;
  12246. _oldDepthWrite = - 1;
  12247. _currentGeometryGroupHash = - 1;
  12248. _currentMaterialId = - 1;
  12249. _lightsNeedUpdate = true;
  12250. _oldDoubleSided = - 1;
  12251. _oldFlipSided = - 1;
  12252. initObjects( scene );
  12253. this.shadowMapPlugin.update( scene, camera );
  12254. };
  12255. // Internal functions
  12256. // Buffer allocation
  12257. function createParticleBuffers ( geometry ) {
  12258. geometry.__webglVertexBuffer = _gl.createBuffer();
  12259. geometry.__webglColorBuffer = _gl.createBuffer();
  12260. _this.info.memory.geometries ++;
  12261. };
  12262. function createLineBuffers ( geometry ) {
  12263. geometry.__webglVertexBuffer = _gl.createBuffer();
  12264. geometry.__webglColorBuffer = _gl.createBuffer();
  12265. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  12266. _this.info.memory.geometries ++;
  12267. };
  12268. function createMeshBuffers ( geometryGroup ) {
  12269. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  12270. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  12271. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  12272. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  12273. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  12274. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  12275. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  12276. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  12277. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  12278. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  12279. var m, ml;
  12280. if ( geometryGroup.numMorphTargets ) {
  12281. geometryGroup.__webglMorphTargetsBuffers = [];
  12282. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  12283. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  12284. }
  12285. }
  12286. if ( geometryGroup.numMorphNormals ) {
  12287. geometryGroup.__webglMorphNormalsBuffers = [];
  12288. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  12289. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  12290. }
  12291. }
  12292. _this.info.memory.geometries ++;
  12293. };
  12294. // Events
  12295. var onGeometryDispose = function ( event ) {
  12296. var geometry = event.target;
  12297. geometry.removeEventListener( 'dispose', onGeometryDispose );
  12298. deallocateGeometry( geometry );
  12299. };
  12300. var onTextureDispose = function ( event ) {
  12301. var texture = event.target;
  12302. texture.removeEventListener( 'dispose', onTextureDispose );
  12303. deallocateTexture( texture );
  12304. _this.info.memory.textures --;
  12305. };
  12306. var onRenderTargetDispose = function ( event ) {
  12307. var renderTarget = event.target;
  12308. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  12309. deallocateRenderTarget( renderTarget );
  12310. _this.info.memory.textures --;
  12311. };
  12312. var onMaterialDispose = function ( event ) {
  12313. var material = event.target;
  12314. material.removeEventListener( 'dispose', onMaterialDispose );
  12315. deallocateMaterial( material );
  12316. };
  12317. // Buffer deallocation
  12318. var deleteBuffers = function ( geometry ) {
  12319. if ( geometry.__webglVertexBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglVertexBuffer );
  12320. if ( geometry.__webglNormalBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglNormalBuffer );
  12321. if ( geometry.__webglTangentBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglTangentBuffer );
  12322. if ( geometry.__webglColorBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglColorBuffer );
  12323. if ( geometry.__webglUVBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglUVBuffer );
  12324. if ( geometry.__webglUV2Buffer !== undefined ) _gl.deleteBuffer( geometry.__webglUV2Buffer );
  12325. if ( geometry.__webglSkinIndicesBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinIndicesBuffer );
  12326. if ( geometry.__webglSkinWeightsBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinWeightsBuffer );
  12327. if ( geometry.__webglFaceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglFaceBuffer );
  12328. if ( geometry.__webglLineBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineBuffer );
  12329. if ( geometry.__webglLineDistanceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  12330. // custom attributes
  12331. if ( geometry.__webglCustomAttributesList !== undefined ) {
  12332. for ( var id in geometry.__webglCustomAttributesList ) {
  12333. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  12334. }
  12335. }
  12336. _this.info.memory.geometries --;
  12337. };
  12338. var deallocateGeometry = function ( geometry ) {
  12339. geometry.__webglInit = undefined;
  12340. if ( geometry instanceof THREE.BufferGeometry ) {
  12341. var attributes = geometry.attributes;
  12342. for ( var key in attributes ) {
  12343. if ( attributes[ key ].buffer !== undefined ) {
  12344. _gl.deleteBuffer( attributes[ key ].buffer );
  12345. }
  12346. }
  12347. _this.info.memory.geometries --;
  12348. } else {
  12349. if ( geometry.geometryGroups !== undefined ) {
  12350. for ( var i = 0,l = geometry.geometryGroupsList.length; i<l;i++ ) {
  12351. var geometryGroup = geometry.geometryGroupsList[ i ];
  12352. if ( geometryGroup.numMorphTargets !== undefined ) {
  12353. for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  12354. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  12355. }
  12356. }
  12357. if ( geometryGroup.numMorphNormals !== undefined ) {
  12358. for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  12359. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  12360. }
  12361. }
  12362. deleteBuffers( geometryGroup );
  12363. }
  12364. } else {
  12365. deleteBuffers( geometry );
  12366. }
  12367. }
  12368. };
  12369. var deallocateTexture = function ( texture ) {
  12370. if ( texture.image && texture.image.__webglTextureCube ) {
  12371. // cube texture
  12372. _gl.deleteTexture( texture.image.__webglTextureCube );
  12373. } else {
  12374. // 2D texture
  12375. if ( ! texture.__webglInit ) return;
  12376. texture.__webglInit = false;
  12377. _gl.deleteTexture( texture.__webglTexture );
  12378. }
  12379. };
  12380. var deallocateRenderTarget = function ( renderTarget ) {
  12381. if ( ! renderTarget || ! renderTarget.__webglTexture ) return;
  12382. _gl.deleteTexture( renderTarget.__webglTexture );
  12383. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  12384. for ( var i = 0; i < 6; i ++ ) {
  12385. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  12386. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  12387. }
  12388. } else {
  12389. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  12390. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  12391. }
  12392. };
  12393. var deallocateMaterial = function ( material ) {
  12394. var program = material.program.program;
  12395. if ( program === undefined ) return;
  12396. material.program = undefined;
  12397. // only deallocate GL program if this was the last use of shared program
  12398. // assumed there is only single copy of any program in the _programs list
  12399. // (that's how it's constructed)
  12400. var i, il, programInfo;
  12401. var deleteProgram = false;
  12402. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  12403. programInfo = _programs[ i ];
  12404. if ( programInfo.program === program ) {
  12405. programInfo.usedTimes --;
  12406. if ( programInfo.usedTimes === 0 ) {
  12407. deleteProgram = true;
  12408. }
  12409. break;
  12410. }
  12411. }
  12412. if ( deleteProgram === true ) {
  12413. // avoid using array.splice, this is costlier than creating new array from scratch
  12414. var newPrograms = [];
  12415. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  12416. programInfo = _programs[ i ];
  12417. if ( programInfo.program !== program ) {
  12418. newPrograms.push( programInfo );
  12419. }
  12420. }
  12421. _programs = newPrograms;
  12422. _gl.deleteProgram( program );
  12423. _this.info.memory.programs --;
  12424. }
  12425. };
  12426. // Buffer initialization
  12427. function initCustomAttributes ( geometry, object ) {
  12428. var nvertices = geometry.vertices.length;
  12429. var material = object.material;
  12430. if ( material.attributes ) {
  12431. if ( geometry.__webglCustomAttributesList === undefined ) {
  12432. geometry.__webglCustomAttributesList = [];
  12433. }
  12434. for ( var a in material.attributes ) {
  12435. var attribute = material.attributes[ a ];
  12436. if ( ! attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  12437. attribute.__webglInitialized = true;
  12438. var size = 1; // "f" and "i"
  12439. if ( attribute.type === 'v2' ) size = 2;
  12440. else if ( attribute.type === 'v3' ) size = 3;
  12441. else if ( attribute.type === 'v4' ) size = 4;
  12442. else if ( attribute.type === 'c' ) size = 3;
  12443. attribute.size = size;
  12444. attribute.array = new Float32Array( nvertices * size );
  12445. attribute.buffer = _gl.createBuffer();
  12446. attribute.buffer.belongsToAttribute = a;
  12447. attribute.needsUpdate = true;
  12448. }
  12449. geometry.__webglCustomAttributesList.push( attribute );
  12450. }
  12451. }
  12452. };
  12453. function initParticleBuffers ( geometry, object ) {
  12454. var nvertices = geometry.vertices.length;
  12455. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  12456. geometry.__colorArray = new Float32Array( nvertices * 3 );
  12457. geometry.__sortArray = [];
  12458. geometry.__webglParticleCount = nvertices;
  12459. initCustomAttributes ( geometry, object );
  12460. };
  12461. function initLineBuffers ( geometry, object ) {
  12462. var nvertices = geometry.vertices.length;
  12463. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  12464. geometry.__colorArray = new Float32Array( nvertices * 3 );
  12465. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  12466. geometry.__webglLineCount = nvertices;
  12467. initCustomAttributes ( geometry, object );
  12468. };
  12469. function initMeshBuffers ( geometryGroup, object ) {
  12470. var geometry = object.geometry,
  12471. faces3 = geometryGroup.faces3,
  12472. nvertices = faces3.length * 3,
  12473. ntris = faces3.length * 1,
  12474. nlines = faces3.length * 3,
  12475. material = getBufferMaterial( object, geometryGroup ),
  12476. uvType = bufferGuessUVType( material ),
  12477. normalType = bufferGuessNormalType( material ),
  12478. vertexColorType = bufferGuessVertexColorType( material );
  12479. // console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  12480. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  12481. if ( normalType ) {
  12482. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  12483. }
  12484. if ( geometry.hasTangents ) {
  12485. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  12486. }
  12487. if ( vertexColorType ) {
  12488. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  12489. }
  12490. if ( uvType ) {
  12491. if ( geometry.faceVertexUvs.length > 0 ) {
  12492. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  12493. }
  12494. if ( geometry.faceVertexUvs.length > 1 ) {
  12495. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  12496. }
  12497. }
  12498. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  12499. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  12500. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  12501. }
  12502. var UintArray = _glExtensionElementIndexUint !== null && ntris > 21845 ? Uint32Array : Uint16Array; // 65535 / 3
  12503. geometryGroup.__typeArray = UintArray;
  12504. geometryGroup.__faceArray = new UintArray( ntris * 3 );
  12505. geometryGroup.__lineArray = new UintArray( nlines * 2 );
  12506. var m, ml;
  12507. if ( geometryGroup.numMorphTargets ) {
  12508. geometryGroup.__morphTargetsArrays = [];
  12509. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  12510. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  12511. }
  12512. }
  12513. if ( geometryGroup.numMorphNormals ) {
  12514. geometryGroup.__morphNormalsArrays = [];
  12515. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  12516. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  12517. }
  12518. }
  12519. geometryGroup.__webglFaceCount = ntris * 3;
  12520. geometryGroup.__webglLineCount = nlines * 2;
  12521. // custom attributes
  12522. if ( material.attributes ) {
  12523. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  12524. geometryGroup.__webglCustomAttributesList = [];
  12525. }
  12526. for ( var a in material.attributes ) {
  12527. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  12528. // attribute buffers which are correctly indexed in the setMeshBuffers function
  12529. var originalAttribute = material.attributes[ a ];
  12530. var attribute = {};
  12531. for ( var property in originalAttribute ) {
  12532. attribute[ property ] = originalAttribute[ property ];
  12533. }
  12534. if ( ! attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  12535. attribute.__webglInitialized = true;
  12536. var size = 1; // "f" and "i"
  12537. if ( attribute.type === 'v2' ) size = 2;
  12538. else if ( attribute.type === 'v3' ) size = 3;
  12539. else if ( attribute.type === 'v4' ) size = 4;
  12540. else if ( attribute.type === 'c' ) size = 3;
  12541. attribute.size = size;
  12542. attribute.array = new Float32Array( nvertices * size );
  12543. attribute.buffer = _gl.createBuffer();
  12544. attribute.buffer.belongsToAttribute = a;
  12545. originalAttribute.needsUpdate = true;
  12546. attribute.__original = originalAttribute;
  12547. }
  12548. geometryGroup.__webglCustomAttributesList.push( attribute );
  12549. }
  12550. }
  12551. geometryGroup.__inittedArrays = true;
  12552. };
  12553. function getBufferMaterial( object, geometryGroup ) {
  12554. return object.material instanceof THREE.MeshFaceMaterial
  12555. ? object.material.materials[ geometryGroup.materialIndex ]
  12556. : object.material;
  12557. };
  12558. function materialNeedsSmoothNormals ( material ) {
  12559. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  12560. };
  12561. function bufferGuessNormalType ( material ) {
  12562. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  12563. if ( ( material instanceof THREE.MeshBasicMaterial && ! material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  12564. return false;
  12565. }
  12566. if ( materialNeedsSmoothNormals( material ) ) {
  12567. return THREE.SmoothShading;
  12568. } else {
  12569. return THREE.FlatShading;
  12570. }
  12571. };
  12572. function bufferGuessVertexColorType( material ) {
  12573. if ( material.vertexColors ) {
  12574. return material.vertexColors;
  12575. }
  12576. return false;
  12577. };
  12578. function bufferGuessUVType( material ) {
  12579. // material must use some texture to require uvs
  12580. if ( material.map ||
  12581. material.lightMap ||
  12582. material.bumpMap ||
  12583. material.normalMap ||
  12584. material.specularMap ||
  12585. material instanceof THREE.ShaderMaterial ) {
  12586. return true;
  12587. }
  12588. return false;
  12589. };
  12590. //
  12591. function initDirectBuffers( geometry ) {
  12592. for ( var name in geometry.attributes ) {
  12593. var bufferType = ( name === 'index' ) ? _gl.ELEMENT_ARRAY_BUFFER : _gl.ARRAY_BUFFER;
  12594. var attribute = geometry.attributes[ name ];
  12595. attribute.buffer = _gl.createBuffer();
  12596. _gl.bindBuffer( bufferType, attribute.buffer );
  12597. _gl.bufferData( bufferType, attribute.array, _gl.STATIC_DRAW );
  12598. }
  12599. }
  12600. // Buffer setting
  12601. function setParticleBuffers ( geometry, hint, object ) {
  12602. var v, c, vertex, offset, index, color,
  12603. vertices = geometry.vertices,
  12604. vl = vertices.length,
  12605. colors = geometry.colors,
  12606. cl = colors.length,
  12607. vertexArray = geometry.__vertexArray,
  12608. colorArray = geometry.__colorArray,
  12609. sortArray = geometry.__sortArray,
  12610. dirtyVertices = geometry.verticesNeedUpdate,
  12611. dirtyElements = geometry.elementsNeedUpdate,
  12612. dirtyColors = geometry.colorsNeedUpdate,
  12613. customAttributes = geometry.__webglCustomAttributesList,
  12614. i, il,
  12615. a, ca, cal, value,
  12616. customAttribute;
  12617. if ( object.sortParticles ) {
  12618. _projScreenMatrixPS.copy( _projScreenMatrix );
  12619. _projScreenMatrixPS.multiply( object.matrixWorld );
  12620. for ( v = 0; v < vl; v ++ ) {
  12621. vertex = vertices[ v ];
  12622. _vector3.copy( vertex );
  12623. _vector3.applyProjection( _projScreenMatrixPS );
  12624. sortArray[ v ] = [ _vector3.z, v ];
  12625. }
  12626. sortArray.sort( numericalSort );
  12627. for ( v = 0; v < vl; v ++ ) {
  12628. vertex = vertices[ sortArray[ v ][ 1 ] ];
  12629. offset = v * 3;
  12630. vertexArray[ offset ] = vertex.x;
  12631. vertexArray[ offset + 1 ] = vertex.y;
  12632. vertexArray[ offset + 2 ] = vertex.z;
  12633. }
  12634. for ( c = 0; c < cl; c ++ ) {
  12635. offset = c * 3;
  12636. color = colors[ sortArray[ c ][ 1 ] ];
  12637. colorArray[ offset ] = color.r;
  12638. colorArray[ offset + 1 ] = color.g;
  12639. colorArray[ offset + 2 ] = color.b;
  12640. }
  12641. if ( customAttributes ) {
  12642. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12643. customAttribute = customAttributes[ i ];
  12644. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) ) continue;
  12645. offset = 0;
  12646. cal = customAttribute.value.length;
  12647. if ( customAttribute.size === 1 ) {
  12648. for ( ca = 0; ca < cal; ca ++ ) {
  12649. index = sortArray[ ca ][ 1 ];
  12650. customAttribute.array[ ca ] = customAttribute.value[ index ];
  12651. }
  12652. } else if ( customAttribute.size === 2 ) {
  12653. for ( ca = 0; ca < cal; ca ++ ) {
  12654. index = sortArray[ ca ][ 1 ];
  12655. value = customAttribute.value[ index ];
  12656. customAttribute.array[ offset ] = value.x;
  12657. customAttribute.array[ offset + 1 ] = value.y;
  12658. offset += 2;
  12659. }
  12660. } else if ( customAttribute.size === 3 ) {
  12661. if ( customAttribute.type === 'c' ) {
  12662. for ( ca = 0; ca < cal; ca ++ ) {
  12663. index = sortArray[ ca ][ 1 ];
  12664. value = customAttribute.value[ index ];
  12665. customAttribute.array[ offset ] = value.r;
  12666. customAttribute.array[ offset + 1 ] = value.g;
  12667. customAttribute.array[ offset + 2 ] = value.b;
  12668. offset += 3;
  12669. }
  12670. } else {
  12671. for ( ca = 0; ca < cal; ca ++ ) {
  12672. index = sortArray[ ca ][ 1 ];
  12673. value = customAttribute.value[ index ];
  12674. customAttribute.array[ offset ] = value.x;
  12675. customAttribute.array[ offset + 1 ] = value.y;
  12676. customAttribute.array[ offset + 2 ] = value.z;
  12677. offset += 3;
  12678. }
  12679. }
  12680. } else if ( customAttribute.size === 4 ) {
  12681. for ( ca = 0; ca < cal; ca ++ ) {
  12682. index = sortArray[ ca ][ 1 ];
  12683. value = customAttribute.value[ index ];
  12684. customAttribute.array[ offset ] = value.x;
  12685. customAttribute.array[ offset + 1 ] = value.y;
  12686. customAttribute.array[ offset + 2 ] = value.z;
  12687. customAttribute.array[ offset + 3 ] = value.w;
  12688. offset += 4;
  12689. }
  12690. }
  12691. }
  12692. }
  12693. } else {
  12694. if ( dirtyVertices ) {
  12695. for ( v = 0; v < vl; v ++ ) {
  12696. vertex = vertices[ v ];
  12697. offset = v * 3;
  12698. vertexArray[ offset ] = vertex.x;
  12699. vertexArray[ offset + 1 ] = vertex.y;
  12700. vertexArray[ offset + 2 ] = vertex.z;
  12701. }
  12702. }
  12703. if ( dirtyColors ) {
  12704. for ( c = 0; c < cl; c ++ ) {
  12705. color = colors[ c ];
  12706. offset = c * 3;
  12707. colorArray[ offset ] = color.r;
  12708. colorArray[ offset + 1 ] = color.g;
  12709. colorArray[ offset + 2 ] = color.b;
  12710. }
  12711. }
  12712. if ( customAttributes ) {
  12713. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12714. customAttribute = customAttributes[ i ];
  12715. if ( customAttribute.needsUpdate &&
  12716. ( customAttribute.boundTo === undefined ||
  12717. customAttribute.boundTo === 'vertices' ) ) {
  12718. cal = customAttribute.value.length;
  12719. offset = 0;
  12720. if ( customAttribute.size === 1 ) {
  12721. for ( ca = 0; ca < cal; ca ++ ) {
  12722. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12723. }
  12724. } else if ( customAttribute.size === 2 ) {
  12725. for ( ca = 0; ca < cal; ca ++ ) {
  12726. value = customAttribute.value[ ca ];
  12727. customAttribute.array[ offset ] = value.x;
  12728. customAttribute.array[ offset + 1 ] = value.y;
  12729. offset += 2;
  12730. }
  12731. } else if ( customAttribute.size === 3 ) {
  12732. if ( customAttribute.type === 'c' ) {
  12733. for ( ca = 0; ca < cal; ca ++ ) {
  12734. value = customAttribute.value[ ca ];
  12735. customAttribute.array[ offset ] = value.r;
  12736. customAttribute.array[ offset + 1 ] = value.g;
  12737. customAttribute.array[ offset + 2 ] = value.b;
  12738. offset += 3;
  12739. }
  12740. } else {
  12741. for ( ca = 0; ca < cal; ca ++ ) {
  12742. value = customAttribute.value[ ca ];
  12743. customAttribute.array[ offset ] = value.x;
  12744. customAttribute.array[ offset + 1 ] = value.y;
  12745. customAttribute.array[ offset + 2 ] = value.z;
  12746. offset += 3;
  12747. }
  12748. }
  12749. } else if ( customAttribute.size === 4 ) {
  12750. for ( ca = 0; ca < cal; ca ++ ) {
  12751. value = customAttribute.value[ ca ];
  12752. customAttribute.array[ offset ] = value.x;
  12753. customAttribute.array[ offset + 1 ] = value.y;
  12754. customAttribute.array[ offset + 2 ] = value.z;
  12755. customAttribute.array[ offset + 3 ] = value.w;
  12756. offset += 4;
  12757. }
  12758. }
  12759. }
  12760. }
  12761. }
  12762. }
  12763. if ( dirtyVertices || object.sortParticles ) {
  12764. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12765. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12766. }
  12767. if ( dirtyColors || object.sortParticles ) {
  12768. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12769. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12770. }
  12771. if ( customAttributes ) {
  12772. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12773. customAttribute = customAttributes[ i ];
  12774. if ( customAttribute.needsUpdate || object.sortParticles ) {
  12775. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12776. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12777. }
  12778. }
  12779. }
  12780. }
  12781. function setLineBuffers ( geometry, hint ) {
  12782. var v, c, d, vertex, offset, color,
  12783. vertices = geometry.vertices,
  12784. colors = geometry.colors,
  12785. lineDistances = geometry.lineDistances,
  12786. vl = vertices.length,
  12787. cl = colors.length,
  12788. dl = lineDistances.length,
  12789. vertexArray = geometry.__vertexArray,
  12790. colorArray = geometry.__colorArray,
  12791. lineDistanceArray = geometry.__lineDistanceArray,
  12792. dirtyVertices = geometry.verticesNeedUpdate,
  12793. dirtyColors = geometry.colorsNeedUpdate,
  12794. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  12795. customAttributes = geometry.__webglCustomAttributesList,
  12796. i, il,
  12797. a, ca, cal, value,
  12798. customAttribute;
  12799. if ( dirtyVertices ) {
  12800. for ( v = 0; v < vl; v ++ ) {
  12801. vertex = vertices[ v ];
  12802. offset = v * 3;
  12803. vertexArray[ offset ] = vertex.x;
  12804. vertexArray[ offset + 1 ] = vertex.y;
  12805. vertexArray[ offset + 2 ] = vertex.z;
  12806. }
  12807. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12808. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12809. }
  12810. if ( dirtyColors ) {
  12811. for ( c = 0; c < cl; c ++ ) {
  12812. color = colors[ c ];
  12813. offset = c * 3;
  12814. colorArray[ offset ] = color.r;
  12815. colorArray[ offset + 1 ] = color.g;
  12816. colorArray[ offset + 2 ] = color.b;
  12817. }
  12818. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12819. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12820. }
  12821. if ( dirtyLineDistances ) {
  12822. for ( d = 0; d < dl; d ++ ) {
  12823. lineDistanceArray[ d ] = lineDistances[ d ];
  12824. }
  12825. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  12826. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  12827. }
  12828. if ( customAttributes ) {
  12829. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12830. customAttribute = customAttributes[ i ];
  12831. if ( customAttribute.needsUpdate &&
  12832. ( customAttribute.boundTo === undefined ||
  12833. customAttribute.boundTo === 'vertices' ) ) {
  12834. offset = 0;
  12835. cal = customAttribute.value.length;
  12836. if ( customAttribute.size === 1 ) {
  12837. for ( ca = 0; ca < cal; ca ++ ) {
  12838. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12839. }
  12840. } else if ( customAttribute.size === 2 ) {
  12841. for ( ca = 0; ca < cal; ca ++ ) {
  12842. value = customAttribute.value[ ca ];
  12843. customAttribute.array[ offset ] = value.x;
  12844. customAttribute.array[ offset + 1 ] = value.y;
  12845. offset += 2;
  12846. }
  12847. } else if ( customAttribute.size === 3 ) {
  12848. if ( customAttribute.type === 'c' ) {
  12849. for ( ca = 0; ca < cal; ca ++ ) {
  12850. value = customAttribute.value[ ca ];
  12851. customAttribute.array[ offset ] = value.r;
  12852. customAttribute.array[ offset + 1 ] = value.g;
  12853. customAttribute.array[ offset + 2 ] = value.b;
  12854. offset += 3;
  12855. }
  12856. } else {
  12857. for ( ca = 0; ca < cal; ca ++ ) {
  12858. value = customAttribute.value[ ca ];
  12859. customAttribute.array[ offset ] = value.x;
  12860. customAttribute.array[ offset + 1 ] = value.y;
  12861. customAttribute.array[ offset + 2 ] = value.z;
  12862. offset += 3;
  12863. }
  12864. }
  12865. } else if ( customAttribute.size === 4 ) {
  12866. for ( ca = 0; ca < cal; ca ++ ) {
  12867. value = customAttribute.value[ ca ];
  12868. customAttribute.array[ offset ] = value.x;
  12869. customAttribute.array[ offset + 1 ] = value.y;
  12870. customAttribute.array[ offset + 2 ] = value.z;
  12871. customAttribute.array[ offset + 3 ] = value.w;
  12872. offset += 4;
  12873. }
  12874. }
  12875. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12876. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12877. }
  12878. }
  12879. }
  12880. }
  12881. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  12882. if ( ! geometryGroup.__inittedArrays ) {
  12883. return;
  12884. }
  12885. var normalType = bufferGuessNormalType( material ),
  12886. vertexColorType = bufferGuessVertexColorType( material ),
  12887. uvType = bufferGuessUVType( material ),
  12888. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  12889. var f, fl, fi, face,
  12890. vertexNormals, faceNormal, normal,
  12891. vertexColors, faceColor,
  12892. vertexTangents,
  12893. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  12894. c1, c2, c3,
  12895. sw1, sw2, sw3, sw4,
  12896. si1, si2, si3, si4,
  12897. sa1, sa2, sa3, sa4,
  12898. sb1, sb2, sb3, sb4,
  12899. m, ml, i, il,
  12900. vn, uvi, uv2i,
  12901. vk, vkl, vka,
  12902. nka, chf, faceVertexNormals,
  12903. a,
  12904. vertexIndex = 0,
  12905. offset = 0,
  12906. offset_uv = 0,
  12907. offset_uv2 = 0,
  12908. offset_face = 0,
  12909. offset_normal = 0,
  12910. offset_tangent = 0,
  12911. offset_line = 0,
  12912. offset_color = 0,
  12913. offset_skin = 0,
  12914. offset_morphTarget = 0,
  12915. offset_custom = 0,
  12916. offset_customSrc = 0,
  12917. value,
  12918. vertexArray = geometryGroup.__vertexArray,
  12919. uvArray = geometryGroup.__uvArray,
  12920. uv2Array = geometryGroup.__uv2Array,
  12921. normalArray = geometryGroup.__normalArray,
  12922. tangentArray = geometryGroup.__tangentArray,
  12923. colorArray = geometryGroup.__colorArray,
  12924. skinIndexArray = geometryGroup.__skinIndexArray,
  12925. skinWeightArray = geometryGroup.__skinWeightArray,
  12926. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  12927. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  12928. customAttributes = geometryGroup.__webglCustomAttributesList,
  12929. customAttribute,
  12930. faceArray = geometryGroup.__faceArray,
  12931. lineArray = geometryGroup.__lineArray,
  12932. geometry = object.geometry, // this is shared for all chunks
  12933. dirtyVertices = geometry.verticesNeedUpdate,
  12934. dirtyElements = geometry.elementsNeedUpdate,
  12935. dirtyUvs = geometry.uvsNeedUpdate,
  12936. dirtyNormals = geometry.normalsNeedUpdate,
  12937. dirtyTangents = geometry.tangentsNeedUpdate,
  12938. dirtyColors = geometry.colorsNeedUpdate,
  12939. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  12940. vertices = geometry.vertices,
  12941. chunk_faces3 = geometryGroup.faces3,
  12942. obj_faces = geometry.faces,
  12943. obj_uvs = geometry.faceVertexUvs[ 0 ],
  12944. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  12945. obj_colors = geometry.colors,
  12946. obj_skinIndices = geometry.skinIndices,
  12947. obj_skinWeights = geometry.skinWeights,
  12948. morphTargets = geometry.morphTargets,
  12949. morphNormals = geometry.morphNormals;
  12950. if ( dirtyVertices ) {
  12951. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12952. face = obj_faces[ chunk_faces3[ f ] ];
  12953. v1 = vertices[ face.a ];
  12954. v2 = vertices[ face.b ];
  12955. v3 = vertices[ face.c ];
  12956. vertexArray[ offset ] = v1.x;
  12957. vertexArray[ offset + 1 ] = v1.y;
  12958. vertexArray[ offset + 2 ] = v1.z;
  12959. vertexArray[ offset + 3 ] = v2.x;
  12960. vertexArray[ offset + 4 ] = v2.y;
  12961. vertexArray[ offset + 5 ] = v2.z;
  12962. vertexArray[ offset + 6 ] = v3.x;
  12963. vertexArray[ offset + 7 ] = v3.y;
  12964. vertexArray[ offset + 8 ] = v3.z;
  12965. offset += 9;
  12966. }
  12967. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12968. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12969. }
  12970. if ( dirtyMorphTargets ) {
  12971. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  12972. offset_morphTarget = 0;
  12973. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12974. chf = chunk_faces3[ f ];
  12975. face = obj_faces[ chf ];
  12976. // morph positions
  12977. v1 = morphTargets[ vk ].vertices[ face.a ];
  12978. v2 = morphTargets[ vk ].vertices[ face.b ];
  12979. v3 = morphTargets[ vk ].vertices[ face.c ];
  12980. vka = morphTargetsArrays[ vk ];
  12981. vka[ offset_morphTarget ] = v1.x;
  12982. vka[ offset_morphTarget + 1 ] = v1.y;
  12983. vka[ offset_morphTarget + 2 ] = v1.z;
  12984. vka[ offset_morphTarget + 3 ] = v2.x;
  12985. vka[ offset_morphTarget + 4 ] = v2.y;
  12986. vka[ offset_morphTarget + 5 ] = v2.z;
  12987. vka[ offset_morphTarget + 6 ] = v3.x;
  12988. vka[ offset_morphTarget + 7 ] = v3.y;
  12989. vka[ offset_morphTarget + 8 ] = v3.z;
  12990. // morph normals
  12991. if ( material.morphNormals ) {
  12992. if ( needsSmoothNormals ) {
  12993. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  12994. n1 = faceVertexNormals.a;
  12995. n2 = faceVertexNormals.b;
  12996. n3 = faceVertexNormals.c;
  12997. } else {
  12998. n1 = morphNormals[ vk ].faceNormals[ chf ];
  12999. n2 = n1;
  13000. n3 = n1;
  13001. }
  13002. nka = morphNormalsArrays[ vk ];
  13003. nka[ offset_morphTarget ] = n1.x;
  13004. nka[ offset_morphTarget + 1 ] = n1.y;
  13005. nka[ offset_morphTarget + 2 ] = n1.z;
  13006. nka[ offset_morphTarget + 3 ] = n2.x;
  13007. nka[ offset_morphTarget + 4 ] = n2.y;
  13008. nka[ offset_morphTarget + 5 ] = n2.z;
  13009. nka[ offset_morphTarget + 6 ] = n3.x;
  13010. nka[ offset_morphTarget + 7 ] = n3.y;
  13011. nka[ offset_morphTarget + 8 ] = n3.z;
  13012. }
  13013. //
  13014. offset_morphTarget += 9;
  13015. }
  13016. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  13017. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  13018. if ( material.morphNormals ) {
  13019. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  13020. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  13021. }
  13022. }
  13023. }
  13024. if ( obj_skinWeights.length ) {
  13025. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13026. face = obj_faces[ chunk_faces3[ f ] ];
  13027. // weights
  13028. sw1 = obj_skinWeights[ face.a ];
  13029. sw2 = obj_skinWeights[ face.b ];
  13030. sw3 = obj_skinWeights[ face.c ];
  13031. skinWeightArray[ offset_skin ] = sw1.x;
  13032. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  13033. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  13034. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  13035. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  13036. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  13037. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  13038. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  13039. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  13040. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  13041. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  13042. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  13043. // indices
  13044. si1 = obj_skinIndices[ face.a ];
  13045. si2 = obj_skinIndices[ face.b ];
  13046. si3 = obj_skinIndices[ face.c ];
  13047. skinIndexArray[ offset_skin ] = si1.x;
  13048. skinIndexArray[ offset_skin + 1 ] = si1.y;
  13049. skinIndexArray[ offset_skin + 2 ] = si1.z;
  13050. skinIndexArray[ offset_skin + 3 ] = si1.w;
  13051. skinIndexArray[ offset_skin + 4 ] = si2.x;
  13052. skinIndexArray[ offset_skin + 5 ] = si2.y;
  13053. skinIndexArray[ offset_skin + 6 ] = si2.z;
  13054. skinIndexArray[ offset_skin + 7 ] = si2.w;
  13055. skinIndexArray[ offset_skin + 8 ] = si3.x;
  13056. skinIndexArray[ offset_skin + 9 ] = si3.y;
  13057. skinIndexArray[ offset_skin + 10 ] = si3.z;
  13058. skinIndexArray[ offset_skin + 11 ] = si3.w;
  13059. offset_skin += 12;
  13060. }
  13061. if ( offset_skin > 0 ) {
  13062. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  13063. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  13064. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  13065. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  13066. }
  13067. }
  13068. if ( dirtyColors && vertexColorType ) {
  13069. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13070. face = obj_faces[ chunk_faces3[ f ] ];
  13071. vertexColors = face.vertexColors;
  13072. faceColor = face.color;
  13073. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  13074. c1 = vertexColors[ 0 ];
  13075. c2 = vertexColors[ 1 ];
  13076. c3 = vertexColors[ 2 ];
  13077. } else {
  13078. c1 = faceColor;
  13079. c2 = faceColor;
  13080. c3 = faceColor;
  13081. }
  13082. colorArray[ offset_color ] = c1.r;
  13083. colorArray[ offset_color + 1 ] = c1.g;
  13084. colorArray[ offset_color + 2 ] = c1.b;
  13085. colorArray[ offset_color + 3 ] = c2.r;
  13086. colorArray[ offset_color + 4 ] = c2.g;
  13087. colorArray[ offset_color + 5 ] = c2.b;
  13088. colorArray[ offset_color + 6 ] = c3.r;
  13089. colorArray[ offset_color + 7 ] = c3.g;
  13090. colorArray[ offset_color + 8 ] = c3.b;
  13091. offset_color += 9;
  13092. }
  13093. if ( offset_color > 0 ) {
  13094. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  13095. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  13096. }
  13097. }
  13098. if ( dirtyTangents && geometry.hasTangents ) {
  13099. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13100. face = obj_faces[ chunk_faces3[ f ] ];
  13101. vertexTangents = face.vertexTangents;
  13102. t1 = vertexTangents[ 0 ];
  13103. t2 = vertexTangents[ 1 ];
  13104. t3 = vertexTangents[ 2 ];
  13105. tangentArray[ offset_tangent ] = t1.x;
  13106. tangentArray[ offset_tangent + 1 ] = t1.y;
  13107. tangentArray[ offset_tangent + 2 ] = t1.z;
  13108. tangentArray[ offset_tangent + 3 ] = t1.w;
  13109. tangentArray[ offset_tangent + 4 ] = t2.x;
  13110. tangentArray[ offset_tangent + 5 ] = t2.y;
  13111. tangentArray[ offset_tangent + 6 ] = t2.z;
  13112. tangentArray[ offset_tangent + 7 ] = t2.w;
  13113. tangentArray[ offset_tangent + 8 ] = t3.x;
  13114. tangentArray[ offset_tangent + 9 ] = t3.y;
  13115. tangentArray[ offset_tangent + 10 ] = t3.z;
  13116. tangentArray[ offset_tangent + 11 ] = t3.w;
  13117. offset_tangent += 12;
  13118. }
  13119. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  13120. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  13121. }
  13122. if ( dirtyNormals && normalType ) {
  13123. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13124. face = obj_faces[ chunk_faces3[ f ] ];
  13125. vertexNormals = face.vertexNormals;
  13126. faceNormal = face.normal;
  13127. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  13128. for ( i = 0; i < 3; i ++ ) {
  13129. vn = vertexNormals[ i ];
  13130. normalArray[ offset_normal ] = vn.x;
  13131. normalArray[ offset_normal + 1 ] = vn.y;
  13132. normalArray[ offset_normal + 2 ] = vn.z;
  13133. offset_normal += 3;
  13134. }
  13135. } else {
  13136. for ( i = 0; i < 3; i ++ ) {
  13137. normalArray[ offset_normal ] = faceNormal.x;
  13138. normalArray[ offset_normal + 1 ] = faceNormal.y;
  13139. normalArray[ offset_normal + 2 ] = faceNormal.z;
  13140. offset_normal += 3;
  13141. }
  13142. }
  13143. }
  13144. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  13145. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  13146. }
  13147. if ( dirtyUvs && obj_uvs && uvType ) {
  13148. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13149. fi = chunk_faces3[ f ];
  13150. uv = obj_uvs[ fi ];
  13151. if ( uv === undefined ) continue;
  13152. for ( i = 0; i < 3; i ++ ) {
  13153. uvi = uv[ i ];
  13154. uvArray[ offset_uv ] = uvi.x;
  13155. uvArray[ offset_uv + 1 ] = uvi.y;
  13156. offset_uv += 2;
  13157. }
  13158. }
  13159. if ( offset_uv > 0 ) {
  13160. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  13161. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  13162. }
  13163. }
  13164. if ( dirtyUvs && obj_uvs2 && uvType ) {
  13165. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13166. fi = chunk_faces3[ f ];
  13167. uv2 = obj_uvs2[ fi ];
  13168. if ( uv2 === undefined ) continue;
  13169. for ( i = 0; i < 3; i ++ ) {
  13170. uv2i = uv2[ i ];
  13171. uv2Array[ offset_uv2 ] = uv2i.x;
  13172. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  13173. offset_uv2 += 2;
  13174. }
  13175. }
  13176. if ( offset_uv2 > 0 ) {
  13177. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  13178. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  13179. }
  13180. }
  13181. if ( dirtyElements ) {
  13182. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13183. faceArray[ offset_face ] = vertexIndex;
  13184. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  13185. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  13186. offset_face += 3;
  13187. lineArray[ offset_line ] = vertexIndex;
  13188. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  13189. lineArray[ offset_line + 2 ] = vertexIndex;
  13190. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  13191. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  13192. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  13193. offset_line += 6;
  13194. vertexIndex += 3;
  13195. }
  13196. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  13197. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  13198. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  13199. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  13200. }
  13201. if ( customAttributes ) {
  13202. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  13203. customAttribute = customAttributes[ i ];
  13204. if ( ! customAttribute.__original.needsUpdate ) continue;
  13205. offset_custom = 0;
  13206. offset_customSrc = 0;
  13207. if ( customAttribute.size === 1 ) {
  13208. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) {
  13209. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13210. face = obj_faces[ chunk_faces3[ f ] ];
  13211. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  13212. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  13213. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  13214. offset_custom += 3;
  13215. }
  13216. } else if ( customAttribute.boundTo === 'faces' ) {
  13217. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13218. value = customAttribute.value[ chunk_faces3[ f ] ];
  13219. customAttribute.array[ offset_custom ] = value;
  13220. customAttribute.array[ offset_custom + 1 ] = value;
  13221. customAttribute.array[ offset_custom + 2 ] = value;
  13222. offset_custom += 3;
  13223. }
  13224. }
  13225. } else if ( customAttribute.size === 2 ) {
  13226. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) {
  13227. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13228. face = obj_faces[ chunk_faces3[ f ] ];
  13229. v1 = customAttribute.value[ face.a ];
  13230. v2 = customAttribute.value[ face.b ];
  13231. v3 = customAttribute.value[ face.c ];
  13232. customAttribute.array[ offset_custom ] = v1.x;
  13233. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13234. customAttribute.array[ offset_custom + 2 ] = v2.x;
  13235. customAttribute.array[ offset_custom + 3 ] = v2.y;
  13236. customAttribute.array[ offset_custom + 4 ] = v3.x;
  13237. customAttribute.array[ offset_custom + 5 ] = v3.y;
  13238. offset_custom += 6;
  13239. }
  13240. } else if ( customAttribute.boundTo === 'faces' ) {
  13241. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13242. value = customAttribute.value[ chunk_faces3[ f ] ];
  13243. v1 = value;
  13244. v2 = value;
  13245. v3 = value;
  13246. customAttribute.array[ offset_custom ] = v1.x;
  13247. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13248. customAttribute.array[ offset_custom + 2 ] = v2.x;
  13249. customAttribute.array[ offset_custom + 3 ] = v2.y;
  13250. customAttribute.array[ offset_custom + 4 ] = v3.x;
  13251. customAttribute.array[ offset_custom + 5 ] = v3.y;
  13252. offset_custom += 6;
  13253. }
  13254. }
  13255. } else if ( customAttribute.size === 3 ) {
  13256. var pp;
  13257. if ( customAttribute.type === 'c' ) {
  13258. pp = [ 'r', 'g', 'b' ];
  13259. } else {
  13260. pp = [ 'x', 'y', 'z' ];
  13261. }
  13262. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) {
  13263. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13264. face = obj_faces[ chunk_faces3[ f ] ];
  13265. v1 = customAttribute.value[ face.a ];
  13266. v2 = customAttribute.value[ face.b ];
  13267. v3 = customAttribute.value[ face.c ];
  13268. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13269. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13270. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13271. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13272. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13273. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13274. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13275. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13276. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13277. offset_custom += 9;
  13278. }
  13279. } else if ( customAttribute.boundTo === 'faces' ) {
  13280. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13281. value = customAttribute.value[ chunk_faces3[ f ] ];
  13282. v1 = value;
  13283. v2 = value;
  13284. v3 = value;
  13285. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13286. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13287. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13288. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13289. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13290. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13291. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13292. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13293. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13294. offset_custom += 9;
  13295. }
  13296. } else if ( customAttribute.boundTo === 'faceVertices' ) {
  13297. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13298. value = customAttribute.value[ chunk_faces3[ f ] ];
  13299. v1 = value[ 0 ];
  13300. v2 = value[ 1 ];
  13301. v3 = value[ 2 ];
  13302. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13303. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13304. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13305. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13306. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13307. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13308. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13309. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13310. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13311. offset_custom += 9;
  13312. }
  13313. }
  13314. } else if ( customAttribute.size === 4 ) {
  13315. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) {
  13316. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13317. face = obj_faces[ chunk_faces3[ f ] ];
  13318. v1 = customAttribute.value[ face.a ];
  13319. v2 = customAttribute.value[ face.b ];
  13320. v3 = customAttribute.value[ face.c ];
  13321. customAttribute.array[ offset_custom ] = v1.x;
  13322. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13323. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13324. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13325. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13326. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13327. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13328. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13329. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13330. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13331. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13332. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13333. offset_custom += 12;
  13334. }
  13335. } else if ( customAttribute.boundTo === 'faces' ) {
  13336. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13337. value = customAttribute.value[ chunk_faces3[ f ] ];
  13338. v1 = value;
  13339. v2 = value;
  13340. v3 = value;
  13341. customAttribute.array[ offset_custom ] = v1.x;
  13342. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13343. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13344. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13345. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13346. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13347. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13348. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13349. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13350. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13351. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13352. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13353. offset_custom += 12;
  13354. }
  13355. } else if ( customAttribute.boundTo === 'faceVertices' ) {
  13356. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13357. value = customAttribute.value[ chunk_faces3[ f ] ];
  13358. v1 = value[ 0 ];
  13359. v2 = value[ 1 ];
  13360. v3 = value[ 2 ];
  13361. customAttribute.array[ offset_custom ] = v1.x;
  13362. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13363. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13364. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13365. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13366. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13367. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13368. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13369. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13370. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13371. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13372. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13373. offset_custom += 12;
  13374. }
  13375. }
  13376. }
  13377. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  13378. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  13379. }
  13380. }
  13381. if ( dispose ) {
  13382. delete geometryGroup.__inittedArrays;
  13383. delete geometryGroup.__colorArray;
  13384. delete geometryGroup.__normalArray;
  13385. delete geometryGroup.__tangentArray;
  13386. delete geometryGroup.__uvArray;
  13387. delete geometryGroup.__uv2Array;
  13388. delete geometryGroup.__faceArray;
  13389. delete geometryGroup.__vertexArray;
  13390. delete geometryGroup.__lineArray;
  13391. delete geometryGroup.__skinIndexArray;
  13392. delete geometryGroup.__skinWeightArray;
  13393. }
  13394. };
  13395. function setDirectBuffers( geometry, hint ) {
  13396. var attributes = geometry.attributes;
  13397. var attributeName, attributeItem;
  13398. for ( attributeName in attributes ) {
  13399. attributeItem = attributes[ attributeName ];
  13400. if ( attributeItem.needsUpdate ) {
  13401. if ( attributeName === 'index' ) {
  13402. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.buffer );
  13403. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.array, hint );
  13404. } else {
  13405. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13406. _gl.bufferData( _gl.ARRAY_BUFFER, attributeItem.array, hint );
  13407. }
  13408. attributeItem.needsUpdate = false;
  13409. }
  13410. }
  13411. }
  13412. // Buffer rendering
  13413. this.renderBufferImmediate = function ( object, program, material ) {
  13414. initAttributes();
  13415. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  13416. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  13417. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  13418. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  13419. if ( object.hasPositions ) {
  13420. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  13421. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  13422. enableAttribute( program.attributes.position );
  13423. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13424. }
  13425. if ( object.hasNormals ) {
  13426. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  13427. if ( material.shading === THREE.FlatShading ) {
  13428. var nx, ny, nz,
  13429. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  13430. normalArray,
  13431. i, il = object.count * 3;
  13432. for ( i = 0; i < il; i += 9 ) {
  13433. normalArray = object.normalArray;
  13434. nax = normalArray[ i ];
  13435. nay = normalArray[ i + 1 ];
  13436. naz = normalArray[ i + 2 ];
  13437. nbx = normalArray[ i + 3 ];
  13438. nby = normalArray[ i + 4 ];
  13439. nbz = normalArray[ i + 5 ];
  13440. ncx = normalArray[ i + 6 ];
  13441. ncy = normalArray[ i + 7 ];
  13442. ncz = normalArray[ i + 8 ];
  13443. nx = ( nax + nbx + ncx ) / 3;
  13444. ny = ( nay + nby + ncy ) / 3;
  13445. nz = ( naz + nbz + ncz ) / 3;
  13446. normalArray[ i ] = nx;
  13447. normalArray[ i + 1 ] = ny;
  13448. normalArray[ i + 2 ] = nz;
  13449. normalArray[ i + 3 ] = nx;
  13450. normalArray[ i + 4 ] = ny;
  13451. normalArray[ i + 5 ] = nz;
  13452. normalArray[ i + 6 ] = nx;
  13453. normalArray[ i + 7 ] = ny;
  13454. normalArray[ i + 8 ] = nz;
  13455. }
  13456. }
  13457. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  13458. enableAttribute( program.attributes.normal );
  13459. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13460. }
  13461. if ( object.hasUvs && material.map ) {
  13462. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  13463. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  13464. enableAttribute( program.attributes.uv );
  13465. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13466. }
  13467. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  13468. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  13469. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  13470. enableAttribute( program.attributes.color );
  13471. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13472. }
  13473. disableUnusedAttributes();
  13474. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  13475. object.count = 0;
  13476. };
  13477. function setupVertexAttributes( material, programAttributes, geometryAttributes, startIndex ) {
  13478. for ( var attributeName in programAttributes ) {
  13479. var attributePointer = programAttributes[ attributeName ];
  13480. var attributeItem = geometryAttributes[ attributeName ];
  13481. if ( attributePointer >= 0 ) {
  13482. if ( attributeItem ) {
  13483. var attributeSize = attributeItem.itemSize;
  13484. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13485. enableAttribute( attributePointer );
  13486. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, startIndex * attributeSize * 4 ); // 4 bytes per Float32
  13487. } else if ( material.defaultAttributeValues ) {
  13488. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  13489. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13490. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  13491. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13492. }
  13493. }
  13494. }
  13495. }
  13496. disableUnusedAttributes();
  13497. }
  13498. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  13499. if ( material.visible === false ) return;
  13500. var linewidth, a, attribute;
  13501. var attributeItem, attributeName, attributePointer, attributeSize;
  13502. var program = setProgram( camera, lights, fog, material, object );
  13503. var programAttributes = program.attributes;
  13504. var geometryAttributes = geometry.attributes;
  13505. var updateBuffers = false,
  13506. wireframeBit = material.wireframe ? 1 : 0,
  13507. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13508. if ( geometryHash !== _currentGeometryGroupHash ) {
  13509. _currentGeometryGroupHash = geometryHash;
  13510. updateBuffers = true;
  13511. }
  13512. if ( updateBuffers ) {
  13513. initAttributes();
  13514. }
  13515. // render mesh
  13516. if ( object instanceof THREE.Mesh ) {
  13517. var index = geometryAttributes[ 'index' ];
  13518. if ( index ) {
  13519. // indexed triangles
  13520. var type, size;
  13521. if ( index.array instanceof Uint32Array ) {
  13522. type = _gl.UNSIGNED_INT;
  13523. size = 4;
  13524. } else {
  13525. type = _gl.UNSIGNED_SHORT;
  13526. size = 2;
  13527. }
  13528. var offsets = geometry.offsets;
  13529. if ( offsets.length === 0 ) {
  13530. if ( updateBuffers ) {
  13531. setupVertexAttributes( material, programAttributes, geometryAttributes, 0 );
  13532. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  13533. }
  13534. _gl.drawElements( _gl.TRIANGLES, index.array.length, type, 0 );
  13535. _this.info.render.calls ++;
  13536. _this.info.render.vertices += index.array.length; // not really true, here vertices can be shared
  13537. _this.info.render.faces += index.array.length / 3;
  13538. } else {
  13539. // if there is more than 1 chunk
  13540. // must set attribute pointers to use new offsets for each chunk
  13541. // even if geometry and materials didn't change
  13542. updateBuffers = true;
  13543. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  13544. var startIndex = offsets[ i ].index;
  13545. if ( updateBuffers ) {
  13546. setupVertexAttributes( material, programAttributes, geometryAttributes, startIndex );
  13547. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  13548. }
  13549. // render indexed triangles
  13550. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, type, offsets[ i ].start * size );
  13551. _this.info.render.calls ++;
  13552. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  13553. _this.info.render.faces += offsets[ i ].count / 3;
  13554. }
  13555. }
  13556. } else {
  13557. // non-indexed triangles
  13558. if ( updateBuffers ) {
  13559. setupVertexAttributes( material, programAttributes, geometryAttributes, 0 );
  13560. }
  13561. var position = geometry.attributes[ 'position' ];
  13562. // render non-indexed triangles
  13563. _gl.drawArrays( _gl.TRIANGLES, 0, position.array.length / 3 );
  13564. _this.info.render.calls ++;
  13565. _this.info.render.vertices += position.array.length / 3;
  13566. _this.info.render.faces += position.array.length / 9;
  13567. }
  13568. } else if ( object instanceof THREE.PointCloud ) {
  13569. // render particles
  13570. if ( updateBuffers ) {
  13571. setupVertexAttributes( material, programAttributes, geometryAttributes, 0 );
  13572. }
  13573. var position = geometryAttributes[ 'position' ];
  13574. // render particles
  13575. _gl.drawArrays( _gl.POINTS, 0, position.array.length / 3 );
  13576. _this.info.render.calls ++;
  13577. _this.info.render.points += position.array.length / 3;
  13578. } else if ( object instanceof THREE.Line ) {
  13579. var mode = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  13580. setLineWidth( material.linewidth );
  13581. var index = geometryAttributes[ 'index' ];
  13582. if ( index ) {
  13583. // indexed lines
  13584. var type, size;
  13585. if ( index.array instanceof Uint32Array ) {
  13586. type = _gl.UNSIGNED_INT;
  13587. size = 4;
  13588. } else {
  13589. type = _gl.UNSIGNED_SHORT;
  13590. size = 2;
  13591. }
  13592. var offsets = geometry.offsets;
  13593. if ( offsets.length === 0 ) {
  13594. if ( updateBuffers ) {
  13595. setupVertexAttributes( material, programAttributes, geometryAttributes, 0 );
  13596. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  13597. }
  13598. _gl.drawElements( mode, index.array.length, type, 0 ); // 2 bytes per Uint16Array
  13599. _this.info.render.calls ++;
  13600. _this.info.render.vertices += index.array.length; // not really true, here vertices can be shared
  13601. } else {
  13602. // if there is more than 1 chunk
  13603. // must set attribute pointers to use new offsets for each chunk
  13604. // even if geometry and materials didn't change
  13605. if ( offsets.length > 1 ) updateBuffers = true;
  13606. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  13607. var startIndex = offsets[ i ].index;
  13608. if ( updateBuffers ) {
  13609. setupVertexAttributes( material, programAttributes, geometryAttributes, startIndex );
  13610. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  13611. }
  13612. // render indexed lines
  13613. _gl.drawElements( mode, offsets[ i ].count, type, offsets[ i ].start * size ); // 2 bytes per Uint16Array
  13614. _this.info.render.calls ++;
  13615. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  13616. }
  13617. }
  13618. } else {
  13619. // non-indexed lines
  13620. if ( updateBuffers ) {
  13621. setupVertexAttributes( material, programAttributes, geometryAttributes, 0 );
  13622. }
  13623. var position = geometryAttributes[ 'position' ];
  13624. _gl.drawArrays( mode, 0, position.array.length / 3 );
  13625. _this.info.render.calls ++;
  13626. _this.info.render.points += position.array.length / 3;
  13627. }
  13628. }
  13629. };
  13630. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  13631. if ( material.visible === false ) return;
  13632. var linewidth, a, attribute, i, il;
  13633. var program = setProgram( camera, lights, fog, material, object );
  13634. var attributes = program.attributes;
  13635. var updateBuffers = false,
  13636. wireframeBit = material.wireframe ? 1 : 0,
  13637. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13638. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  13639. _currentGeometryGroupHash = geometryGroupHash;
  13640. updateBuffers = true;
  13641. }
  13642. if ( updateBuffers ) {
  13643. initAttributes();
  13644. }
  13645. // vertices
  13646. if ( ! material.morphTargets && attributes.position >= 0 ) {
  13647. if ( updateBuffers ) {
  13648. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13649. enableAttribute( attributes.position );
  13650. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13651. }
  13652. } else {
  13653. if ( object.morphTargetBase ) {
  13654. setupMorphTargets( material, geometryGroup, object );
  13655. }
  13656. }
  13657. if ( updateBuffers ) {
  13658. // custom attributes
  13659. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  13660. if ( geometryGroup.__webglCustomAttributesList ) {
  13661. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  13662. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  13663. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  13664. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  13665. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  13666. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  13667. }
  13668. }
  13669. }
  13670. // colors
  13671. if ( attributes.color >= 0 ) {
  13672. if ( object.geometry.colors.length > 0 || object.geometry.faces.length > 0 ) {
  13673. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  13674. enableAttribute( attributes.color );
  13675. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13676. } else if ( material.defaultAttributeValues ) {
  13677. _gl.vertexAttrib3fv( attributes.color, material.defaultAttributeValues.color );
  13678. }
  13679. }
  13680. // normals
  13681. if ( attributes.normal >= 0 ) {
  13682. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  13683. enableAttribute( attributes.normal );
  13684. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13685. }
  13686. // tangents
  13687. if ( attributes.tangent >= 0 ) {
  13688. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  13689. enableAttribute( attributes.tangent );
  13690. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  13691. }
  13692. // uvs
  13693. if ( attributes.uv >= 0 ) {
  13694. if ( object.geometry.faceVertexUvs[ 0 ] ) {
  13695. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  13696. enableAttribute( attributes.uv );
  13697. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13698. } else if ( material.defaultAttributeValues ) {
  13699. _gl.vertexAttrib2fv( attributes.uv, material.defaultAttributeValues.uv );
  13700. }
  13701. }
  13702. if ( attributes.uv2 >= 0 ) {
  13703. if ( object.geometry.faceVertexUvs[ 1 ] ) {
  13704. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  13705. enableAttribute( attributes.uv2 );
  13706. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  13707. } else if ( material.defaultAttributeValues ) {
  13708. _gl.vertexAttrib2fv( attributes.uv2, material.defaultAttributeValues.uv2 );
  13709. }
  13710. }
  13711. if ( material.skinning &&
  13712. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  13713. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  13714. enableAttribute( attributes.skinIndex );
  13715. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  13716. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  13717. enableAttribute( attributes.skinWeight );
  13718. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  13719. }
  13720. // line distances
  13721. if ( attributes.lineDistance >= 0 ) {
  13722. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  13723. enableAttribute( attributes.lineDistance );
  13724. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  13725. }
  13726. }
  13727. disableUnusedAttributes();
  13728. // render mesh
  13729. if ( object instanceof THREE.Mesh ) {
  13730. var type = geometryGroup.__typeArray === Uint32Array ? _gl.UNSIGNED_INT : _gl.UNSIGNED_SHORT;
  13731. // wireframe
  13732. if ( material.wireframe ) {
  13733. setLineWidth( material.wireframeLinewidth );
  13734. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  13735. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, type, 0 );
  13736. // triangles
  13737. } else {
  13738. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  13739. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, type, 0 );
  13740. }
  13741. _this.info.render.calls ++;
  13742. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  13743. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  13744. // render lines
  13745. } else if ( object instanceof THREE.Line ) {
  13746. var mode = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  13747. setLineWidth( material.linewidth );
  13748. _gl.drawArrays( mode, 0, geometryGroup.__webglLineCount );
  13749. _this.info.render.calls ++;
  13750. // render particles
  13751. } else if ( object instanceof THREE.PointCloud ) {
  13752. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  13753. _this.info.render.calls ++;
  13754. _this.info.render.points += geometryGroup.__webglParticleCount;
  13755. }
  13756. };
  13757. function initAttributes() {
  13758. for ( var i = 0, l = _newAttributes.length; i < l; i ++ ) {
  13759. _newAttributes[ i ] = 0;
  13760. }
  13761. }
  13762. function enableAttribute( attribute ) {
  13763. _newAttributes[ attribute ] = 1;
  13764. if ( _enabledAttributes[ attribute ] === 0 ) {
  13765. _gl.enableVertexAttribArray( attribute );
  13766. _enabledAttributes[ attribute ] = 1;
  13767. }
  13768. }
  13769. function disableUnusedAttributes() {
  13770. for ( var i = 0, l = _enabledAttributes.length; i < l; i ++ ) {
  13771. if ( _enabledAttributes[ i ] !== _newAttributes[ i ] ) {
  13772. _gl.disableVertexAttribArray( i );
  13773. _enabledAttributes[ i ] = 0;
  13774. }
  13775. }
  13776. }
  13777. function setupMorphTargets ( material, geometryGroup, object ) {
  13778. // set base
  13779. var attributes = material.program.attributes;
  13780. if ( object.morphTargetBase !== - 1 && attributes.position >= 0 ) {
  13781. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  13782. enableAttribute( attributes.position );
  13783. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13784. } else if ( attributes.position >= 0 ) {
  13785. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13786. enableAttribute( attributes.position );
  13787. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13788. }
  13789. if ( object.morphTargetForcedOrder.length ) {
  13790. // set forced order
  13791. var m = 0;
  13792. var order = object.morphTargetForcedOrder;
  13793. var influences = object.morphTargetInfluences;
  13794. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  13795. if ( attributes[ 'morphTarget' + m ] >= 0 ) {
  13796. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  13797. enableAttribute( attributes[ 'morphTarget' + m ] );
  13798. _gl.vertexAttribPointer( attributes[ 'morphTarget' + m ], 3, _gl.FLOAT, false, 0, 0 );
  13799. }
  13800. if ( attributes[ 'morphNormal' + m ] >= 0 && material.morphNormals ) {
  13801. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  13802. enableAttribute( attributes[ 'morphNormal' + m ] );
  13803. _gl.vertexAttribPointer( attributes[ 'morphNormal' + m ], 3, _gl.FLOAT, false, 0, 0 );
  13804. }
  13805. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  13806. m ++;
  13807. }
  13808. } else {
  13809. // find the most influencing
  13810. var influence, activeInfluenceIndices = [];
  13811. var influences = object.morphTargetInfluences;
  13812. var i, il = influences.length;
  13813. for ( i = 0; i < il; i ++ ) {
  13814. influence = influences[ i ];
  13815. if ( influence > 0 ) {
  13816. activeInfluenceIndices.push( [ influence, i ] );
  13817. }
  13818. }
  13819. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  13820. activeInfluenceIndices.sort( numericalSort );
  13821. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  13822. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  13823. activeInfluenceIndices.sort( numericalSort );
  13824. } else if ( activeInfluenceIndices.length === 0 ) {
  13825. activeInfluenceIndices.push( [ 0, 0 ] );
  13826. };
  13827. var influenceIndex, m = 0;
  13828. while ( m < material.numSupportedMorphTargets ) {
  13829. if ( activeInfluenceIndices[ m ] ) {
  13830. influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  13831. if ( attributes[ 'morphTarget' + m ] >= 0 ) {
  13832. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  13833. enableAttribute( attributes[ 'morphTarget' + m ] );
  13834. _gl.vertexAttribPointer( attributes[ 'morphTarget' + m ], 3, _gl.FLOAT, false, 0, 0 );
  13835. }
  13836. if ( attributes[ 'morphNormal' + m ] >= 0 && material.morphNormals ) {
  13837. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  13838. enableAttribute( attributes[ 'morphNormal' + m ] );
  13839. _gl.vertexAttribPointer( attributes[ 'morphNormal' + m ], 3, _gl.FLOAT, false, 0, 0 );
  13840. }
  13841. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  13842. } else {
  13843. /*
  13844. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13845. if ( material.morphNormals ) {
  13846. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13847. }
  13848. */
  13849. object.__webglMorphTargetInfluences[ m ] = 0;
  13850. }
  13851. m ++;
  13852. }
  13853. }
  13854. // load updated influences uniform
  13855. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  13856. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  13857. }
  13858. };
  13859. // Sorting
  13860. function painterSortStable ( a, b ) {
  13861. if ( a.z !== b.z ) {
  13862. return b.z - a.z;
  13863. } else {
  13864. return a.id - b.id;
  13865. }
  13866. };
  13867. function reversePainterSortStable ( a, b ) {
  13868. if ( a.z !== b.z ) {
  13869. return a.z - b.z;
  13870. } else {
  13871. return a.id - b.id;
  13872. }
  13873. };
  13874. function numericalSort ( a, b ) {
  13875. return b[ 0 ] - a[ 0 ];
  13876. };
  13877. // Rendering
  13878. this.render = function ( scene, camera, renderTarget, forceClear ) {
  13879. if ( camera instanceof THREE.Camera === false ) {
  13880. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  13881. return;
  13882. }
  13883. var i, il,
  13884. webglObject, object,
  13885. renderList,
  13886. lights = scene.__lights,
  13887. fog = scene.fog;
  13888. // reset caching for this frame
  13889. _currentMaterialId = - 1;
  13890. _lightsNeedUpdate = true;
  13891. // update scene graph
  13892. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  13893. // update camera matrices and frustum
  13894. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  13895. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  13896. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  13897. _frustum.setFromMatrix( _projScreenMatrix );
  13898. initObjects( scene );
  13899. opaqueObjects.length = 0;
  13900. transparentObjects.length = 0;
  13901. _sortObjects = this.sortObjects;
  13902. projectObject(scene,scene,camera);
  13903. if ( this.sortObjects ) {
  13904. opaqueObjects.sort( painterSortStable );
  13905. transparentObjects.sort( reversePainterSortStable );
  13906. }
  13907. // custom render plugins (pre pass)
  13908. renderPlugins( this.renderPluginsPre, scene, camera );
  13909. //
  13910. _this.info.render.calls = 0;
  13911. _this.info.render.vertices = 0;
  13912. _this.info.render.faces = 0;
  13913. _this.info.render.points = 0;
  13914. this.setRenderTarget( renderTarget );
  13915. if ( this.autoClear || forceClear ) {
  13916. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  13917. }
  13918. // set matrices for regular objects (frustum culled)
  13919. // set matrices for immediate objects
  13920. renderList = scene.__webglObjectsImmediate;
  13921. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13922. webglObject = renderList[ i ];
  13923. object = webglObject.object;
  13924. if ( object.visible ) {
  13925. setupMatrices( object, camera );
  13926. unrollImmediateBufferMaterial( webglObject );
  13927. }
  13928. }
  13929. if ( scene.overrideMaterial ) {
  13930. var material = scene.overrideMaterial;
  13931. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13932. this.setDepthTest( material.depthTest );
  13933. this.setDepthWrite( material.depthWrite );
  13934. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13935. renderObjects( opaqueObjects, camera, lights, fog, true, material );
  13936. renderObjects( transparentObjects, camera, lights, fog, true, material );
  13937. renderObjectsImmediate( scene.__webglObjectsImmediate, '', camera, lights, fog, false, material );
  13938. } else {
  13939. var material = null;
  13940. // opaque pass (front-to-back order)
  13941. this.setBlending( THREE.NoBlending );
  13942. renderObjects( opaqueObjects, camera, lights, fog, false, material );
  13943. renderObjectsImmediate( scene.__webglObjectsImmediate, 'opaque', camera, lights, fog, false, material );
  13944. // transparent pass (back-to-front order)
  13945. renderObjects( transparentObjects, camera, lights, fog, true, material );
  13946. renderObjectsImmediate( scene.__webglObjectsImmediate, 'transparent', camera, lights, fog, true, material );
  13947. }
  13948. // custom render plugins (post pass)
  13949. renderPlugins( this.renderPluginsPost, scene, camera );
  13950. // Generate mipmap if we're using any kind of mipmap filtering
  13951. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  13952. updateRenderTargetMipmap( renderTarget );
  13953. }
  13954. // Ensure depth buffer writing is enabled so it can be cleared on next render
  13955. this.setDepthTest( true );
  13956. this.setDepthWrite( true );
  13957. // _gl.finish();
  13958. };
  13959. function projectObject(scene, object,camera){
  13960. if ( object.visible === false ) return;
  13961. var webglObjects = scene.__webglObjects[ object.id ];
  13962. if ( webglObjects && (object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) ) {
  13963. updateObject( scene, object );
  13964. for ( var i = 0, l = webglObjects.length; i < l; i ++ ) {
  13965. var webglObject = webglObjects[i];
  13966. unrollBufferMaterial( webglObject );
  13967. webglObject.render = true;
  13968. if ( _sortObjects === true ) {
  13969. if ( object.renderDepth !== null ) {
  13970. webglObject.z = object.renderDepth;
  13971. } else {
  13972. _vector3.setFromMatrixPosition( object.matrixWorld );
  13973. _vector3.applyProjection( _projScreenMatrix );
  13974. webglObject.z = _vector3.z;
  13975. }
  13976. }
  13977. }
  13978. }
  13979. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  13980. projectObject( scene, object.children[ i ], camera );
  13981. }
  13982. }
  13983. function renderPlugins( plugins, scene, camera ) {
  13984. if ( plugins.length === 0 ) return;
  13985. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  13986. // reset state for plugin (to start from clean slate)
  13987. _currentProgram = null;
  13988. _currentCamera = null;
  13989. _oldBlending = - 1;
  13990. _oldDepthTest = - 1;
  13991. _oldDepthWrite = - 1;
  13992. _oldDoubleSided = - 1;
  13993. _oldFlipSided = - 1;
  13994. _currentGeometryGroupHash = - 1;
  13995. _currentMaterialId = - 1;
  13996. _lightsNeedUpdate = true;
  13997. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  13998. // reset state after plugin (anything could have changed)
  13999. _currentProgram = null;
  14000. _currentCamera = null;
  14001. _oldBlending = - 1;
  14002. _oldDepthTest = - 1;
  14003. _oldDepthWrite = - 1;
  14004. _oldDoubleSided = - 1;
  14005. _oldFlipSided = - 1;
  14006. _currentGeometryGroupHash = - 1;
  14007. _currentMaterialId = - 1;
  14008. _lightsNeedUpdate = true;
  14009. }
  14010. };
  14011. function renderObjects( renderList, camera, lights, fog, useBlending, overrideMaterial ) {
  14012. var webglObject, object, buffer, material;
  14013. for ( var i = renderList.length - 1; i !== - 1; i -- ) {
  14014. webglObject = renderList[ i ];
  14015. object = webglObject.object;
  14016. buffer = webglObject.buffer;
  14017. setupMatrices( object, camera );
  14018. if ( overrideMaterial ) {
  14019. material = overrideMaterial;
  14020. } else {
  14021. material = webglObject.material;
  14022. if ( ! material ) continue;
  14023. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  14024. _this.setDepthTest( material.depthTest );
  14025. _this.setDepthWrite( material.depthWrite );
  14026. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  14027. }
  14028. _this.setMaterialFaces( material );
  14029. if ( buffer instanceof THREE.BufferGeometry ) {
  14030. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  14031. } else {
  14032. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  14033. }
  14034. }
  14035. };
  14036. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  14037. var webglObject, object, material, program;
  14038. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  14039. webglObject = renderList[ i ];
  14040. object = webglObject.object;
  14041. if ( object.visible ) {
  14042. if ( overrideMaterial ) {
  14043. material = overrideMaterial;
  14044. } else {
  14045. material = webglObject[ materialType ];
  14046. if ( ! material ) continue;
  14047. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  14048. _this.setDepthTest( material.depthTest );
  14049. _this.setDepthWrite( material.depthWrite );
  14050. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  14051. }
  14052. _this.renderImmediateObject( camera, lights, fog, material, object );
  14053. }
  14054. }
  14055. };
  14056. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  14057. var program = setProgram( camera, lights, fog, material, object );
  14058. _currentGeometryGroupHash = - 1;
  14059. _this.setMaterialFaces( material );
  14060. if ( object.immediateRenderCallback ) {
  14061. object.immediateRenderCallback( program, _gl, _frustum );
  14062. } else {
  14063. object.render( function ( object ) { _this.renderBufferImmediate( object, program, material ); } );
  14064. }
  14065. };
  14066. function unrollImmediateBufferMaterial ( globject ) {
  14067. var object = globject.object,
  14068. material = object.material;
  14069. if ( material.transparent ) {
  14070. globject.transparent = material;
  14071. globject.opaque = null;
  14072. } else {
  14073. globject.opaque = material;
  14074. globject.transparent = null;
  14075. }
  14076. };
  14077. function unrollBufferMaterial ( globject ) {
  14078. var object = globject.object;
  14079. var buffer = globject.buffer;
  14080. var geometry = object.geometry;
  14081. var material = object.material;
  14082. if ( material instanceof THREE.MeshFaceMaterial ) {
  14083. var materialIndex = geometry instanceof THREE.BufferGeometry ? 0 : buffer.materialIndex;
  14084. material = material.materials[ materialIndex ];
  14085. if ( material.transparent ) {
  14086. globject.material = material;
  14087. transparentObjects.push(globject);
  14088. } else {
  14089. globject.material = material;
  14090. opaqueObjects.push(globject);
  14091. }
  14092. } else {
  14093. if ( material ) {
  14094. if ( material.transparent ) {
  14095. globject.material = material;
  14096. transparentObjects.push(globject);
  14097. } else {
  14098. globject.material = material;
  14099. opaqueObjects.push(globject);
  14100. }
  14101. }
  14102. }
  14103. };
  14104. // Objects refresh
  14105. var initObjects = function ( scene ) {
  14106. if ( ! scene.__webglObjects ) {
  14107. scene.__webglObjects = {};
  14108. scene.__webglObjectsImmediate = [];
  14109. }
  14110. while ( scene.__objectsAdded.length ) {
  14111. addObject( scene.__objectsAdded[ 0 ], scene );
  14112. scene.__objectsAdded.splice( 0, 1 );
  14113. }
  14114. while ( scene.__objectsRemoved.length ) {
  14115. removeObject( scene.__objectsRemoved[ 0 ], scene );
  14116. scene.__objectsRemoved.splice( 0, 1 );
  14117. }
  14118. };
  14119. // Objects adding
  14120. function addObject( object, scene ) {
  14121. var g, geometry, geometryGroup;
  14122. if ( object.__webglInit === undefined ) {
  14123. object.__webglInit = true;
  14124. object._modelViewMatrix = new THREE.Matrix4();
  14125. object._normalMatrix = new THREE.Matrix3();
  14126. }
  14127. geometry = object.geometry;
  14128. if ( geometry === undefined ) {
  14129. // ImmediateRenderObject
  14130. } else if ( geometry.__webglInit === undefined ) {
  14131. geometry.__webglInit = true;
  14132. geometry.addEventListener( 'dispose', onGeometryDispose );
  14133. if ( geometry instanceof THREE.BufferGeometry ) {
  14134. initDirectBuffers( geometry );
  14135. } else if ( object instanceof THREE.Mesh ) {
  14136. if ( object.__webglActive !== undefined ) {
  14137. removeObject( object, scene );
  14138. }
  14139. initGeometryGroups(scene, object, geometry);
  14140. } else if ( object instanceof THREE.Line ) {
  14141. if ( ! geometry.__webglVertexBuffer ) {
  14142. createLineBuffers( geometry );
  14143. initLineBuffers( geometry, object );
  14144. geometry.verticesNeedUpdate = true;
  14145. geometry.colorsNeedUpdate = true;
  14146. geometry.lineDistancesNeedUpdate = true;
  14147. }
  14148. } else if ( object instanceof THREE.PointCloud ) {
  14149. if ( ! geometry.__webglVertexBuffer ) {
  14150. createParticleBuffers( geometry );
  14151. initParticleBuffers( geometry, object );
  14152. geometry.verticesNeedUpdate = true;
  14153. geometry.colorsNeedUpdate = true;
  14154. }
  14155. }
  14156. }
  14157. if ( object.__webglActive === undefined) {
  14158. if ( object instanceof THREE.Mesh ) {
  14159. geometry = object.geometry;
  14160. if ( geometry instanceof THREE.BufferGeometry ) {
  14161. addBuffer( scene.__webglObjects, geometry, object );
  14162. } else if ( geometry instanceof THREE.Geometry ) {
  14163. for ( var i = 0,l = geometry.geometryGroupsList.length; i<l;i++ ) {
  14164. geometryGroup = geometry.geometryGroupsList[ i ];
  14165. addBuffer( scene.__webglObjects, geometryGroup, object );
  14166. }
  14167. }
  14168. } else if ( object instanceof THREE.Line ||
  14169. object instanceof THREE.PointCloud ) {
  14170. geometry = object.geometry;
  14171. addBuffer( scene.__webglObjects, geometry, object );
  14172. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  14173. addBufferImmediate( scene.__webglObjectsImmediate, object );
  14174. }
  14175. object.__webglActive = true;
  14176. }
  14177. };
  14178. function initGeometryGroups( scene, object, geometry ) {
  14179. var g, geometryGroup, material,addBuffers = false;
  14180. material = object.material;
  14181. if ( geometry.geometryGroups === undefined || geometry.groupsNeedUpdate ) {
  14182. delete scene.__webglObjects[object.id];
  14183. geometry.makeGroups( material instanceof THREE.MeshFaceMaterial, _glExtensionElementIndexUint ? 4294967296 : 65535 );
  14184. geometry.groupsNeedUpdate = false;
  14185. }
  14186. // create separate VBOs per geometry chunk
  14187. for ( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  14188. geometryGroup = geometry.geometryGroupsList[ i ];
  14189. // initialise VBO on the first access
  14190. if ( ! geometryGroup.__webglVertexBuffer ) {
  14191. createMeshBuffers( geometryGroup );
  14192. initMeshBuffers( geometryGroup, object );
  14193. geometry.verticesNeedUpdate = true;
  14194. geometry.morphTargetsNeedUpdate = true;
  14195. geometry.elementsNeedUpdate = true;
  14196. geometry.uvsNeedUpdate = true;
  14197. geometry.normalsNeedUpdate = true;
  14198. geometry.tangentsNeedUpdate = true;
  14199. geometry.colorsNeedUpdate = true;
  14200. addBuffers = true;
  14201. } else {
  14202. addBuffers = false;
  14203. }
  14204. if ( addBuffers || object.__webglActive === undefined ) {
  14205. addBuffer( scene.__webglObjects, geometryGroup, object );
  14206. }
  14207. }
  14208. object.__webglActive = true;
  14209. }
  14210. function addBuffer( objlist, buffer, object ) {
  14211. var id = object.id;
  14212. objlist[id] = objlist[id] || [];
  14213. objlist[id].push(
  14214. {
  14215. id: id,
  14216. buffer: buffer,
  14217. object: object,
  14218. material: null,
  14219. z: 0
  14220. }
  14221. );
  14222. };
  14223. function addBufferImmediate( objlist, object ) {
  14224. objlist.push(
  14225. {
  14226. id: null,
  14227. object: object,
  14228. opaque: null,
  14229. transparent: null,
  14230. z: 0
  14231. }
  14232. );
  14233. };
  14234. // Objects updates
  14235. function updateObject(scene, object ) {
  14236. var geometry = object.geometry,
  14237. geometryGroup, customAttributesDirty, material;
  14238. if ( geometry instanceof THREE.BufferGeometry ) {
  14239. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW );
  14240. } else if ( object instanceof THREE.Mesh ) {
  14241. // check all geometry groups
  14242. if ( geometry.buffersNeedUpdate || geometry.groupsNeedUpdate ) {
  14243. if ( geometry instanceof THREE.BufferGeometry ) {
  14244. initDirectBuffers( geometry );
  14245. } else if ( object instanceof THREE.Mesh ) {
  14246. initGeometryGroups(scene, object,geometry);
  14247. }
  14248. }
  14249. for ( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  14250. geometryGroup = geometry.geometryGroupsList[ i ];
  14251. material = getBufferMaterial( object, geometryGroup );
  14252. if ( geometry.buffersNeedUpdate || geometry.groupsNeedUpdate) {
  14253. initMeshBuffers( geometryGroup, object );
  14254. }
  14255. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14256. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  14257. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  14258. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  14259. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, ! geometry.dynamic, material );
  14260. }
  14261. }
  14262. geometry.verticesNeedUpdate = false;
  14263. geometry.morphTargetsNeedUpdate = false;
  14264. geometry.elementsNeedUpdate = false;
  14265. geometry.uvsNeedUpdate = false;
  14266. geometry.normalsNeedUpdate = false;
  14267. geometry.colorsNeedUpdate = false;
  14268. geometry.tangentsNeedUpdate = false;
  14269. geometry.buffersNeedUpdate = false;
  14270. material.attributes && clearCustomAttributes( material );
  14271. } else if ( object instanceof THREE.Line ) {
  14272. material = getBufferMaterial( object, geometry );
  14273. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14274. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  14275. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  14276. }
  14277. geometry.verticesNeedUpdate = false;
  14278. geometry.colorsNeedUpdate = false;
  14279. geometry.lineDistancesNeedUpdate = false;
  14280. material.attributes && clearCustomAttributes( material );
  14281. } else if ( object instanceof THREE.PointCloud ) {
  14282. material = getBufferMaterial( object, geometry );
  14283. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14284. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  14285. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  14286. }
  14287. geometry.verticesNeedUpdate = false;
  14288. geometry.colorsNeedUpdate = false;
  14289. material.attributes && clearCustomAttributes( material );
  14290. }
  14291. };
  14292. // Objects updates - custom attributes check
  14293. function areCustomAttributesDirty( material ) {
  14294. for ( var a in material.attributes ) {
  14295. if ( material.attributes[ a ].needsUpdate ) return true;
  14296. }
  14297. return false;
  14298. };
  14299. function clearCustomAttributes( material ) {
  14300. for ( var a in material.attributes ) {
  14301. material.attributes[ a ].needsUpdate = false;
  14302. }
  14303. };
  14304. // Objects removal
  14305. function removeObject( object, scene ) {
  14306. if ( object instanceof THREE.Mesh ||
  14307. object instanceof THREE.PointCloud ||
  14308. object instanceof THREE.Line ) {
  14309. removeInstancesWebglObjects( scene.__webglObjects, object );
  14310. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  14311. removeInstances( scene.__webglObjectsImmediate, object );
  14312. }
  14313. delete object.__webglActive;
  14314. };
  14315. function removeInstancesWebglObjects( objlist, object ) {
  14316. delete objlist[ object.id ];
  14317. };
  14318. function removeInstances( objlist, object ) {
  14319. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  14320. if ( objlist[ o ].object === object ) {
  14321. objlist.splice( o, 1 );
  14322. }
  14323. }
  14324. };
  14325. // Materials
  14326. this.initMaterial = function ( material, lights, fog, object ) {
  14327. material.addEventListener( 'dispose', onMaterialDispose );
  14328. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  14329. if ( material instanceof THREE.MeshDepthMaterial ) {
  14330. shaderID = 'depth';
  14331. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  14332. shaderID = 'normal';
  14333. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  14334. shaderID = 'basic';
  14335. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  14336. shaderID = 'lambert';
  14337. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  14338. shaderID = 'phong';
  14339. } else if ( material instanceof THREE.LineBasicMaterial ) {
  14340. shaderID = 'basic';
  14341. } else if ( material instanceof THREE.LineDashedMaterial ) {
  14342. shaderID = 'dashed';
  14343. } else if ( material instanceof THREE.PointCloudMaterial ) {
  14344. shaderID = 'particle_basic';
  14345. }
  14346. if ( shaderID ) {
  14347. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  14348. }
  14349. // heuristics to create shader parameters according to lights in the scene
  14350. // (not to blow over maxLights budget)
  14351. maxLightCount = allocateLights( lights );
  14352. maxShadows = allocateShadows( lights );
  14353. maxBones = allocateBones( object );
  14354. parameters = {
  14355. precision: _precision,
  14356. supportsVertexTextures: _supportsVertexTextures,
  14357. map: !! material.map,
  14358. envMap: !! material.envMap,
  14359. lightMap: !! material.lightMap,
  14360. bumpMap: !! material.bumpMap,
  14361. normalMap: !! material.normalMap,
  14362. specularMap: !! material.specularMap,
  14363. vertexColors: material.vertexColors,
  14364. fog: fog,
  14365. useFog: material.fog,
  14366. fogExp: fog instanceof THREE.FogExp2,
  14367. sizeAttenuation: material.sizeAttenuation,
  14368. logarithmicDepthBuffer: _logarithmicDepthBuffer,
  14369. skinning: material.skinning,
  14370. maxBones: maxBones,
  14371. useVertexTexture: _supportsBoneTextures && object && object.skeleton && object.skeleton.useVertexTexture,
  14372. morphTargets: material.morphTargets,
  14373. morphNormals: material.morphNormals,
  14374. maxMorphTargets: this.maxMorphTargets,
  14375. maxMorphNormals: this.maxMorphNormals,
  14376. maxDirLights: maxLightCount.directional,
  14377. maxPointLights: maxLightCount.point,
  14378. maxSpotLights: maxLightCount.spot,
  14379. maxHemiLights: maxLightCount.hemi,
  14380. maxShadows: maxShadows,
  14381. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow && maxShadows > 0,
  14382. shadowMapType: this.shadowMapType,
  14383. shadowMapDebug: this.shadowMapDebug,
  14384. shadowMapCascade: this.shadowMapCascade,
  14385. alphaTest: material.alphaTest,
  14386. metal: material.metal,
  14387. wrapAround: material.wrapAround,
  14388. doubleSided: material.side === THREE.DoubleSide,
  14389. flipSided: material.side === THREE.BackSide
  14390. };
  14391. // Generate code
  14392. var chunks = [];
  14393. if ( shaderID ) {
  14394. chunks.push( shaderID );
  14395. } else {
  14396. chunks.push( material.fragmentShader );
  14397. chunks.push( material.vertexShader );
  14398. }
  14399. for ( var d in material.defines ) {
  14400. chunks.push( d );
  14401. chunks.push( material.defines[ d ] );
  14402. }
  14403. for ( var p in parameters ) {
  14404. chunks.push( p );
  14405. chunks.push( parameters[ p ] );
  14406. }
  14407. var code = chunks.join();
  14408. var program;
  14409. // Check if code has been already compiled
  14410. for ( var p = 0, pl = _programs.length; p < pl; p ++ ) {
  14411. var programInfo = _programs[ p ];
  14412. if ( programInfo.code === code ) {
  14413. program = programInfo;
  14414. program.usedTimes ++;
  14415. break;
  14416. }
  14417. }
  14418. if ( program === undefined ) {
  14419. program = new THREE.WebGLProgram( this, code, material, parameters );
  14420. _programs.push( program );
  14421. _this.info.memory.programs = _programs.length;
  14422. }
  14423. material.program = program;
  14424. var attributes = material.program.attributes;
  14425. if ( material.morphTargets ) {
  14426. material.numSupportedMorphTargets = 0;
  14427. var id, base = 'morphTarget';
  14428. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  14429. id = base + i;
  14430. if ( attributes[ id ] >= 0 ) {
  14431. material.numSupportedMorphTargets ++;
  14432. }
  14433. }
  14434. }
  14435. if ( material.morphNormals ) {
  14436. material.numSupportedMorphNormals = 0;
  14437. var id, base = 'morphNormal';
  14438. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  14439. id = base + i;
  14440. if ( attributes[ id ] >= 0 ) {
  14441. material.numSupportedMorphNormals ++;
  14442. }
  14443. }
  14444. }
  14445. material.uniformsList = [];
  14446. for ( u in material.uniforms ) {
  14447. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  14448. }
  14449. };
  14450. function setMaterialShaders( material, shaders ) {
  14451. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  14452. material.vertexShader = shaders.vertexShader;
  14453. material.fragmentShader = shaders.fragmentShader;
  14454. };
  14455. function setProgram( camera, lights, fog, material, object ) {
  14456. _usedTextureUnits = 0;
  14457. if ( material.needsUpdate ) {
  14458. if ( material.program ) deallocateMaterial( material );
  14459. _this.initMaterial( material, lights, fog, object );
  14460. material.needsUpdate = false;
  14461. }
  14462. if ( material.morphTargets ) {
  14463. if ( ! object.__webglMorphTargetInfluences ) {
  14464. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  14465. }
  14466. }
  14467. var refreshMaterial = false;
  14468. var program = material.program,
  14469. p_uniforms = program.uniforms,
  14470. m_uniforms = material.uniforms;
  14471. if ( program.id !== _currentProgram ) {
  14472. _gl.useProgram( program.program );
  14473. _currentProgram = program.id;
  14474. refreshMaterial = true;
  14475. }
  14476. if ( material.id !== _currentMaterialId ) {
  14477. _currentMaterialId = material.id;
  14478. refreshMaterial = true;
  14479. }
  14480. if ( refreshMaterial || camera !== _currentCamera ) {
  14481. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  14482. if ( _logarithmicDepthBuffer ) {
  14483. _gl.uniform1f( p_uniforms.logDepthBufFC, 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  14484. }
  14485. if ( camera !== _currentCamera ) _currentCamera = camera;
  14486. }
  14487. // skinning uniforms must be set even if material didn't change
  14488. // auto-setting of texture unit for bone texture must go before other textures
  14489. // not sure why, but otherwise weird things happen
  14490. if ( material.skinning ) {
  14491. if ( _supportsBoneTextures && object.skeleton.useVertexTexture ) {
  14492. if ( p_uniforms.boneTexture !== null ) {
  14493. var textureUnit = getTextureUnit();
  14494. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  14495. _this.setTexture( object.skeleton.boneTexture, textureUnit );
  14496. }
  14497. if ( p_uniforms.boneTextureWidth !== null ) {
  14498. _gl.uniform1i( p_uniforms.boneTextureWidth, object.skeleton.boneTextureWidth );
  14499. }
  14500. if ( p_uniforms.boneTextureHeight !== null ) {
  14501. _gl.uniform1i( p_uniforms.boneTextureHeight, object.skeleton.boneTextureHeight );
  14502. }
  14503. } else {
  14504. if ( p_uniforms.boneGlobalMatrices !== null ) {
  14505. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.skeleton.boneMatrices );
  14506. }
  14507. }
  14508. }
  14509. if ( refreshMaterial ) {
  14510. // refresh uniforms common to several materials
  14511. if ( fog && material.fog ) {
  14512. refreshUniformsFog( m_uniforms, fog );
  14513. }
  14514. if ( material instanceof THREE.MeshPhongMaterial ||
  14515. material instanceof THREE.MeshLambertMaterial ||
  14516. material.lights ) {
  14517. if ( _lightsNeedUpdate ) {
  14518. setupLights( program, lights );
  14519. _lightsNeedUpdate = false;
  14520. }
  14521. refreshUniformsLights( m_uniforms, _lights );
  14522. }
  14523. if ( material instanceof THREE.MeshBasicMaterial ||
  14524. material instanceof THREE.MeshLambertMaterial ||
  14525. material instanceof THREE.MeshPhongMaterial ) {
  14526. refreshUniformsCommon( m_uniforms, material );
  14527. }
  14528. // refresh single material specific uniforms
  14529. if ( material instanceof THREE.LineBasicMaterial ) {
  14530. refreshUniformsLine( m_uniforms, material );
  14531. } else if ( material instanceof THREE.LineDashedMaterial ) {
  14532. refreshUniformsLine( m_uniforms, material );
  14533. refreshUniformsDash( m_uniforms, material );
  14534. } else if ( material instanceof THREE.PointCloudMaterial ) {
  14535. refreshUniformsParticle( m_uniforms, material );
  14536. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  14537. refreshUniformsPhong( m_uniforms, material );
  14538. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  14539. refreshUniformsLambert( m_uniforms, material );
  14540. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  14541. m_uniforms.mNear.value = camera.near;
  14542. m_uniforms.mFar.value = camera.far;
  14543. m_uniforms.opacity.value = material.opacity;
  14544. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  14545. m_uniforms.opacity.value = material.opacity;
  14546. }
  14547. if ( object.receiveShadow && ! material._shadowPass ) {
  14548. refreshUniformsShadow( m_uniforms, lights );
  14549. }
  14550. // load common uniforms
  14551. loadUniformsGeneric( program, material.uniformsList );
  14552. // load material specific uniforms
  14553. // (shader material also gets them for the sake of genericity)
  14554. if ( material instanceof THREE.ShaderMaterial ||
  14555. material instanceof THREE.MeshPhongMaterial ||
  14556. material.envMap ) {
  14557. if ( p_uniforms.cameraPosition !== null ) {
  14558. _vector3.setFromMatrixPosition( camera.matrixWorld );
  14559. _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  14560. }
  14561. }
  14562. if ( material instanceof THREE.MeshPhongMaterial ||
  14563. material instanceof THREE.MeshLambertMaterial ||
  14564. material instanceof THREE.ShaderMaterial ||
  14565. material.skinning ) {
  14566. if ( p_uniforms.viewMatrix !== null ) {
  14567. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  14568. }
  14569. }
  14570. }
  14571. loadUniformsMatrices( p_uniforms, object );
  14572. if ( p_uniforms.modelMatrix !== null ) {
  14573. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  14574. }
  14575. return program;
  14576. };
  14577. // Uniforms (refresh uniforms objects)
  14578. function refreshUniformsCommon ( uniforms, material ) {
  14579. uniforms.opacity.value = material.opacity;
  14580. if ( _this.gammaInput ) {
  14581. uniforms.diffuse.value.copyGammaToLinear( material.color );
  14582. } else {
  14583. uniforms.diffuse.value = material.color;
  14584. }
  14585. uniforms.map.value = material.map;
  14586. uniforms.lightMap.value = material.lightMap;
  14587. uniforms.specularMap.value = material.specularMap;
  14588. if ( material.bumpMap ) {
  14589. uniforms.bumpMap.value = material.bumpMap;
  14590. uniforms.bumpScale.value = material.bumpScale;
  14591. }
  14592. if ( material.normalMap ) {
  14593. uniforms.normalMap.value = material.normalMap;
  14594. uniforms.normalScale.value.copy( material.normalScale );
  14595. }
  14596. // uv repeat and offset setting priorities
  14597. // 1. color map
  14598. // 2. specular map
  14599. // 3. normal map
  14600. // 4. bump map
  14601. var uvScaleMap;
  14602. if ( material.map ) {
  14603. uvScaleMap = material.map;
  14604. } else if ( material.specularMap ) {
  14605. uvScaleMap = material.specularMap;
  14606. } else if ( material.normalMap ) {
  14607. uvScaleMap = material.normalMap;
  14608. } else if ( material.bumpMap ) {
  14609. uvScaleMap = material.bumpMap;
  14610. }
  14611. if ( uvScaleMap !== undefined ) {
  14612. var offset = uvScaleMap.offset;
  14613. var repeat = uvScaleMap.repeat;
  14614. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  14615. }
  14616. uniforms.envMap.value = material.envMap;
  14617. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : - 1;
  14618. if ( _this.gammaInput ) {
  14619. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  14620. uniforms.reflectivity.value = material.reflectivity;
  14621. } else {
  14622. uniforms.reflectivity.value = material.reflectivity;
  14623. }
  14624. uniforms.refractionRatio.value = material.refractionRatio;
  14625. uniforms.combine.value = material.combine;
  14626. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  14627. };
  14628. function refreshUniformsLine ( uniforms, material ) {
  14629. uniforms.diffuse.value = material.color;
  14630. uniforms.opacity.value = material.opacity;
  14631. };
  14632. function refreshUniformsDash ( uniforms, material ) {
  14633. uniforms.dashSize.value = material.dashSize;
  14634. uniforms.totalSize.value = material.dashSize + material.gapSize;
  14635. uniforms.scale.value = material.scale;
  14636. };
  14637. function refreshUniformsParticle ( uniforms, material ) {
  14638. uniforms.psColor.value = material.color;
  14639. uniforms.opacity.value = material.opacity;
  14640. uniforms.size.value = material.size;
  14641. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  14642. uniforms.map.value = material.map;
  14643. };
  14644. function refreshUniformsFog ( uniforms, fog ) {
  14645. uniforms.fogColor.value = fog.color;
  14646. if ( fog instanceof THREE.Fog ) {
  14647. uniforms.fogNear.value = fog.near;
  14648. uniforms.fogFar.value = fog.far;
  14649. } else if ( fog instanceof THREE.FogExp2 ) {
  14650. uniforms.fogDensity.value = fog.density;
  14651. }
  14652. };
  14653. function refreshUniformsPhong ( uniforms, material ) {
  14654. uniforms.shininess.value = material.shininess;
  14655. if ( _this.gammaInput ) {
  14656. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14657. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14658. uniforms.specular.value.copyGammaToLinear( material.specular );
  14659. } else {
  14660. uniforms.ambient.value = material.ambient;
  14661. uniforms.emissive.value = material.emissive;
  14662. uniforms.specular.value = material.specular;
  14663. }
  14664. if ( material.wrapAround ) {
  14665. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14666. }
  14667. };
  14668. function refreshUniformsLambert ( uniforms, material ) {
  14669. if ( _this.gammaInput ) {
  14670. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14671. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14672. } else {
  14673. uniforms.ambient.value = material.ambient;
  14674. uniforms.emissive.value = material.emissive;
  14675. }
  14676. if ( material.wrapAround ) {
  14677. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14678. }
  14679. };
  14680. function refreshUniformsLights ( uniforms, lights ) {
  14681. uniforms.ambientLightColor.value = lights.ambient;
  14682. uniforms.directionalLightColor.value = lights.directional.colors;
  14683. uniforms.directionalLightDirection.value = lights.directional.positions;
  14684. uniforms.pointLightColor.value = lights.point.colors;
  14685. uniforms.pointLightPosition.value = lights.point.positions;
  14686. uniforms.pointLightDistance.value = lights.point.distances;
  14687. uniforms.spotLightColor.value = lights.spot.colors;
  14688. uniforms.spotLightPosition.value = lights.spot.positions;
  14689. uniforms.spotLightDistance.value = lights.spot.distances;
  14690. uniforms.spotLightDirection.value = lights.spot.directions;
  14691. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  14692. uniforms.spotLightExponent.value = lights.spot.exponents;
  14693. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  14694. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  14695. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  14696. };
  14697. function refreshUniformsShadow ( uniforms, lights ) {
  14698. if ( uniforms.shadowMatrix ) {
  14699. var j = 0;
  14700. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  14701. var light = lights[ i ];
  14702. if ( ! light.castShadow ) continue;
  14703. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  14704. uniforms.shadowMap.value[ j ] = light.shadowMap;
  14705. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  14706. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  14707. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  14708. uniforms.shadowBias.value[ j ] = light.shadowBias;
  14709. j ++;
  14710. }
  14711. }
  14712. }
  14713. };
  14714. // Uniforms (load to GPU)
  14715. function loadUniformsMatrices ( uniforms, object ) {
  14716. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  14717. if ( uniforms.normalMatrix ) {
  14718. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  14719. }
  14720. };
  14721. function getTextureUnit() {
  14722. var textureUnit = _usedTextureUnits;
  14723. if ( textureUnit >= _maxTextures ) {
  14724. console.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + _maxTextures );
  14725. }
  14726. _usedTextureUnits += 1;
  14727. return textureUnit;
  14728. };
  14729. function loadUniformsGeneric ( program, uniforms ) {
  14730. var texture, textureUnit, offset;
  14731. for ( var j = 0, jl = uniforms.length; j < jl; j ++ ) {
  14732. var location = program.uniforms[ uniforms[ j ][ 1 ] ];
  14733. if ( ! location ) continue;
  14734. var uniform = uniforms[ j ][ 0 ];
  14735. var type = uniform.type;
  14736. var value = uniform.value;
  14737. if ( type === 'i' ) { // single integer
  14738. _gl.uniform1i( location, value );
  14739. } else if ( type === 'f' ) { // single float
  14740. _gl.uniform1f( location, value );
  14741. } else if ( type === 'v2' ) { // single THREE.Vector2
  14742. _gl.uniform2f( location, value.x, value.y );
  14743. } else if ( type === 'v3' ) { // single THREE.Vector3
  14744. _gl.uniform3f( location, value.x, value.y, value.z );
  14745. } else if ( type === 'v4' ) { // single THREE.Vector4
  14746. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  14747. } else if ( type === 'c' ) { // single THREE.Color
  14748. _gl.uniform3f( location, value.r, value.g, value.b );
  14749. } else if ( type === 'iv1' ) { // flat array of integers (JS or typed array)
  14750. _gl.uniform1iv( location, value );
  14751. } else if ( type === 'iv' ) { // flat array of integers with 3 x N size (JS or typed array)
  14752. _gl.uniform3iv( location, value );
  14753. } else if ( type === 'fv1' ) { // flat array of floats (JS or typed array)
  14754. _gl.uniform1fv( location, value );
  14755. } else if ( type === 'fv' ) { // flat array of floats with 3 x N size (JS or typed array)
  14756. _gl.uniform3fv( location, value );
  14757. } else if ( type === 'v2v' ) { // array of THREE.Vector2
  14758. if ( uniform._array === undefined ) {
  14759. uniform._array = new Float32Array( 2 * value.length );
  14760. }
  14761. for ( var i = 0, il = value.length; i < il; i ++ ) {
  14762. offset = i * 2;
  14763. uniform._array[ offset ] = value[ i ].x;
  14764. uniform._array[ offset + 1 ] = value[ i ].y;
  14765. }
  14766. _gl.uniform2fv( location, uniform._array );
  14767. } else if ( type === 'v3v' ) { // array of THREE.Vector3
  14768. if ( uniform._array === undefined ) {
  14769. uniform._array = new Float32Array( 3 * value.length );
  14770. }
  14771. for ( var i = 0, il = value.length; i < il; i ++ ) {
  14772. offset = i * 3;
  14773. uniform._array[ offset ] = value[ i ].x;
  14774. uniform._array[ offset + 1 ] = value[ i ].y;
  14775. uniform._array[ offset + 2 ] = value[ i ].z;
  14776. }
  14777. _gl.uniform3fv( location, uniform._array );
  14778. } else if ( type === 'v4v' ) { // array of THREE.Vector4
  14779. if ( uniform._array === undefined ) {
  14780. uniform._array = new Float32Array( 4 * value.length );
  14781. }
  14782. for ( var i = 0, il = value.length; i < il; i ++ ) {
  14783. offset = i * 4;
  14784. uniform._array[ offset ] = value[ i ].x;
  14785. uniform._array[ offset + 1 ] = value[ i ].y;
  14786. uniform._array[ offset + 2 ] = value[ i ].z;
  14787. uniform._array[ offset + 3 ] = value[ i ].w;
  14788. }
  14789. _gl.uniform4fv( location, uniform._array );
  14790. } else if ( type === 'm3' ) { // single THREE.Matrix3
  14791. _gl.uniformMatrix3fv( location, false, value.elements );
  14792. } else if ( type === 'm3v' ) { // array of THREE.Matrix3
  14793. if ( uniform._array === undefined ) {
  14794. uniform._array = new Float32Array( 9 * value.length );
  14795. }
  14796. for ( var i = 0, il = value.length; i < il; i ++ ) {
  14797. value[ i ].flattenToArrayOffset( uniform._array, i * 9 );
  14798. }
  14799. _gl.uniformMatrix3fv( location, false, uniform._array );
  14800. } else if ( type === 'm4' ) { // single THREE.Matrix4
  14801. _gl.uniformMatrix4fv( location, false, value.elements );
  14802. } else if ( type === 'm4v' ) { // array of THREE.Matrix4
  14803. if ( uniform._array === undefined ) {
  14804. uniform._array = new Float32Array( 16 * value.length );
  14805. }
  14806. for ( var i = 0, il = value.length; i < il; i ++ ) {
  14807. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  14808. }
  14809. _gl.uniformMatrix4fv( location, false, uniform._array );
  14810. } else if ( type === 't' ) { // single THREE.Texture (2d or cube)
  14811. texture = value;
  14812. textureUnit = getTextureUnit();
  14813. _gl.uniform1i( location, textureUnit );
  14814. if ( ! texture ) continue;
  14815. if ( texture instanceof THREE.CubeTexture ||
  14816. ( texture.image instanceof Array && texture.image.length === 6 ) ) { // CompressedTexture can have Array in image :/
  14817. setCubeTexture( texture, textureUnit );
  14818. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  14819. setCubeTextureDynamic( texture, textureUnit );
  14820. } else {
  14821. _this.setTexture( texture, textureUnit );
  14822. }
  14823. } else if ( type === 'tv' ) { // array of THREE.Texture (2d)
  14824. if ( uniform._array === undefined ) {
  14825. uniform._array = [];
  14826. }
  14827. for ( var i = 0, il = uniform.value.length; i < il; i ++ ) {
  14828. uniform._array[ i ] = getTextureUnit();
  14829. }
  14830. _gl.uniform1iv( location, uniform._array );
  14831. for ( var i = 0, il = uniform.value.length; i < il; i ++ ) {
  14832. texture = uniform.value[ i ];
  14833. textureUnit = uniform._array[ i ];
  14834. if ( ! texture ) continue;
  14835. _this.setTexture( texture, textureUnit );
  14836. }
  14837. } else {
  14838. console.warn( 'THREE.WebGLRenderer: Unknown uniform type: ' + type );
  14839. }
  14840. }
  14841. };
  14842. function setupMatrices ( object, camera ) {
  14843. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  14844. object._normalMatrix.getNormalMatrix( object._modelViewMatrix );
  14845. };
  14846. //
  14847. function setColorGamma( array, offset, color, intensitySq ) {
  14848. array[ offset ] = color.r * color.r * intensitySq;
  14849. array[ offset + 1 ] = color.g * color.g * intensitySq;
  14850. array[ offset + 2 ] = color.b * color.b * intensitySq;
  14851. };
  14852. function setColorLinear( array, offset, color, intensity ) {
  14853. array[ offset ] = color.r * intensity;
  14854. array[ offset + 1 ] = color.g * intensity;
  14855. array[ offset + 2 ] = color.b * intensity;
  14856. };
  14857. function setupLights ( program, lights ) {
  14858. var l, ll, light, n,
  14859. r = 0, g = 0, b = 0,
  14860. color, skyColor, groundColor,
  14861. intensity, intensitySq,
  14862. position,
  14863. distance,
  14864. zlights = _lights,
  14865. dirColors = zlights.directional.colors,
  14866. dirPositions = zlights.directional.positions,
  14867. pointColors = zlights.point.colors,
  14868. pointPositions = zlights.point.positions,
  14869. pointDistances = zlights.point.distances,
  14870. spotColors = zlights.spot.colors,
  14871. spotPositions = zlights.spot.positions,
  14872. spotDistances = zlights.spot.distances,
  14873. spotDirections = zlights.spot.directions,
  14874. spotAnglesCos = zlights.spot.anglesCos,
  14875. spotExponents = zlights.spot.exponents,
  14876. hemiSkyColors = zlights.hemi.skyColors,
  14877. hemiGroundColors = zlights.hemi.groundColors,
  14878. hemiPositions = zlights.hemi.positions,
  14879. dirLength = 0,
  14880. pointLength = 0,
  14881. spotLength = 0,
  14882. hemiLength = 0,
  14883. dirCount = 0,
  14884. pointCount = 0,
  14885. spotCount = 0,
  14886. hemiCount = 0,
  14887. dirOffset = 0,
  14888. pointOffset = 0,
  14889. spotOffset = 0,
  14890. hemiOffset = 0;
  14891. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  14892. light = lights[ l ];
  14893. if ( light.onlyShadow ) continue;
  14894. color = light.color;
  14895. intensity = light.intensity;
  14896. distance = light.distance;
  14897. if ( light instanceof THREE.AmbientLight ) {
  14898. if ( ! light.visible ) continue;
  14899. if ( _this.gammaInput ) {
  14900. r += color.r * color.r;
  14901. g += color.g * color.g;
  14902. b += color.b * color.b;
  14903. } else {
  14904. r += color.r;
  14905. g += color.g;
  14906. b += color.b;
  14907. }
  14908. } else if ( light instanceof THREE.DirectionalLight ) {
  14909. dirCount += 1;
  14910. if ( ! light.visible ) continue;
  14911. _direction.setFromMatrixPosition( light.matrixWorld );
  14912. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  14913. _direction.sub( _vector3 );
  14914. _direction.normalize();
  14915. // skip lights with undefined direction
  14916. // these create troubles in OpenGL (making pixel black)
  14917. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14918. dirOffset = dirLength * 3;
  14919. dirPositions[ dirOffset ] = _direction.x;
  14920. dirPositions[ dirOffset + 1 ] = _direction.y;
  14921. dirPositions[ dirOffset + 2 ] = _direction.z;
  14922. if ( _this.gammaInput ) {
  14923. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  14924. } else {
  14925. setColorLinear( dirColors, dirOffset, color, intensity );
  14926. }
  14927. dirLength += 1;
  14928. } else if ( light instanceof THREE.PointLight ) {
  14929. pointCount += 1;
  14930. if ( ! light.visible ) continue;
  14931. pointOffset = pointLength * 3;
  14932. if ( _this.gammaInput ) {
  14933. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  14934. } else {
  14935. setColorLinear( pointColors, pointOffset, color, intensity );
  14936. }
  14937. _vector3.setFromMatrixPosition( light.matrixWorld );
  14938. pointPositions[ pointOffset ] = _vector3.x;
  14939. pointPositions[ pointOffset + 1 ] = _vector3.y;
  14940. pointPositions[ pointOffset + 2 ] = _vector3.z;
  14941. pointDistances[ pointLength ] = distance;
  14942. pointLength += 1;
  14943. } else if ( light instanceof THREE.SpotLight ) {
  14944. spotCount += 1;
  14945. if ( ! light.visible ) continue;
  14946. spotOffset = spotLength * 3;
  14947. if ( _this.gammaInput ) {
  14948. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  14949. } else {
  14950. setColorLinear( spotColors, spotOffset, color, intensity );
  14951. }
  14952. _vector3.setFromMatrixPosition( light.matrixWorld );
  14953. spotPositions[ spotOffset ] = _vector3.x;
  14954. spotPositions[ spotOffset + 1 ] = _vector3.y;
  14955. spotPositions[ spotOffset + 2 ] = _vector3.z;
  14956. spotDistances[ spotLength ] = distance;
  14957. _direction.copy( _vector3 );
  14958. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  14959. _direction.sub( _vector3 );
  14960. _direction.normalize();
  14961. spotDirections[ spotOffset ] = _direction.x;
  14962. spotDirections[ spotOffset + 1 ] = _direction.y;
  14963. spotDirections[ spotOffset + 2 ] = _direction.z;
  14964. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  14965. spotExponents[ spotLength ] = light.exponent;
  14966. spotLength += 1;
  14967. } else if ( light instanceof THREE.HemisphereLight ) {
  14968. hemiCount += 1;
  14969. if ( ! light.visible ) continue;
  14970. _direction.setFromMatrixPosition( light.matrixWorld );
  14971. _direction.normalize();
  14972. // skip lights with undefined direction
  14973. // these create troubles in OpenGL (making pixel black)
  14974. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14975. hemiOffset = hemiLength * 3;
  14976. hemiPositions[ hemiOffset ] = _direction.x;
  14977. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  14978. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  14979. skyColor = light.color;
  14980. groundColor = light.groundColor;
  14981. if ( _this.gammaInput ) {
  14982. intensitySq = intensity * intensity;
  14983. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  14984. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  14985. } else {
  14986. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  14987. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  14988. }
  14989. hemiLength += 1;
  14990. }
  14991. }
  14992. // null eventual remains from removed lights
  14993. // (this is to avoid if in shader)
  14994. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  14995. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  14996. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  14997. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  14998. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  14999. zlights.directional.length = dirLength;
  15000. zlights.point.length = pointLength;
  15001. zlights.spot.length = spotLength;
  15002. zlights.hemi.length = hemiLength;
  15003. zlights.ambient[ 0 ] = r;
  15004. zlights.ambient[ 1 ] = g;
  15005. zlights.ambient[ 2 ] = b;
  15006. };
  15007. // GL state setting
  15008. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  15009. if ( cullFace === THREE.CullFaceNone ) {
  15010. _gl.disable( _gl.CULL_FACE );
  15011. } else {
  15012. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  15013. _gl.frontFace( _gl.CW );
  15014. } else {
  15015. _gl.frontFace( _gl.CCW );
  15016. }
  15017. if ( cullFace === THREE.CullFaceBack ) {
  15018. _gl.cullFace( _gl.BACK );
  15019. } else if ( cullFace === THREE.CullFaceFront ) {
  15020. _gl.cullFace( _gl.FRONT );
  15021. } else {
  15022. _gl.cullFace( _gl.FRONT_AND_BACK );
  15023. }
  15024. _gl.enable( _gl.CULL_FACE );
  15025. }
  15026. };
  15027. this.setMaterialFaces = function ( material ) {
  15028. var doubleSided = material.side === THREE.DoubleSide;
  15029. var flipSided = material.side === THREE.BackSide;
  15030. if ( _oldDoubleSided !== doubleSided ) {
  15031. if ( doubleSided ) {
  15032. _gl.disable( _gl.CULL_FACE );
  15033. } else {
  15034. _gl.enable( _gl.CULL_FACE );
  15035. }
  15036. _oldDoubleSided = doubleSided;
  15037. }
  15038. if ( _oldFlipSided !== flipSided ) {
  15039. if ( flipSided ) {
  15040. _gl.frontFace( _gl.CW );
  15041. } else {
  15042. _gl.frontFace( _gl.CCW );
  15043. }
  15044. _oldFlipSided = flipSided;
  15045. }
  15046. };
  15047. this.setDepthTest = function ( depthTest ) {
  15048. if ( _oldDepthTest !== depthTest ) {
  15049. if ( depthTest ) {
  15050. _gl.enable( _gl.DEPTH_TEST );
  15051. } else {
  15052. _gl.disable( _gl.DEPTH_TEST );
  15053. }
  15054. _oldDepthTest = depthTest;
  15055. }
  15056. };
  15057. this.setDepthWrite = function ( depthWrite ) {
  15058. if ( _oldDepthWrite !== depthWrite ) {
  15059. _gl.depthMask( depthWrite );
  15060. _oldDepthWrite = depthWrite;
  15061. }
  15062. };
  15063. function setLineWidth ( width ) {
  15064. if ( width !== _oldLineWidth ) {
  15065. _gl.lineWidth( width );
  15066. _oldLineWidth = width;
  15067. }
  15068. };
  15069. function setPolygonOffset ( polygonoffset, factor, units ) {
  15070. if ( _oldPolygonOffset !== polygonoffset ) {
  15071. if ( polygonoffset ) {
  15072. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  15073. } else {
  15074. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  15075. }
  15076. _oldPolygonOffset = polygonoffset;
  15077. }
  15078. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  15079. _gl.polygonOffset( factor, units );
  15080. _oldPolygonOffsetFactor = factor;
  15081. _oldPolygonOffsetUnits = units;
  15082. }
  15083. };
  15084. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  15085. if ( blending !== _oldBlending ) {
  15086. if ( blending === THREE.NoBlending ) {
  15087. _gl.disable( _gl.BLEND );
  15088. } else if ( blending === THREE.AdditiveBlending ) {
  15089. _gl.enable( _gl.BLEND );
  15090. _gl.blendEquation( _gl.FUNC_ADD );
  15091. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  15092. } else if ( blending === THREE.SubtractiveBlending ) {
  15093. // TODO: Find blendFuncSeparate() combination
  15094. _gl.enable( _gl.BLEND );
  15095. _gl.blendEquation( _gl.FUNC_ADD );
  15096. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  15097. } else if ( blending === THREE.MultiplyBlending ) {
  15098. // TODO: Find blendFuncSeparate() combination
  15099. _gl.enable( _gl.BLEND );
  15100. _gl.blendEquation( _gl.FUNC_ADD );
  15101. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  15102. } else if ( blending === THREE.CustomBlending ) {
  15103. _gl.enable( _gl.BLEND );
  15104. } else {
  15105. _gl.enable( _gl.BLEND );
  15106. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  15107. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  15108. }
  15109. _oldBlending = blending;
  15110. }
  15111. if ( blending === THREE.CustomBlending ) {
  15112. if ( blendEquation !== _oldBlendEquation ) {
  15113. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  15114. _oldBlendEquation = blendEquation;
  15115. }
  15116. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  15117. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  15118. _oldBlendSrc = blendSrc;
  15119. _oldBlendDst = blendDst;
  15120. }
  15121. } else {
  15122. _oldBlendEquation = null;
  15123. _oldBlendSrc = null;
  15124. _oldBlendDst = null;
  15125. }
  15126. };
  15127. // Textures
  15128. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  15129. if ( isImagePowerOfTwo ) {
  15130. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  15131. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  15132. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  15133. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  15134. } else {
  15135. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  15136. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  15137. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  15138. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  15139. }
  15140. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  15141. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  15142. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  15143. texture.__oldAnisotropy = texture.anisotropy;
  15144. }
  15145. }
  15146. };
  15147. this.setTexture = function ( texture, slot ) {
  15148. if ( texture.needsUpdate ) {
  15149. if ( ! texture.__webglInit ) {
  15150. texture.__webglInit = true;
  15151. texture.addEventListener( 'dispose', onTextureDispose );
  15152. texture.__webglTexture = _gl.createTexture();
  15153. _this.info.memory.textures ++;
  15154. }
  15155. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15156. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  15157. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15158. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  15159. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  15160. var image = texture.image,
  15161. isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ),
  15162. glFormat = paramThreeToGL( texture.format ),
  15163. glType = paramThreeToGL( texture.type );
  15164. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  15165. var mipmap, mipmaps = texture.mipmaps;
  15166. if ( texture instanceof THREE.DataTexture ) {
  15167. // use manually created mipmaps if available
  15168. // if there are no manual mipmaps
  15169. // set 0 level mipmap and then use GL to generate other mipmap levels
  15170. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  15171. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15172. mipmap = mipmaps[ i ];
  15173. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15174. }
  15175. texture.generateMipmaps = false;
  15176. } else {
  15177. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  15178. }
  15179. } else if ( texture instanceof THREE.CompressedTexture ) {
  15180. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15181. mipmap = mipmaps[ i ];
  15182. if ( texture.format !== THREE.RGBAFormat ) {
  15183. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15184. } else {
  15185. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15186. }
  15187. }
  15188. } else { // regular Texture (image, video, canvas)
  15189. // use manually created mipmaps if available
  15190. // if there are no manual mipmaps
  15191. // set 0 level mipmap and then use GL to generate other mipmap levels
  15192. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  15193. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15194. mipmap = mipmaps[ i ];
  15195. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  15196. }
  15197. texture.generateMipmaps = false;
  15198. } else {
  15199. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  15200. }
  15201. }
  15202. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15203. texture.needsUpdate = false;
  15204. if ( texture.onUpdate ) texture.onUpdate();
  15205. } else {
  15206. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15207. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  15208. }
  15209. };
  15210. function clampToMaxSize ( image, maxSize ) {
  15211. if ( image.width <= maxSize && image.height <= maxSize ) {
  15212. return image;
  15213. }
  15214. // Warning: Scaling through the canvas will only work with images that use
  15215. // premultiplied alpha.
  15216. var maxDimension = Math.max( image.width, image.height );
  15217. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  15218. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  15219. var canvas = document.createElement( 'canvas' );
  15220. canvas.width = newWidth;
  15221. canvas.height = newHeight;
  15222. var ctx = canvas.getContext( '2d' );
  15223. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  15224. return canvas;
  15225. }
  15226. function setCubeTexture ( texture, slot ) {
  15227. if ( texture.image.length === 6 ) {
  15228. if ( texture.needsUpdate ) {
  15229. if ( ! texture.image.__webglTextureCube ) {
  15230. texture.addEventListener( 'dispose', onTextureDispose );
  15231. texture.image.__webglTextureCube = _gl.createTexture();
  15232. _this.info.memory.textures ++;
  15233. }
  15234. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15235. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15236. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15237. var isCompressed = texture instanceof THREE.CompressedTexture;
  15238. var cubeImage = [];
  15239. for ( var i = 0; i < 6; i ++ ) {
  15240. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  15241. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  15242. } else {
  15243. cubeImage[ i ] = texture.image[ i ];
  15244. }
  15245. }
  15246. var image = cubeImage[ 0 ],
  15247. isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ),
  15248. glFormat = paramThreeToGL( texture.format ),
  15249. glType = paramThreeToGL( texture.type );
  15250. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  15251. for ( var i = 0; i < 6; i ++ ) {
  15252. if ( ! isCompressed ) {
  15253. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  15254. } else {
  15255. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  15256. for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  15257. mipmap = mipmaps[ j ];
  15258. if ( texture.format !== THREE.RGBAFormat ) {
  15259. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15260. } else {
  15261. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15262. }
  15263. }
  15264. }
  15265. }
  15266. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  15267. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15268. }
  15269. texture.needsUpdate = false;
  15270. if ( texture.onUpdate ) texture.onUpdate();
  15271. } else {
  15272. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15273. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15274. }
  15275. }
  15276. };
  15277. function setCubeTextureDynamic ( texture, slot ) {
  15278. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15279. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  15280. };
  15281. // Render targets
  15282. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  15283. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15284. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  15285. };
  15286. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  15287. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  15288. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15289. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  15290. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15291. /* For some reason this is not working. Defaulting to RGBA4.
  15292. } else if ( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15293. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  15294. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15295. */
  15296. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15297. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  15298. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15299. } else {
  15300. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  15301. }
  15302. };
  15303. this.setRenderTarget = function ( renderTarget ) {
  15304. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  15305. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  15306. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  15307. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  15308. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  15309. renderTarget.__webglTexture = _gl.createTexture();
  15310. _this.info.memory.textures ++;
  15311. // Setup texture, create render and frame buffers
  15312. var isTargetPowerOfTwo = THREE.Math.isPowerOfTwo( renderTarget.width ) && THREE.Math.isPowerOfTwo( renderTarget.height ),
  15313. glFormat = paramThreeToGL( renderTarget.format ),
  15314. glType = paramThreeToGL( renderTarget.type );
  15315. if ( isCube ) {
  15316. renderTarget.__webglFramebuffer = [];
  15317. renderTarget.__webglRenderbuffer = [];
  15318. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15319. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  15320. for ( var i = 0; i < 6; i ++ ) {
  15321. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  15322. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  15323. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15324. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  15325. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  15326. }
  15327. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15328. } else {
  15329. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  15330. if ( renderTarget.shareDepthFrom ) {
  15331. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  15332. } else {
  15333. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  15334. }
  15335. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15336. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  15337. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15338. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  15339. if ( renderTarget.shareDepthFrom ) {
  15340. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15341. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15342. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15343. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15344. }
  15345. } else {
  15346. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  15347. }
  15348. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15349. }
  15350. // Release everything
  15351. if ( isCube ) {
  15352. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15353. } else {
  15354. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15355. }
  15356. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  15357. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15358. }
  15359. var framebuffer, width, height, vx, vy;
  15360. if ( renderTarget ) {
  15361. if ( isCube ) {
  15362. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  15363. } else {
  15364. framebuffer = renderTarget.__webglFramebuffer;
  15365. }
  15366. width = renderTarget.width;
  15367. height = renderTarget.height;
  15368. vx = 0;
  15369. vy = 0;
  15370. } else {
  15371. framebuffer = null;
  15372. width = _viewportWidth;
  15373. height = _viewportHeight;
  15374. vx = _viewportX;
  15375. vy = _viewportY;
  15376. }
  15377. if ( framebuffer !== _currentFramebuffer ) {
  15378. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15379. _gl.viewport( vx, vy, width, height );
  15380. _currentFramebuffer = framebuffer;
  15381. }
  15382. _currentWidth = width;
  15383. _currentHeight = height;
  15384. };
  15385. function updateRenderTargetMipmap ( renderTarget ) {
  15386. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  15387. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15388. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15389. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15390. } else {
  15391. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15392. _gl.generateMipmap( _gl.TEXTURE_2D );
  15393. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15394. }
  15395. };
  15396. // Fallback filters for non-power-of-2 textures
  15397. function filterFallback ( f ) {
  15398. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  15399. return _gl.NEAREST;
  15400. }
  15401. return _gl.LINEAR;
  15402. };
  15403. // Map three.js constants to WebGL constants
  15404. function paramThreeToGL ( p ) {
  15405. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  15406. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  15407. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  15408. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  15409. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  15410. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  15411. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  15412. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  15413. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  15414. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  15415. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  15416. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  15417. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  15418. if ( p === THREE.ByteType ) return _gl.BYTE;
  15419. if ( p === THREE.ShortType ) return _gl.SHORT;
  15420. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  15421. if ( p === THREE.IntType ) return _gl.INT;
  15422. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  15423. if ( p === THREE.FloatType ) return _gl.FLOAT;
  15424. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  15425. if ( p === THREE.RGBFormat ) return _gl.RGB;
  15426. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  15427. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  15428. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  15429. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  15430. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  15431. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  15432. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  15433. if ( p === THREE.OneFactor ) return _gl.ONE;
  15434. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  15435. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  15436. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  15437. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  15438. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  15439. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  15440. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  15441. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  15442. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  15443. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  15444. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  15445. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  15446. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  15447. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  15448. }
  15449. return 0;
  15450. };
  15451. // Allocations
  15452. function allocateBones ( object ) {
  15453. if ( _supportsBoneTextures && object && object.skeleton && object.skeleton.useVertexTexture ) {
  15454. return 1024;
  15455. } else {
  15456. // default for when object is not specified
  15457. // ( for example when prebuilding shader
  15458. // to be used with multiple objects )
  15459. //
  15460. // - leave some extra space for other uniforms
  15461. // - limit here is ANGLE's 254 max uniform vectors
  15462. // (up to 54 should be safe)
  15463. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  15464. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  15465. var maxBones = nVertexMatrices;
  15466. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  15467. maxBones = Math.min( object.skeleton.bones.length, maxBones );
  15468. if ( maxBones < object.skeleton.bones.length ) {
  15469. console.warn( 'WebGLRenderer: too many bones - ' + object.skeleton.bones.length + ', this GPU supports just ' + maxBones + ' (try OpenGL instead of ANGLE)' );
  15470. }
  15471. }
  15472. return maxBones;
  15473. }
  15474. };
  15475. function allocateLights( lights ) {
  15476. var dirLights = 0;
  15477. var pointLights = 0;
  15478. var spotLights = 0;
  15479. var hemiLights = 0;
  15480. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  15481. var light = lights[ l ];
  15482. if ( light.onlyShadow || light.visible === false ) continue;
  15483. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  15484. if ( light instanceof THREE.PointLight ) pointLights ++;
  15485. if ( light instanceof THREE.SpotLight ) spotLights ++;
  15486. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  15487. }
  15488. return { 'directional': dirLights, 'point': pointLights, 'spot': spotLights, 'hemi': hemiLights };
  15489. };
  15490. function allocateShadows( lights ) {
  15491. var maxShadows = 0;
  15492. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  15493. var light = lights[ l ];
  15494. if ( ! light.castShadow ) continue;
  15495. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  15496. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  15497. }
  15498. return maxShadows;
  15499. };
  15500. // Initialization
  15501. function initGL() {
  15502. try {
  15503. var attributes = {
  15504. alpha: _alpha,
  15505. depth: _depth,
  15506. stencil: _stencil,
  15507. antialias: _antialias,
  15508. premultipliedAlpha: _premultipliedAlpha,
  15509. preserveDrawingBuffer: _preserveDrawingBuffer
  15510. };
  15511. _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  15512. if ( _gl === null ) {
  15513. throw 'Error creating WebGL context.';
  15514. }
  15515. } catch ( error ) {
  15516. console.error( error );
  15517. }
  15518. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  15519. _glExtensionTextureFloatLinear = _gl.getExtension( 'OES_texture_float_linear' );
  15520. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  15521. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  15522. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  15523. _glExtensionElementIndexUint = _gl.getExtension( 'OES_element_index_uint' );
  15524. if ( _glExtensionTextureFloat === null ) {
  15525. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  15526. }
  15527. if ( _glExtensionStandardDerivatives === null ) {
  15528. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  15529. }
  15530. if ( _glExtensionTextureFilterAnisotropic === null ) {
  15531. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  15532. }
  15533. if ( _glExtensionCompressedTextureS3TC === null ) {
  15534. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  15535. }
  15536. if ( _glExtensionElementIndexUint === null ) {
  15537. console.log( 'THREE.WebGLRenderer: elementindex as unsigned integer not supported.' );
  15538. }
  15539. if ( _gl.getShaderPrecisionFormat === undefined ) {
  15540. _gl.getShaderPrecisionFormat = function () {
  15541. return {
  15542. 'rangeMin': 1,
  15543. 'rangeMax': 1,
  15544. 'precision': 1
  15545. };
  15546. }
  15547. }
  15548. if ( _logarithmicDepthBuffer ) {
  15549. _glExtensionFragDepth = _gl.getExtension( 'EXT_frag_depth' );
  15550. }
  15551. };
  15552. function setDefaultGLState () {
  15553. _gl.clearColor( 0, 0, 0, 1 );
  15554. _gl.clearDepth( 1 );
  15555. _gl.clearStencil( 0 );
  15556. _gl.enable( _gl.DEPTH_TEST );
  15557. _gl.depthFunc( _gl.LEQUAL );
  15558. _gl.frontFace( _gl.CCW );
  15559. _gl.cullFace( _gl.BACK );
  15560. _gl.enable( _gl.CULL_FACE );
  15561. _gl.enable( _gl.BLEND );
  15562. _gl.blendEquation( _gl.FUNC_ADD );
  15563. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  15564. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  15565. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  15566. };
  15567. // default plugins (order is important)
  15568. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  15569. this.addPrePlugin( this.shadowMapPlugin );
  15570. this.addPostPlugin( new THREE.SpritePlugin() );
  15571. this.addPostPlugin( new THREE.LensFlarePlugin() );
  15572. };
  15573. // File:src/renderers/WebGLRenderTarget.js
  15574. /**
  15575. * @author szimek / https://github.com/szimek/
  15576. * @author alteredq / http://alteredqualia.com/
  15577. */
  15578. THREE.WebGLRenderTarget = function ( width, height, options ) {
  15579. this.width = width;
  15580. this.height = height;
  15581. options = options || {};
  15582. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  15583. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  15584. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  15585. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  15586. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  15587. this.offset = new THREE.Vector2( 0, 0 );
  15588. this.repeat = new THREE.Vector2( 1, 1 );
  15589. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  15590. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  15591. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  15592. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  15593. this.generateMipmaps = true;
  15594. this.shareDepthFrom = null;
  15595. };
  15596. THREE.WebGLRenderTarget.prototype = {
  15597. constructor: THREE.WebGLRenderTarget,
  15598. setSize: function ( width, height ) {
  15599. this.width = width;
  15600. this.height = height;
  15601. },
  15602. clone: function () {
  15603. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  15604. tmp.wrapS = this.wrapS;
  15605. tmp.wrapT = this.wrapT;
  15606. tmp.magFilter = this.magFilter;
  15607. tmp.minFilter = this.minFilter;
  15608. tmp.anisotropy = this.anisotropy;
  15609. tmp.offset.copy( this.offset );
  15610. tmp.repeat.copy( this.repeat );
  15611. tmp.format = this.format;
  15612. tmp.type = this.type;
  15613. tmp.depthBuffer = this.depthBuffer;
  15614. tmp.stencilBuffer = this.stencilBuffer;
  15615. tmp.generateMipmaps = this.generateMipmaps;
  15616. tmp.shareDepthFrom = this.shareDepthFrom;
  15617. return tmp;
  15618. },
  15619. dispose: function () {
  15620. this.dispatchEvent( { type: 'dispose' } );
  15621. }
  15622. };
  15623. THREE.EventDispatcher.prototype.apply( THREE.WebGLRenderTarget.prototype );
  15624. // File:src/renderers/WebGLRenderTargetCube.js
  15625. /**
  15626. * @author alteredq / http://alteredqualia.com
  15627. */
  15628. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  15629. THREE.WebGLRenderTarget.call( this, width, height, options );
  15630. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  15631. };
  15632. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  15633. // File:src/renderers/webgl/WebGLProgram.js
  15634. THREE.WebGLProgram = ( function () {
  15635. var programIdCount = 0;
  15636. var generateDefines = function ( defines ) {
  15637. var value, chunk, chunks = [];
  15638. for ( var d in defines ) {
  15639. value = defines[ d ];
  15640. if ( value === false ) continue;
  15641. chunk = "#define " + d + " " + value;
  15642. chunks.push( chunk );
  15643. }
  15644. return chunks.join( "\n" );
  15645. };
  15646. var cacheUniformLocations = function ( gl, program, identifiers ) {
  15647. var uniforms = {};
  15648. for ( var i = 0, l = identifiers.length; i < l; i ++ ) {
  15649. var id = identifiers[ i ];
  15650. uniforms[ id ] = gl.getUniformLocation( program, id );
  15651. }
  15652. return uniforms;
  15653. };
  15654. var cacheAttributeLocations = function ( gl, program, identifiers ) {
  15655. var attributes = {};
  15656. for ( var i = 0, l = identifiers.length; i < l; i ++ ) {
  15657. var id = identifiers[ i ];
  15658. attributes[ id ] = gl.getAttribLocation( program, id );
  15659. }
  15660. return attributes;
  15661. };
  15662. return function ( renderer, code, material, parameters ) {
  15663. var _this = renderer;
  15664. var _gl = _this.context;
  15665. var fragmentShader = material.fragmentShader;
  15666. var vertexShader = material.vertexShader;
  15667. var uniforms = material.uniforms;
  15668. var attributes = material.attributes;
  15669. var defines = material.defines;
  15670. var index0AttributeName = material.index0AttributeName;
  15671. if ( index0AttributeName === undefined && parameters.morphTargets === true ) {
  15672. // programs with morphTargets displace position out of attribute 0
  15673. index0AttributeName = 'position';
  15674. }
  15675. var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC";
  15676. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  15677. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF";
  15678. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  15679. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT";
  15680. }
  15681. // console.log( "building new program " );
  15682. //
  15683. var customDefines = generateDefines( defines );
  15684. //
  15685. var program = _gl.createProgram();
  15686. var prefix_vertex, prefix_fragment;
  15687. if ( material instanceof THREE.RawShaderMaterial ) {
  15688. prefix_vertex = '';
  15689. prefix_fragment = '';
  15690. } else {
  15691. prefix_vertex = [
  15692. "precision " + parameters.precision + " float;",
  15693. "precision " + parameters.precision + " int;",
  15694. customDefines,
  15695. parameters.supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  15696. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  15697. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  15698. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  15699. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  15700. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  15701. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  15702. "#define MAX_SHADOWS " + parameters.maxShadows,
  15703. "#define MAX_BONES " + parameters.maxBones,
  15704. parameters.map ? "#define USE_MAP" : "",
  15705. parameters.envMap ? "#define USE_ENVMAP" : "",
  15706. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  15707. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  15708. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  15709. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  15710. parameters.vertexColors ? "#define USE_COLOR" : "",
  15711. parameters.skinning ? "#define USE_SKINNING" : "",
  15712. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  15713. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  15714. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  15715. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  15716. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  15717. parameters.flipSided ? "#define FLIP_SIDED" : "",
  15718. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  15719. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  15720. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  15721. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  15722. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  15723. parameters.logarithmicDepthBuffer ? "#define USE_LOGDEPTHBUF" : "",
  15724. //_this._glExtensionFragDepth ? "#define USE_LOGDEPTHBUF_EXT" : "",
  15725. "uniform mat4 modelMatrix;",
  15726. "uniform mat4 modelViewMatrix;",
  15727. "uniform mat4 projectionMatrix;",
  15728. "uniform mat4 viewMatrix;",
  15729. "uniform mat3 normalMatrix;",
  15730. "uniform vec3 cameraPosition;",
  15731. "attribute vec3 position;",
  15732. "attribute vec3 normal;",
  15733. "attribute vec2 uv;",
  15734. "attribute vec2 uv2;",
  15735. "#ifdef USE_COLOR",
  15736. " attribute vec3 color;",
  15737. "#endif",
  15738. "#ifdef USE_MORPHTARGETS",
  15739. " attribute vec3 morphTarget0;",
  15740. " attribute vec3 morphTarget1;",
  15741. " attribute vec3 morphTarget2;",
  15742. " attribute vec3 morphTarget3;",
  15743. " #ifdef USE_MORPHNORMALS",
  15744. " attribute vec3 morphNormal0;",
  15745. " attribute vec3 morphNormal1;",
  15746. " attribute vec3 morphNormal2;",
  15747. " attribute vec3 morphNormal3;",
  15748. " #else",
  15749. " attribute vec3 morphTarget4;",
  15750. " attribute vec3 morphTarget5;",
  15751. " attribute vec3 morphTarget6;",
  15752. " attribute vec3 morphTarget7;",
  15753. " #endif",
  15754. "#endif",
  15755. "#ifdef USE_SKINNING",
  15756. " attribute vec4 skinIndex;",
  15757. " attribute vec4 skinWeight;",
  15758. "#endif",
  15759. ""
  15760. ].join( '\n' );
  15761. prefix_fragment = [
  15762. "precision " + parameters.precision + " float;",
  15763. "precision " + parameters.precision + " int;",
  15764. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  15765. customDefines,
  15766. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  15767. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  15768. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  15769. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  15770. "#define MAX_SHADOWS " + parameters.maxShadows,
  15771. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  15772. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  15773. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  15774. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  15775. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  15776. parameters.map ? "#define USE_MAP" : "",
  15777. parameters.envMap ? "#define USE_ENVMAP" : "",
  15778. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  15779. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  15780. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  15781. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  15782. parameters.vertexColors ? "#define USE_COLOR" : "",
  15783. parameters.metal ? "#define METAL" : "",
  15784. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  15785. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  15786. parameters.flipSided ? "#define FLIP_SIDED" : "",
  15787. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  15788. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  15789. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  15790. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  15791. parameters.logarithmicDepthBuffer ? "#define USE_LOGDEPTHBUF" : "",
  15792. //_this._glExtensionFragDepth ? "#define USE_LOGDEPTHBUF_EXT" : "",
  15793. "uniform mat4 viewMatrix;",
  15794. "uniform vec3 cameraPosition;",
  15795. ""
  15796. ].join( '\n' );
  15797. }
  15798. var glVertexShader = new THREE.WebGLShader( _gl, _gl.VERTEX_SHADER, prefix_vertex + vertexShader );
  15799. var glFragmentShader = new THREE.WebGLShader( _gl, _gl.FRAGMENT_SHADER, prefix_fragment + fragmentShader );
  15800. _gl.attachShader( program, glVertexShader );
  15801. _gl.attachShader( program, glFragmentShader );
  15802. if ( index0AttributeName !== undefined ) {
  15803. // Force a particular attribute to index 0.
  15804. // because potentially expensive emulation is done by browser if attribute 0 is disabled.
  15805. // And, color, for example is often automatically bound to index 0 so disabling it
  15806. _gl.bindAttribLocation( program, 0, index0AttributeName );
  15807. }
  15808. _gl.linkProgram( program );
  15809. if ( _gl.getProgramParameter( program, _gl.LINK_STATUS ) === false ) {
  15810. console.error( 'THREE.WebGLProgram: Could not initialise shader.' );
  15811. console.error( 'gl.VALIDATE_STATUS', _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) );
  15812. console.error( 'gl.getError()', _gl.getError() );
  15813. }
  15814. if ( _gl.getProgramInfoLog( program ) !== '' ) {
  15815. console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', _gl.getProgramInfoLog( program ) );
  15816. }
  15817. // clean up
  15818. _gl.deleteShader( glVertexShader );
  15819. _gl.deleteShader( glFragmentShader );
  15820. // cache uniform locations
  15821. var identifiers = [
  15822. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  15823. 'morphTargetInfluences'
  15824. ];
  15825. if ( parameters.useVertexTexture ) {
  15826. identifiers.push( 'boneTexture' );
  15827. identifiers.push( 'boneTextureWidth' );
  15828. identifiers.push( 'boneTextureHeight' );
  15829. } else {
  15830. identifiers.push( 'boneGlobalMatrices' );
  15831. }
  15832. if ( parameters.logarithmicDepthBuffer ) {
  15833. identifiers.push('logDepthBufFC');
  15834. }
  15835. for ( var u in uniforms ) {
  15836. identifiers.push( u );
  15837. }
  15838. this.uniforms = cacheUniformLocations( _gl, program, identifiers );
  15839. // cache attributes locations
  15840. identifiers = [
  15841. "position", "normal", "uv", "uv2", "tangent", "color",
  15842. "skinIndex", "skinWeight", "lineDistance"
  15843. ];
  15844. for ( var i = 0; i < parameters.maxMorphTargets; i ++ ) {
  15845. identifiers.push( "morphTarget" + i );
  15846. }
  15847. for ( var i = 0; i < parameters.maxMorphNormals; i ++ ) {
  15848. identifiers.push( "morphNormal" + i );
  15849. }
  15850. for ( var a in attributes ) {
  15851. identifiers.push( a );
  15852. }
  15853. this.attributes = cacheAttributeLocations( _gl, program, identifiers );
  15854. //
  15855. this.id = programIdCount ++;
  15856. this.code = code;
  15857. this.usedTimes = 1;
  15858. this.program = program;
  15859. this.vertexShader = glVertexShader;
  15860. this.fragmentShader = glFragmentShader;
  15861. return this;
  15862. };
  15863. } )();
  15864. // File:src/renderers/webgl/WebGLShader.js
  15865. THREE.WebGLShader = ( function () {
  15866. var addLineNumbers = function ( string ) {
  15867. var lines = string.split( '\n' );
  15868. for ( var i = 0; i < lines.length; i ++ ) {
  15869. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  15870. }
  15871. return lines.join( '\n' );
  15872. };
  15873. return function ( gl, type, string ) {
  15874. var shader = gl.createShader( type );
  15875. gl.shaderSource( shader, string );
  15876. gl.compileShader( shader );
  15877. if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) {
  15878. console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' );
  15879. }
  15880. if ( gl.getShaderInfoLog( shader ) !== '' ) {
  15881. console.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', gl.getShaderInfoLog( shader ) );
  15882. console.warn( addLineNumbers( string ) );
  15883. }
  15884. // --enable-privileged-webgl-extension
  15885. // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  15886. return shader;
  15887. };
  15888. } )();
  15889. // File:src/renderers/renderables/RenderableVertex.js
  15890. /**
  15891. * @author mrdoob / http://mrdoob.com/
  15892. */
  15893. THREE.RenderableVertex = function () {
  15894. this.position = new THREE.Vector3();
  15895. this.positionWorld = new THREE.Vector3();
  15896. this.positionScreen = new THREE.Vector4();
  15897. this.visible = true;
  15898. };
  15899. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  15900. this.positionWorld.copy( vertex.positionWorld );
  15901. this.positionScreen.copy( vertex.positionScreen );
  15902. };
  15903. // File:src/renderers/renderables/RenderableFace.js
  15904. /**
  15905. * @author mrdoob / http://mrdoob.com/
  15906. */
  15907. THREE.RenderableFace = function () {
  15908. this.id = 0;
  15909. this.v1 = new THREE.RenderableVertex();
  15910. this.v2 = new THREE.RenderableVertex();
  15911. this.v3 = new THREE.RenderableVertex();
  15912. this.normalModel = new THREE.Vector3();
  15913. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15914. this.vertexNormalsLength = 0;
  15915. this.color = new THREE.Color();
  15916. this.material = null;
  15917. this.uvs = [ new THREE.Vector2(), new THREE.Vector2(), new THREE.Vector2() ];
  15918. this.z = 0;
  15919. };
  15920. // File:src/renderers/renderables/RenderableObject.js
  15921. /**
  15922. * @author mrdoob / http://mrdoob.com/
  15923. */
  15924. THREE.RenderableObject = function () {
  15925. this.id = 0;
  15926. this.object = null;
  15927. this.z = 0;
  15928. };
  15929. // File:src/renderers/renderables/RenderableSprite.js
  15930. /**
  15931. * @author mrdoob / http://mrdoob.com/
  15932. */
  15933. THREE.RenderableSprite = function () {
  15934. this.id = 0;
  15935. this.object = null;
  15936. this.x = 0;
  15937. this.y = 0;
  15938. this.z = 0;
  15939. this.rotation = 0;
  15940. this.scale = new THREE.Vector2();
  15941. this.material = null;
  15942. };
  15943. // File:src/renderers/renderables/RenderableLine.js
  15944. /**
  15945. * @author mrdoob / http://mrdoob.com/
  15946. */
  15947. THREE.RenderableLine = function () {
  15948. this.id = 0;
  15949. this.v1 = new THREE.RenderableVertex();
  15950. this.v2 = new THREE.RenderableVertex();
  15951. this.vertexColors = [ new THREE.Color(), new THREE.Color() ];
  15952. this.material = null;
  15953. this.z = 0;
  15954. };
  15955. // File:src/extras/GeometryUtils.js
  15956. /**
  15957. * @author mrdoob / http://mrdoob.com/
  15958. */
  15959. THREE.GeometryUtils = {
  15960. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  15961. console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  15962. var matrix;
  15963. if ( geometry2 instanceof THREE.Mesh ) {
  15964. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  15965. matrix = geometry2.matrix;
  15966. geometry2 = geometry2.geometry;
  15967. }
  15968. geometry1.merge( geometry2, matrix, materialIndexOffset );
  15969. },
  15970. center: function ( geometry ) {
  15971. console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
  15972. return geometry.center();
  15973. }
  15974. };
  15975. // File:src/extras/ImageUtils.js
  15976. /**
  15977. * @author alteredq / http://alteredqualia.com/
  15978. * @author mrdoob / http://mrdoob.com/
  15979. * @author Daosheng Mu / https://github.com/DaoshengMu/
  15980. */
  15981. THREE.ImageUtils = {
  15982. crossOrigin: undefined,
  15983. loadTexture: function ( url, mapping, onLoad, onError ) {
  15984. var loader = new THREE.ImageLoader();
  15985. loader.crossOrigin = this.crossOrigin;
  15986. var texture = new THREE.Texture( undefined, mapping );
  15987. loader.load( url, function ( image ) {
  15988. texture.image = image;
  15989. texture.needsUpdate = true;
  15990. if ( onLoad ) onLoad( texture );
  15991. }, undefined, function ( event ) {
  15992. if ( onError ) onError( event );
  15993. } );
  15994. texture.sourceFile = url;
  15995. return texture;
  15996. },
  15997. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  15998. var images = [];
  15999. var loader = new THREE.ImageLoader();
  16000. loader.crossOrigin = this.crossOrigin;
  16001. var texture = new THREE.CubeTexture( images, mapping );
  16002. // no flipping needed for cube textures
  16003. texture.flipY = false;
  16004. var loaded = 0;
  16005. var loadTexture = function ( i ) {
  16006. loader.load( array[ i ], function ( image ) {
  16007. texture.images[ i ] = image;
  16008. loaded += 1;
  16009. if ( loaded === 6 ) {
  16010. texture.needsUpdate = true;
  16011. if ( onLoad ) onLoad( texture );
  16012. }
  16013. } );
  16014. }
  16015. for ( var i = 0, il = array.length; i < il; ++ i ) {
  16016. loadTexture( i );
  16017. }
  16018. return texture;
  16019. },
  16020. loadCompressedTexture: function () {
  16021. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' )
  16022. },
  16023. loadCompressedTextureCube: function () {
  16024. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' )
  16025. },
  16026. getNormalMap: function ( image, depth ) {
  16027. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  16028. var cross = function ( a, b ) {
  16029. 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 ] ];
  16030. }
  16031. var subtract = function ( a, b ) {
  16032. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  16033. }
  16034. var normalize = function ( a ) {
  16035. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  16036. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  16037. }
  16038. depth = depth | 1;
  16039. var width = image.width;
  16040. var height = image.height;
  16041. var canvas = document.createElement( 'canvas' );
  16042. canvas.width = width;
  16043. canvas.height = height;
  16044. var context = canvas.getContext( '2d' );
  16045. context.drawImage( image, 0, 0 );
  16046. var data = context.getImageData( 0, 0, width, height ).data;
  16047. var imageData = context.createImageData( width, height );
  16048. var output = imageData.data;
  16049. for ( var x = 0; x < width; x ++ ) {
  16050. for ( var y = 0; y < height; y ++ ) {
  16051. var ly = y - 1 < 0 ? 0 : y - 1;
  16052. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  16053. var lx = x - 1 < 0 ? 0 : x - 1;
  16054. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  16055. var points = [];
  16056. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  16057. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  16058. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  16059. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  16060. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  16061. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  16062. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  16063. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  16064. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  16065. var normals = [];
  16066. var num_points = points.length;
  16067. for ( var i = 0; i < num_points; i ++ ) {
  16068. var v1 = points[ i ];
  16069. var v2 = points[ ( i + 1 ) % num_points ];
  16070. v1 = subtract( v1, origin );
  16071. v2 = subtract( v2, origin );
  16072. normals.push( normalize( cross( v1, v2 ) ) );
  16073. }
  16074. var normal = [ 0, 0, 0 ];
  16075. for ( var i = 0; i < normals.length; i ++ ) {
  16076. normal[ 0 ] += normals[ i ][ 0 ];
  16077. normal[ 1 ] += normals[ i ][ 1 ];
  16078. normal[ 2 ] += normals[ i ][ 2 ];
  16079. }
  16080. normal[ 0 ] /= normals.length;
  16081. normal[ 1 ] /= normals.length;
  16082. normal[ 2 ] /= normals.length;
  16083. var idx = ( y * width + x ) * 4;
  16084. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16085. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16086. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  16087. output[ idx + 3 ] = 255;
  16088. }
  16089. }
  16090. context.putImageData( imageData, 0, 0 );
  16091. return canvas;
  16092. },
  16093. generateDataTexture: function ( width, height, color ) {
  16094. var size = width * height;
  16095. var data = new Uint8Array( 3 * size );
  16096. var r = Math.floor( color.r * 255 );
  16097. var g = Math.floor( color.g * 255 );
  16098. var b = Math.floor( color.b * 255 );
  16099. for ( var i = 0; i < size; i ++ ) {
  16100. data[ i * 3 ] = r;
  16101. data[ i * 3 + 1 ] = g;
  16102. data[ i * 3 + 2 ] = b;
  16103. }
  16104. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  16105. texture.needsUpdate = true;
  16106. return texture;
  16107. }
  16108. };
  16109. // File:src/extras/SceneUtils.js
  16110. /**
  16111. * @author alteredq / http://alteredqualia.com/
  16112. */
  16113. THREE.SceneUtils = {
  16114. createMultiMaterialObject: function ( geometry, materials ) {
  16115. var group = new THREE.Object3D();
  16116. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  16117. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  16118. }
  16119. return group;
  16120. },
  16121. detach: function ( child, parent, scene ) {
  16122. child.applyMatrix( parent.matrixWorld );
  16123. parent.remove( child );
  16124. scene.add( child );
  16125. },
  16126. attach: function ( child, scene, parent ) {
  16127. var matrixWorldInverse = new THREE.Matrix4();
  16128. matrixWorldInverse.getInverse( parent.matrixWorld );
  16129. child.applyMatrix( matrixWorldInverse );
  16130. scene.remove( child );
  16131. parent.add( child );
  16132. }
  16133. };
  16134. // File:src/extras/FontUtils.js
  16135. /**
  16136. * @author zz85 / http://www.lab4games.net/zz85/blog
  16137. * @author alteredq / http://alteredqualia.com/
  16138. *
  16139. * For Text operations in three.js (See TextGeometry)
  16140. *
  16141. * It uses techniques used in:
  16142. *
  16143. * typeface.js and canvastext
  16144. * For converting fonts and rendering with javascript
  16145. * http://typeface.neocracy.org
  16146. *
  16147. * Triangulation ported from AS3
  16148. * Simple Polygon Triangulation
  16149. * http://actionsnippet.com/?p=1462
  16150. *
  16151. * A Method to triangulate shapes with holes
  16152. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  16153. *
  16154. */
  16155. THREE.FontUtils = {
  16156. faces: {},
  16157. // Just for now. face[weight][style]
  16158. face: 'helvetiker',
  16159. weight: 'normal',
  16160. style: 'normal',
  16161. size: 150,
  16162. divisions: 10,
  16163. getFace: function () {
  16164. try {
  16165. return this.faces[ this.face ][ this.weight ][ this.style ];
  16166. } catch (e) {
  16167. throw "The font " + this.face + " with " + this.weight + " weight and " + this.style + " style is missing."
  16168. };
  16169. },
  16170. loadFace: function ( data ) {
  16171. var family = data.familyName.toLowerCase();
  16172. var ThreeFont = this;
  16173. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  16174. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  16175. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16176. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16177. return data;
  16178. },
  16179. drawText: function ( text ) {
  16180. var characterPts = [], allPts = [];
  16181. // RenderText
  16182. var i, p,
  16183. face = this.getFace(),
  16184. scale = this.size / face.resolution,
  16185. offset = 0,
  16186. chars = String( text ).split( '' ),
  16187. length = chars.length;
  16188. var fontPaths = [];
  16189. for ( i = 0; i < length; i ++ ) {
  16190. var path = new THREE.Path();
  16191. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  16192. offset += ret.offset;
  16193. fontPaths.push( ret.path );
  16194. }
  16195. // get the width
  16196. var width = offset / 2;
  16197. //
  16198. // for ( p = 0; p < allPts.length; p++ ) {
  16199. //
  16200. // allPts[ p ].x -= width;
  16201. //
  16202. // }
  16203. //var extract = this.extractPoints( allPts, characterPts );
  16204. //extract.contour = allPts;
  16205. //extract.paths = fontPaths;
  16206. //extract.offset = width;
  16207. return { paths: fontPaths, offset: width };
  16208. },
  16209. extractGlyphPoints: function ( c, face, scale, offset, path ) {
  16210. var pts = [];
  16211. var i, i2, divisions,
  16212. outline, action, length,
  16213. scaleX, scaleY,
  16214. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  16215. laste,
  16216. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  16217. if ( ! glyph ) return;
  16218. if ( glyph.o ) {
  16219. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  16220. length = outline.length;
  16221. scaleX = scale;
  16222. scaleY = scale;
  16223. for ( i = 0; i < length; ) {
  16224. action = outline[ i ++ ];
  16225. //console.log( action );
  16226. switch ( action ) {
  16227. case 'm':
  16228. // Move To
  16229. x = outline[ i ++ ] * scaleX + offset;
  16230. y = outline[ i ++ ] * scaleY;
  16231. path.moveTo( x, y );
  16232. break;
  16233. case 'l':
  16234. // Line To
  16235. x = outline[ i ++ ] * scaleX + offset;
  16236. y = outline[ i ++ ] * scaleY;
  16237. path.lineTo( x,y );
  16238. break;
  16239. case 'q':
  16240. // QuadraticCurveTo
  16241. cpx = outline[ i ++ ] * scaleX + offset;
  16242. cpy = outline[ i ++ ] * scaleY;
  16243. cpx1 = outline[ i ++ ] * scaleX + offset;
  16244. cpy1 = outline[ i ++ ] * scaleY;
  16245. path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
  16246. laste = pts[ pts.length - 1 ];
  16247. if ( laste ) {
  16248. cpx0 = laste.x;
  16249. cpy0 = laste.y;
  16250. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16251. var t = i2 / divisions;
  16252. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16253. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16254. }
  16255. }
  16256. break;
  16257. case 'b':
  16258. // Cubic Bezier Curve
  16259. cpx = outline[ i ++ ] * scaleX + offset;
  16260. cpy = outline[ i ++ ] * scaleY;
  16261. cpx1 = outline[ i ++ ] * scaleX + offset;
  16262. cpy1 = outline[ i ++ ] * scaleY;
  16263. cpx2 = outline[ i ++ ] * scaleX + offset;
  16264. cpy2 = outline[ i ++ ] * scaleY;
  16265. path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
  16266. laste = pts[ pts.length - 1 ];
  16267. if ( laste ) {
  16268. cpx0 = laste.x;
  16269. cpy0 = laste.y;
  16270. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16271. var t = i2 / divisions;
  16272. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16273. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16274. }
  16275. }
  16276. break;
  16277. }
  16278. }
  16279. }
  16280. return { offset: glyph.ha * scale, path:path };
  16281. }
  16282. };
  16283. THREE.FontUtils.generateShapes = function ( text, parameters ) {
  16284. // Parameters
  16285. parameters = parameters || {};
  16286. var size = parameters.size !== undefined ? parameters.size : 100;
  16287. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments : 4;
  16288. var font = parameters.font !== undefined ? parameters.font : 'helvetiker';
  16289. var weight = parameters.weight !== undefined ? parameters.weight : 'normal';
  16290. var style = parameters.style !== undefined ? parameters.style : 'normal';
  16291. THREE.FontUtils.size = size;
  16292. THREE.FontUtils.divisions = curveSegments;
  16293. THREE.FontUtils.face = font;
  16294. THREE.FontUtils.weight = weight;
  16295. THREE.FontUtils.style = style;
  16296. // Get a Font data json object
  16297. var data = THREE.FontUtils.drawText( text );
  16298. var paths = data.paths;
  16299. var shapes = [];
  16300. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  16301. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  16302. }
  16303. return shapes;
  16304. };
  16305. /**
  16306. * This code is a quick port of code written in C++ which was submitted to
  16307. * flipcode.com by John W. Ratcliff // July 22, 2000
  16308. * See original code and more information here:
  16309. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  16310. *
  16311. * ported to actionscript by Zevan Rosser
  16312. * www.actionsnippet.com
  16313. *
  16314. * ported to javascript by Joshua Koo
  16315. * http://www.lab4games.net/zz85/blog
  16316. *
  16317. */
  16318. ( function ( namespace ) {
  16319. var EPSILON = 0.0000000001;
  16320. // takes in an contour array and returns
  16321. var process = function ( contour, indices ) {
  16322. var n = contour.length;
  16323. if ( n < 3 ) return null;
  16324. var result = [],
  16325. verts = [],
  16326. vertIndices = [];
  16327. /* we want a counter-clockwise polygon in verts */
  16328. var u, v, w;
  16329. if ( area( contour ) > 0.0 ) {
  16330. for ( v = 0; v < n; v ++ ) verts[ v ] = v;
  16331. } else {
  16332. for ( v = 0; v < n; v ++ ) verts[ v ] = ( n - 1 ) - v;
  16333. }
  16334. var nv = n;
  16335. /* remove nv - 2 vertices, creating 1 triangle every time */
  16336. var count = 2 * nv; /* error detection */
  16337. for ( v = nv - 1; nv > 2; ) {
  16338. /* if we loop, it is probably a non-simple polygon */
  16339. if ( ( count -- ) <= 0 ) {
  16340. //** Triangulate: ERROR - probable bad polygon!
  16341. //throw ( "Warning, unable to triangulate polygon!" );
  16342. //return null;
  16343. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  16344. console.log( 'Warning, unable to triangulate polygon!' );
  16345. if ( indices ) return vertIndices;
  16346. return result;
  16347. }
  16348. /* three consecutive vertices in current polygon, <u,v,w> */
  16349. u = v; if ( nv <= u ) u = 0; /* previous */
  16350. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  16351. w = v + 1; if ( nv <= w ) w = 0; /* next */
  16352. if ( snip( contour, u, v, w, nv, verts ) ) {
  16353. var a, b, c, s, t;
  16354. /* true names of the vertices */
  16355. a = verts[ u ];
  16356. b = verts[ v ];
  16357. c = verts[ w ];
  16358. /* output Triangle */
  16359. result.push( [ contour[ a ],
  16360. contour[ b ],
  16361. contour[ c ] ] );
  16362. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  16363. /* remove v from the remaining polygon */
  16364. for ( s = v, t = v + 1; t < nv; s++, t++ ) {
  16365. verts[ s ] = verts[ t ];
  16366. }
  16367. nv --;
  16368. /* reset error detection counter */
  16369. count = 2 * nv;
  16370. }
  16371. }
  16372. if ( indices ) return vertIndices;
  16373. return result;
  16374. };
  16375. // calculate area of the contour polygon
  16376. var area = function ( contour ) {
  16377. var n = contour.length;
  16378. var a = 0.0;
  16379. for ( var p = n - 1, q = 0; q < n; p = q ++ ) {
  16380. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  16381. }
  16382. return a * 0.5;
  16383. };
  16384. var snip = function ( contour, u, v, w, n, verts ) {
  16385. var p;
  16386. var ax, ay, bx, by;
  16387. var cx, cy, px, py;
  16388. ax = contour[ verts[ u ] ].x;
  16389. ay = contour[ verts[ u ] ].y;
  16390. bx = contour[ verts[ v ] ].x;
  16391. by = contour[ verts[ v ] ].y;
  16392. cx = contour[ verts[ w ] ].x;
  16393. cy = contour[ verts[ w ] ].y;
  16394. if ( EPSILON > ( ( ( bx - ax ) * ( cy - ay ) ) - ( ( by - ay ) * ( cx - ax ) ) ) ) return false;
  16395. var aX, aY, bX, bY, cX, cY;
  16396. var apx, apy, bpx, bpy, cpx, cpy;
  16397. var cCROSSap, bCROSScp, aCROSSbp;
  16398. aX = cx - bx; aY = cy - by;
  16399. bX = ax - cx; bY = ay - cy;
  16400. cX = bx - ax; cY = by - ay;
  16401. for ( p = 0; p < n; p ++ ) {
  16402. px = contour[ verts[ p ] ].x
  16403. py = contour[ verts[ p ] ].y
  16404. if ( ( ( px === ax ) && ( py === ay ) ) ||
  16405. ( ( px === bx ) && ( py === by ) ) ||
  16406. ( ( px === cx ) && ( py === cy ) ) ) continue;
  16407. apx = px - ax; apy = py - ay;
  16408. bpx = px - bx; bpy = py - by;
  16409. cpx = px - cx; cpy = py - cy;
  16410. // see if p is inside triangle abc
  16411. aCROSSbp = aX * bpy - aY * bpx;
  16412. cCROSSap = cX * apy - cY * apx;
  16413. bCROSScp = bX * cpy - bY * cpx;
  16414. if ( ( aCROSSbp >= - EPSILON ) && ( bCROSScp >= - EPSILON ) && ( cCROSSap >= - EPSILON ) ) return false;
  16415. }
  16416. return true;
  16417. };
  16418. namespace.Triangulate = process;
  16419. namespace.Triangulate.area = area;
  16420. return namespace;
  16421. } )( THREE.FontUtils );
  16422. // To use the typeface.js face files, hook up the API
  16423. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };
  16424. THREE.typeface_js = self._typeface_js;
  16425. // File:src/extras/core/Curve.js
  16426. /**
  16427. * @author zz85 / http://www.lab4games.net/zz85/blog
  16428. * Extensible curve object
  16429. *
  16430. * Some common of Curve methods
  16431. * .getPoint(t), getTangent(t)
  16432. * .getPointAt(u), getTagentAt(u)
  16433. * .getPoints(), .getSpacedPoints()
  16434. * .getLength()
  16435. * .updateArcLengths()
  16436. *
  16437. * This following classes subclasses THREE.Curve:
  16438. *
  16439. * -- 2d classes --
  16440. * THREE.LineCurve
  16441. * THREE.QuadraticBezierCurve
  16442. * THREE.CubicBezierCurve
  16443. * THREE.SplineCurve
  16444. * THREE.ArcCurve
  16445. * THREE.EllipseCurve
  16446. *
  16447. * -- 3d classes --
  16448. * THREE.LineCurve3
  16449. * THREE.QuadraticBezierCurve3
  16450. * THREE.CubicBezierCurve3
  16451. * THREE.SplineCurve3
  16452. * THREE.ClosedSplineCurve3
  16453. *
  16454. * A series of curves can be represented as a THREE.CurvePath
  16455. *
  16456. **/
  16457. /**************************************************************
  16458. * Abstract Curve base class
  16459. **************************************************************/
  16460. THREE.Curve = function () {
  16461. };
  16462. // Virtual base class method to overwrite and implement in subclasses
  16463. // - t [0 .. 1]
  16464. THREE.Curve.prototype.getPoint = function ( t ) {
  16465. console.log( "Warning, getPoint() not implemented!" );
  16466. return null;
  16467. };
  16468. // Get point at relative position in curve according to arc length
  16469. // - u [0 .. 1]
  16470. THREE.Curve.prototype.getPointAt = function ( u ) {
  16471. var t = this.getUtoTmapping( u );
  16472. return this.getPoint( t );
  16473. };
  16474. // Get sequence of points using getPoint( t )
  16475. THREE.Curve.prototype.getPoints = function ( divisions ) {
  16476. if ( ! divisions ) divisions = 5;
  16477. var d, pts = [];
  16478. for ( d = 0; d <= divisions; d ++ ) {
  16479. pts.push( this.getPoint( d / divisions ) );
  16480. }
  16481. return pts;
  16482. };
  16483. // Get sequence of points using getPointAt( u )
  16484. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  16485. if ( ! divisions ) divisions = 5;
  16486. var d, pts = [];
  16487. for ( d = 0; d <= divisions; d ++ ) {
  16488. pts.push( this.getPointAt( d / divisions ) );
  16489. }
  16490. return pts;
  16491. };
  16492. // Get total curve arc length
  16493. THREE.Curve.prototype.getLength = function () {
  16494. var lengths = this.getLengths();
  16495. return lengths[ lengths.length - 1 ];
  16496. };
  16497. // Get list of cumulative segment lengths
  16498. THREE.Curve.prototype.getLengths = function ( divisions ) {
  16499. if ( ! divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  16500. if ( this.cacheArcLengths
  16501. && ( this.cacheArcLengths.length == divisions + 1 )
  16502. && ! this.needsUpdate) {
  16503. //console.log( "cached", this.cacheArcLengths );
  16504. return this.cacheArcLengths;
  16505. }
  16506. this.needsUpdate = false;
  16507. var cache = [];
  16508. var current, last = this.getPoint( 0 );
  16509. var p, sum = 0;
  16510. cache.push( 0 );
  16511. for ( p = 1; p <= divisions; p ++ ) {
  16512. current = this.getPoint ( p / divisions );
  16513. sum += current.distanceTo( last );
  16514. cache.push( sum );
  16515. last = current;
  16516. }
  16517. this.cacheArcLengths = cache;
  16518. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  16519. };
  16520. THREE.Curve.prototype.updateArcLengths = function() {
  16521. this.needsUpdate = true;
  16522. this.getLengths();
  16523. };
  16524. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  16525. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  16526. var arcLengths = this.getLengths();
  16527. var i = 0, il = arcLengths.length;
  16528. var targetArcLength; // The targeted u distance value to get
  16529. if ( distance ) {
  16530. targetArcLength = distance;
  16531. } else {
  16532. targetArcLength = u * arcLengths[ il - 1 ];
  16533. }
  16534. //var time = Date.now();
  16535. // binary search for the index with largest value smaller than target u distance
  16536. var low = 0, high = il - 1, comparison;
  16537. while ( low <= high ) {
  16538. 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
  16539. comparison = arcLengths[ i ] - targetArcLength;
  16540. if ( comparison < 0 ) {
  16541. low = i + 1;
  16542. continue;
  16543. } else if ( comparison > 0 ) {
  16544. high = i - 1;
  16545. continue;
  16546. } else {
  16547. high = i;
  16548. break;
  16549. // DONE
  16550. }
  16551. }
  16552. i = high;
  16553. //console.log('b' , i, low, high, Date.now()- time);
  16554. if ( arcLengths[ i ] == targetArcLength ) {
  16555. var t = i / ( il - 1 );
  16556. return t;
  16557. }
  16558. // we could get finer grain at lengths, or use simple interpolatation between two points
  16559. var lengthBefore = arcLengths[ i ];
  16560. var lengthAfter = arcLengths[ i + 1 ];
  16561. var segmentLength = lengthAfter - lengthBefore;
  16562. // determine where we are between the 'before' and 'after' points
  16563. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  16564. // add that fractional amount to t
  16565. var t = ( i + segmentFraction ) / ( il -1 );
  16566. return t;
  16567. };
  16568. // Returns a unit vector tangent at t
  16569. // In case any sub curve does not implement its tangent derivation,
  16570. // 2 points a small delta apart will be used to find its gradient
  16571. // which seems to give a reasonable approximation
  16572. THREE.Curve.prototype.getTangent = function( t ) {
  16573. var delta = 0.0001;
  16574. var t1 = t - delta;
  16575. var t2 = t + delta;
  16576. // Capping in case of danger
  16577. if ( t1 < 0 ) t1 = 0;
  16578. if ( t2 > 1 ) t2 = 1;
  16579. var pt1 = this.getPoint( t1 );
  16580. var pt2 = this.getPoint( t2 );
  16581. var vec = pt2.clone().sub(pt1);
  16582. return vec.normalize();
  16583. };
  16584. THREE.Curve.prototype.getTangentAt = function ( u ) {
  16585. var t = this.getUtoTmapping( u );
  16586. return this.getTangent( t );
  16587. };
  16588. /**************************************************************
  16589. * Utils
  16590. **************************************************************/
  16591. THREE.Curve.Utils = {
  16592. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  16593. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  16594. },
  16595. // Puay Bing, thanks for helping with this derivative!
  16596. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  16597. return - 3 * p0 * (1 - t) * (1 - t) +
  16598. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  16599. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  16600. 3 * t * t * p3;
  16601. },
  16602. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  16603. // To check if my formulas are correct
  16604. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  16605. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  16606. var h01 = - 6 * t * t + 6 * t; // − 2t3 + 3t2
  16607. var h11 = 3 * t * t - 2 * t; // t3 − t2
  16608. return h00 + h10 + h01 + h11;
  16609. },
  16610. // Catmull-Rom
  16611. interpolate: function( p0, p1, p2, p3, t ) {
  16612. var v0 = ( p2 - p0 ) * 0.5;
  16613. var v1 = ( p3 - p1 ) * 0.5;
  16614. var t2 = t * t;
  16615. var t3 = t * t2;
  16616. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  16617. }
  16618. };
  16619. // TODO: Transformation for Curves?
  16620. /**************************************************************
  16621. * 3D Curves
  16622. **************************************************************/
  16623. // A Factory method for creating new curve subclasses
  16624. THREE.Curve.create = function ( constructor, getPointFunc ) {
  16625. constructor.prototype = Object.create( THREE.Curve.prototype );
  16626. constructor.prototype.getPoint = getPointFunc;
  16627. return constructor;
  16628. };
  16629. // File:src/extras/core/CurvePath.js
  16630. /**
  16631. * @author zz85 / http://www.lab4games.net/zz85/blog
  16632. *
  16633. **/
  16634. /**************************************************************
  16635. * Curved Path - a curve path is simply a array of connected
  16636. * curves, but retains the api of a curve
  16637. **************************************************************/
  16638. THREE.CurvePath = function () {
  16639. this.curves = [];
  16640. this.bends = [];
  16641. this.autoClose = false; // Automatically closes the path
  16642. };
  16643. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  16644. THREE.CurvePath.prototype.add = function ( curve ) {
  16645. this.curves.push( curve );
  16646. };
  16647. THREE.CurvePath.prototype.checkConnection = function() {
  16648. // TODO
  16649. // If the ending of curve is not connected to the starting
  16650. // or the next curve, then, this is not a real path
  16651. };
  16652. THREE.CurvePath.prototype.closePath = function() {
  16653. // TODO Test
  16654. // and verify for vector3 (needs to implement equals)
  16655. // Add a line curve if start and end of lines are not connected
  16656. var startPoint = this.curves[0].getPoint(0);
  16657. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  16658. if (! startPoint.equals(endPoint)) {
  16659. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  16660. }
  16661. };
  16662. // To get accurate point with reference to
  16663. // entire path distance at time t,
  16664. // following has to be done:
  16665. // 1. Length of each sub path have to be known
  16666. // 2. Locate and identify type of curve
  16667. // 3. Get t for the curve
  16668. // 4. Return curve.getPointAt(t')
  16669. THREE.CurvePath.prototype.getPoint = function( t ) {
  16670. var d = t * this.getLength();
  16671. var curveLengths = this.getCurveLengths();
  16672. var i = 0, diff, curve;
  16673. // To think about boundaries points.
  16674. while ( i < curveLengths.length ) {
  16675. if ( curveLengths[ i ] >= d ) {
  16676. diff = curveLengths[ i ] - d;
  16677. curve = this.curves[ i ];
  16678. var u = 1 - diff / curve.getLength();
  16679. return curve.getPointAt( u );
  16680. break;
  16681. }
  16682. i ++;
  16683. }
  16684. return null;
  16685. // loop where sum != 0, sum > d , sum+1 <d
  16686. };
  16687. /*
  16688. THREE.CurvePath.prototype.getTangent = function( t ) {
  16689. };*/
  16690. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  16691. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  16692. // getPoint() depends on getLength
  16693. THREE.CurvePath.prototype.getLength = function() {
  16694. var lens = this.getCurveLengths();
  16695. return lens[ lens.length - 1 ];
  16696. };
  16697. // Compute lengths and cache them
  16698. // We cannot overwrite getLengths() because UtoT mapping uses it.
  16699. THREE.CurvePath.prototype.getCurveLengths = function() {
  16700. // We use cache values if curves and cache array are same length
  16701. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  16702. return this.cacheLengths;
  16703. };
  16704. // Get length of subsurve
  16705. // Push sums into cached array
  16706. var lengths = [], sums = 0;
  16707. var i, il = this.curves.length;
  16708. for ( i = 0; i < il; i ++ ) {
  16709. sums += this.curves[ i ].getLength();
  16710. lengths.push( sums );
  16711. }
  16712. this.cacheLengths = lengths;
  16713. return lengths;
  16714. };
  16715. // Returns min and max coordinates
  16716. THREE.CurvePath.prototype.getBoundingBox = function () {
  16717. var points = this.getPoints();
  16718. var maxX, maxY, maxZ;
  16719. var minX, minY, minZ;
  16720. maxX = maxY = Number.NEGATIVE_INFINITY;
  16721. minX = minY = Number.POSITIVE_INFINITY;
  16722. var p, i, il, sum;
  16723. var v3 = points[0] instanceof THREE.Vector3;
  16724. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  16725. for ( i = 0, il = points.length; i < il; i ++ ) {
  16726. p = points[ i ];
  16727. if ( p.x > maxX ) maxX = p.x;
  16728. else if ( p.x < minX ) minX = p.x;
  16729. if ( p.y > maxY ) maxY = p.y;
  16730. else if ( p.y < minY ) minY = p.y;
  16731. if ( v3 ) {
  16732. if ( p.z > maxZ ) maxZ = p.z;
  16733. else if ( p.z < minZ ) minZ = p.z;
  16734. }
  16735. sum.add( p );
  16736. }
  16737. var ret = {
  16738. minX: minX,
  16739. minY: minY,
  16740. maxX: maxX,
  16741. maxY: maxY
  16742. };
  16743. if ( v3 ) {
  16744. ret.maxZ = maxZ;
  16745. ret.minZ = minZ;
  16746. }
  16747. return ret;
  16748. };
  16749. /**************************************************************
  16750. * Create Geometries Helpers
  16751. **************************************************************/
  16752. /// Generate geometry from path points (for Line or Points objects)
  16753. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  16754. var pts = this.getPoints( divisions, true );
  16755. return this.createGeometry( pts );
  16756. };
  16757. // Generate geometry from equidistance sampling along the path
  16758. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  16759. var pts = this.getSpacedPoints( divisions, true );
  16760. return this.createGeometry( pts );
  16761. };
  16762. THREE.CurvePath.prototype.createGeometry = function( points ) {
  16763. var geometry = new THREE.Geometry();
  16764. for ( var i = 0; i < points.length; i ++ ) {
  16765. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  16766. }
  16767. return geometry;
  16768. };
  16769. /**************************************************************
  16770. * Bend / Wrap Helper Methods
  16771. **************************************************************/
  16772. // Wrap path / Bend modifiers?
  16773. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  16774. this.bends.push( bendpath );
  16775. };
  16776. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  16777. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  16778. var i, il;
  16779. if ( ! bends ) {
  16780. bends = this.bends;
  16781. }
  16782. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16783. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16784. }
  16785. return oldPts;
  16786. };
  16787. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  16788. var oldPts = this.getSpacedPoints( segments );
  16789. var i, il;
  16790. if ( ! bends ) {
  16791. bends = this.bends;
  16792. }
  16793. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16794. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16795. }
  16796. return oldPts;
  16797. };
  16798. // This returns getPoints() bend/wrapped around the contour of a path.
  16799. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  16800. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  16801. var bounds = this.getBoundingBox();
  16802. var i, il, p, oldX, oldY, xNorm;
  16803. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  16804. p = oldPts[ i ];
  16805. oldX = p.x;
  16806. oldY = p.y;
  16807. xNorm = oldX / bounds.maxX;
  16808. // If using actual distance, for length > path, requires line extrusions
  16809. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  16810. xNorm = path.getUtoTmapping( xNorm, oldX );
  16811. // check for out of bounds?
  16812. var pathPt = path.getPoint( xNorm );
  16813. var normal = path.getTangent( xNorm );
  16814. normal.set( - normal.y, normal.x ).multiplyScalar( oldY );
  16815. p.x = pathPt.x + normal.x;
  16816. p.y = pathPt.y + normal.y;
  16817. }
  16818. return oldPts;
  16819. };
  16820. // File:src/extras/core/Gyroscope.js
  16821. /**
  16822. * @author alteredq / http://alteredqualia.com/
  16823. */
  16824. THREE.Gyroscope = function () {
  16825. THREE.Object3D.call( this );
  16826. };
  16827. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  16828. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  16829. this.matrixAutoUpdate && this.updateMatrix();
  16830. // update matrixWorld
  16831. if ( this.matrixWorldNeedsUpdate || force ) {
  16832. if ( this.parent ) {
  16833. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  16834. this.matrixWorld.decompose( this.translationWorld, this.quaternionWorld, this.scaleWorld );
  16835. this.matrix.decompose( this.translationObject, this.quaternionObject, this.scaleObject );
  16836. this.matrixWorld.compose( this.translationWorld, this.quaternionObject, this.scaleWorld );
  16837. } else {
  16838. this.matrixWorld.copy( this.matrix );
  16839. }
  16840. this.matrixWorldNeedsUpdate = false;
  16841. force = true;
  16842. }
  16843. // update children
  16844. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  16845. this.children[ i ].updateMatrixWorld( force );
  16846. }
  16847. };
  16848. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  16849. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  16850. THREE.Gyroscope.prototype.quaternionWorld = new THREE.Quaternion();
  16851. THREE.Gyroscope.prototype.quaternionObject = new THREE.Quaternion();
  16852. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  16853. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  16854. // File:src/extras/core/Path.js
  16855. /**
  16856. * @author zz85 / http://www.lab4games.net/zz85/blog
  16857. * Creates free form 2d path using series of points, lines or curves.
  16858. *
  16859. **/
  16860. THREE.Path = function ( points ) {
  16861. THREE.CurvePath.call(this);
  16862. this.actions = [];
  16863. if ( points ) {
  16864. this.fromPoints( points );
  16865. }
  16866. };
  16867. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  16868. THREE.PathActions = {
  16869. MOVE_TO: 'moveTo',
  16870. LINE_TO: 'lineTo',
  16871. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  16872. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  16873. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  16874. ARC: 'arc', // Circle
  16875. ELLIPSE: 'ellipse'
  16876. };
  16877. // TODO Clean up PATH API
  16878. // Create path using straight lines to connect all points
  16879. // - vectors: array of Vector2
  16880. THREE.Path.prototype.fromPoints = function ( vectors ) {
  16881. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  16882. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  16883. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  16884. };
  16885. };
  16886. // startPath() endPath()?
  16887. THREE.Path.prototype.moveTo = function ( x, y ) {
  16888. var args = Array.prototype.slice.call( arguments );
  16889. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  16890. };
  16891. THREE.Path.prototype.lineTo = function ( x, y ) {
  16892. var args = Array.prototype.slice.call( arguments );
  16893. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16894. var x0 = lastargs[ lastargs.length - 2 ];
  16895. var y0 = lastargs[ lastargs.length - 1 ];
  16896. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  16897. this.curves.push( curve );
  16898. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  16899. };
  16900. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  16901. var args = Array.prototype.slice.call( arguments );
  16902. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16903. var x0 = lastargs[ lastargs.length - 2 ];
  16904. var y0 = lastargs[ lastargs.length - 1 ];
  16905. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  16906. new THREE.Vector2( aCPx, aCPy ),
  16907. new THREE.Vector2( aX, aY ) );
  16908. this.curves.push( curve );
  16909. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  16910. };
  16911. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  16912. aCP2x, aCP2y,
  16913. aX, aY ) {
  16914. var args = Array.prototype.slice.call( arguments );
  16915. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16916. var x0 = lastargs[ lastargs.length - 2 ];
  16917. var y0 = lastargs[ lastargs.length - 1 ];
  16918. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  16919. new THREE.Vector2( aCP1x, aCP1y ),
  16920. new THREE.Vector2( aCP2x, aCP2y ),
  16921. new THREE.Vector2( aX, aY ) );
  16922. this.curves.push( curve );
  16923. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  16924. };
  16925. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  16926. var args = Array.prototype.slice.call( arguments );
  16927. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16928. var x0 = lastargs[ lastargs.length - 2 ];
  16929. var y0 = lastargs[ lastargs.length - 1 ];
  16930. //---
  16931. var npts = [ new THREE.Vector2( x0, y0 ) ];
  16932. Array.prototype.push.apply( npts, pts );
  16933. var curve = new THREE.SplineCurve( npts );
  16934. this.curves.push( curve );
  16935. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  16936. };
  16937. // FUTURE: Change the API or follow canvas API?
  16938. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  16939. aStartAngle, aEndAngle, aClockwise ) {
  16940. var lastargs = this.actions[ this.actions.length - 1].args;
  16941. var x0 = lastargs[ lastargs.length - 2 ];
  16942. var y0 = lastargs[ lastargs.length - 1 ];
  16943. this.absarc(aX + x0, aY + y0, aRadius,
  16944. aStartAngle, aEndAngle, aClockwise );
  16945. };
  16946. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  16947. aStartAngle, aEndAngle, aClockwise ) {
  16948. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  16949. };
  16950. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  16951. aStartAngle, aEndAngle, aClockwise ) {
  16952. var lastargs = this.actions[ this.actions.length - 1].args;
  16953. var x0 = lastargs[ lastargs.length - 2 ];
  16954. var y0 = lastargs[ lastargs.length - 1 ];
  16955. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  16956. aStartAngle, aEndAngle, aClockwise );
  16957. };
  16958. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  16959. aStartAngle, aEndAngle, aClockwise ) {
  16960. var args = Array.prototype.slice.call( arguments );
  16961. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  16962. aStartAngle, aEndAngle, aClockwise );
  16963. this.curves.push( curve );
  16964. var lastPoint = curve.getPoint(1);
  16965. args.push(lastPoint.x);
  16966. args.push(lastPoint.y);
  16967. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  16968. };
  16969. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  16970. if ( ! divisions ) divisions = 40;
  16971. var points = [];
  16972. for ( var i = 0; i < divisions; i ++ ) {
  16973. points.push( this.getPoint( i / divisions ) );
  16974. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  16975. }
  16976. // if ( closedPath ) {
  16977. //
  16978. // points.push( points[ 0 ] );
  16979. //
  16980. // }
  16981. return points;
  16982. };
  16983. /* Return an array of vectors based on contour of the path */
  16984. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  16985. if (this.useSpacedPoints) {
  16986. console.log('tata');
  16987. return this.getSpacedPoints( divisions, closedPath );
  16988. }
  16989. divisions = divisions || 12;
  16990. var points = [];
  16991. var i, il, item, action, args;
  16992. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  16993. laste, j,
  16994. t, tx, ty;
  16995. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  16996. item = this.actions[ i ];
  16997. action = item.action;
  16998. args = item.args;
  16999. switch( action ) {
  17000. case THREE.PathActions.MOVE_TO:
  17001. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17002. break;
  17003. case THREE.PathActions.LINE_TO:
  17004. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17005. break;
  17006. case THREE.PathActions.QUADRATIC_CURVE_TO:
  17007. cpx = args[ 2 ];
  17008. cpy = args[ 3 ];
  17009. cpx1 = args[ 0 ];
  17010. cpy1 = args[ 1 ];
  17011. if ( points.length > 0 ) {
  17012. laste = points[ points.length - 1 ];
  17013. cpx0 = laste.x;
  17014. cpy0 = laste.y;
  17015. } else {
  17016. laste = this.actions[ i - 1 ].args;
  17017. cpx0 = laste[ laste.length - 2 ];
  17018. cpy0 = laste[ laste.length - 1 ];
  17019. }
  17020. for ( j = 1; j <= divisions; j ++ ) {
  17021. t = j / divisions;
  17022. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  17023. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  17024. points.push( new THREE.Vector2( tx, ty ) );
  17025. }
  17026. break;
  17027. case THREE.PathActions.BEZIER_CURVE_TO:
  17028. cpx = args[ 4 ];
  17029. cpy = args[ 5 ];
  17030. cpx1 = args[ 0 ];
  17031. cpy1 = args[ 1 ];
  17032. cpx2 = args[ 2 ];
  17033. cpy2 = args[ 3 ];
  17034. if ( points.length > 0 ) {
  17035. laste = points[ points.length - 1 ];
  17036. cpx0 = laste.x;
  17037. cpy0 = laste.y;
  17038. } else {
  17039. laste = this.actions[ i - 1 ].args;
  17040. cpx0 = laste[ laste.length - 2 ];
  17041. cpy0 = laste[ laste.length - 1 ];
  17042. }
  17043. for ( j = 1; j <= divisions; j ++ ) {
  17044. t = j / divisions;
  17045. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  17046. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  17047. points.push( new THREE.Vector2( tx, ty ) );
  17048. }
  17049. break;
  17050. case THREE.PathActions.CSPLINE_THRU:
  17051. laste = this.actions[ i - 1 ].args;
  17052. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  17053. var spts = [ last ];
  17054. var n = divisions * args[ 0 ].length;
  17055. spts = spts.concat( args[ 0 ] );
  17056. var spline = new THREE.SplineCurve( spts );
  17057. for ( j = 1; j <= n; j ++ ) {
  17058. points.push( spline.getPointAt( j / n ) ) ;
  17059. }
  17060. break;
  17061. case THREE.PathActions.ARC:
  17062. var aX = args[ 0 ], aY = args[ 1 ],
  17063. aRadius = args[ 2 ],
  17064. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  17065. aClockwise = !! args[ 5 ];
  17066. var deltaAngle = aEndAngle - aStartAngle;
  17067. var angle;
  17068. var tdivisions = divisions * 2;
  17069. for ( j = 1; j <= tdivisions; j ++ ) {
  17070. t = j / tdivisions;
  17071. if ( ! aClockwise ) {
  17072. t = 1 - t;
  17073. }
  17074. angle = aStartAngle + t * deltaAngle;
  17075. tx = aX + aRadius * Math.cos( angle );
  17076. ty = aY + aRadius * Math.sin( angle );
  17077. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17078. points.push( new THREE.Vector2( tx, ty ) );
  17079. }
  17080. //console.log(points);
  17081. break;
  17082. case THREE.PathActions.ELLIPSE:
  17083. var aX = args[ 0 ], aY = args[ 1 ],
  17084. xRadius = args[ 2 ],
  17085. yRadius = args[ 3 ],
  17086. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  17087. aClockwise = !! args[ 6 ];
  17088. var deltaAngle = aEndAngle - aStartAngle;
  17089. var angle;
  17090. var tdivisions = divisions * 2;
  17091. for ( j = 1; j <= tdivisions; j ++ ) {
  17092. t = j / tdivisions;
  17093. if ( ! aClockwise ) {
  17094. t = 1 - t;
  17095. }
  17096. angle = aStartAngle + t * deltaAngle;
  17097. tx = aX + xRadius * Math.cos( angle );
  17098. ty = aY + yRadius * Math.sin( angle );
  17099. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17100. points.push( new THREE.Vector2( tx, ty ) );
  17101. }
  17102. //console.log(points);
  17103. break;
  17104. } // end switch
  17105. }
  17106. // Normalize to remove the closing point by default.
  17107. var lastPoint = points[ points.length - 1];
  17108. var EPSILON = 0.0000000001;
  17109. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  17110. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  17111. points.splice( points.length - 1, 1);
  17112. if ( closedPath ) {
  17113. points.push( points[ 0 ] );
  17114. }
  17115. return points;
  17116. };
  17117. //
  17118. // Breaks path into shapes
  17119. //
  17120. // Assumptions (if parameter isCCW==true the opposite holds):
  17121. // - solid shapes are defined clockwise (CW)
  17122. // - holes are defined counterclockwise (CCW)
  17123. //
  17124. // If parameter noHoles==true:
  17125. // - all subPaths are regarded as solid shapes
  17126. // - definition order CW/CCW has no relevance
  17127. //
  17128. THREE.Path.prototype.toShapes = function( isCCW, noHoles ) {
  17129. function extractSubpaths( inActions ) {
  17130. var i, il, item, action, args;
  17131. var subPaths = [], lastPath = new THREE.Path();
  17132. for ( i = 0, il = inActions.length; i < il; i ++ ) {
  17133. item = inActions[ i ];
  17134. args = item.args;
  17135. action = item.action;
  17136. if ( action == THREE.PathActions.MOVE_TO ) {
  17137. if ( lastPath.actions.length != 0 ) {
  17138. subPaths.push( lastPath );
  17139. lastPath = new THREE.Path();
  17140. }
  17141. }
  17142. lastPath[ action ].apply( lastPath, args );
  17143. }
  17144. if ( lastPath.actions.length != 0 ) {
  17145. subPaths.push( lastPath );
  17146. }
  17147. // console.log(subPaths);
  17148. return subPaths;
  17149. }
  17150. function toShapesNoHoles( inSubpaths ) {
  17151. var shapes = [];
  17152. for ( var i = 0, il = inSubpaths.length; i < il; i ++ ) {
  17153. var tmpPath = inSubpaths[ i ];
  17154. var tmpShape = new THREE.Shape();
  17155. tmpShape.actions = tmpPath.actions;
  17156. tmpShape.curves = tmpPath.curves;
  17157. shapes.push( tmpShape );
  17158. }
  17159. //console.log("shape", shapes);
  17160. return shapes;
  17161. };
  17162. function isPointInsidePolygon( inPt, inPolygon ) {
  17163. var EPSILON = 0.0000000001;
  17164. var polyLen = inPolygon.length;
  17165. // inPt on polygon contour => immediate success or
  17166. // toggling of inside/outside at every single! intersection point of an edge
  17167. // with the horizontal line through inPt, left of inPt
  17168. // not counting lowerY endpoints of edges and whole edges on that line
  17169. var inside = false;
  17170. for( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  17171. var edgeLowPt = inPolygon[ p ];
  17172. var edgeHighPt = inPolygon[ q ];
  17173. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  17174. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  17175. if ( Math.abs(edgeDy) > EPSILON ) { // not parallel
  17176. if ( edgeDy < 0 ) {
  17177. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  17178. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  17179. }
  17180. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  17181. if ( inPt.y == edgeLowPt.y ) {
  17182. if ( inPt.x == edgeLowPt.x ) return true; // inPt is on contour ?
  17183. // continue; // no intersection or edgeLowPt => doesn't count !!!
  17184. } else {
  17185. var perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  17186. if ( perpEdge == 0 ) return true; // inPt is on contour ?
  17187. if ( perpEdge < 0 ) continue;
  17188. inside = ! inside; // true intersection left of inPt
  17189. }
  17190. } else { // parallel or colinear
  17191. if ( inPt.y != edgeLowPt.y ) continue; // parallel
  17192. // egde lies on the same horizontal line as inPt
  17193. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  17194. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  17195. // continue;
  17196. }
  17197. }
  17198. return inside;
  17199. }
  17200. var subPaths = extractSubpaths( this.actions );
  17201. if ( subPaths.length == 0 ) return [];
  17202. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  17203. var solid, tmpPath, tmpShape, shapes = [];
  17204. if ( subPaths.length == 1) {
  17205. tmpPath = subPaths[0];
  17206. tmpShape = new THREE.Shape();
  17207. tmpShape.actions = tmpPath.actions;
  17208. tmpShape.curves = tmpPath.curves;
  17209. shapes.push( tmpShape );
  17210. return shapes;
  17211. }
  17212. var holesFirst = ! THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  17213. holesFirst = isCCW ? ! holesFirst : holesFirst;
  17214. // console.log("Holes first", holesFirst);
  17215. var betterShapeHoles = [];
  17216. var newShapes = [];
  17217. var newShapeHoles = [];
  17218. var mainIdx = 0;
  17219. var tmpPoints;
  17220. newShapes[mainIdx] = undefined;
  17221. newShapeHoles[mainIdx] = [];
  17222. var i, il;
  17223. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17224. tmpPath = subPaths[ i ];
  17225. tmpPoints = tmpPath.getPoints();
  17226. solid = THREE.Shape.Utils.isClockWise( tmpPoints );
  17227. solid = isCCW ? ! solid : solid;
  17228. if ( solid ) {
  17229. if ( (! holesFirst ) && ( newShapes[mainIdx] ) ) mainIdx ++;
  17230. newShapes[mainIdx] = { s: new THREE.Shape(), p: tmpPoints };
  17231. newShapes[mainIdx].s.actions = tmpPath.actions;
  17232. newShapes[mainIdx].s.curves = tmpPath.curves;
  17233. if ( holesFirst ) mainIdx ++;
  17234. newShapeHoles[mainIdx] = [];
  17235. //console.log('cw', i);
  17236. } else {
  17237. newShapeHoles[mainIdx].push( { h: tmpPath, p: tmpPoints[0] } );
  17238. //console.log('ccw', i);
  17239. }
  17240. }
  17241. // only Holes? -> probably all Shapes with wrong orientation
  17242. if ( ! newShapes[0] ) return toShapesNoHoles( subPaths );
  17243. if ( newShapes.length > 1 ) {
  17244. var ambigious = false;
  17245. var toChange = [];
  17246. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  17247. betterShapeHoles[sIdx] = [];
  17248. }
  17249. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  17250. var sh = newShapes[sIdx];
  17251. var sho = newShapeHoles[sIdx];
  17252. for (var hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  17253. var ho = sho[hIdx];
  17254. var hole_unassigned = true;
  17255. for (var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  17256. if ( isPointInsidePolygon( ho.p, newShapes[s2Idx].p ) ) {
  17257. if ( sIdx != s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  17258. if ( hole_unassigned ) {
  17259. hole_unassigned = false;
  17260. betterShapeHoles[s2Idx].push( ho );
  17261. } else {
  17262. ambigious = true;
  17263. }
  17264. }
  17265. }
  17266. if ( hole_unassigned ) { betterShapeHoles[sIdx].push( ho ); }
  17267. }
  17268. }
  17269. // console.log("ambigious: ", ambigious);
  17270. if ( toChange.length > 0 ) {
  17271. // console.log("to change: ", toChange);
  17272. if (! ambigious) newShapeHoles = betterShapeHoles;
  17273. }
  17274. }
  17275. var tmpHoles, j, jl;
  17276. for ( i = 0, il = newShapes.length; i < il; i ++ ) {
  17277. tmpShape = newShapes[i].s;
  17278. shapes.push( tmpShape );
  17279. tmpHoles = newShapeHoles[i];
  17280. for ( j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  17281. tmpShape.holes.push( tmpHoles[j].h );
  17282. }
  17283. }
  17284. //console.log("shape", shapes);
  17285. return shapes;
  17286. };
  17287. // File:src/extras/core/Shape.js
  17288. /**
  17289. * @author zz85 / http://www.lab4games.net/zz85/blog
  17290. * Defines a 2d shape plane using paths.
  17291. **/
  17292. // STEP 1 Create a path.
  17293. // STEP 2 Turn path into shape.
  17294. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  17295. // STEP 3a - Extract points from each shape, turn to vertices
  17296. // STEP 3b - Triangulate each shape, add faces.
  17297. THREE.Shape = function () {
  17298. THREE.Path.apply( this, arguments );
  17299. this.holes = [];
  17300. };
  17301. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  17302. // Convenience method to return ExtrudeGeometry
  17303. THREE.Shape.prototype.extrude = function ( options ) {
  17304. var extruded = new THREE.ExtrudeGeometry( this, options );
  17305. return extruded;
  17306. };
  17307. // Convenience method to return ShapeGeometry
  17308. THREE.Shape.prototype.makeGeometry = function ( options ) {
  17309. var geometry = new THREE.ShapeGeometry( this, options );
  17310. return geometry;
  17311. };
  17312. // Get points of holes
  17313. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  17314. var i, il = this.holes.length, holesPts = [];
  17315. for ( i = 0; i < il; i ++ ) {
  17316. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  17317. }
  17318. return holesPts;
  17319. };
  17320. // Get points of holes (spaced by regular distance)
  17321. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  17322. var i, il = this.holes.length, holesPts = [];
  17323. for ( i = 0; i < il; i ++ ) {
  17324. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  17325. }
  17326. return holesPts;
  17327. };
  17328. // Get points of shape and holes (keypoints based on segments parameter)
  17329. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  17330. return {
  17331. shape: this.getTransformedPoints( divisions ),
  17332. holes: this.getPointsHoles( divisions )
  17333. };
  17334. };
  17335. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  17336. if (this.useSpacedPoints) {
  17337. return this.extractAllSpacedPoints(divisions);
  17338. }
  17339. return this.extractAllPoints(divisions);
  17340. };
  17341. //
  17342. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  17343. //
  17344. // return {
  17345. //
  17346. // shape: this.transform( bend, divisions ),
  17347. // holes: this.getPointsHoles( divisions, bend )
  17348. //
  17349. // };
  17350. //
  17351. // };
  17352. // Get points of shape and holes (spaced by regular distance)
  17353. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  17354. return {
  17355. shape: this.getTransformedSpacedPoints( divisions ),
  17356. holes: this.getSpacedPointsHoles( divisions )
  17357. };
  17358. };
  17359. /**************************************************************
  17360. * Utils
  17361. **************************************************************/
  17362. THREE.Shape.Utils = {
  17363. triangulateShape: function ( contour, holes ) {
  17364. function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) {
  17365. // inOtherPt needs to be colinear to the inSegment
  17366. if ( inSegPt1.x != inSegPt2.x ) {
  17367. if ( inSegPt1.x < inSegPt2.x ) {
  17368. return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) );
  17369. } else {
  17370. return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) );
  17371. }
  17372. } else {
  17373. if ( inSegPt1.y < inSegPt2.y ) {
  17374. return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) );
  17375. } else {
  17376. return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) );
  17377. }
  17378. }
  17379. }
  17380. function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) {
  17381. var EPSILON = 0.0000000001;
  17382. var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y;
  17383. var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y;
  17384. var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x;
  17385. var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y;
  17386. var limit = seg1dy * seg2dx - seg1dx * seg2dy;
  17387. var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy;
  17388. if ( Math.abs(limit) > EPSILON ) { // not parallel
  17389. var perpSeg2;
  17390. if ( limit > 0 ) {
  17391. if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return [];
  17392. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  17393. if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return [];
  17394. } else {
  17395. if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return [];
  17396. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  17397. if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return [];
  17398. }
  17399. // i.e. to reduce rounding errors
  17400. // intersection at endpoint of segment#1?
  17401. if ( perpSeg2 == 0 ) {
  17402. if ( ( inExcludeAdjacentSegs ) &&
  17403. ( ( perpSeg1 == 0 ) || ( perpSeg1 == limit ) ) ) return [];
  17404. return [ inSeg1Pt1 ];
  17405. }
  17406. if ( perpSeg2 == limit ) {
  17407. if ( ( inExcludeAdjacentSegs ) &&
  17408. ( ( perpSeg1 == 0 ) || ( perpSeg1 == limit ) ) ) return [];
  17409. return [ inSeg1Pt2 ];
  17410. }
  17411. // intersection at endpoint of segment#2?
  17412. if ( perpSeg1 == 0 ) return [ inSeg2Pt1 ];
  17413. if ( perpSeg1 == limit ) return [ inSeg2Pt2 ];
  17414. // return real intersection point
  17415. var factorSeg1 = perpSeg2 / limit;
  17416. return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx,
  17417. y: inSeg1Pt1.y + factorSeg1 * seg1dy } ];
  17418. } else { // parallel or colinear
  17419. if ( ( perpSeg1 != 0 ) ||
  17420. ( seg2dy * seg1seg2dx != seg2dx * seg1seg2dy ) ) return [];
  17421. // they are collinear or degenerate
  17422. var seg1Pt = ( (seg1dx == 0) && (seg1dy == 0) ); // segment1 ist just a point?
  17423. var seg2Pt = ( (seg2dx == 0) && (seg2dy == 0) ); // segment2 ist just a point?
  17424. // both segments are points
  17425. if ( seg1Pt && seg2Pt ) {
  17426. if ( (inSeg1Pt1.x != inSeg2Pt1.x) ||
  17427. (inSeg1Pt1.y != inSeg2Pt1.y) ) return []; // they are distinct points
  17428. return [ inSeg1Pt1 ]; // they are the same point
  17429. }
  17430. // segment#1 is a single point
  17431. if ( seg1Pt ) {
  17432. if (! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2
  17433. return [ inSeg1Pt1 ];
  17434. }
  17435. // segment#2 is a single point
  17436. if ( seg2Pt ) {
  17437. if (! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1
  17438. return [ inSeg2Pt1 ];
  17439. }
  17440. // they are collinear segments, which might overlap
  17441. var seg1min, seg1max, seg1minVal, seg1maxVal;
  17442. var seg2min, seg2max, seg2minVal, seg2maxVal;
  17443. if (seg1dx != 0) { // the segments are NOT on a vertical line
  17444. if ( inSeg1Pt1.x < inSeg1Pt2.x ) {
  17445. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x;
  17446. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x;
  17447. } else {
  17448. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x;
  17449. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x;
  17450. }
  17451. if ( inSeg2Pt1.x < inSeg2Pt2.x ) {
  17452. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x;
  17453. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x;
  17454. } else {
  17455. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x;
  17456. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x;
  17457. }
  17458. } else { // the segments are on a vertical line
  17459. if ( inSeg1Pt1.y < inSeg1Pt2.y ) {
  17460. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y;
  17461. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y;
  17462. } else {
  17463. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y;
  17464. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y;
  17465. }
  17466. if ( inSeg2Pt1.y < inSeg2Pt2.y ) {
  17467. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y;
  17468. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y;
  17469. } else {
  17470. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y;
  17471. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y;
  17472. }
  17473. }
  17474. if ( seg1minVal <= seg2minVal ) {
  17475. if ( seg1maxVal < seg2minVal ) return [];
  17476. if ( seg1maxVal == seg2minVal ) {
  17477. if ( inExcludeAdjacentSegs ) return [];
  17478. return [ seg2min ];
  17479. }
  17480. if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ];
  17481. return [ seg2min, seg2max ];
  17482. } else {
  17483. if ( seg1minVal > seg2maxVal ) return [];
  17484. if ( seg1minVal == seg2maxVal ) {
  17485. if ( inExcludeAdjacentSegs ) return [];
  17486. return [ seg1min ];
  17487. }
  17488. if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ];
  17489. return [ seg1min, seg2max ];
  17490. }
  17491. }
  17492. }
  17493. function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) {
  17494. // The order of legs is important
  17495. var EPSILON = 0.0000000001;
  17496. // translation of all points, so that Vertex is at (0,0)
  17497. var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y;
  17498. var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y;
  17499. var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y;
  17500. // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg.
  17501. var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX;
  17502. var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX;
  17503. if ( Math.abs(from2toAngle) > EPSILON ) { // angle != 180 deg.
  17504. var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX;
  17505. // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle );
  17506. if ( from2toAngle > 0 ) { // main angle < 180 deg.
  17507. return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) );
  17508. } else { // main angle > 180 deg.
  17509. return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) );
  17510. }
  17511. } else { // angle == 180 deg.
  17512. // console.log( "from2to: 180 deg., from2other: " + from2otherAngle );
  17513. return ( from2otherAngle > 0 );
  17514. }
  17515. }
  17516. function removeHoles( contour, holes ) {
  17517. var shape = contour.concat(); // work on this shape
  17518. var hole;
  17519. function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) {
  17520. // Check if hole point lies within angle around shape point
  17521. var lastShapeIdx = shape.length - 1;
  17522. var prevShapeIdx = inShapeIdx - 1;
  17523. if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx;
  17524. var nextShapeIdx = inShapeIdx + 1;
  17525. if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0;
  17526. var insideAngle = isPointInsideAngle( shape[inShapeIdx], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[inHoleIdx] );
  17527. if (! insideAngle ) {
  17528. // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y );
  17529. return false;
  17530. }
  17531. // Check if shape point lies within angle around hole point
  17532. var lastHoleIdx = hole.length - 1;
  17533. var prevHoleIdx = inHoleIdx - 1;
  17534. if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx;
  17535. var nextHoleIdx = inHoleIdx + 1;
  17536. if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0;
  17537. insideAngle = isPointInsideAngle( hole[inHoleIdx], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[inShapeIdx] );
  17538. if (! insideAngle ) {
  17539. // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y );
  17540. return false;
  17541. }
  17542. return true;
  17543. }
  17544. function intersectsShapeEdge( inShapePt, inHolePt ) {
  17545. // checks for intersections with shape edges
  17546. var sIdx, nextIdx, intersection;
  17547. for ( sIdx = 0; sIdx < shape.length; sIdx ++ ) {
  17548. nextIdx = sIdx+1; nextIdx %= shape.length;
  17549. intersection = intersect_segments_2D( inShapePt, inHolePt, shape[sIdx], shape[nextIdx], true );
  17550. if ( intersection.length > 0 ) return true;
  17551. }
  17552. return false;
  17553. }
  17554. var indepHoles = [];
  17555. function intersectsHoleEdge( inShapePt, inHolePt ) {
  17556. // checks for intersections with hole edges
  17557. var ihIdx, chkHole,
  17558. hIdx, nextIdx, intersection;
  17559. for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx ++ ) {
  17560. chkHole = holes[indepHoles[ihIdx]];
  17561. for ( hIdx = 0; hIdx < chkHole.length; hIdx ++ ) {
  17562. nextIdx = hIdx+1; nextIdx %= chkHole.length;
  17563. intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[hIdx], chkHole[nextIdx], true );
  17564. if ( intersection.length > 0 ) return true;
  17565. }
  17566. }
  17567. return false;
  17568. }
  17569. var holeIndex, shapeIndex,
  17570. shapePt, holePt,
  17571. holeIdx, cutKey, failedCuts = [],
  17572. tmpShape1, tmpShape2,
  17573. tmpHole1, tmpHole2;
  17574. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  17575. indepHoles.push( h );
  17576. }
  17577. var minShapeIndex = 0;
  17578. var counter = indepHoles.length * 2;
  17579. while ( indepHoles.length > 0 ) {
  17580. counter --;
  17581. if ( counter < 0 ) {
  17582. console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" );
  17583. break;
  17584. }
  17585. // search for shape-vertex and hole-vertex,
  17586. // which can be connected without intersections
  17587. for ( shapeIndex = minShapeIndex; shapeIndex < shape.length; shapeIndex ++ ) {
  17588. shapePt = shape[ shapeIndex ];
  17589. holeIndex = - 1;
  17590. // search for hole which can be reached without intersections
  17591. for ( var h = 0; h < indepHoles.length; h ++ ) {
  17592. holeIdx = indepHoles[h];
  17593. // prevent multiple checks
  17594. cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx;
  17595. if ( failedCuts[cutKey] !== undefined ) continue;
  17596. hole = holes[holeIdx];
  17597. for ( var h2 = 0; h2 < hole.length; h2 ++ ) {
  17598. holePt = hole[ h2 ];
  17599. if (! isCutLineInsideAngles( shapeIndex, h2 ) ) continue;
  17600. if ( intersectsShapeEdge( shapePt, holePt ) ) continue;
  17601. if ( intersectsHoleEdge( shapePt, holePt ) ) continue;
  17602. holeIndex = h2;
  17603. indepHoles.splice(h,1);
  17604. tmpShape1 = shape.slice( 0, shapeIndex+1 );
  17605. tmpShape2 = shape.slice( shapeIndex );
  17606. tmpHole1 = hole.slice( holeIndex );
  17607. tmpHole2 = hole.slice( 0, holeIndex+1 );
  17608. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  17609. minShapeIndex = shapeIndex;
  17610. // Debug only, to show the selected cuts
  17611. // glob_CutLines.push( [ shapePt, holePt ] );
  17612. break;
  17613. }
  17614. if ( holeIndex >= 0 ) break; // hole-vertex found
  17615. failedCuts[cutKey] = true; // remember failure
  17616. }
  17617. if ( holeIndex >= 0 ) break; // hole-vertex found
  17618. }
  17619. }
  17620. return shape; /* shape with no holes */
  17621. }
  17622. var i, il, f, face,
  17623. key, index,
  17624. allPointsMap = {};
  17625. // 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.
  17626. var allpoints = contour.concat();
  17627. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  17628. Array.prototype.push.apply( allpoints, holes[h] );
  17629. }
  17630. //console.log( "allpoints",allpoints, allpoints.length );
  17631. // prepare all points map
  17632. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  17633. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  17634. if ( allPointsMap[ key ] !== undefined ) {
  17635. console.log( "Duplicate point", key );
  17636. }
  17637. allPointsMap[ key ] = i;
  17638. }
  17639. // remove holes by cutting paths to holes and adding them to the shape
  17640. var shapeWithoutHoles = removeHoles( contour, holes );
  17641. var triangles = THREE.FontUtils.Triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape
  17642. //console.log( "triangles",triangles, triangles.length );
  17643. // check all face vertices against all points map
  17644. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  17645. face = triangles[ i ];
  17646. for ( f = 0; f < 3; f ++ ) {
  17647. key = face[ f ].x + ":" + face[ f ].y;
  17648. index = allPointsMap[ key ];
  17649. if ( index !== undefined ) {
  17650. face[ f ] = index;
  17651. }
  17652. }
  17653. }
  17654. return triangles.concat();
  17655. },
  17656. isClockWise: function ( pts ) {
  17657. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  17658. },
  17659. // Bezier Curves formulas obtained from
  17660. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  17661. // Quad Bezier Functions
  17662. b2p0: function ( t, p ) {
  17663. var k = 1 - t;
  17664. return k * k * p;
  17665. },
  17666. b2p1: function ( t, p ) {
  17667. return 2 * ( 1 - t ) * t * p;
  17668. },
  17669. b2p2: function ( t, p ) {
  17670. return t * t * p;
  17671. },
  17672. b2: function ( t, p0, p1, p2 ) {
  17673. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  17674. },
  17675. // Cubic Bezier Functions
  17676. b3p0: function ( t, p ) {
  17677. var k = 1 - t;
  17678. return k * k * k * p;
  17679. },
  17680. b3p1: function ( t, p ) {
  17681. var k = 1 - t;
  17682. return 3 * k * k * t * p;
  17683. },
  17684. b3p2: function ( t, p ) {
  17685. var k = 1 - t;
  17686. return 3 * k * t * t * p;
  17687. },
  17688. b3p3: function ( t, p ) {
  17689. return t * t * t * p;
  17690. },
  17691. b3: function ( t, p0, p1, p2, p3 ) {
  17692. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  17693. }
  17694. };
  17695. // File:src/extras/curves/LineCurve.js
  17696. /**************************************************************
  17697. * Line
  17698. **************************************************************/
  17699. THREE.LineCurve = function ( v1, v2 ) {
  17700. this.v1 = v1;
  17701. this.v2 = v2;
  17702. };
  17703. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  17704. THREE.LineCurve.prototype.getPoint = function ( t ) {
  17705. var point = this.v2.clone().sub(this.v1);
  17706. point.multiplyScalar( t ).add( this.v1 );
  17707. return point;
  17708. };
  17709. // Line curve is linear, so we can overwrite default getPointAt
  17710. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  17711. return this.getPoint( u );
  17712. };
  17713. THREE.LineCurve.prototype.getTangent = function( t ) {
  17714. var tangent = this.v2.clone().sub(this.v1);
  17715. return tangent.normalize();
  17716. };
  17717. // File:src/extras/curves/QuadraticBezierCurve.js
  17718. /**************************************************************
  17719. * Quadratic Bezier curve
  17720. **************************************************************/
  17721. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  17722. this.v0 = v0;
  17723. this.v1 = v1;
  17724. this.v2 = v2;
  17725. };
  17726. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  17727. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  17728. var tx, ty;
  17729. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  17730. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  17731. return new THREE.Vector2( tx, ty );
  17732. };
  17733. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  17734. var tx, ty;
  17735. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  17736. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  17737. // returns unit vector
  17738. var tangent = new THREE.Vector2( tx, ty );
  17739. tangent.normalize();
  17740. return tangent;
  17741. };
  17742. // File:src/extras/curves/CubicBezierCurve.js
  17743. /**************************************************************
  17744. * Cubic Bezier curve
  17745. **************************************************************/
  17746. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  17747. this.v0 = v0;
  17748. this.v1 = v1;
  17749. this.v2 = v2;
  17750. this.v3 = v3;
  17751. };
  17752. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  17753. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  17754. var tx, ty;
  17755. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17756. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17757. return new THREE.Vector2( tx, ty );
  17758. };
  17759. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  17760. var tx, ty;
  17761. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17762. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17763. var tangent = new THREE.Vector2( tx, ty );
  17764. tangent.normalize();
  17765. return tangent;
  17766. };
  17767. // File:src/extras/curves/SplineCurve.js
  17768. /**************************************************************
  17769. * Spline curve
  17770. **************************************************************/
  17771. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  17772. this.points = (points == undefined) ? [] : points;
  17773. };
  17774. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  17775. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  17776. var v = new THREE.Vector2();
  17777. var c = [];
  17778. var points = this.points, point, intPoint, weight;
  17779. point = ( points.length - 1 ) * t;
  17780. intPoint = Math.floor( point );
  17781. weight = point - intPoint;
  17782. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  17783. c[ 1 ] = intPoint;
  17784. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  17785. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  17786. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  17787. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  17788. return v;
  17789. };
  17790. // File:src/extras/curves/EllipseCurve.js
  17791. /**************************************************************
  17792. * Ellipse curve
  17793. **************************************************************/
  17794. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise ) {
  17795. this.aX = aX;
  17796. this.aY = aY;
  17797. this.xRadius = xRadius;
  17798. this.yRadius = yRadius;
  17799. this.aStartAngle = aStartAngle;
  17800. this.aEndAngle = aEndAngle;
  17801. this.aClockwise = aClockwise;
  17802. };
  17803. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  17804. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  17805. var angle;
  17806. var deltaAngle = this.aEndAngle - this.aStartAngle;
  17807. if ( deltaAngle < 0 ) deltaAngle += Math.PI * 2;
  17808. if ( deltaAngle > Math.PI * 2 ) deltaAngle -= Math.PI * 2;
  17809. if ( this.aClockwise === true ) {
  17810. angle = this.aEndAngle + ( 1 - t ) * ( Math.PI * 2 - deltaAngle );
  17811. } else {
  17812. angle = this.aStartAngle + t * deltaAngle;
  17813. }
  17814. var tx = this.aX + this.xRadius * Math.cos( angle );
  17815. var ty = this.aY + this.yRadius * Math.sin( angle );
  17816. return new THREE.Vector2( tx, ty );
  17817. };
  17818. // File:src/extras/curves/ArcCurve.js
  17819. /**************************************************************
  17820. * Arc curve
  17821. **************************************************************/
  17822. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  17823. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  17824. };
  17825. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  17826. // File:src/extras/curves/LineCurve3.js
  17827. /**************************************************************
  17828. * Line3D
  17829. **************************************************************/
  17830. THREE.LineCurve3 = THREE.Curve.create(
  17831. function ( v1, v2 ) {
  17832. this.v1 = v1;
  17833. this.v2 = v2;
  17834. },
  17835. function ( t ) {
  17836. var r = new THREE.Vector3();
  17837. r.subVectors( this.v2, this.v1 ); // diff
  17838. r.multiplyScalar( t );
  17839. r.add( this.v1 );
  17840. return r;
  17841. }
  17842. );
  17843. // File:src/extras/curves/QuadraticBezierCurve3.js
  17844. /**************************************************************
  17845. * Quadratic Bezier 3D curve
  17846. **************************************************************/
  17847. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  17848. function ( v0, v1, v2 ) {
  17849. this.v0 = v0;
  17850. this.v1 = v1;
  17851. this.v2 = v2;
  17852. },
  17853. function ( t ) {
  17854. var tx, ty, tz;
  17855. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  17856. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  17857. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  17858. return new THREE.Vector3( tx, ty, tz );
  17859. }
  17860. );
  17861. // File:src/extras/curves/CubicBezierCurve3.js
  17862. /**************************************************************
  17863. * Cubic Bezier 3D curve
  17864. **************************************************************/
  17865. THREE.CubicBezierCurve3 = THREE.Curve.create(
  17866. function ( v0, v1, v2, v3 ) {
  17867. this.v0 = v0;
  17868. this.v1 = v1;
  17869. this.v2 = v2;
  17870. this.v3 = v3;
  17871. },
  17872. function ( t ) {
  17873. var tx, ty, tz;
  17874. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17875. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17876. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  17877. return new THREE.Vector3( tx, ty, tz );
  17878. }
  17879. );
  17880. // File:src/extras/curves/SplineCurve3.js
  17881. /**************************************************************
  17882. * Spline 3D curve
  17883. **************************************************************/
  17884. THREE.SplineCurve3 = THREE.Curve.create(
  17885. function ( points /* array of Vector3 */) {
  17886. this.points = (points == undefined) ? [] : points;
  17887. },
  17888. function ( t ) {
  17889. var v = new THREE.Vector3();
  17890. var c = [];
  17891. var points = this.points, point, intPoint, weight;
  17892. point = ( points.length - 1 ) * t;
  17893. intPoint = Math.floor( point );
  17894. weight = point - intPoint;
  17895. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  17896. c[ 1 ] = intPoint;
  17897. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  17898. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  17899. var pt0 = points[ c[0] ],
  17900. pt1 = points[ c[1] ],
  17901. pt2 = points[ c[2] ],
  17902. pt3 = points[ c[3] ];
  17903. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  17904. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  17905. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  17906. return v;
  17907. }
  17908. );
  17909. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  17910. // var v = new THREE.Vector3();
  17911. // var c = [];
  17912. // var points = this.points, point, intPoint, weight;
  17913. // point = ( points.length - 1 ) * t;
  17914. // intPoint = Math.floor( point );
  17915. // weight = point - intPoint;
  17916. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  17917. // c[ 1 ] = intPoint;
  17918. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  17919. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  17920. // var pt0 = points[ c[0] ],
  17921. // pt1 = points[ c[1] ],
  17922. // pt2 = points[ c[2] ],
  17923. // pt3 = points[ c[3] ];
  17924. // // t = weight;
  17925. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  17926. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  17927. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  17928. // return v;
  17929. // }
  17930. // File:src/extras/curves/ClosedSplineCurve3.js
  17931. /**************************************************************
  17932. * Closed Spline 3D curve
  17933. **************************************************************/
  17934. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  17935. function ( points /* array of Vector3 */) {
  17936. this.points = (points == undefined) ? [] : points;
  17937. },
  17938. function ( t ) {
  17939. var v = new THREE.Vector3();
  17940. var c = [];
  17941. var points = this.points, point, intPoint, weight;
  17942. point = ( points.length - 0 ) * t;
  17943. // This needs to be from 0-length +1
  17944. intPoint = Math.floor( point );
  17945. weight = point - intPoint;
  17946. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  17947. c[ 0 ] = ( intPoint - 1 ) % points.length;
  17948. c[ 1 ] = ( intPoint ) % points.length;
  17949. c[ 2 ] = ( intPoint + 1 ) % points.length;
  17950. c[ 3 ] = ( intPoint + 2 ) % points.length;
  17951. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  17952. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  17953. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  17954. return v;
  17955. }
  17956. );
  17957. // File:src/extras/animation/AnimationHandler.js
  17958. /**
  17959. * @author mikael emtinger / http://gomo.se/
  17960. */
  17961. THREE.AnimationHandler = {
  17962. LINEAR: 0,
  17963. CATMULLROM: 1,
  17964. CATMULLROM_FORWARD: 2,
  17965. //
  17966. add: function () { console.warn( 'THREE.AnimationHandler.add() has been deprecated.' ); },
  17967. get: function () { console.warn( 'THREE.AnimationHandler.get() has been deprecated.' ); },
  17968. remove: function () { console.warn( 'THREE.AnimationHandler.remove() has been deprecated.' ); },
  17969. //
  17970. animations: [],
  17971. init: function ( data ) {
  17972. if ( data.initialized === true ) return;
  17973. // loop through all keys
  17974. for ( var h = 0; h < data.hierarchy.length; h ++ ) {
  17975. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17976. // remove minus times
  17977. if ( data.hierarchy[ h ].keys[ k ].time < 0 ) {
  17978. data.hierarchy[ h ].keys[ k ].time = 0;
  17979. }
  17980. // create quaternions
  17981. if ( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  17982. ! ( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  17983. var quat = data.hierarchy[ h ].keys[ k ].rot;
  17984. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion().fromArray( quat );
  17985. }
  17986. }
  17987. // prepare morph target keys
  17988. if ( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  17989. // get all used
  17990. var usedMorphTargets = {};
  17991. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17992. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17993. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  17994. usedMorphTargets[ morphTargetName ] = - 1;
  17995. }
  17996. }
  17997. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  17998. // set all used on all frames
  17999. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18000. var influences = {};
  18001. for ( var morphTargetName in usedMorphTargets ) {
  18002. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  18003. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  18004. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  18005. break;
  18006. }
  18007. }
  18008. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  18009. influences[ morphTargetName ] = 0;
  18010. }
  18011. }
  18012. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  18013. }
  18014. }
  18015. // remove all keys that are on the same time
  18016. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18017. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  18018. data.hierarchy[ h ].keys.splice( k, 1 );
  18019. k --;
  18020. }
  18021. }
  18022. // set index
  18023. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18024. data.hierarchy[ h ].keys[ k ].index = k;
  18025. }
  18026. }
  18027. data.initialized = true;
  18028. return data;
  18029. },
  18030. parse: function ( root ) {
  18031. var parseRecurseHierarchy = function ( root, hierarchy ) {
  18032. hierarchy.push( root );
  18033. for ( var c = 0; c < root.children.length; c ++ )
  18034. parseRecurseHierarchy( root.children[ c ], hierarchy );
  18035. };
  18036. // setup hierarchy
  18037. var hierarchy = [];
  18038. if ( root instanceof THREE.SkinnedMesh ) {
  18039. for ( var b = 0; b < root.skeleton.bones.length; b ++ ) {
  18040. hierarchy.push( root.skeleton.bones[ b ] );
  18041. }
  18042. } else {
  18043. parseRecurseHierarchy( root, hierarchy );
  18044. }
  18045. return hierarchy;
  18046. },
  18047. play: function ( animation ) {
  18048. if ( this.animations.indexOf( animation ) === - 1 ) {
  18049. this.animations.push( animation );
  18050. }
  18051. },
  18052. stop: function ( animation ) {
  18053. var index = this.animations.indexOf( animation );
  18054. if ( index !== - 1 ) {
  18055. this.animations.splice( index, 1 );
  18056. }
  18057. },
  18058. update: function ( deltaTimeMS ) {
  18059. for ( var i = 0; i < this.animations.length; i ++ ) {
  18060. this.animations[ i ].update( deltaTimeMS );
  18061. }
  18062. }
  18063. };
  18064. // File:src/extras/animation/Animation.js
  18065. /**
  18066. * @author mikael emtinger / http://gomo.se/
  18067. * @author mrdoob / http://mrdoob.com/
  18068. * @author alteredq / http://alteredqualia.com/
  18069. */
  18070. THREE.Animation = function ( root, data ) {
  18071. this.root = root;
  18072. this.data = THREE.AnimationHandler.init( data );
  18073. this.hierarchy = THREE.AnimationHandler.parse( root );
  18074. this.currentTime = 0;
  18075. this.timeScale = 1;
  18076. this.isPlaying = false;
  18077. this.loop = true;
  18078. this.weight = 0;
  18079. this.interpolationType = THREE.AnimationHandler.LINEAR;
  18080. };
  18081. THREE.Animation.prototype.keyTypes = [ "pos", "rot", "scl" ];
  18082. THREE.Animation.prototype.play = function ( startTime, weight ) {
  18083. this.currentTime = startTime !== undefined ? startTime : 0;
  18084. this.weight = weight !== undefined ? weight: 1;
  18085. this.isPlaying = true;
  18086. this.reset();
  18087. THREE.AnimationHandler.play( this );
  18088. };
  18089. THREE.Animation.prototype.stop = function() {
  18090. this.isPlaying = false;
  18091. THREE.AnimationHandler.stop( this );
  18092. };
  18093. THREE.Animation.prototype.reset = function () {
  18094. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18095. var object = this.hierarchy[ h ];
  18096. object.matrixAutoUpdate = true;
  18097. if ( object.animationCache === undefined ) {
  18098. object.animationCache = {};
  18099. }
  18100. if ( object.animationCache[this.data.name] === undefined ) {
  18101. object.animationCache[this.data.name] = {};
  18102. object.animationCache[this.data.name].prevKey = { pos: 0, rot: 0, scl: 0 };
  18103. object.animationCache[this.data.name].nextKey = { pos: 0, rot: 0, scl: 0 };
  18104. object.animationCache[this.data.name].originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18105. }
  18106. var animationCache = object.animationCache[this.data.name];
  18107. // Get keys to match our current time
  18108. for ( var t = 0; t < 3; t ++ ) {
  18109. var type = this.keyTypes[ t ];
  18110. var prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  18111. var nextKey = this.getNextKeyWith( type, h, 1 );
  18112. while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {
  18113. prevKey = nextKey;
  18114. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  18115. }
  18116. animationCache.prevKey[ type ] = prevKey;
  18117. animationCache.nextKey[ type ] = nextKey;
  18118. }
  18119. }
  18120. };
  18121. THREE.Animation.prototype.update = (function(){
  18122. var points = [];
  18123. var target = new THREE.Vector3();
  18124. var newVector = new THREE.Vector3();
  18125. var newQuat = new THREE.Quaternion();
  18126. // Catmull-Rom spline
  18127. var interpolateCatmullRom = function ( points, scale ) {
  18128. var c = [], v3 = [],
  18129. point, intPoint, weight, w2, w3,
  18130. pa, pb, pc, pd;
  18131. point = ( points.length - 1 ) * scale;
  18132. intPoint = Math.floor( point );
  18133. weight = point - intPoint;
  18134. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  18135. c[ 1 ] = intPoint;
  18136. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  18137. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  18138. pa = points[ c[ 0 ] ];
  18139. pb = points[ c[ 1 ] ];
  18140. pc = points[ c[ 2 ] ];
  18141. pd = points[ c[ 3 ] ];
  18142. w2 = weight * weight;
  18143. w3 = weight * w2;
  18144. v3[ 0 ] = interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  18145. v3[ 1 ] = interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  18146. v3[ 2 ] = interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  18147. return v3;
  18148. };
  18149. var interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  18150. var v0 = ( p2 - p0 ) * 0.5,
  18151. v1 = ( p3 - p1 ) * 0.5;
  18152. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  18153. };
  18154. return function ( delta ) {
  18155. if ( this.isPlaying === false ) return;
  18156. this.currentTime += delta * this.timeScale;
  18157. if ( this.weight === 0 )
  18158. return;
  18159. //
  18160. var duration = this.data.length;
  18161. if ( this.loop === true && this.currentTime > duration ) {
  18162. this.currentTime %= duration;
  18163. this.reset();
  18164. } else if ( this.loop === false && this.currentTime > duration ) {
  18165. this.stop();
  18166. return;
  18167. }
  18168. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18169. var object = this.hierarchy[ h ];
  18170. var animationCache = object.animationCache[this.data.name];
  18171. // loop through pos/rot/scl
  18172. for ( var t = 0; t < 3; t ++ ) {
  18173. // get keys
  18174. var type = this.keyTypes[ t ];
  18175. var prevKey = animationCache.prevKey[ type ];
  18176. var nextKey = animationCache.nextKey[ type ];
  18177. if ( nextKey.time <= this.currentTime ) {
  18178. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  18179. nextKey = this.getNextKeyWith( type, h, 1 );
  18180. while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {
  18181. prevKey = nextKey;
  18182. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  18183. }
  18184. animationCache.prevKey[ type ] = prevKey;
  18185. animationCache.nextKey[ type ] = nextKey;
  18186. }
  18187. object.matrixAutoUpdate = true;
  18188. object.matrixWorldNeedsUpdate = true;
  18189. var scale = ( this.currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  18190. var prevXYZ = prevKey[ type ];
  18191. var nextXYZ = nextKey[ type ];
  18192. if ( scale < 0 ) scale = 0;
  18193. if ( scale > 1 ) scale = 1;
  18194. // interpolate
  18195. if ( type === "pos" ) {
  18196. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  18197. newVector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18198. newVector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18199. newVector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18200. // blend
  18201. if ( object instanceof THREE.Bone ) {
  18202. var proportionalWeight = this.weight / ( this.weight + object.accumulatedPosWeight );
  18203. object.position.lerp( newVector, proportionalWeight );
  18204. object.accumulatedPosWeight += this.weight;
  18205. } else {
  18206. object.position.copy( newVector );
  18207. }
  18208. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18209. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18210. points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  18211. points[ 1 ] = prevXYZ;
  18212. points[ 2 ] = nextXYZ;
  18213. points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  18214. scale = scale * 0.33 + 0.33;
  18215. var currentPoint = interpolateCatmullRom( points, scale );
  18216. var proportionalWeight = 1;
  18217. if ( object instanceof THREE.Bone ) {
  18218. proportionalWeight = this.weight / ( this.weight + object.accumulatedPosWeight );
  18219. object.accumulatedPosWeight += this.weight;
  18220. }
  18221. // blend
  18222. var vector = object.position;
  18223. vector.x = vector.x + ( currentPoint[ 0 ] - vector.x ) * proportionalWeight;
  18224. vector.y = vector.y + ( currentPoint[ 1 ] - vector.y ) * proportionalWeight;
  18225. vector.z = vector.z + ( currentPoint[ 2 ] - vector.z ) * proportionalWeight;
  18226. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18227. var forwardPoint = interpolateCatmullRom( points, scale * 1.01 );
  18228. target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  18229. target.sub( vector );
  18230. target.y = 0;
  18231. target.normalize();
  18232. var angle = Math.atan2( target.x, target.z );
  18233. object.rotation.set( 0, angle, 0 );
  18234. }
  18235. }
  18236. } else if ( type === "rot" ) {
  18237. THREE.Quaternion.slerp( prevXYZ, nextXYZ, newQuat, scale );
  18238. // Avoid paying the cost of an additional slerp if we don't have to
  18239. if ( ! ( object instanceof THREE.Bone ) ) {
  18240. object.quaternion.copy(newQuat);
  18241. } else if ( object.accumulatedRotWeight === 0 ) {
  18242. object.quaternion.copy(newQuat);
  18243. object.accumulatedRotWeight = this.weight;
  18244. } else {
  18245. var proportionalWeight = this.weight / ( this.weight + object.accumulatedRotWeight );
  18246. THREE.Quaternion.slerp( object.quaternion, newQuat, object.quaternion, proportionalWeight );
  18247. object.accumulatedRotWeight += this.weight;
  18248. }
  18249. } else if ( type === "scl" ) {
  18250. newVector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18251. newVector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18252. newVector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18253. if ( object instanceof THREE.Bone ) {
  18254. var proportionalWeight = this.weight / ( this.weight + object.accumulatedSclWeight);
  18255. object.scale.lerp( newVector, proportionalWeight );
  18256. object.accumulatedSclWeight += this.weight;
  18257. } else {
  18258. object.scale.copy( newVector );
  18259. }
  18260. }
  18261. }
  18262. }
  18263. return true;
  18264. };
  18265. })();
  18266. // Get next key with
  18267. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  18268. var keys = this.data.hierarchy[ h ].keys;
  18269. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18270. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18271. key = key < keys.length - 1 ? key : keys.length - 1;
  18272. } else {
  18273. key = key % keys.length;
  18274. }
  18275. for ( ; key < keys.length; key ++ ) {
  18276. if ( keys[ key ][ type ] !== undefined ) {
  18277. return keys[ key ];
  18278. }
  18279. }
  18280. return this.data.hierarchy[ h ].keys[ 0 ];
  18281. };
  18282. // Get previous key with
  18283. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  18284. var keys = this.data.hierarchy[ h ].keys;
  18285. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18286. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18287. key = key > 0 ? key : 0;
  18288. } else {
  18289. key = key >= 0 ? key : key + keys.length;
  18290. }
  18291. for ( ; key >= 0; key -- ) {
  18292. if ( keys[ key ][ type ] !== undefined ) {
  18293. return keys[ key ];
  18294. }
  18295. }
  18296. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  18297. };
  18298. // File:src/extras/animation/KeyFrameAnimation.js
  18299. /**
  18300. * @author mikael emtinger / http://gomo.se/
  18301. * @author mrdoob / http://mrdoob.com/
  18302. * @author alteredq / http://alteredqualia.com/
  18303. * @author khang duong
  18304. * @author erik kitson
  18305. */
  18306. THREE.KeyFrameAnimation = function ( data ) {
  18307. this.root = data.node;
  18308. this.data = THREE.AnimationHandler.init( data );
  18309. this.hierarchy = THREE.AnimationHandler.parse( this.root );
  18310. this.currentTime = 0;
  18311. this.timeScale = 0.001;
  18312. this.isPlaying = false;
  18313. this.isPaused = true;
  18314. this.loop = true;
  18315. // initialize to first keyframes
  18316. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18317. var keys = this.data.hierarchy[h].keys,
  18318. sids = this.data.hierarchy[h].sids,
  18319. obj = this.hierarchy[h];
  18320. if ( keys.length && sids ) {
  18321. for ( var s = 0; s < sids.length; s ++ ) {
  18322. var sid = sids[ s ],
  18323. next = this.getNextKeyWith( sid, h, 0 );
  18324. if ( next ) {
  18325. next.apply( sid );
  18326. }
  18327. }
  18328. obj.matrixAutoUpdate = false;
  18329. this.data.hierarchy[h].node.updateMatrix();
  18330. obj.matrixWorldNeedsUpdate = true;
  18331. }
  18332. }
  18333. };
  18334. THREE.KeyFrameAnimation.prototype.play = function ( startTime ) {
  18335. this.currentTime = startTime !== undefined ? startTime : 0;
  18336. if ( this.isPlaying === false ) {
  18337. this.isPlaying = true;
  18338. // reset key cache
  18339. var h, hl = this.hierarchy.length,
  18340. object,
  18341. node;
  18342. for ( h = 0; h < hl; h ++ ) {
  18343. object = this.hierarchy[ h ];
  18344. node = this.data.hierarchy[ h ];
  18345. if ( node.animationCache === undefined ) {
  18346. node.animationCache = {};
  18347. node.animationCache.prevKey = null;
  18348. node.animationCache.nextKey = null;
  18349. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18350. }
  18351. var keys = this.data.hierarchy[h].keys;
  18352. if (keys.length) {
  18353. node.animationCache.prevKey = keys[ 0 ];
  18354. node.animationCache.nextKey = keys[ 1 ];
  18355. this.startTime = Math.min( keys[0].time, this.startTime );
  18356. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  18357. }
  18358. }
  18359. this.update( 0 );
  18360. }
  18361. this.isPaused = false;
  18362. THREE.AnimationHandler.play( this );
  18363. };
  18364. THREE.KeyFrameAnimation.prototype.stop = function() {
  18365. this.isPlaying = false;
  18366. this.isPaused = false;
  18367. THREE.AnimationHandler.stop( this );
  18368. // reset JIT matrix and remove cache
  18369. for ( var h = 0; h < this.data.hierarchy.length; h ++ ) {
  18370. var obj = this.hierarchy[ h ];
  18371. var node = this.data.hierarchy[ h ];
  18372. if ( node.animationCache !== undefined ) {
  18373. var original = node.animationCache.originalMatrix;
  18374. if( obj instanceof THREE.Bone ) {
  18375. original.copy( obj.skinMatrix );
  18376. obj.skinMatrix = original;
  18377. } else {
  18378. original.copy( obj.matrix );
  18379. obj.matrix = original;
  18380. }
  18381. delete node.animationCache;
  18382. }
  18383. }
  18384. };
  18385. // Update
  18386. THREE.KeyFrameAnimation.prototype.update = function ( delta ) {
  18387. if ( this.isPlaying === false ) return;
  18388. this.currentTime += delta * this.timeScale;
  18389. //
  18390. var duration = this.data.length;
  18391. if ( this.loop === true && this.currentTime > duration ) {
  18392. this.currentTime %= duration;
  18393. }
  18394. this.currentTime = Math.min( this.currentTime, duration );
  18395. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18396. var object = this.hierarchy[ h ];
  18397. var node = this.data.hierarchy[ h ];
  18398. var keys = node.keys,
  18399. animationCache = node.animationCache;
  18400. if ( keys.length ) {
  18401. var prevKey = animationCache.prevKey;
  18402. var nextKey = animationCache.nextKey;
  18403. if ( nextKey.time <= this.currentTime ) {
  18404. while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {
  18405. prevKey = nextKey;
  18406. nextKey = keys[ prevKey.index + 1 ];
  18407. }
  18408. animationCache.prevKey = prevKey;
  18409. animationCache.nextKey = nextKey;
  18410. }
  18411. if ( nextKey.time >= this.currentTime ) {
  18412. prevKey.interpolate( nextKey, this.currentTime );
  18413. } else {
  18414. prevKey.interpolate( nextKey, nextKey.time );
  18415. }
  18416. this.data.hierarchy[ h ].node.updateMatrix();
  18417. object.matrixWorldNeedsUpdate = true;
  18418. }
  18419. }
  18420. };
  18421. // Get next key with
  18422. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  18423. var keys = this.data.hierarchy[ h ].keys;
  18424. key = key % keys.length;
  18425. for ( ; key < keys.length; key ++ ) {
  18426. if ( keys[ key ].hasTarget( sid ) ) {
  18427. return keys[ key ];
  18428. }
  18429. }
  18430. return keys[ 0 ];
  18431. };
  18432. // Get previous key with
  18433. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  18434. var keys = this.data.hierarchy[ h ].keys;
  18435. key = key >= 0 ? key : key + keys.length;
  18436. for ( ; key >= 0; key -- ) {
  18437. if ( keys[ key ].hasTarget( sid ) ) {
  18438. return keys[ key ];
  18439. }
  18440. }
  18441. return keys[ keys.length - 1 ];
  18442. };
  18443. // File:src/extras/animation/MorphAnimation.js
  18444. /**
  18445. * @author mrdoob / http://mrdoob.com
  18446. */
  18447. THREE.MorphAnimation = function ( mesh ) {
  18448. this.mesh = mesh;
  18449. this.frames = mesh.morphTargetInfluences.length;
  18450. this.currentTime = 0;
  18451. this.duration = 1000;
  18452. this.loop = true;
  18453. this.isPlaying = false;
  18454. };
  18455. THREE.MorphAnimation.prototype = {
  18456. play: function () {
  18457. this.isPlaying = true;
  18458. },
  18459. pause: function () {
  18460. this.isPlaying = false;
  18461. },
  18462. update: ( function () {
  18463. var lastFrame = 0;
  18464. var currentFrame = 0;
  18465. return function ( delta ) {
  18466. if ( this.isPlaying === false ) return;
  18467. this.currentTime += delta;
  18468. if ( this.loop === true && this.currentTime > this.duration ) {
  18469. this.currentTime %= this.duration;
  18470. }
  18471. this.currentTime = Math.min( this.currentTime, this.duration );
  18472. var interpolation = this.duration / this.frames;
  18473. var frame = Math.floor( this.currentTime / interpolation );
  18474. if ( frame != currentFrame ) {
  18475. this.mesh.morphTargetInfluences[ lastFrame ] = 0;
  18476. this.mesh.morphTargetInfluences[ currentFrame ] = 1;
  18477. this.mesh.morphTargetInfluences[ frame ] = 0;
  18478. lastFrame = currentFrame;
  18479. currentFrame = frame;
  18480. }
  18481. this.mesh.morphTargetInfluences[ frame ] = ( this.currentTime % interpolation ) / interpolation;
  18482. this.mesh.morphTargetInfluences[ lastFrame ] = 1 - this.mesh.morphTargetInfluences[ frame ];
  18483. }
  18484. } )()
  18485. };
  18486. // File:src/extras/geometries/BoxGeometry.js
  18487. /**
  18488. * @author mrdoob / http://mrdoob.com/
  18489. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  18490. */
  18491. THREE.BoxGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  18492. THREE.Geometry.call( this );
  18493. this.parameters = {
  18494. width: width,
  18495. height: height,
  18496. depth: depth,
  18497. widthSegments: widthSegments,
  18498. heightSegments: heightSegments,
  18499. depthSegments: depthSegments
  18500. };
  18501. this.widthSegments = widthSegments || 1;
  18502. this.heightSegments = heightSegments || 1;
  18503. this.depthSegments = depthSegments || 1;
  18504. var scope = this;
  18505. var width_half = width / 2;
  18506. var height_half = height / 2;
  18507. var depth_half = depth / 2;
  18508. buildPlane( 'z', 'y', - 1, - 1, depth, height, width_half, 0 ); // px
  18509. buildPlane( 'z', 'y', 1, - 1, depth, height, - width_half, 1 ); // nx
  18510. buildPlane( 'x', 'z', 1, 1, width, depth, height_half, 2 ); // py
  18511. buildPlane( 'x', 'z', 1, - 1, width, depth, - height_half, 3 ); // ny
  18512. buildPlane( 'x', 'y', 1, - 1, width, height, depth_half, 4 ); // pz
  18513. buildPlane( 'x', 'y', - 1, - 1, width, height, - depth_half, 5 ); // nz
  18514. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  18515. var w, ix, iy,
  18516. gridX = scope.widthSegments,
  18517. gridY = scope.heightSegments,
  18518. width_half = width / 2,
  18519. height_half = height / 2,
  18520. offset = scope.vertices.length;
  18521. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  18522. w = 'z';
  18523. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  18524. w = 'y';
  18525. gridY = scope.depthSegments;
  18526. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  18527. w = 'x';
  18528. gridX = scope.depthSegments;
  18529. }
  18530. var gridX1 = gridX + 1,
  18531. gridY1 = gridY + 1,
  18532. segment_width = width / gridX,
  18533. segment_height = height / gridY,
  18534. normal = new THREE.Vector3();
  18535. normal[ w ] = depth > 0 ? 1 : - 1;
  18536. for ( iy = 0; iy < gridY1; iy ++ ) {
  18537. for ( ix = 0; ix < gridX1; ix ++ ) {
  18538. var vector = new THREE.Vector3();
  18539. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  18540. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  18541. vector[ w ] = depth;
  18542. scope.vertices.push( vector );
  18543. }
  18544. }
  18545. for ( iy = 0; iy < gridY; iy ++ ) {
  18546. for ( ix = 0; ix < gridX; ix ++ ) {
  18547. var a = ix + gridX1 * iy;
  18548. var b = ix + gridX1 * ( iy + 1 );
  18549. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  18550. var d = ( ix + 1 ) + gridX1 * iy;
  18551. var uva = new THREE.Vector2( ix / gridX, 1 - iy / gridY );
  18552. var uvb = new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY );
  18553. var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iy + 1 ) / gridY );
  18554. var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY );
  18555. var face = new THREE.Face3( a + offset, b + offset, d + offset );
  18556. face.normal.copy( normal );
  18557. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  18558. face.materialIndex = materialIndex;
  18559. scope.faces.push( face );
  18560. scope.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  18561. face = new THREE.Face3( b + offset, c + offset, d + offset );
  18562. face.normal.copy( normal );
  18563. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  18564. face.materialIndex = materialIndex;
  18565. scope.faces.push( face );
  18566. scope.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  18567. }
  18568. }
  18569. }
  18570. this.mergeVertices();
  18571. };
  18572. THREE.BoxGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18573. // File:src/extras/geometries/CircleGeometry.js
  18574. /**
  18575. * @author hughes
  18576. */
  18577. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  18578. THREE.Geometry.call( this );
  18579. this.parameters = {
  18580. radius: radius,
  18581. segments: segments,
  18582. thetaStart: thetaStart,
  18583. thetaLength: thetaLength
  18584. };
  18585. radius = radius || 50;
  18586. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  18587. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18588. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  18589. var i, uvs = [],
  18590. center = new THREE.Vector3(), centerUV = new THREE.Vector2( 0.5, 0.5 );
  18591. this.vertices.push(center);
  18592. uvs.push( centerUV );
  18593. for ( i = 0; i <= segments; i ++ ) {
  18594. var vertex = new THREE.Vector3();
  18595. var segment = thetaStart + i / segments * thetaLength;
  18596. vertex.x = radius * Math.cos( segment );
  18597. vertex.y = radius * Math.sin( segment );
  18598. this.vertices.push( vertex );
  18599. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, ( vertex.y / radius + 1 ) / 2 ) );
  18600. }
  18601. var n = new THREE.Vector3( 0, 0, 1 );
  18602. for ( i = 1; i <= segments; i ++ ) {
  18603. this.faces.push( new THREE.Face3( i, i + 1, 0, [ n.clone(), n.clone(), n.clone() ] ) );
  18604. this.faceVertexUvs[ 0 ].push( [ uvs[ i ].clone(), uvs[ i + 1 ].clone(), centerUV.clone() ] );
  18605. }
  18606. this.computeFaceNormals();
  18607. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  18608. };
  18609. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18610. // File:src/extras/geometries/CubeGeometry.js
  18611. /**
  18612. * @author mrdoob / http://mrdoob.com/
  18613. */
  18614. THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  18615. console.warn( 'THEE.CubeGeometry has been renamed to THREE.BoxGeometry.' );
  18616. return new THREE.BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments );
  18617. };
  18618. // File:src/extras/geometries/CylinderGeometry.js
  18619. /**
  18620. * @author mrdoob / http://mrdoob.com/
  18621. */
  18622. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded ) {
  18623. THREE.Geometry.call( this );
  18624. this.parameters = {
  18625. radiusTop: radiusTop,
  18626. radiusBottom: radiusBottom,
  18627. height: height,
  18628. radialSegments: radialSegments,
  18629. heightSegments: heightSegments,
  18630. openEnded: openEnded
  18631. };
  18632. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  18633. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  18634. height = height !== undefined ? height : 100;
  18635. radialSegments = radialSegments || 8;
  18636. heightSegments = heightSegments || 1;
  18637. openEnded = openEnded !== undefined ? openEnded : false;
  18638. var heightHalf = height / 2;
  18639. var x, y, vertices = [], uvs = [];
  18640. for ( y = 0; y <= heightSegments; y ++ ) {
  18641. var verticesRow = [];
  18642. var uvsRow = [];
  18643. var v = y / heightSegments;
  18644. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  18645. for ( x = 0; x <= radialSegments; x ++ ) {
  18646. var u = x / radialSegments;
  18647. var vertex = new THREE.Vector3();
  18648. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  18649. vertex.y = - v * height + heightHalf;
  18650. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  18651. this.vertices.push( vertex );
  18652. verticesRow.push( this.vertices.length - 1 );
  18653. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  18654. }
  18655. vertices.push( verticesRow );
  18656. uvs.push( uvsRow );
  18657. }
  18658. var tanTheta = ( radiusBottom - radiusTop ) / height;
  18659. var na, nb;
  18660. for ( x = 0; x < radialSegments; x ++ ) {
  18661. if ( radiusTop !== 0 ) {
  18662. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  18663. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  18664. } else {
  18665. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  18666. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  18667. }
  18668. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  18669. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  18670. for ( y = 0; y < heightSegments; y ++ ) {
  18671. var v1 = vertices[ y ][ x ];
  18672. var v2 = vertices[ y + 1 ][ x ];
  18673. var v3 = vertices[ y + 1 ][ x + 1 ];
  18674. var v4 = vertices[ y ][ x + 1 ];
  18675. var n1 = na.clone();
  18676. var n2 = na.clone();
  18677. var n3 = nb.clone();
  18678. var n4 = nb.clone();
  18679. var uv1 = uvs[ y ][ x ].clone();
  18680. var uv2 = uvs[ y + 1 ][ x ].clone();
  18681. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  18682. var uv4 = uvs[ y ][ x + 1 ].clone();
  18683. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  18684. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  18685. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  18686. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  18687. }
  18688. }
  18689. // top cap
  18690. if ( openEnded === false && radiusTop > 0 ) {
  18691. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  18692. for ( x = 0; x < radialSegments; x ++ ) {
  18693. var v1 = vertices[ 0 ][ x ];
  18694. var v2 = vertices[ 0 ][ x + 1 ];
  18695. var v3 = this.vertices.length - 1;
  18696. var n1 = new THREE.Vector3( 0, 1, 0 );
  18697. var n2 = new THREE.Vector3( 0, 1, 0 );
  18698. var n3 = new THREE.Vector3( 0, 1, 0 );
  18699. var uv1 = uvs[ 0 ][ x ].clone();
  18700. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  18701. var uv3 = new THREE.Vector2( uv2.x, 0 );
  18702. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18703. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18704. }
  18705. }
  18706. // bottom cap
  18707. if ( openEnded === false && radiusBottom > 0 ) {
  18708. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  18709. for ( x = 0; x < radialSegments; x ++ ) {
  18710. var v1 = vertices[ y ][ x + 1 ];
  18711. var v2 = vertices[ y ][ x ];
  18712. var v3 = this.vertices.length - 1;
  18713. var n1 = new THREE.Vector3( 0, - 1, 0 );
  18714. var n2 = new THREE.Vector3( 0, - 1, 0 );
  18715. var n3 = new THREE.Vector3( 0, - 1, 0 );
  18716. var uv1 = uvs[ y ][ x + 1 ].clone();
  18717. var uv2 = uvs[ y ][ x ].clone();
  18718. var uv3 = new THREE.Vector2( uv2.x, 1 );
  18719. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18720. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18721. }
  18722. }
  18723. this.computeFaceNormals();
  18724. }
  18725. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18726. // File:src/extras/geometries/ExtrudeGeometry.js
  18727. /**
  18728. * @author zz85 / http://www.lab4games.net/zz85/blog
  18729. *
  18730. * Creates extruded geometry from a path shape.
  18731. *
  18732. * parameters = {
  18733. *
  18734. * curveSegments: <int>, // number of points on the curves
  18735. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  18736. * amount: <int>, // Depth to extrude the shape
  18737. *
  18738. * bevelEnabled: <bool>, // turn on bevel
  18739. * bevelThickness: <float>, // how deep into the original shape bevel goes
  18740. * bevelSize: <float>, // how far from shape outline is bevel
  18741. * bevelSegments: <int>, // number of bevel layers
  18742. *
  18743. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  18744. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  18745. *
  18746. * material: <int> // material index for front and back faces
  18747. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  18748. * uvGenerator: <Object> // object that provides UV generator functions
  18749. *
  18750. * }
  18751. **/
  18752. THREE.ExtrudeGeometry = function ( shapes, options ) {
  18753. if ( typeof( shapes ) === "undefined" ) {
  18754. shapes = [];
  18755. return;
  18756. }
  18757. THREE.Geometry.call( this );
  18758. shapes = shapes instanceof Array ? shapes : [ shapes ];
  18759. this.addShapeList( shapes, options );
  18760. this.computeFaceNormals();
  18761. // can't really use automatic vertex normals
  18762. // as then front and back sides get smoothed too
  18763. // should do separate smoothing just for sides
  18764. //this.computeVertexNormals();
  18765. //console.log( "took", ( Date.now() - startTime ) );
  18766. };
  18767. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18768. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18769. var sl = shapes.length;
  18770. for ( var s = 0; s < sl; s ++ ) {
  18771. var shape = shapes[ s ];
  18772. this.addShape( shape, options );
  18773. }
  18774. };
  18775. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  18776. var amount = options.amount !== undefined ? options.amount : 100;
  18777. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  18778. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  18779. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18780. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  18781. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18782. var steps = options.steps !== undefined ? options.steps : 1;
  18783. var extrudePath = options.extrudePath;
  18784. var extrudePts, extrudeByPath = false;
  18785. var material = options.material;
  18786. var extrudeMaterial = options.extrudeMaterial;
  18787. // Use default WorldUVGenerator if no UV generators are specified.
  18788. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  18789. var splineTube, binormal, normal, position2;
  18790. if ( extrudePath ) {
  18791. extrudePts = extrudePath.getSpacedPoints( steps );
  18792. extrudeByPath = true;
  18793. bevelEnabled = false; // bevels not supported for path extrusion
  18794. // SETUP TNB variables
  18795. // Reuse TNB from TubeGeomtry for now.
  18796. // TODO1 - have a .isClosed in spline?
  18797. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  18798. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18799. binormal = new THREE.Vector3();
  18800. normal = new THREE.Vector3();
  18801. position2 = new THREE.Vector3();
  18802. }
  18803. // Safeguards if bevels are not enabled
  18804. if ( ! bevelEnabled ) {
  18805. bevelSegments = 0;
  18806. bevelThickness = 0;
  18807. bevelSize = 0;
  18808. }
  18809. // Variables initalization
  18810. var ahole, h, hl; // looping of holes
  18811. var scope = this;
  18812. var bevelPoints = [];
  18813. var shapesOffset = this.vertices.length;
  18814. var shapePoints = shape.extractPoints( curveSegments );
  18815. var vertices = shapePoints.shape;
  18816. var holes = shapePoints.holes;
  18817. var reverse = ! THREE.Shape.Utils.isClockWise( vertices ) ;
  18818. if ( reverse ) {
  18819. vertices = vertices.reverse();
  18820. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18821. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18822. ahole = holes[ h ];
  18823. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  18824. holes[ h ] = ahole.reverse();
  18825. }
  18826. }
  18827. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  18828. }
  18829. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  18830. /* Vertices */
  18831. var contour = vertices; // vertices has all points but contour has only points of circumference
  18832. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18833. ahole = holes[ h ];
  18834. vertices = vertices.concat( ahole );
  18835. }
  18836. function scalePt2 ( pt, vec, size ) {
  18837. if ( ! vec ) console.log( "die" );
  18838. return vec.clone().multiplyScalar( size ).add( pt );
  18839. }
  18840. var b, bs, t, z,
  18841. vert, vlen = vertices.length,
  18842. face, flen = faces.length,
  18843. cont, clen = contour.length;
  18844. // Find directions for point movement
  18845. var RAD_TO_DEGREES = 180 / Math.PI;
  18846. function getBevelVec( inPt, inPrev, inNext ) {
  18847. var EPSILON = 0.0000000001;
  18848. var sign = THREE.Math.sign;
  18849. // computes for inPt the corresponding point inPt' on a new contour
  18850. // shiftet by 1 unit (length of normalized vector) to the left
  18851. // if we walk along contour clockwise, this new contour is outside the old one
  18852. //
  18853. // inPt' is the intersection of the two lines parallel to the two
  18854. // adjacent edges of inPt at a distance of 1 unit on the left side.
  18855. var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt
  18856. // good reading for geometry algorithms (here: line-line intersection)
  18857. // http://geomalgorithms.com/a05-_intersect-1.html
  18858. var v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y;
  18859. var v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y;
  18860. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  18861. // check for colinear edges
  18862. var colinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  18863. if ( Math.abs( colinear0 ) > EPSILON ) { // not colinear
  18864. // length of vectors for normalizing
  18865. var v_prev_len = Math.sqrt( v_prev_lensq );
  18866. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  18867. // shift adjacent points by unit vectors to the left
  18868. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  18869. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  18870. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  18871. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  18872. // scaling factor for v_prev to intersection point
  18873. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  18874. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  18875. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  18876. // vector from inPt to intersection point
  18877. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  18878. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  18879. // Don't normalize!, otherwise sharp corners become ugly
  18880. // but prevent crazy spikes
  18881. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y )
  18882. if ( v_trans_lensq <= 2 ) {
  18883. return new THREE.Vector2( v_trans_x, v_trans_y );
  18884. } else {
  18885. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  18886. }
  18887. } else { // handle special case of colinear edges
  18888. var direction_eq = false; // assumes: opposite
  18889. if ( v_prev_x > EPSILON ) {
  18890. if ( v_next_x > EPSILON ) { direction_eq = true; }
  18891. } else {
  18892. if ( v_prev_x < - EPSILON ) {
  18893. if ( v_next_x < - EPSILON ) { direction_eq = true; }
  18894. } else {
  18895. if ( sign(v_prev_y) == sign(v_next_y) ) { direction_eq = true; }
  18896. }
  18897. }
  18898. if ( direction_eq ) {
  18899. // console.log("Warning: lines are a straight sequence");
  18900. v_trans_x = - v_prev_y;
  18901. v_trans_y = v_prev_x;
  18902. shrink_by = Math.sqrt( v_prev_lensq );
  18903. } else {
  18904. // console.log("Warning: lines are a straight spike");
  18905. v_trans_x = v_prev_x;
  18906. v_trans_y = v_prev_y;
  18907. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  18908. }
  18909. }
  18910. return new THREE.Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  18911. }
  18912. var contourMovements = [];
  18913. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18914. if ( j === il ) j = 0;
  18915. if ( k === il ) k = 0;
  18916. // (j)---(i)---(k)
  18917. // console.log('i,j,k', i, j , k)
  18918. var pt_i = contour[ i ];
  18919. var pt_j = contour[ j ];
  18920. var pt_k = contour[ k ];
  18921. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  18922. }
  18923. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  18924. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18925. ahole = holes[ h ];
  18926. oneHoleMovements = [];
  18927. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18928. if ( j === il ) j = 0;
  18929. if ( k === il ) k = 0;
  18930. // (j)---(i)---(k)
  18931. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  18932. }
  18933. holesMovements.push( oneHoleMovements );
  18934. verticesMovements = verticesMovements.concat( oneHoleMovements );
  18935. }
  18936. // Loop bevelSegments, 1 for the front, 1 for the back
  18937. for ( b = 0; b < bevelSegments; b ++ ) {
  18938. //for ( b = bevelSegments; b > 0; b -- ) {
  18939. t = b / bevelSegments;
  18940. z = bevelThickness * ( 1 - t );
  18941. //z = bevelThickness * t;
  18942. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  18943. //bs = bevelSize * t ; // linear
  18944. // contract shape
  18945. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18946. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18947. v( vert.x, vert.y, - z );
  18948. }
  18949. // expand holes
  18950. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18951. ahole = holes[ h ];
  18952. oneHoleMovements = holesMovements[ h ];
  18953. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  18954. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18955. v( vert.x, vert.y, - z );
  18956. }
  18957. }
  18958. }
  18959. bs = bevelSize;
  18960. // Back facing vertices
  18961. for ( i = 0; i < vlen; i ++ ) {
  18962. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18963. if ( ! extrudeByPath ) {
  18964. v( vert.x, vert.y, 0 );
  18965. } else {
  18966. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  18967. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  18968. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  18969. position2.copy( extrudePts[0] ).add(normal).add(binormal);
  18970. v( position2.x, position2.y, position2.z );
  18971. }
  18972. }
  18973. // Add stepped vertices...
  18974. // Including front facing vertices
  18975. var s;
  18976. for ( s = 1; s <= steps; s ++ ) {
  18977. for ( i = 0; i < vlen; i ++ ) {
  18978. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18979. if ( ! extrudeByPath ) {
  18980. v( vert.x, vert.y, amount / steps * s );
  18981. } else {
  18982. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  18983. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  18984. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  18985. position2.copy( extrudePts[s] ).add( normal ).add( binormal );
  18986. v( position2.x, position2.y, position2.z );
  18987. }
  18988. }
  18989. }
  18990. // Add bevel segments planes
  18991. //for ( b = 1; b <= bevelSegments; b ++ ) {
  18992. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  18993. t = b / bevelSegments;
  18994. z = bevelThickness * ( 1 - t );
  18995. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  18996. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  18997. // contract shape
  18998. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18999. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19000. v( vert.x, vert.y, amount + z );
  19001. }
  19002. // expand holes
  19003. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19004. ahole = holes[ h ];
  19005. oneHoleMovements = holesMovements[ h ];
  19006. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  19007. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19008. if ( ! extrudeByPath ) {
  19009. v( vert.x, vert.y, amount + z );
  19010. } else {
  19011. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  19012. }
  19013. }
  19014. }
  19015. }
  19016. /* Faces */
  19017. // Top and bottom faces
  19018. buildLidFaces();
  19019. // Sides faces
  19020. buildSideFaces();
  19021. ///// Internal functions
  19022. function buildLidFaces() {
  19023. if ( bevelEnabled ) {
  19024. var layer = 0 ; // steps + 1
  19025. var offset = vlen * layer;
  19026. // Bottom faces
  19027. for ( i = 0; i < flen; i ++ ) {
  19028. face = faces[ i ];
  19029. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  19030. }
  19031. layer = steps + bevelSegments * 2;
  19032. offset = vlen * layer;
  19033. // Top faces
  19034. for ( i = 0; i < flen; i ++ ) {
  19035. face = faces[ i ];
  19036. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  19037. }
  19038. } else {
  19039. // Bottom faces
  19040. for ( i = 0; i < flen; i ++ ) {
  19041. face = faces[ i ];
  19042. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  19043. }
  19044. // Top faces
  19045. for ( i = 0; i < flen; i ++ ) {
  19046. face = faces[ i ];
  19047. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  19048. }
  19049. }
  19050. }
  19051. // Create faces for the z-sides of the shape
  19052. function buildSideFaces() {
  19053. var layeroffset = 0;
  19054. sidewalls( contour, layeroffset );
  19055. layeroffset += contour.length;
  19056. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19057. ahole = holes[ h ];
  19058. sidewalls( ahole, layeroffset );
  19059. //, true
  19060. layeroffset += ahole.length;
  19061. }
  19062. }
  19063. function sidewalls( contour, layeroffset ) {
  19064. var j, k;
  19065. i = contour.length;
  19066. while ( --i >= 0 ) {
  19067. j = i;
  19068. k = i - 1;
  19069. if ( k < 0 ) k = contour.length - 1;
  19070. //console.log('b', i,j, i-1, k,vertices.length);
  19071. var s = 0, sl = steps + bevelSegments * 2;
  19072. for ( s = 0; s < sl; s ++ ) {
  19073. var slen1 = vlen * s;
  19074. var slen2 = vlen * ( s + 1 );
  19075. var a = layeroffset + j + slen1,
  19076. b = layeroffset + k + slen1,
  19077. c = layeroffset + k + slen2,
  19078. d = layeroffset + j + slen2;
  19079. f4( a, b, c, d, contour, s, sl, j, k );
  19080. }
  19081. }
  19082. }
  19083. function v( x, y, z ) {
  19084. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  19085. }
  19086. function f3( a, b, c, isBottom ) {
  19087. a += shapesOffset;
  19088. b += shapesOffset;
  19089. c += shapesOffset;
  19090. // normal, color, material
  19091. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19092. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  19093. scope.faceVertexUvs[ 0 ].push( uvs );
  19094. }
  19095. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  19096. a += shapesOffset;
  19097. b += shapesOffset;
  19098. c += shapesOffset;
  19099. d += shapesOffset;
  19100. scope.faces.push( new THREE.Face3( a, b, d, null, null, extrudeMaterial ) );
  19101. scope.faces.push( new THREE.Face3( b, c, d, null, null, extrudeMaterial ) );
  19102. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  19103. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  19104. scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] );
  19105. scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] );
  19106. }
  19107. };
  19108. THREE.ExtrudeGeometry.WorldUVGenerator = {
  19109. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19110. var ax = geometry.vertices[ indexA ].x,
  19111. ay = geometry.vertices[ indexA ].y,
  19112. bx = geometry.vertices[ indexB ].x,
  19113. by = geometry.vertices[ indexB ].y,
  19114. cx = geometry.vertices[ indexC ].x,
  19115. cy = geometry.vertices[ indexC ].y;
  19116. return [
  19117. new THREE.Vector2( ax, ay ),
  19118. new THREE.Vector2( bx, by ),
  19119. new THREE.Vector2( cx, cy )
  19120. ];
  19121. },
  19122. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19123. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  19124. },
  19125. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  19126. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  19127. contourIndex1, contourIndex2 ) {
  19128. var ax = geometry.vertices[ indexA ].x,
  19129. ay = geometry.vertices[ indexA ].y,
  19130. az = geometry.vertices[ indexA ].z,
  19131. bx = geometry.vertices[ indexB ].x,
  19132. by = geometry.vertices[ indexB ].y,
  19133. bz = geometry.vertices[ indexB ].z,
  19134. cx = geometry.vertices[ indexC ].x,
  19135. cy = geometry.vertices[ indexC ].y,
  19136. cz = geometry.vertices[ indexC ].z,
  19137. dx = geometry.vertices[ indexD ].x,
  19138. dy = geometry.vertices[ indexD ].y,
  19139. dz = geometry.vertices[ indexD ].z;
  19140. if ( Math.abs( ay - by ) < 0.01 ) {
  19141. return [
  19142. new THREE.Vector2( ax, 1 - az ),
  19143. new THREE.Vector2( bx, 1 - bz ),
  19144. new THREE.Vector2( cx, 1 - cz ),
  19145. new THREE.Vector2( dx, 1 - dz )
  19146. ];
  19147. } else {
  19148. return [
  19149. new THREE.Vector2( ay, 1 - az ),
  19150. new THREE.Vector2( by, 1 - bz ),
  19151. new THREE.Vector2( cy, 1 - cz ),
  19152. new THREE.Vector2( dy, 1 - dz )
  19153. ];
  19154. }
  19155. }
  19156. };
  19157. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  19158. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  19159. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  19160. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  19161. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  19162. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  19163. // File:src/extras/geometries/ShapeGeometry.js
  19164. /**
  19165. * @author jonobr1 / http://jonobr1.com
  19166. *
  19167. * Creates a one-sided polygonal geometry from a path shape. Similar to
  19168. * ExtrudeGeometry.
  19169. *
  19170. * parameters = {
  19171. *
  19172. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  19173. *
  19174. * material: <int> // material index for front and back faces
  19175. * uvGenerator: <Object> // object that provides UV generator functions
  19176. *
  19177. * }
  19178. **/
  19179. THREE.ShapeGeometry = function ( shapes, options ) {
  19180. THREE.Geometry.call( this );
  19181. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  19182. this.addShapeList( shapes, options );
  19183. this.computeFaceNormals();
  19184. };
  19185. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19186. /**
  19187. * Add an array of shapes to THREE.ShapeGeometry.
  19188. */
  19189. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19190. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  19191. this.addShape( shapes[ i ], options );
  19192. }
  19193. return this;
  19194. };
  19195. /**
  19196. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  19197. */
  19198. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  19199. if ( options === undefined ) options = {};
  19200. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19201. var material = options.material;
  19202. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  19203. //
  19204. var i, l, hole, s;
  19205. var shapesOffset = this.vertices.length;
  19206. var shapePoints = shape.extractPoints( curveSegments );
  19207. var vertices = shapePoints.shape;
  19208. var holes = shapePoints.holes;
  19209. var reverse = ! THREE.Shape.Utils.isClockWise( vertices );
  19210. if ( reverse ) {
  19211. vertices = vertices.reverse();
  19212. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  19213. for ( i = 0, l = holes.length; i < l; i ++ ) {
  19214. hole = holes[ i ];
  19215. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  19216. holes[ i ] = hole.reverse();
  19217. }
  19218. }
  19219. reverse = false;
  19220. }
  19221. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  19222. // Vertices
  19223. var contour = vertices;
  19224. for ( i = 0, l = holes.length; i < l; i ++ ) {
  19225. hole = holes[ i ];
  19226. vertices = vertices.concat( hole );
  19227. }
  19228. //
  19229. var vert, vlen = vertices.length;
  19230. var face, flen = faces.length;
  19231. var cont, clen = contour.length;
  19232. for ( i = 0; i < vlen; i ++ ) {
  19233. vert = vertices[ i ];
  19234. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  19235. }
  19236. for ( i = 0; i < flen; i ++ ) {
  19237. face = faces[ i ];
  19238. var a = face[ 0 ] + shapesOffset;
  19239. var b = face[ 1 ] + shapesOffset;
  19240. var c = face[ 2 ] + shapesOffset;
  19241. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19242. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  19243. }
  19244. };
  19245. // File:src/extras/geometries/LatheGeometry.js
  19246. /**
  19247. * @author astrodud / http://astrodud.isgreat.org/
  19248. * @author zz85 / https://github.com/zz85
  19249. * @author bhouston / http://exocortex.com
  19250. */
  19251. // points - to create a closed torus, one must use a set of points
  19252. // like so: [ a, b, c, d, a ], see first is the same as last.
  19253. // segments - the number of circumference segments to create
  19254. // phiStart - the starting radian
  19255. // phiLength - the radian (0 to 2*PI) range of the lathed section
  19256. // 2*pi is a closed lathe, less than 2PI is a portion.
  19257. THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
  19258. THREE.Geometry.call( this );
  19259. segments = segments || 12;
  19260. phiStart = phiStart || 0;
  19261. phiLength = phiLength || 2 * Math.PI;
  19262. var inversePointLength = 1.0 / ( points.length - 1 );
  19263. var inverseSegments = 1.0 / segments;
  19264. for ( var i = 0, il = segments; i <= il; i ++ ) {
  19265. var phi = phiStart + i * inverseSegments * phiLength;
  19266. var c = Math.cos( phi ),
  19267. s = Math.sin( phi );
  19268. for ( var j = 0, jl = points.length; j < jl; j ++ ) {
  19269. var pt = points[ j ];
  19270. var vertex = new THREE.Vector3();
  19271. vertex.x = c * pt.x - s * pt.y;
  19272. vertex.y = s * pt.x + c * pt.y;
  19273. vertex.z = pt.z;
  19274. this.vertices.push( vertex );
  19275. }
  19276. }
  19277. var np = points.length;
  19278. for ( var i = 0, il = segments; i < il; i ++ ) {
  19279. for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) {
  19280. var base = j + np * i;
  19281. var a = base;
  19282. var b = base + np;
  19283. var c = base + 1 + np;
  19284. var d = base + 1;
  19285. var u0 = i * inverseSegments;
  19286. var v0 = j * inversePointLength;
  19287. var u1 = u0 + inverseSegments;
  19288. var v1 = v0 + inversePointLength;
  19289. this.faces.push( new THREE.Face3( a, b, d ) );
  19290. this.faceVertexUvs[ 0 ].push( [
  19291. new THREE.Vector2( u0, v0 ),
  19292. new THREE.Vector2( u1, v0 ),
  19293. new THREE.Vector2( u0, v1 )
  19294. ] );
  19295. this.faces.push( new THREE.Face3( b, c, d ) );
  19296. this.faceVertexUvs[ 0 ].push( [
  19297. new THREE.Vector2( u1, v0 ),
  19298. new THREE.Vector2( u1, v1 ),
  19299. new THREE.Vector2( u0, v1 )
  19300. ] );
  19301. }
  19302. }
  19303. this.mergeVertices();
  19304. this.computeFaceNormals();
  19305. this.computeVertexNormals();
  19306. };
  19307. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19308. // File:src/extras/geometries/PlaneGeometry.js
  19309. /**
  19310. * @author mrdoob / http://mrdoob.com/
  19311. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  19312. */
  19313. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  19314. THREE.Geometry.call( this );
  19315. this.parameters = {
  19316. width: width,
  19317. height: height,
  19318. widthSegments: widthSegments,
  19319. heightSegments: heightSegments
  19320. };
  19321. var ix, iz;
  19322. var width_half = width / 2;
  19323. var height_half = height / 2;
  19324. var gridX = widthSegments || 1;
  19325. var gridZ = heightSegments || 1;
  19326. var gridX1 = gridX + 1;
  19327. var gridZ1 = gridZ + 1;
  19328. var segment_width = width / gridX;
  19329. var segment_height = height / gridZ;
  19330. var normal = new THREE.Vector3( 0, 0, 1 );
  19331. for ( iz = 0; iz < gridZ1; iz ++ ) {
  19332. var y = iz * segment_height - height_half;
  19333. for ( ix = 0; ix < gridX1; ix ++ ) {
  19334. var x = ix * segment_width - width_half;
  19335. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  19336. }
  19337. }
  19338. for ( iz = 0; iz < gridZ; iz ++ ) {
  19339. for ( ix = 0; ix < gridX; ix ++ ) {
  19340. var a = ix + gridX1 * iz;
  19341. var b = ix + gridX1 * ( iz + 1 );
  19342. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  19343. var d = ( ix + 1 ) + gridX1 * iz;
  19344. var uva = new THREE.Vector2( ix / gridX, 1 - iz / gridZ );
  19345. var uvb = new THREE.Vector2( ix / gridX, 1 - ( iz + 1 ) / gridZ );
  19346. var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ );
  19347. var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iz / gridZ );
  19348. var face = new THREE.Face3( a, b, d );
  19349. face.normal.copy( normal );
  19350. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  19351. this.faces.push( face );
  19352. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19353. face = new THREE.Face3( b, c, d );
  19354. face.normal.copy( normal );
  19355. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  19356. this.faces.push( face );
  19357. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19358. }
  19359. }
  19360. };
  19361. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19362. // File:src/extras/geometries/RingGeometry.js
  19363. /**
  19364. * @author Kaleb Murphy
  19365. */
  19366. THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  19367. THREE.Geometry.call( this );
  19368. innerRadius = innerRadius || 0;
  19369. outerRadius = outerRadius || 50;
  19370. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19371. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19372. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  19373. phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 8;
  19374. var i, o, uvs = [], radius = innerRadius, radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  19375. for ( i = 0; i < phiSegments + 1; i ++ ) { // concentric circles inside ring
  19376. for ( o = 0; o < thetaSegments + 1; o ++ ) { // number of segments per circle
  19377. var vertex = new THREE.Vector3();
  19378. var segment = thetaStart + o / thetaSegments * thetaLength;
  19379. vertex.x = radius * Math.cos( segment );
  19380. vertex.y = radius * Math.sin( segment );
  19381. this.vertices.push( vertex );
  19382. uvs.push( new THREE.Vector2( ( vertex.x / outerRadius + 1 ) / 2, ( vertex.y / outerRadius + 1 ) / 2 ) );
  19383. }
  19384. radius += radiusStep;
  19385. }
  19386. var n = new THREE.Vector3( 0, 0, 1 );
  19387. for ( i = 0; i < phiSegments; i ++ ) { // concentric circles inside ring
  19388. var thetaSegment = i * (thetaSegments + 1);
  19389. for ( o = 0; o < thetaSegments ; o ++ ) { // number of segments per circle
  19390. var segment = o + thetaSegment;
  19391. var v1 = segment;
  19392. var v2 = segment + thetaSegments + 1;
  19393. var v3 = segment + thetaSegments + 2;
  19394. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  19395. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]);
  19396. v1 = segment;
  19397. v2 = segment + thetaSegments + 2;
  19398. v3 = segment + 1;
  19399. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  19400. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]);
  19401. }
  19402. }
  19403. this.computeFaceNormals();
  19404. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19405. };
  19406. THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19407. // File:src/extras/geometries/SphereGeometry.js
  19408. /**
  19409. * @author mrdoob / http://mrdoob.com/
  19410. */
  19411. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  19412. THREE.Geometry.call( this );
  19413. this.parameters = {
  19414. radius: radius,
  19415. widthSegments: widthSegments,
  19416. heightSegments: heightSegments,
  19417. phiStart: phiStart,
  19418. phiLength: phiLength,
  19419. thetaStart: thetaStart,
  19420. thetaLength: thetaLength
  19421. };
  19422. radius = radius || 50;
  19423. widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  19424. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  19425. phiStart = phiStart !== undefined ? phiStart : 0;
  19426. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19427. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19428. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19429. var x, y, vertices = [], uvs = [];
  19430. for ( y = 0; y <= heightSegments; y ++ ) {
  19431. var verticesRow = [];
  19432. var uvsRow = [];
  19433. for ( x = 0; x <= widthSegments; x ++ ) {
  19434. var u = x / widthSegments;
  19435. var v = y / heightSegments;
  19436. var vertex = new THREE.Vector3();
  19437. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19438. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  19439. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19440. this.vertices.push( vertex );
  19441. verticesRow.push( this.vertices.length - 1 );
  19442. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19443. }
  19444. vertices.push( verticesRow );
  19445. uvs.push( uvsRow );
  19446. }
  19447. for ( y = 0; y < heightSegments; y ++ ) {
  19448. for ( x = 0; x < widthSegments; x ++ ) {
  19449. var v1 = vertices[ y ][ x + 1 ];
  19450. var v2 = vertices[ y ][ x ];
  19451. var v3 = vertices[ y + 1 ][ x ];
  19452. var v4 = vertices[ y + 1 ][ x + 1 ];
  19453. var n1 = this.vertices[ v1 ].clone().normalize();
  19454. var n2 = this.vertices[ v2 ].clone().normalize();
  19455. var n3 = this.vertices[ v3 ].clone().normalize();
  19456. var n4 = this.vertices[ v4 ].clone().normalize();
  19457. var uv1 = uvs[ y ][ x + 1 ].clone();
  19458. var uv2 = uvs[ y ][ x ].clone();
  19459. var uv3 = uvs[ y + 1 ][ x ].clone();
  19460. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  19461. if ( Math.abs( this.vertices[ v1 ].y ) === radius ) {
  19462. uv1.x = ( uv1.x + uv2.x ) / 2;
  19463. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  19464. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  19465. } else if ( Math.abs( this.vertices[ v3 ].y ) === radius ) {
  19466. uv3.x = ( uv3.x + uv4.x ) / 2;
  19467. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19468. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19469. } else {
  19470. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  19471. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  19472. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  19473. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  19474. }
  19475. }
  19476. }
  19477. this.computeFaceNormals();
  19478. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19479. };
  19480. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19481. // File:src/extras/geometries/TextGeometry.js
  19482. /**
  19483. * @author zz85 / http://www.lab4games.net/zz85/blog
  19484. * @author alteredq / http://alteredqualia.com/
  19485. *
  19486. * For creating 3D text geometry in three.js
  19487. *
  19488. * Text = 3D Text
  19489. *
  19490. * parameters = {
  19491. * size: <float>, // size of the text
  19492. * height: <float>, // thickness to extrude text
  19493. * curveSegments: <int>, // number of points on the curves
  19494. *
  19495. * font: <string>, // font name
  19496. * weight: <string>, // font weight (normal, bold)
  19497. * style: <string>, // font style (normal, italics)
  19498. *
  19499. * bevelEnabled: <bool>, // turn on bevel
  19500. * bevelThickness: <float>, // how deep into text bevel goes
  19501. * bevelSize: <float>, // how far from text outline is bevel
  19502. * }
  19503. *
  19504. */
  19505. /* Usage Examples
  19506. // TextGeometry wrapper
  19507. var text3d = new TextGeometry( text, options );
  19508. // Complete manner
  19509. var textShapes = THREE.FontUtils.generateShapes( text, options );
  19510. var text3d = new ExtrudeGeometry( textShapes, options );
  19511. */
  19512. THREE.TextGeometry = function ( text, parameters ) {
  19513. parameters = parameters || {};
  19514. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  19515. // translate parameters to ExtrudeGeometry API
  19516. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  19517. // defaults
  19518. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  19519. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  19520. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  19521. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  19522. };
  19523. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  19524. // File:src/extras/geometries/TorusGeometry.js
  19525. /**
  19526. * @author oosmoxiecode
  19527. * @author mrdoob / http://mrdoob.com/
  19528. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  19529. */
  19530. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  19531. THREE.Geometry.call( this );
  19532. this.parameters = {
  19533. radius: radius,
  19534. tube: tube,
  19535. radialSegments: radialSegments,
  19536. tubularSegments: tubularSegments,
  19537. arc: arc
  19538. };
  19539. radius = radius || 100;
  19540. tube = tube || 40;
  19541. radialSegments = radialSegments || 8;
  19542. tubularSegments = tubularSegments || 6;
  19543. arc = arc || Math.PI * 2;
  19544. var center = new THREE.Vector3(), uvs = [], normals = [];
  19545. for ( var j = 0; j <= radialSegments; j ++ ) {
  19546. for ( var i = 0; i <= tubularSegments; i ++ ) {
  19547. var u = i / tubularSegments * arc;
  19548. var v = j / radialSegments * Math.PI * 2;
  19549. center.x = radius * Math.cos( u );
  19550. center.y = radius * Math.sin( u );
  19551. var vertex = new THREE.Vector3();
  19552. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  19553. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  19554. vertex.z = tube * Math.sin( v );
  19555. this.vertices.push( vertex );
  19556. uvs.push( new THREE.Vector2( i / tubularSegments, j / radialSegments ) );
  19557. normals.push( vertex.clone().sub( center ).normalize() );
  19558. }
  19559. }
  19560. for ( var j = 1; j <= radialSegments; j ++ ) {
  19561. for ( var i = 1; i <= tubularSegments; i ++ ) {
  19562. var a = ( tubularSegments + 1 ) * j + i - 1;
  19563. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  19564. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  19565. var d = ( tubularSegments + 1 ) * j + i;
  19566. var face = new THREE.Face3( a, b, d, [ normals[ a ].clone(), normals[ b ].clone(), normals[ d ].clone() ] );
  19567. this.faces.push( face );
  19568. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ d ].clone() ] );
  19569. face = new THREE.Face3( b, c, d, [ normals[ b ].clone(), normals[ c ].clone(), normals[ d ].clone() ] );
  19570. this.faces.push( face );
  19571. this.faceVertexUvs[ 0 ].push( [ uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  19572. }
  19573. }
  19574. this.computeFaceNormals();
  19575. };
  19576. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19577. // File:src/extras/geometries/TorusKnotGeometry.js
  19578. /**
  19579. * @author oosmoxiecode
  19580. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  19581. */
  19582. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  19583. THREE.Geometry.call( this );
  19584. this.parameters = {
  19585. radius: radius,
  19586. tube: tube,
  19587. radialSegments: radialSegments,
  19588. tubularSegments: tubularSegments,
  19589. p: p,
  19590. q: q,
  19591. heightScale: heightScale
  19592. };
  19593. radius = radius || 100;
  19594. tube = tube || 40;
  19595. radialSegments = radialSegments || 64;
  19596. tubularSegments = tubularSegments || 8;
  19597. p = p || 2;
  19598. q = q || 3;
  19599. heightScale = heightScale || 1;
  19600. var grid = new Array( radialSegments );
  19601. var tang = new THREE.Vector3();
  19602. var n = new THREE.Vector3();
  19603. var bitan = new THREE.Vector3();
  19604. for ( var i = 0; i < radialSegments; ++ i ) {
  19605. grid[ i ] = new Array( tubularSegments );
  19606. var u = i / radialSegments * 2 * p * Math.PI;
  19607. var p1 = getPos( u, q, p, radius, heightScale );
  19608. var p2 = getPos( u + 0.01, q, p, radius, heightScale );
  19609. tang.subVectors( p2, p1 );
  19610. n.addVectors( p2, p1 );
  19611. bitan.crossVectors( tang, n );
  19612. n.crossVectors( bitan, tang );
  19613. bitan.normalize();
  19614. n.normalize();
  19615. for ( var j = 0; j < tubularSegments; ++ j ) {
  19616. var v = j / tubularSegments * 2 * Math.PI;
  19617. var cx = - tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19618. var cy = tube * Math.sin( v );
  19619. var pos = new THREE.Vector3();
  19620. pos.x = p1.x + cx * n.x + cy * bitan.x;
  19621. pos.y = p1.y + cx * n.y + cy * bitan.y;
  19622. pos.z = p1.z + cx * n.z + cy * bitan.z;
  19623. grid[ i ][ j ] = this.vertices.push( pos ) - 1;
  19624. }
  19625. }
  19626. for ( var i = 0; i < radialSegments; ++ i ) {
  19627. for ( var j = 0; j < tubularSegments; ++ j ) {
  19628. var ip = ( i + 1 ) % radialSegments;
  19629. var jp = ( j + 1 ) % tubularSegments;
  19630. var a = grid[ i ][ j ];
  19631. var b = grid[ ip ][ j ];
  19632. var c = grid[ ip ][ jp ];
  19633. var d = grid[ i ][ jp ];
  19634. var uva = new THREE.Vector2( i / radialSegments, j / tubularSegments );
  19635. var uvb = new THREE.Vector2( ( i + 1 ) / radialSegments, j / tubularSegments );
  19636. var uvc = new THREE.Vector2( ( i + 1 ) / radialSegments, ( j + 1 ) / tubularSegments );
  19637. var uvd = new THREE.Vector2( i / radialSegments, ( j + 1 ) / tubularSegments );
  19638. this.faces.push( new THREE.Face3( a, b, d ) );
  19639. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19640. this.faces.push( new THREE.Face3( b, c, d ) );
  19641. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19642. }
  19643. }
  19644. this.computeFaceNormals();
  19645. this.computeVertexNormals();
  19646. function getPos( u, in_q, in_p, radius, heightScale ) {
  19647. var cu = Math.cos( u );
  19648. var su = Math.sin( u );
  19649. var quOverP = in_q / in_p * u;
  19650. var cs = Math.cos( quOverP );
  19651. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  19652. var ty = radius * ( 2 + cs ) * su * 0.5;
  19653. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  19654. return new THREE.Vector3( tx, ty, tz );
  19655. }
  19656. };
  19657. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19658. // File:src/extras/geometries/TubeGeometry.js
  19659. /**
  19660. * @author WestLangley / https://github.com/WestLangley
  19661. * @author zz85 / https://github.com/zz85
  19662. * @author miningold / https://github.com/miningold
  19663. *
  19664. * Modified from the TorusKnotGeometry by @oosmoxiecode
  19665. *
  19666. * Creates a tube which extrudes along a 3d spline
  19667. *
  19668. * Uses parallel transport frames as described in
  19669. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  19670. */
  19671. THREE.TubeGeometry = function ( path, segments, radius, radialSegments, closed ) {
  19672. THREE.Geometry.call( this );
  19673. this.parameters = {
  19674. path: path,
  19675. segments: segments,
  19676. radius: radius,
  19677. radialSegments: radialSegments,
  19678. closed: closed
  19679. };
  19680. segments = segments || 64;
  19681. radius = radius || 1;
  19682. radialSegments = radialSegments || 8;
  19683. closed = closed || false;
  19684. var grid = [];
  19685. var scope = this,
  19686. tangent,
  19687. normal,
  19688. binormal,
  19689. numpoints = segments + 1,
  19690. x, y, z,
  19691. tx, ty, tz,
  19692. u, v,
  19693. cx, cy,
  19694. pos, pos2 = new THREE.Vector3(),
  19695. i, j,
  19696. ip, jp,
  19697. a, b, c, d,
  19698. uva, uvb, uvc, uvd;
  19699. var frames = new THREE.TubeGeometry.FrenetFrames( path, segments, closed ),
  19700. tangents = frames.tangents,
  19701. normals = frames.normals,
  19702. binormals = frames.binormals;
  19703. // proxy internals
  19704. this.tangents = tangents;
  19705. this.normals = normals;
  19706. this.binormals = binormals;
  19707. function vert( x, y, z ) {
  19708. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19709. }
  19710. // consruct the grid
  19711. for ( i = 0; i < numpoints; i ++ ) {
  19712. grid[ i ] = [];
  19713. u = i / ( numpoints - 1 );
  19714. pos = path.getPointAt( u );
  19715. tangent = tangents[ i ];
  19716. normal = normals[ i ];
  19717. binormal = binormals[ i ];
  19718. for ( j = 0; j < radialSegments; j ++ ) {
  19719. v = j / radialSegments * 2 * Math.PI;
  19720. cx = - radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19721. cy = radius * Math.sin( v );
  19722. pos2.copy( pos );
  19723. pos2.x += cx * normal.x + cy * binormal.x;
  19724. pos2.y += cx * normal.y + cy * binormal.y;
  19725. pos2.z += cx * normal.z + cy * binormal.z;
  19726. grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  19727. }
  19728. }
  19729. // construct the mesh
  19730. for ( i = 0; i < segments; i ++ ) {
  19731. for ( j = 0; j < radialSegments; j ++ ) {
  19732. ip = ( closed ) ? (i + 1) % segments : i + 1;
  19733. jp = (j + 1) % radialSegments;
  19734. a = grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  19735. b = grid[ ip ][ j ];
  19736. c = grid[ ip ][ jp ];
  19737. d = grid[ i ][ jp ];
  19738. uva = new THREE.Vector2( i / segments, j / radialSegments );
  19739. uvb = new THREE.Vector2( ( i + 1 ) / segments, j / radialSegments );
  19740. uvc = new THREE.Vector2( ( i + 1 ) / segments, ( j + 1 ) / radialSegments );
  19741. uvd = new THREE.Vector2( i / segments, ( j + 1 ) / radialSegments );
  19742. this.faces.push( new THREE.Face3( a, b, d ) );
  19743. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19744. this.faces.push( new THREE.Face3( b, c, d ) );
  19745. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19746. }
  19747. }
  19748. this.computeFaceNormals();
  19749. this.computeVertexNormals();
  19750. };
  19751. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19752. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  19753. THREE.TubeGeometry.FrenetFrames = function ( path, segments, closed ) {
  19754. var tangent = new THREE.Vector3(),
  19755. normal = new THREE.Vector3(),
  19756. binormal = new THREE.Vector3(),
  19757. tangents = [],
  19758. normals = [],
  19759. binormals = [],
  19760. vec = new THREE.Vector3(),
  19761. mat = new THREE.Matrix4(),
  19762. numpoints = segments + 1,
  19763. theta,
  19764. epsilon = 0.0001,
  19765. smallest,
  19766. tx, ty, tz,
  19767. i, u, v;
  19768. // expose internals
  19769. this.tangents = tangents;
  19770. this.normals = normals;
  19771. this.binormals = binormals;
  19772. // compute the tangent vectors for each segment on the path
  19773. for ( i = 0; i < numpoints; i ++ ) {
  19774. u = i / ( numpoints - 1 );
  19775. tangents[ i ] = path.getTangentAt( u );
  19776. tangents[ i ].normalize();
  19777. }
  19778. initialNormal3();
  19779. /*
  19780. function initialNormal1(lastBinormal) {
  19781. // fixed start binormal. Has dangers of 0 vectors
  19782. normals[ 0 ] = new THREE.Vector3();
  19783. binormals[ 0 ] = new THREE.Vector3();
  19784. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  19785. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  19786. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19787. }
  19788. function initialNormal2() {
  19789. // This uses the Frenet-Serret formula for deriving binormal
  19790. var t2 = path.getTangentAt( epsilon );
  19791. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  19792. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  19793. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  19794. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19795. }
  19796. */
  19797. function initialNormal3() {
  19798. // select an initial normal vector perpenicular to the first tangent vector,
  19799. // and in the direction of the smallest tangent xyz component
  19800. normals[ 0 ] = new THREE.Vector3();
  19801. binormals[ 0 ] = new THREE.Vector3();
  19802. smallest = Number.MAX_VALUE;
  19803. tx = Math.abs( tangents[ 0 ].x );
  19804. ty = Math.abs( tangents[ 0 ].y );
  19805. tz = Math.abs( tangents[ 0 ].z );
  19806. if ( tx <= smallest ) {
  19807. smallest = tx;
  19808. normal.set( 1, 0, 0 );
  19809. }
  19810. if ( ty <= smallest ) {
  19811. smallest = ty;
  19812. normal.set( 0, 1, 0 );
  19813. }
  19814. if ( tz <= smallest ) {
  19815. normal.set( 0, 0, 1 );
  19816. }
  19817. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  19818. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  19819. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  19820. }
  19821. // compute the slowly-varying normal and binormal vectors for each segment on the path
  19822. for ( i = 1; i < numpoints; i ++ ) {
  19823. normals[ i ] = normals[ i-1 ].clone();
  19824. binormals[ i ] = binormals[ i-1 ].clone();
  19825. vec.crossVectors( tangents[ i-1 ], tangents[ i ] );
  19826. if ( vec.length() > epsilon ) {
  19827. vec.normalize();
  19828. theta = Math.acos( THREE.Math.clamp( tangents[ i-1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  19829. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  19830. }
  19831. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19832. }
  19833. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  19834. if ( closed ) {
  19835. theta = Math.acos( THREE.Math.clamp( normals[ 0 ].dot( normals[ numpoints-1 ] ), - 1, 1 ) );
  19836. theta /= ( numpoints - 1 );
  19837. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  19838. theta = - theta;
  19839. }
  19840. for ( i = 1; i < numpoints; i ++ ) {
  19841. // twist a little...
  19842. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  19843. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19844. }
  19845. }
  19846. };
  19847. // File:src/extras/geometries/PolyhedronGeometry.js
  19848. /**
  19849. * @author clockworkgeek / https://github.com/clockworkgeek
  19850. * @author timothypratley / https://github.com/timothypratley
  19851. * @author WestLangley / http://github.com/WestLangley
  19852. */
  19853. THREE.PolyhedronGeometry = function ( vertices, indices, radius, detail ) {
  19854. THREE.Geometry.call( this );
  19855. radius = radius || 1;
  19856. detail = detail || 0;
  19857. var that = this;
  19858. for ( var i = 0, l = vertices.length; i < l; i += 3 ) {
  19859. prepare( new THREE.Vector3( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] ) );
  19860. }
  19861. var midpoints = [], p = this.vertices;
  19862. var faces = [];
  19863. for ( var i = 0, j = 0, l = indices.length; i < l; i += 3, j ++ ) {
  19864. var v1 = p[ indices[ i ] ];
  19865. var v2 = p[ indices[ i + 1 ] ];
  19866. var v3 = p[ indices[ i + 2 ] ];
  19867. faces[ j ] = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19868. }
  19869. var centroid = new THREE.Vector3();
  19870. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  19871. subdivide( faces[ i ], detail );
  19872. }
  19873. // Handle case when face straddles the seam
  19874. for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) {
  19875. var uvs = this.faceVertexUvs[ 0 ][ i ];
  19876. var x0 = uvs[ 0 ].x;
  19877. var x1 = uvs[ 1 ].x;
  19878. var x2 = uvs[ 2 ].x;
  19879. var max = Math.max( x0, Math.max( x1, x2 ) );
  19880. var min = Math.min( x0, Math.min( x1, x2 ) );
  19881. if ( max > 0.9 && min < 0.1 ) { // 0.9 is somewhat arbitrary
  19882. if ( x0 < 0.2 ) uvs[ 0 ].x += 1;
  19883. if ( x1 < 0.2 ) uvs[ 1 ].x += 1;
  19884. if ( x2 < 0.2 ) uvs[ 2 ].x += 1;
  19885. }
  19886. }
  19887. // Apply radius
  19888. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  19889. this.vertices[ i ].multiplyScalar( radius );
  19890. }
  19891. // Merge vertices
  19892. this.mergeVertices();
  19893. this.computeFaceNormals();
  19894. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19895. // Project vector onto sphere's surface
  19896. function prepare( vector ) {
  19897. var vertex = vector.normalize().clone();
  19898. vertex.index = that.vertices.push( vertex ) - 1;
  19899. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  19900. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  19901. var v = inclination( vector ) / Math.PI + 0.5;
  19902. vertex.uv = new THREE.Vector2( u, 1 - v );
  19903. return vertex;
  19904. }
  19905. // Approximate a curved face with recursively sub-divided triangles.
  19906. function make( v1, v2, v3 ) {
  19907. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19908. that.faces.push( face );
  19909. centroid.copy( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  19910. var azi = azimuth( centroid );
  19911. that.faceVertexUvs[ 0 ].push( [
  19912. correctUV( v1.uv, v1, azi ),
  19913. correctUV( v2.uv, v2, azi ),
  19914. correctUV( v3.uv, v3, azi )
  19915. ] );
  19916. }
  19917. // Analytically subdivide a face to the required detail level.
  19918. function subdivide( face, detail ) {
  19919. var cols = Math.pow(2, detail);
  19920. var cells = Math.pow(4, detail);
  19921. var a = prepare( that.vertices[ face.a ] );
  19922. var b = prepare( that.vertices[ face.b ] );
  19923. var c = prepare( that.vertices[ face.c ] );
  19924. var v = [];
  19925. // Construct all of the vertices for this subdivision.
  19926. for ( var i = 0 ; i <= cols; i ++ ) {
  19927. v[ i ] = [];
  19928. var aj = prepare( a.clone().lerp( c, i / cols ) );
  19929. var bj = prepare( b.clone().lerp( c, i / cols ) );
  19930. var rows = cols - i;
  19931. for ( var j = 0; j <= rows; j ++) {
  19932. if ( j == 0 && i == cols ) {
  19933. v[ i ][ j ] = aj;
  19934. } else {
  19935. v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) );
  19936. }
  19937. }
  19938. }
  19939. // Construct all of the faces.
  19940. for ( var i = 0; i < cols ; i ++ ) {
  19941. for ( var j = 0; j < 2 * (cols - i) - 1; j ++ ) {
  19942. var k = Math.floor( j / 2 );
  19943. if ( j % 2 == 0 ) {
  19944. make(
  19945. v[ i ][ k + 1],
  19946. v[ i + 1 ][ k ],
  19947. v[ i ][ k ]
  19948. );
  19949. } else {
  19950. make(
  19951. v[ i ][ k + 1 ],
  19952. v[ i + 1][ k + 1],
  19953. v[ i + 1 ][ k ]
  19954. );
  19955. }
  19956. }
  19957. }
  19958. }
  19959. // Angle around the Y axis, counter-clockwise when looking from above.
  19960. function azimuth( vector ) {
  19961. return Math.atan2( vector.z, - vector.x );
  19962. }
  19963. // Angle above the XZ plane.
  19964. function inclination( vector ) {
  19965. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  19966. }
  19967. // Texture fixing helper. Spheres have some odd behaviours.
  19968. function correctUV( uv, vector, azimuth ) {
  19969. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  19970. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  19971. return uv.clone();
  19972. }
  19973. };
  19974. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19975. // File:src/extras/geometries/IcosahedronGeometry.js
  19976. /**
  19977. * @author timothypratley / https://github.com/timothypratley
  19978. */
  19979. THREE.IcosahedronGeometry = function ( radius, detail ) {
  19980. this.parameters = {
  19981. radius: radius,
  19982. detail: detail
  19983. };
  19984. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19985. var vertices = [
  19986. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  19987. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  19988. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  19989. ];
  19990. var indices = [
  19991. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  19992. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  19993. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  19994. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  19995. ];
  19996. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  19997. };
  19998. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19999. // File:src/extras/geometries/OctahedronGeometry.js
  20000. /**
  20001. * @author timothypratley / https://github.com/timothypratley
  20002. */
  20003. THREE.OctahedronGeometry = function ( radius, detail ) {
  20004. this.parameters = {
  20005. radius: radius,
  20006. detail: detail
  20007. };
  20008. var vertices = [
  20009. 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0,- 1, 0, 0, 0, 1, 0, 0,- 1
  20010. ];
  20011. var indices = [
  20012. 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2
  20013. ];
  20014. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  20015. };
  20016. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20017. // File:src/extras/geometries/TetrahedronGeometry.js
  20018. /**
  20019. * @author timothypratley / https://github.com/timothypratley
  20020. */
  20021. THREE.TetrahedronGeometry = function ( radius, detail ) {
  20022. var vertices = [
  20023. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  20024. ];
  20025. var indices = [
  20026. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  20027. ];
  20028. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  20029. };
  20030. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20031. // File:src/extras/geometries/ParametricGeometry.js
  20032. /**
  20033. * @author zz85 / https://github.com/zz85
  20034. * Parametric Surfaces Geometry
  20035. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  20036. *
  20037. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements );
  20038. *
  20039. */
  20040. THREE.ParametricGeometry = function ( func, slices, stacks ) {
  20041. THREE.Geometry.call( this );
  20042. var verts = this.vertices;
  20043. var faces = this.faces;
  20044. var uvs = this.faceVertexUvs[ 0 ];
  20045. var i, il, j, p;
  20046. var u, v;
  20047. var stackCount = stacks + 1;
  20048. var sliceCount = slices + 1;
  20049. for ( i = 0; i <= stacks; i ++ ) {
  20050. v = i / stacks;
  20051. for ( j = 0; j <= slices; j ++ ) {
  20052. u = j / slices;
  20053. p = func( u, v );
  20054. verts.push( p );
  20055. }
  20056. }
  20057. var a, b, c, d;
  20058. var uva, uvb, uvc, uvd;
  20059. for ( i = 0; i < stacks; i ++ ) {
  20060. for ( j = 0; j < slices; j ++ ) {
  20061. a = i * sliceCount + j;
  20062. b = i * sliceCount + j + 1;
  20063. c = (i + 1) * sliceCount + j + 1;
  20064. d = (i + 1) * sliceCount + j;
  20065. uva = new THREE.Vector2( j / slices, i / stacks );
  20066. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  20067. uvc = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  20068. uvd = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  20069. faces.push( new THREE.Face3( a, b, d ) );
  20070. uvs.push( [ uva, uvb, uvd ] );
  20071. faces.push( new THREE.Face3( b, c, d ) );
  20072. uvs.push( [ uvb.clone(), uvc, uvd.clone() ] );
  20073. }
  20074. }
  20075. // console.log(this);
  20076. // magic bullet
  20077. // var diff = this.mergeVertices();
  20078. // console.log('removed ', diff, ' vertices by merging');
  20079. this.computeFaceNormals();
  20080. this.computeVertexNormals();
  20081. };
  20082. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20083. // File:src/extras/helpers/AxisHelper.js
  20084. /**
  20085. * @author sroucheray / http://sroucheray.org/
  20086. * @author mrdoob / http://mrdoob.com/
  20087. */
  20088. THREE.AxisHelper = function ( size ) {
  20089. size = size || 1;
  20090. var vertices = new Float32Array( [
  20091. 0, 0, 0, size, 0, 0,
  20092. 0, 0, 0, 0, size, 0,
  20093. 0, 0, 0, 0, 0, size
  20094. ] );
  20095. var colors = new Float32Array( [
  20096. 1, 0, 0, 1, 0.6, 0,
  20097. 0, 1, 0, 0.6, 1, 0,
  20098. 0, 0, 1, 0, 0.6, 1
  20099. ] );
  20100. var geometry = new THREE.BufferGeometry();
  20101. geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  20102. geometry.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) );
  20103. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20104. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20105. };
  20106. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  20107. // File:src/extras/helpers/ArrowHelper.js
  20108. /**
  20109. * @author WestLangley / http://github.com/WestLangley
  20110. * @author zz85 / http://github.com/zz85
  20111. * @author bhouston / http://exocortex.com
  20112. *
  20113. * Creates an arrow for visualizing directions
  20114. *
  20115. * Parameters:
  20116. * dir - Vector3
  20117. * origin - Vector3
  20118. * length - Number
  20119. * color - color in hex value
  20120. * headLength - Number
  20121. * headWidth - Number
  20122. */
  20123. THREE.ArrowHelper = ( function () {
  20124. var lineGeometry = new THREE.Geometry();
  20125. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, 1, 0 ) );
  20126. var coneGeometry = new THREE.CylinderGeometry( 0, 0.5, 1, 5, 1 );
  20127. coneGeometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, - 0.5, 0 ) );
  20128. return function ( dir, origin, length, color, headLength, headWidth ) {
  20129. // dir is assumed to be normalized
  20130. THREE.Object3D.call( this );
  20131. if ( color === undefined ) color = 0xffff00;
  20132. if ( length === undefined ) length = 1;
  20133. if ( headLength === undefined ) headLength = 0.2 * length;
  20134. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  20135. this.position.copy( origin );
  20136. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: color } ) );
  20137. this.line.matrixAutoUpdate = false;
  20138. this.add( this.line );
  20139. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: color } ) );
  20140. this.cone.matrixAutoUpdate = false;
  20141. this.add( this.cone );
  20142. this.setDirection( dir );
  20143. this.setLength( length, headLength, headWidth );
  20144. }
  20145. }() );
  20146. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  20147. THREE.ArrowHelper.prototype.setDirection = ( function () {
  20148. var axis = new THREE.Vector3();
  20149. var radians;
  20150. return function ( dir ) {
  20151. // dir is assumed to be normalized
  20152. if ( dir.y > 0.99999 ) {
  20153. this.quaternion.set( 0, 0, 0, 1 );
  20154. } else if ( dir.y < - 0.99999 ) {
  20155. this.quaternion.set( 1, 0, 0, 0 );
  20156. } else {
  20157. axis.set( dir.z, 0, - dir.x ).normalize();
  20158. radians = Math.acos( dir.y );
  20159. this.quaternion.setFromAxisAngle( axis, radians );
  20160. }
  20161. };
  20162. }() );
  20163. THREE.ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  20164. if ( headLength === undefined ) headLength = 0.2 * length;
  20165. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  20166. this.line.scale.set( 1, length, 1 );
  20167. this.line.updateMatrix();
  20168. this.cone.scale.set( headWidth, headLength, headWidth );
  20169. this.cone.position.y = length;
  20170. this.cone.updateMatrix();
  20171. };
  20172. THREE.ArrowHelper.prototype.setColor = function ( color ) {
  20173. this.line.material.color.set( color );
  20174. this.cone.material.color.set( color );
  20175. };
  20176. // File:src/extras/helpers/BoxHelper.js
  20177. /**
  20178. * @author mrdoob / http://mrdoob.com/
  20179. */
  20180. THREE.BoxHelper = function ( object ) {
  20181. var geometry = new THREE.BufferGeometry();
  20182. geometry.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( 72 ), 3 ) );
  20183. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffff00 } ), THREE.LinePieces );
  20184. if ( object !== undefined ) {
  20185. this.update( object );
  20186. }
  20187. };
  20188. THREE.BoxHelper.prototype = Object.create( THREE.Line.prototype );
  20189. THREE.BoxHelper.prototype.update = function ( object ) {
  20190. var geometry = object.geometry;
  20191. if ( geometry.boundingBox === null ) {
  20192. geometry.computeBoundingBox();
  20193. }
  20194. var min = geometry.boundingBox.min;
  20195. var max = geometry.boundingBox.max;
  20196. /*
  20197. 5____4
  20198. 1/___0/|
  20199. | 6__|_7
  20200. 2/___3/
  20201. 0: max.x, max.y, max.z
  20202. 1: min.x, max.y, max.z
  20203. 2: min.x, min.y, max.z
  20204. 3: max.x, min.y, max.z
  20205. 4: max.x, max.y, min.z
  20206. 5: min.x, max.y, min.z
  20207. 6: min.x, min.y, min.z
  20208. 7: max.x, min.y, min.z
  20209. */
  20210. var vertices = this.geometry.attributes.position.array;
  20211. vertices[ 0 ] = max.x; vertices[ 1 ] = max.y; vertices[ 2 ] = max.z;
  20212. vertices[ 3 ] = min.x; vertices[ 4 ] = max.y; vertices[ 5 ] = max.z;
  20213. vertices[ 6 ] = min.x; vertices[ 7 ] = max.y; vertices[ 8 ] = max.z;
  20214. vertices[ 9 ] = min.x; vertices[ 10 ] = min.y; vertices[ 11 ] = max.z;
  20215. vertices[ 12 ] = min.x; vertices[ 13 ] = min.y; vertices[ 14 ] = max.z;
  20216. vertices[ 15 ] = max.x; vertices[ 16 ] = min.y; vertices[ 17 ] = max.z;
  20217. vertices[ 18 ] = max.x; vertices[ 19 ] = min.y; vertices[ 20 ] = max.z;
  20218. vertices[ 21 ] = max.x; vertices[ 22 ] = max.y; vertices[ 23 ] = max.z;
  20219. //
  20220. vertices[ 24 ] = max.x; vertices[ 25 ] = max.y; vertices[ 26 ] = min.z;
  20221. vertices[ 27 ] = min.x; vertices[ 28 ] = max.y; vertices[ 29 ] = min.z;
  20222. vertices[ 30 ] = min.x; vertices[ 31 ] = max.y; vertices[ 32 ] = min.z;
  20223. vertices[ 33 ] = min.x; vertices[ 34 ] = min.y; vertices[ 35 ] = min.z;
  20224. vertices[ 36 ] = min.x; vertices[ 37 ] = min.y; vertices[ 38 ] = min.z;
  20225. vertices[ 39 ] = max.x; vertices[ 40 ] = min.y; vertices[ 41 ] = min.z;
  20226. vertices[ 42 ] = max.x; vertices[ 43 ] = min.y; vertices[ 44 ] = min.z;
  20227. vertices[ 45 ] = max.x; vertices[ 46 ] = max.y; vertices[ 47 ] = min.z;
  20228. //
  20229. vertices[ 48 ] = max.x; vertices[ 49 ] = max.y; vertices[ 50 ] = max.z;
  20230. vertices[ 51 ] = max.x; vertices[ 52 ] = max.y; vertices[ 53 ] = min.z;
  20231. vertices[ 54 ] = min.x; vertices[ 55 ] = max.y; vertices[ 56 ] = max.z;
  20232. vertices[ 57 ] = min.x; vertices[ 58 ] = max.y; vertices[ 59 ] = min.z;
  20233. vertices[ 60 ] = min.x; vertices[ 61 ] = min.y; vertices[ 62 ] = max.z;
  20234. vertices[ 63 ] = min.x; vertices[ 64 ] = min.y; vertices[ 65 ] = min.z;
  20235. vertices[ 66 ] = max.x; vertices[ 67 ] = min.y; vertices[ 68 ] = max.z;
  20236. vertices[ 69 ] = max.x; vertices[ 70 ] = min.y; vertices[ 71 ] = min.z;
  20237. this.geometry.attributes.position.needsUpdate = true;
  20238. this.geometry.computeBoundingSphere();
  20239. this.matrixAutoUpdate = false;
  20240. this.matrixWorld = object.matrixWorld;
  20241. };
  20242. // File:src/extras/helpers/BoundingBoxHelper.js
  20243. /**
  20244. * @author WestLangley / http://github.com/WestLangley
  20245. */
  20246. // a helper to show the world-axis-aligned bounding box for an object
  20247. THREE.BoundingBoxHelper = function ( object, hex ) {
  20248. var color = ( hex !== undefined ) ? hex : 0x888888;
  20249. this.object = object;
  20250. this.box = new THREE.Box3();
  20251. THREE.Mesh.call( this, new THREE.BoxGeometry( 1, 1, 1 ), new THREE.MeshBasicMaterial( { color: color, wireframe: true } ) );
  20252. };
  20253. THREE.BoundingBoxHelper.prototype = Object.create( THREE.Mesh.prototype );
  20254. THREE.BoundingBoxHelper.prototype.update = function () {
  20255. this.box.setFromObject( this.object );
  20256. this.box.size( this.scale );
  20257. this.box.center( this.position );
  20258. };
  20259. // File:src/extras/helpers/CameraHelper.js
  20260. /**
  20261. * @author alteredq / http://alteredqualia.com/
  20262. *
  20263. * - shows frustum, line of sight and up of the camera
  20264. * - suitable for fast updates
  20265. * - based on frustum visualization in lightgl.js shadowmap example
  20266. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  20267. */
  20268. THREE.CameraHelper = function ( camera ) {
  20269. var geometry = new THREE.Geometry();
  20270. var material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  20271. var pointMap = {};
  20272. // colors
  20273. var hexFrustum = 0xffaa00;
  20274. var hexCone = 0xff0000;
  20275. var hexUp = 0x00aaff;
  20276. var hexTarget = 0xffffff;
  20277. var hexCross = 0x333333;
  20278. // near
  20279. addLine( "n1", "n2", hexFrustum );
  20280. addLine( "n2", "n4", hexFrustum );
  20281. addLine( "n4", "n3", hexFrustum );
  20282. addLine( "n3", "n1", hexFrustum );
  20283. // far
  20284. addLine( "f1", "f2", hexFrustum );
  20285. addLine( "f2", "f4", hexFrustum );
  20286. addLine( "f4", "f3", hexFrustum );
  20287. addLine( "f3", "f1", hexFrustum );
  20288. // sides
  20289. addLine( "n1", "f1", hexFrustum );
  20290. addLine( "n2", "f2", hexFrustum );
  20291. addLine( "n3", "f3", hexFrustum );
  20292. addLine( "n4", "f4", hexFrustum );
  20293. // cone
  20294. addLine( "p", "n1", hexCone );
  20295. addLine( "p", "n2", hexCone );
  20296. addLine( "p", "n3", hexCone );
  20297. addLine( "p", "n4", hexCone );
  20298. // up
  20299. addLine( "u1", "u2", hexUp );
  20300. addLine( "u2", "u3", hexUp );
  20301. addLine( "u3", "u1", hexUp );
  20302. // target
  20303. addLine( "c", "t", hexTarget );
  20304. addLine( "p", "c", hexCross );
  20305. // cross
  20306. addLine( "cn1", "cn2", hexCross );
  20307. addLine( "cn3", "cn4", hexCross );
  20308. addLine( "cf1", "cf2", hexCross );
  20309. addLine( "cf3", "cf4", hexCross );
  20310. function addLine( a, b, hex ) {
  20311. addPoint( a, hex );
  20312. addPoint( b, hex );
  20313. }
  20314. function addPoint( id, hex ) {
  20315. geometry.vertices.push( new THREE.Vector3() );
  20316. geometry.colors.push( new THREE.Color( hex ) );
  20317. if ( pointMap[ id ] === undefined ) {
  20318. pointMap[ id ] = [];
  20319. }
  20320. pointMap[ id ].push( geometry.vertices.length - 1 );
  20321. }
  20322. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20323. this.camera = camera;
  20324. this.matrixWorld = camera.matrixWorld;
  20325. this.matrixAutoUpdate = false;
  20326. this.pointMap = pointMap;
  20327. this.update();
  20328. };
  20329. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  20330. THREE.CameraHelper.prototype.update = function () {
  20331. var vector = new THREE.Vector3();
  20332. var camera = new THREE.Camera();
  20333. var projector = new THREE.Projector();
  20334. return function () {
  20335. var scope = this;
  20336. var w = 1, h = 1;
  20337. // we need just camera projection matrix
  20338. // world matrix must be identity
  20339. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  20340. // center / target
  20341. setPoint( "c", 0, 0, - 1 );
  20342. setPoint( "t", 0, 0, 1 );
  20343. // near
  20344. setPoint( "n1", - w, - h, - 1 );
  20345. setPoint( "n2", w, - h, - 1 );
  20346. setPoint( "n3", - w, h, - 1 );
  20347. setPoint( "n4", w, h, - 1 );
  20348. // far
  20349. setPoint( "f1", - w, - h, 1 );
  20350. setPoint( "f2", w, - h, 1 );
  20351. setPoint( "f3", - w, h, 1 );
  20352. setPoint( "f4", w, h, 1 );
  20353. // up
  20354. setPoint( "u1", w * 0.7, h * 1.1, - 1 );
  20355. setPoint( "u2", - w * 0.7, h * 1.1, - 1 );
  20356. setPoint( "u3", 0, h * 2, - 1 );
  20357. // cross
  20358. setPoint( "cf1", - w, 0, 1 );
  20359. setPoint( "cf2", w, 0, 1 );
  20360. setPoint( "cf3", 0, - h, 1 );
  20361. setPoint( "cf4", 0, h, 1 );
  20362. setPoint( "cn1", - w, 0, - 1 );
  20363. setPoint( "cn2", w, 0, - 1 );
  20364. setPoint( "cn3", 0, - h, - 1 );
  20365. setPoint( "cn4", 0, h, - 1 );
  20366. function setPoint( point, x, y, z ) {
  20367. vector.set( x, y, z );
  20368. projector.unprojectVector( vector, camera );
  20369. var points = scope.pointMap[ point ];
  20370. if ( points !== undefined ) {
  20371. for ( var i = 0, il = points.length; i < il; i ++ ) {
  20372. scope.geometry.vertices[ points[ i ] ].copy( vector );
  20373. }
  20374. }
  20375. }
  20376. this.geometry.verticesNeedUpdate = true;
  20377. };
  20378. }();
  20379. // File:src/extras/helpers/DirectionalLightHelper.js
  20380. /**
  20381. * @author alteredq / http://alteredqualia.com/
  20382. * @author mrdoob / http://mrdoob.com/
  20383. * @author WestLangley / http://github.com/WestLangley
  20384. */
  20385. THREE.DirectionalLightHelper = function ( light, size ) {
  20386. THREE.Object3D.call( this );
  20387. this.light = light;
  20388. this.light.updateMatrixWorld();
  20389. this.matrixWorld = light.matrixWorld;
  20390. this.matrixAutoUpdate = false;
  20391. size = size || 1;
  20392. var geometry = new THREE.Geometry();
  20393. geometry.vertices.push(
  20394. new THREE.Vector3( - size, size, 0 ),
  20395. new THREE.Vector3( size, size, 0 ),
  20396. new THREE.Vector3( size, - size, 0 ),
  20397. new THREE.Vector3( - size, - size, 0 ),
  20398. new THREE.Vector3( - size, size, 0 )
  20399. );
  20400. var material = new THREE.LineBasicMaterial( { fog: false } );
  20401. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20402. this.lightPlane = new THREE.Line( geometry, material );
  20403. this.add( this.lightPlane );
  20404. geometry = new THREE.Geometry();
  20405. geometry.vertices.push(
  20406. new THREE.Vector3(),
  20407. new THREE.Vector3()
  20408. );
  20409. material = new THREE.LineBasicMaterial( { fog: false } );
  20410. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20411. this.targetLine = new THREE.Line( geometry, material );
  20412. this.add( this.targetLine );
  20413. this.update();
  20414. };
  20415. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20416. THREE.DirectionalLightHelper.prototype.dispose = function () {
  20417. this.lightPlane.geometry.dispose();
  20418. this.lightPlane.material.dispose();
  20419. this.targetLine.geometry.dispose();
  20420. this.targetLine.material.dispose();
  20421. };
  20422. THREE.DirectionalLightHelper.prototype.update = function () {
  20423. var v1 = new THREE.Vector3();
  20424. var v2 = new THREE.Vector3();
  20425. var v3 = new THREE.Vector3();
  20426. return function () {
  20427. v1.setFromMatrixPosition( this.light.matrixWorld );
  20428. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  20429. v3.subVectors( v2, v1 );
  20430. this.lightPlane.lookAt( v3 );
  20431. this.lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20432. this.targetLine.geometry.vertices[ 1 ].copy( v3 );
  20433. this.targetLine.geometry.verticesNeedUpdate = true;
  20434. this.targetLine.material.color.copy( this.lightPlane.material.color );
  20435. }
  20436. }();
  20437. // File:src/extras/helpers/EdgesHelper.js
  20438. /**
  20439. * @author WestLangley / http://github.com/WestLangley
  20440. */
  20441. THREE.EdgesHelper = function ( object, hex ) {
  20442. var color = ( hex !== undefined ) ? hex : 0xffffff;
  20443. var edge = [ 0, 0 ], hash = {};
  20444. var sortFunction = function ( a, b ) { return a - b };
  20445. var keys = [ 'a', 'b', 'c' ];
  20446. var geometry = new THREE.BufferGeometry();
  20447. var geometry2 = object.geometry.clone();
  20448. geometry2.mergeVertices();
  20449. geometry2.computeFaceNormals();
  20450. var vertices = geometry2.vertices;
  20451. var faces = geometry2.faces;
  20452. var numEdges = 0;
  20453. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20454. var face = faces[ i ];
  20455. for ( var j = 0; j < 3; j ++ ) {
  20456. edge[ 0 ] = face[ keys[ j ] ];
  20457. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  20458. edge.sort( sortFunction );
  20459. var key = edge.toString();
  20460. if ( hash[ key ] === undefined ) {
  20461. hash[ key ] = { vert1: edge[ 0 ], vert2: edge[ 1 ], face1: i, face2: undefined };
  20462. numEdges ++;
  20463. } else {
  20464. hash[ key ].face2 = i;
  20465. }
  20466. }
  20467. }
  20468. geometry.addAttribute( 'position', new THREE.Float32Attribute( numEdges * 2 * 3, 3 ) );
  20469. var coords = geometry.attributes.position.array;
  20470. var index = 0;
  20471. for ( var key in hash ) {
  20472. var h = hash[ key ];
  20473. if ( h.face2 === undefined || faces[ h.face1 ].normal.dot( faces[ h.face2 ].normal ) < 0.9999 ) { // hardwired const OK
  20474. var vertex = vertices[ h.vert1 ];
  20475. coords[ index ++ ] = vertex.x;
  20476. coords[ index ++ ] = vertex.y;
  20477. coords[ index ++ ] = vertex.z;
  20478. vertex = vertices[ h.vert2 ];
  20479. coords[ index ++ ] = vertex.x;
  20480. coords[ index ++ ] = vertex.y;
  20481. coords[ index ++ ] = vertex.z;
  20482. }
  20483. }
  20484. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color } ), THREE.LinePieces );
  20485. this.matrixAutoUpdate = false;
  20486. this.matrixWorld = object.matrixWorld;
  20487. };
  20488. THREE.EdgesHelper.prototype = Object.create( THREE.Line.prototype );
  20489. // File:src/extras/helpers/FaceNormalsHelper.js
  20490. /**
  20491. * @author mrdoob / http://mrdoob.com/
  20492. * @author WestLangley / http://github.com/WestLangley
  20493. */
  20494. THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) {
  20495. this.object = object;
  20496. this.size = ( size !== undefined ) ? size : 1;
  20497. var color = ( hex !== undefined ) ? hex : 0xffff00;
  20498. var width = ( linewidth !== undefined ) ? linewidth : 1;
  20499. var geometry = new THREE.Geometry();
  20500. var faces = this.object.geometry.faces;
  20501. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20502. geometry.vertices.push( new THREE.Vector3(), new THREE.Vector3() );
  20503. }
  20504. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  20505. this.matrixAutoUpdate = false;
  20506. this.normalMatrix = new THREE.Matrix3();
  20507. this.update();
  20508. };
  20509. THREE.FaceNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  20510. THREE.FaceNormalsHelper.prototype.update = function () {
  20511. var vertices = this.geometry.vertices;
  20512. var object = this.object;
  20513. var objectVertices = object.geometry.vertices;
  20514. var objectFaces = object.geometry.faces;
  20515. var objectWorldMatrix = object.matrixWorld;
  20516. object.updateMatrixWorld( true );
  20517. this.normalMatrix.getNormalMatrix( objectWorldMatrix );
  20518. for ( var i = 0, i2 = 0, l = objectFaces.length; i < l; i ++, i2 += 2 ) {
  20519. var face = objectFaces[ i ];
  20520. vertices[ i2 ].copy( objectVertices[ face.a ] )
  20521. .add( objectVertices[ face.b ] )
  20522. .add( objectVertices[ face.c ] )
  20523. .divideScalar( 3 )
  20524. .applyMatrix4( objectWorldMatrix );
  20525. vertices[ i2 + 1 ].copy( face.normal )
  20526. .applyMatrix3( this.normalMatrix )
  20527. .normalize()
  20528. .multiplyScalar( this.size )
  20529. .add( vertices[ i2 ] );
  20530. }
  20531. this.geometry.verticesNeedUpdate = true;
  20532. return this;
  20533. };
  20534. // File:src/extras/helpers/GridHelper.js
  20535. /**
  20536. * @author mrdoob / http://mrdoob.com/
  20537. */
  20538. THREE.GridHelper = function ( size, step ) {
  20539. var geometry = new THREE.Geometry();
  20540. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20541. this.color1 = new THREE.Color( 0x444444 );
  20542. this.color2 = new THREE.Color( 0x888888 );
  20543. for ( var i = - size; i <= size; i += step ) {
  20544. geometry.vertices.push(
  20545. new THREE.Vector3( - size, 0, i ), new THREE.Vector3( size, 0, i ),
  20546. new THREE.Vector3( i, 0, - size ), new THREE.Vector3( i, 0, size )
  20547. );
  20548. var color = i === 0 ? this.color1 : this.color2;
  20549. geometry.colors.push( color, color, color, color );
  20550. }
  20551. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20552. };
  20553. THREE.GridHelper.prototype = Object.create( THREE.Line.prototype );
  20554. THREE.GridHelper.prototype.setColors = function( colorCenterLine, colorGrid ) {
  20555. this.color1.set( colorCenterLine );
  20556. this.color2.set( colorGrid );
  20557. this.geometry.colorsNeedUpdate = true;
  20558. }
  20559. // File:src/extras/helpers/HemisphereLightHelper.js
  20560. /**
  20561. * @author alteredq / http://alteredqualia.com/
  20562. * @author mrdoob / http://mrdoob.com/
  20563. */
  20564. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  20565. THREE.Object3D.call( this );
  20566. this.light = light;
  20567. this.light.updateMatrixWorld();
  20568. this.matrixWorld = light.matrixWorld;
  20569. this.matrixAutoUpdate = false;
  20570. this.colors = [ new THREE.Color(), new THREE.Color() ];
  20571. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20572. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  20573. for ( var i = 0, il = 8; i < il; i ++ ) {
  20574. geometry.faces[ i ].color = this.colors[ i < 4 ? 0 : 1 ];
  20575. }
  20576. var material = new THREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors, wireframe: true } );
  20577. this.lightSphere = new THREE.Mesh( geometry, material );
  20578. this.add( this.lightSphere );
  20579. this.update();
  20580. };
  20581. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20582. THREE.HemisphereLightHelper.prototype.dispose = function () {
  20583. this.lightSphere.geometry.dispose();
  20584. this.lightSphere.material.dispose();
  20585. };
  20586. THREE.HemisphereLightHelper.prototype.update = function () {
  20587. var vector = new THREE.Vector3();
  20588. return function () {
  20589. this.colors[ 0 ].copy( this.light.color ).multiplyScalar( this.light.intensity );
  20590. this.colors[ 1 ].copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  20591. this.lightSphere.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  20592. this.lightSphere.geometry.colorsNeedUpdate = true;
  20593. }
  20594. }();
  20595. // File:src/extras/helpers/PointLightHelper.js
  20596. /**
  20597. * @author alteredq / http://alteredqualia.com/
  20598. * @author mrdoob / http://mrdoob.com/
  20599. */
  20600. THREE.PointLightHelper = function ( light, sphereSize ) {
  20601. this.light = light;
  20602. this.light.updateMatrixWorld();
  20603. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20604. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  20605. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20606. THREE.Mesh.call( this, geometry, material );
  20607. this.matrixWorld = this.light.matrixWorld;
  20608. this.matrixAutoUpdate = false;
  20609. /*
  20610. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  20611. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  20612. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20613. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  20614. var d = light.distance;
  20615. if ( d === 0.0 ) {
  20616. this.lightDistance.visible = false;
  20617. } else {
  20618. this.lightDistance.scale.set( d, d, d );
  20619. }
  20620. this.add( this.lightDistance );
  20621. */
  20622. };
  20623. THREE.PointLightHelper.prototype = Object.create( THREE.Mesh.prototype );
  20624. THREE.PointLightHelper.prototype.dispose = function () {
  20625. this.geometry.dispose();
  20626. this.material.dispose();
  20627. };
  20628. THREE.PointLightHelper.prototype.update = function () {
  20629. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20630. /*
  20631. var d = this.light.distance;
  20632. if ( d === 0.0 ) {
  20633. this.lightDistance.visible = false;
  20634. } else {
  20635. this.lightDistance.visible = true;
  20636. this.lightDistance.scale.set( d, d, d );
  20637. }
  20638. */
  20639. };
  20640. // File:src/extras/helpers/SkeletonHelper.js
  20641. /**
  20642. * @author Sean Griffin / http://twitter.com/sgrif
  20643. * @author Michael Guerrero / http://realitymeltdown.com
  20644. * @author mrdoob / http://mrdoob.com/
  20645. */
  20646. THREE.SkeletonHelper = function ( object ) {
  20647. var skeleton = object.skeleton;
  20648. var geometry = new THREE.Geometry();
  20649. for ( var i = 0; i < skeleton.bones.length; i ++ ) {
  20650. var bone = skeleton.bones[ i ];
  20651. if ( bone.parent instanceof THREE.Bone ) {
  20652. geometry.vertices.push( new THREE.Vector3() );
  20653. geometry.vertices.push( new THREE.Vector3() );
  20654. geometry.colors.push( new THREE.Color( 0, 0, 1 ) );
  20655. geometry.colors.push( new THREE.Color( 0, 1, 0 ) );
  20656. }
  20657. }
  20658. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors, depthTest: false, depthWrite: false, transparent: true } );
  20659. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20660. this.skeleton = skeleton;
  20661. this.matrixWorld = object.matrixWorld;
  20662. this.matrixAutoUpdate = false;
  20663. this.update();
  20664. };
  20665. THREE.SkeletonHelper.prototype = Object.create( THREE.Line.prototype );
  20666. THREE.SkeletonHelper.prototype.update = function () {
  20667. var geometry = this.geometry;
  20668. var j = 0;
  20669. for ( var i = 0; i < this.skeleton.bones.length; i ++ ) {
  20670. var bone = this.skeleton.bones[ i ];
  20671. if ( bone.parent instanceof THREE.Bone ) {
  20672. geometry.vertices[ j ].setFromMatrixPosition( bone.skinMatrix );
  20673. geometry.vertices[ j + 1 ].setFromMatrixPosition( bone.parent.skinMatrix );
  20674. j += 2;
  20675. }
  20676. }
  20677. geometry.verticesNeedUpdate = true;
  20678. geometry.computeBoundingSphere();
  20679. };
  20680. // File:src/extras/helpers/SpotLightHelper.js
  20681. /**
  20682. * @author alteredq / http://alteredqualia.com/
  20683. * @author mrdoob / http://mrdoob.com/
  20684. * @author WestLangley / http://github.com/WestLangley
  20685. */
  20686. THREE.SpotLightHelper = function ( light ) {
  20687. THREE.Object3D.call( this );
  20688. this.light = light;
  20689. this.light.updateMatrixWorld();
  20690. this.matrixWorld = light.matrixWorld;
  20691. this.matrixAutoUpdate = false;
  20692. var geometry = new THREE.CylinderGeometry( 0, 1, 1, 8, 1, true );
  20693. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, - 0.5, 0 ) );
  20694. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  20695. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  20696. this.cone = new THREE.Mesh( geometry, material );
  20697. this.add( this.cone );
  20698. this.update();
  20699. };
  20700. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20701. THREE.SpotLightHelper.prototype.dispose = function () {
  20702. this.cone.geometry.dispose();
  20703. this.cone.material.dispose();
  20704. };
  20705. THREE.SpotLightHelper.prototype.update = function () {
  20706. var vector = new THREE.Vector3();
  20707. var vector2 = new THREE.Vector3();
  20708. return function () {
  20709. var coneLength = this.light.distance ? this.light.distance : 10000;
  20710. var coneWidth = coneLength * Math.tan( this.light.angle );
  20711. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  20712. vector.setFromMatrixPosition( this.light.matrixWorld );
  20713. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  20714. this.cone.lookAt( vector2.sub( vector ) );
  20715. this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20716. };
  20717. }();
  20718. // File:src/extras/helpers/VertexNormalsHelper.js
  20719. /**
  20720. * @author mrdoob / http://mrdoob.com/
  20721. * @author WestLangley / http://github.com/WestLangley
  20722. */
  20723. THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) {
  20724. this.object = object;
  20725. this.size = ( size !== undefined ) ? size : 1;
  20726. var color = ( hex !== undefined ) ? hex : 0xff0000;
  20727. var width = ( linewidth !== undefined ) ? linewidth : 1;
  20728. var geometry = new THREE.Geometry();
  20729. var vertices = object.geometry.vertices;
  20730. var faces = object.geometry.faces;
  20731. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20732. var face = faces[ i ];
  20733. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  20734. geometry.vertices.push( new THREE.Vector3(), new THREE.Vector3() );
  20735. }
  20736. }
  20737. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  20738. this.matrixAutoUpdate = false;
  20739. this.normalMatrix = new THREE.Matrix3();
  20740. this.update();
  20741. };
  20742. THREE.VertexNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  20743. THREE.VertexNormalsHelper.prototype.update = ( function ( object ) {
  20744. var v1 = new THREE.Vector3();
  20745. return function( object ) {
  20746. var keys = [ 'a', 'b', 'c', 'd' ];
  20747. this.object.updateMatrixWorld( true );
  20748. this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
  20749. var vertices = this.geometry.vertices;
  20750. var verts = this.object.geometry.vertices;
  20751. var faces = this.object.geometry.faces;
  20752. var worldMatrix = this.object.matrixWorld;
  20753. var idx = 0;
  20754. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20755. var face = faces[ i ];
  20756. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  20757. var vertexId = face[ keys[ j ] ];
  20758. var vertex = verts[ vertexId ];
  20759. var normal = face.vertexNormals[ j ];
  20760. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  20761. v1.copy( normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
  20762. v1.add( vertices[ idx ] );
  20763. idx = idx + 1;
  20764. vertices[ idx ].copy( v1 );
  20765. idx = idx + 1;
  20766. }
  20767. }
  20768. this.geometry.verticesNeedUpdate = true;
  20769. return this;
  20770. }
  20771. }());
  20772. // File:src/extras/helpers/VertexTangentsHelper.js
  20773. /**
  20774. * @author mrdoob / http://mrdoob.com/
  20775. * @author WestLangley / http://github.com/WestLangley
  20776. */
  20777. THREE.VertexTangentsHelper = function ( object, size, hex, linewidth ) {
  20778. this.object = object;
  20779. this.size = ( size !== undefined ) ? size : 1;
  20780. var color = ( hex !== undefined ) ? hex : 0x0000ff;
  20781. var width = ( linewidth !== undefined ) ? linewidth : 1;
  20782. var geometry = new THREE.Geometry();
  20783. var vertices = object.geometry.vertices;
  20784. var faces = object.geometry.faces;
  20785. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20786. var face = faces[ i ];
  20787. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  20788. geometry.vertices.push( new THREE.Vector3() );
  20789. geometry.vertices.push( new THREE.Vector3() );
  20790. }
  20791. }
  20792. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  20793. this.matrixAutoUpdate = false;
  20794. this.update();
  20795. };
  20796. THREE.VertexTangentsHelper.prototype = Object.create( THREE.Line.prototype );
  20797. THREE.VertexTangentsHelper.prototype.update = ( function ( object ) {
  20798. var v1 = new THREE.Vector3();
  20799. return function( object ) {
  20800. var keys = [ 'a', 'b', 'c', 'd' ];
  20801. this.object.updateMatrixWorld( true );
  20802. var vertices = this.geometry.vertices;
  20803. var verts = this.object.geometry.vertices;
  20804. var faces = this.object.geometry.faces;
  20805. var worldMatrix = this.object.matrixWorld;
  20806. var idx = 0;
  20807. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20808. var face = faces[ i ];
  20809. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  20810. var vertexId = face[ keys[ j ] ];
  20811. var vertex = verts[ vertexId ];
  20812. var tangent = face.vertexTangents[ j ];
  20813. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  20814. v1.copy( tangent ).transformDirection( worldMatrix ).multiplyScalar( this.size );
  20815. v1.add( vertices[ idx ] );
  20816. idx = idx + 1;
  20817. vertices[ idx ].copy( v1 );
  20818. idx = idx + 1;
  20819. }
  20820. }
  20821. this.geometry.verticesNeedUpdate = true;
  20822. return this;
  20823. }
  20824. }());
  20825. // File:src/extras/helpers/WireframeHelper.js
  20826. /**
  20827. * @author mrdoob / http://mrdoob.com/
  20828. */
  20829. THREE.WireframeHelper = function ( object, hex ) {
  20830. var color = ( hex !== undefined ) ? hex : 0xffffff;
  20831. var edge = [ 0, 0 ], hash = {};
  20832. var sortFunction = function ( a, b ) { return a - b };
  20833. var keys = [ 'a', 'b', 'c' ];
  20834. var geometry = new THREE.BufferGeometry();
  20835. if ( object.geometry instanceof THREE.Geometry ) {
  20836. var vertices = object.geometry.vertices;
  20837. var faces = object.geometry.faces;
  20838. var numEdges = 0;
  20839. // allocate maximal size
  20840. var edges = new Uint32Array( 6 * faces.length );
  20841. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20842. var face = faces[ i ];
  20843. for ( var j = 0; j < 3; j ++ ) {
  20844. edge[ 0 ] = face[ keys[ j ] ];
  20845. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  20846. edge.sort( sortFunction );
  20847. var key = edge.toString();
  20848. if ( hash[ key ] === undefined ) {
  20849. edges[ 2 * numEdges ] = edge[ 0 ];
  20850. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  20851. hash[ key ] = true;
  20852. numEdges ++;
  20853. }
  20854. }
  20855. }
  20856. var coords = new Float32Array( numEdges * 2 * 3 );
  20857. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  20858. for ( var j = 0; j < 2; j ++ ) {
  20859. var vertex = vertices[ edges [ 2 * i + j] ];
  20860. var index = 6 * i + 3 * j;
  20861. coords[ index + 0 ] = vertex.x;
  20862. coords[ index + 1 ] = vertex.y;
  20863. coords[ index + 2 ] = vertex.z;
  20864. }
  20865. }
  20866. geometry.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  20867. } else if ( object.geometry instanceof THREE.BufferGeometry ) {
  20868. if ( object.geometry.attributes.index !== undefined ) { // Indexed BufferGeometry
  20869. var vertices = object.geometry.attributes.position.array;
  20870. var indices = object.geometry.attributes.index.array;
  20871. var offsets = object.geometry.offsets;
  20872. var numEdges = 0;
  20873. // allocate maximal size
  20874. var edges = new Uint32Array( 2 * indices.length );
  20875. for ( var o = 0, ol = offsets.length; o < ol; ++ o ) {
  20876. var start = offsets[ o ].start;
  20877. var count = offsets[ o ].count;
  20878. var index = offsets[ o ].index;
  20879. for ( var i = start, il = start + count; i < il; i += 3 ) {
  20880. for ( var j = 0; j < 3; j ++ ) {
  20881. edge[ 0 ] = index + indices[ i + j ];
  20882. edge[ 1 ] = index + indices[ i + ( j + 1 ) % 3 ];
  20883. edge.sort( sortFunction );
  20884. var key = edge.toString();
  20885. if ( hash[ key ] === undefined ) {
  20886. edges[ 2 * numEdges ] = edge[ 0 ];
  20887. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  20888. hash[ key ] = true;
  20889. numEdges ++;
  20890. }
  20891. }
  20892. }
  20893. }
  20894. var coords = new Float32Array( numEdges * 2 * 3 );
  20895. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  20896. for ( var j = 0; j < 2; j ++ ) {
  20897. var index = 6 * i + 3 * j;
  20898. var index2 = 3 * edges[ 2 * i + j];
  20899. coords[ index + 0 ] = vertices[ index2 ];
  20900. coords[ index + 1 ] = vertices[ index2 + 1 ];
  20901. coords[ index + 2 ] = vertices[ index2 + 2 ];
  20902. }
  20903. }
  20904. geometry.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  20905. } else { // non-indexed BufferGeometry
  20906. var vertices = object.geometry.attributes.position.array;
  20907. var numEdges = vertices.length / 3;
  20908. var numTris = numEdges / 3;
  20909. var coords = new Float32Array( numEdges * 2 * 3 );
  20910. for ( var i = 0, l = numTris; i < l; i ++ ) {
  20911. for ( var j = 0; j < 3; j ++ ) {
  20912. var index = 18 * i + 6 * j;
  20913. var index1 = 9 * i + 3 * j;
  20914. coords[ index + 0 ] = vertices[ index1 ];
  20915. coords[ index + 1 ] = vertices[ index1 + 1 ];
  20916. coords[ index + 2 ] = vertices[ index1 + 2 ];
  20917. var index2 = 9 * i + 3 * ( ( j + 1 ) % 3 );
  20918. coords[ index + 3 ] = vertices[ index2 ];
  20919. coords[ index + 4 ] = vertices[ index2 + 1 ];
  20920. coords[ index + 5 ] = vertices[ index2 + 2 ];
  20921. }
  20922. }
  20923. geometry.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  20924. }
  20925. }
  20926. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color } ), THREE.LinePieces );
  20927. this.matrixAutoUpdate = false;
  20928. this.matrixWorld = object.matrixWorld;
  20929. };
  20930. THREE.WireframeHelper.prototype = Object.create( THREE.Line.prototype );
  20931. // File:src/extras/objects/ImmediateRenderObject.js
  20932. /**
  20933. * @author alteredq / http://alteredqualia.com/
  20934. */
  20935. THREE.ImmediateRenderObject = function () {
  20936. THREE.Object3D.call( this );
  20937. this.render = function ( renderCallback ) {};
  20938. };
  20939. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  20940. // File:src/extras/objects/LensFlare.js
  20941. /**
  20942. * @author mikael emtinger / http://gomo.se/
  20943. * @author alteredq / http://alteredqualia.com/
  20944. */
  20945. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  20946. THREE.Object3D.call( this );
  20947. this.lensFlares = [];
  20948. this.positionScreen = new THREE.Vector3();
  20949. this.customUpdateCallback = undefined;
  20950. if( texture !== undefined ) {
  20951. this.add( texture, size, distance, blending, color );
  20952. }
  20953. };
  20954. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  20955. /*
  20956. * Add: adds another flare
  20957. */
  20958. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  20959. if( size === undefined ) size = - 1;
  20960. if( distance === undefined ) distance = 0;
  20961. if( opacity === undefined ) opacity = 1;
  20962. if( color === undefined ) color = new THREE.Color( 0xffffff );
  20963. if( blending === undefined ) blending = THREE.NormalBlending;
  20964. distance = Math.min( distance, Math.max( 0, distance ) );
  20965. this.lensFlares.push( { texture: texture, // THREE.Texture
  20966. size: size, // size in pixels (-1 = use texture.width)
  20967. distance: distance, // distance (0-1) from light source (0=at light source)
  20968. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  20969. scale: 1, // scale
  20970. rotation: 1, // rotation
  20971. opacity: opacity, // opacity
  20972. color: color, // color
  20973. blending: blending } ); // blending
  20974. };
  20975. /*
  20976. * Update lens flares update positions on all flares based on the screen position
  20977. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  20978. */
  20979. THREE.LensFlare.prototype.updateLensFlares = function () {
  20980. var f, fl = this.lensFlares.length;
  20981. var flare;
  20982. var vecX = - this.positionScreen.x * 2;
  20983. var vecY = - this.positionScreen.y * 2;
  20984. for( f = 0; f < fl; f ++ ) {
  20985. flare = this.lensFlares[ f ];
  20986. flare.x = this.positionScreen.x + vecX * flare.distance;
  20987. flare.y = this.positionScreen.y + vecY * flare.distance;
  20988. flare.wantedRotation = flare.x * Math.PI * 0.25;
  20989. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  20990. }
  20991. };
  20992. // File:src/extras/objects/MorphBlendMesh.js
  20993. /**
  20994. * @author alteredq / http://alteredqualia.com/
  20995. */
  20996. THREE.MorphBlendMesh = function( geometry, material ) {
  20997. THREE.Mesh.call( this, geometry, material );
  20998. this.animationsMap = {};
  20999. this.animationsList = [];
  21000. // prepare default animation
  21001. // (all frames played together in 1 second)
  21002. var numFrames = this.geometry.morphTargets.length;
  21003. var name = "__default";
  21004. var startFrame = 0;
  21005. var endFrame = numFrames - 1;
  21006. var fps = numFrames / 1;
  21007. this.createAnimation( name, startFrame, endFrame, fps );
  21008. this.setAnimationWeight( name, 1 );
  21009. };
  21010. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  21011. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  21012. var animation = {
  21013. startFrame: start,
  21014. endFrame: end,
  21015. length: end - start + 1,
  21016. fps: fps,
  21017. duration: ( end - start ) / fps,
  21018. lastFrame: 0,
  21019. currentFrame: 0,
  21020. active: false,
  21021. time: 0,
  21022. direction: 1,
  21023. weight: 1,
  21024. directionBackwards: false,
  21025. mirroredLoop: false
  21026. };
  21027. this.animationsMap[ name ] = animation;
  21028. this.animationsList.push( animation );
  21029. };
  21030. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  21031. var pattern = /([a-z]+)_?(\d+)/;
  21032. var firstAnimation, frameRanges = {};
  21033. var geometry = this.geometry;
  21034. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  21035. var morph = geometry.morphTargets[ i ];
  21036. var chunks = morph.name.match( pattern );
  21037. if ( chunks && chunks.length > 1 ) {
  21038. var name = chunks[ 1 ];
  21039. var num = chunks[ 2 ];
  21040. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: - Infinity };
  21041. var range = frameRanges[ name ];
  21042. if ( i < range.start ) range.start = i;
  21043. if ( i > range.end ) range.end = i;
  21044. if ( ! firstAnimation ) firstAnimation = name;
  21045. }
  21046. }
  21047. for ( var name in frameRanges ) {
  21048. var range = frameRanges[ name ];
  21049. this.createAnimation( name, range.start, range.end, fps );
  21050. }
  21051. this.firstAnimation = firstAnimation;
  21052. };
  21053. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  21054. var animation = this.animationsMap[ name ];
  21055. if ( animation ) {
  21056. animation.direction = 1;
  21057. animation.directionBackwards = false;
  21058. }
  21059. };
  21060. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  21061. var animation = this.animationsMap[ name ];
  21062. if ( animation ) {
  21063. animation.direction = - 1;
  21064. animation.directionBackwards = true;
  21065. }
  21066. };
  21067. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  21068. var animation = this.animationsMap[ name ];
  21069. if ( animation ) {
  21070. animation.fps = fps;
  21071. animation.duration = ( animation.end - animation.start ) / animation.fps;
  21072. }
  21073. };
  21074. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  21075. var animation = this.animationsMap[ name ];
  21076. if ( animation ) {
  21077. animation.duration = duration;
  21078. animation.fps = ( animation.end - animation.start ) / animation.duration;
  21079. }
  21080. };
  21081. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  21082. var animation = this.animationsMap[ name ];
  21083. if ( animation ) {
  21084. animation.weight = weight;
  21085. }
  21086. };
  21087. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  21088. var animation = this.animationsMap[ name ];
  21089. if ( animation ) {
  21090. animation.time = time;
  21091. }
  21092. };
  21093. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  21094. var time = 0;
  21095. var animation = this.animationsMap[ name ];
  21096. if ( animation ) {
  21097. time = animation.time;
  21098. }
  21099. return time;
  21100. };
  21101. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  21102. var duration = - 1;
  21103. var animation = this.animationsMap[ name ];
  21104. if ( animation ) {
  21105. duration = animation.duration;
  21106. }
  21107. return duration;
  21108. };
  21109. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  21110. var animation = this.animationsMap[ name ];
  21111. if ( animation ) {
  21112. animation.time = 0;
  21113. animation.active = true;
  21114. } else {
  21115. console.warn( "animation[" + name + "] undefined" );
  21116. }
  21117. };
  21118. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  21119. var animation = this.animationsMap[ name ];
  21120. if ( animation ) {
  21121. animation.active = false;
  21122. }
  21123. };
  21124. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  21125. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  21126. var animation = this.animationsList[ i ];
  21127. if ( ! animation.active ) continue;
  21128. var frameTime = animation.duration / animation.length;
  21129. animation.time += animation.direction * delta;
  21130. if ( animation.mirroredLoop ) {
  21131. if ( animation.time > animation.duration || animation.time < 0 ) {
  21132. animation.direction *= - 1;
  21133. if ( animation.time > animation.duration ) {
  21134. animation.time = animation.duration;
  21135. animation.directionBackwards = true;
  21136. }
  21137. if ( animation.time < 0 ) {
  21138. animation.time = 0;
  21139. animation.directionBackwards = false;
  21140. }
  21141. }
  21142. } else {
  21143. animation.time = animation.time % animation.duration;
  21144. if ( animation.time < 0 ) animation.time += animation.duration;
  21145. }
  21146. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  21147. var weight = animation.weight;
  21148. if ( keyframe !== animation.currentFrame ) {
  21149. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  21150. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  21151. this.morphTargetInfluences[ keyframe ] = 0;
  21152. animation.lastFrame = animation.currentFrame;
  21153. animation.currentFrame = keyframe;
  21154. }
  21155. var mix = ( animation.time % frameTime ) / frameTime;
  21156. if ( animation.directionBackwards ) mix = 1 - mix;
  21157. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  21158. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  21159. }
  21160. };
  21161. // File:src/extras/renderers/plugins/LensFlarePlugin.js
  21162. /**
  21163. * @author mikael emtinger / http://gomo.se/
  21164. * @author alteredq / http://alteredqualia.com/
  21165. */
  21166. THREE.LensFlarePlugin = function () {
  21167. var flares = [];
  21168. var _gl, _renderer, _precision, _lensFlare = {};
  21169. this.init = function ( renderer ) {
  21170. _gl = renderer.context;
  21171. _renderer = renderer;
  21172. _precision = renderer.getPrecision();
  21173. _lensFlare.vertices = new Float32Array( 8 + 8 );
  21174. _lensFlare.faces = new Uint16Array( 6 );
  21175. var i = 0;
  21176. _lensFlare.vertices[ i ++ ] = - 1; _lensFlare.vertices[ i ++ ] = - 1; // vertex
  21177. _lensFlare.vertices[ i ++ ] = 0; _lensFlare.vertices[ i ++ ] = 0; // uv... etc.
  21178. _lensFlare.vertices[ i ++ ] = 1; _lensFlare.vertices[ i ++ ] = - 1;
  21179. _lensFlare.vertices[ i ++ ] = 1; _lensFlare.vertices[ i ++ ] = 0;
  21180. _lensFlare.vertices[ i ++ ] = 1; _lensFlare.vertices[ i ++ ] = 1;
  21181. _lensFlare.vertices[ i ++ ] = 1; _lensFlare.vertices[ i ++ ] = 1;
  21182. _lensFlare.vertices[ i ++ ] = - 1; _lensFlare.vertices[ i ++ ] = 1;
  21183. _lensFlare.vertices[ i ++ ] = 0; _lensFlare.vertices[ i ++ ] = 1;
  21184. i = 0;
  21185. _lensFlare.faces[ i ++ ] = 0; _lensFlare.faces[ i ++ ] = 1; _lensFlare.faces[ i ++ ] = 2;
  21186. _lensFlare.faces[ i ++ ] = 0; _lensFlare.faces[ i ++ ] = 2; _lensFlare.faces[ i ++ ] = 3;
  21187. // buffers
  21188. _lensFlare.vertexBuffer = _gl.createBuffer();
  21189. _lensFlare.elementBuffer = _gl.createBuffer();
  21190. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21191. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  21192. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21193. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  21194. // textures
  21195. _lensFlare.tempTexture = _gl.createTexture();
  21196. _lensFlare.occlusionTexture = _gl.createTexture();
  21197. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21198. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  21199. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21200. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21201. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21202. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21203. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21204. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  21205. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21206. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21207. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21208. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21209. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  21210. _lensFlare.hasVertexTexture = false;
  21211. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ], _precision );
  21212. } else {
  21213. _lensFlare.hasVertexTexture = true;
  21214. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ], _precision );
  21215. }
  21216. _lensFlare.attributes = {};
  21217. _lensFlare.uniforms = {};
  21218. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  21219. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  21220. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  21221. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  21222. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  21223. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  21224. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  21225. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  21226. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  21227. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  21228. };
  21229. /*
  21230. * Render lens flares
  21231. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  21232. * reads these back and calculates occlusion.
  21233. * Then _lensFlare.update_lensFlares() is called to re-position and
  21234. * update transparency of flares. Then they are rendered.
  21235. *
  21236. */
  21237. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21238. flares.length = 0;
  21239. scene.traverseVisible( function ( child ) {
  21240. if ( child instanceof THREE.LensFlare ) {
  21241. flares.push( child );
  21242. }
  21243. } );
  21244. if ( flares.length === 0 ) return;
  21245. var tempPosition = new THREE.Vector3();
  21246. var invAspect = viewportHeight / viewportWidth,
  21247. halfViewportWidth = viewportWidth * 0.5,
  21248. halfViewportHeight = viewportHeight * 0.5;
  21249. var size = 16 / viewportHeight,
  21250. scale = new THREE.Vector2( size * invAspect, size );
  21251. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  21252. screenPositionPixels = new THREE.Vector2( 1, 1 );
  21253. var uniforms = _lensFlare.uniforms,
  21254. attributes = _lensFlare.attributes;
  21255. // set _lensFlare program and reset blending
  21256. _gl.useProgram( _lensFlare.program );
  21257. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  21258. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  21259. // loop through all lens flares to update their occlusion and positions
  21260. // setup gl and common used attribs/unforms
  21261. _gl.uniform1i( uniforms.occlusionMap, 0 );
  21262. _gl.uniform1i( uniforms.map, 1 );
  21263. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21264. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21265. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21266. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21267. _gl.disable( _gl.CULL_FACE );
  21268. _gl.depthMask( false );
  21269. for ( var i = 0, l = flares.length; i < l; i ++ ) {
  21270. size = 16 / viewportHeight;
  21271. scale.set( size * invAspect, size );
  21272. // calc object screen position
  21273. var flare = flares[ i ];
  21274. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  21275. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  21276. tempPosition.applyProjection( camera.projectionMatrix );
  21277. // setup arrays for gl programs
  21278. screenPosition.copy( tempPosition )
  21279. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  21280. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  21281. // screen cull
  21282. if ( _lensFlare.hasVertexTexture || (
  21283. screenPositionPixels.x > 0 &&
  21284. screenPositionPixels.x < viewportWidth &&
  21285. screenPositionPixels.y > 0 &&
  21286. screenPositionPixels.y < viewportHeight ) ) {
  21287. // save current RGB to temp texture
  21288. _gl.activeTexture( _gl.TEXTURE1 );
  21289. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21290. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21291. // render pink quad
  21292. _gl.uniform1i( uniforms.renderType, 0 );
  21293. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21294. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21295. _gl.disable( _gl.BLEND );
  21296. _gl.enable( _gl.DEPTH_TEST );
  21297. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21298. // copy result to occlusionMap
  21299. _gl.activeTexture( _gl.TEXTURE0 );
  21300. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21301. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21302. // restore graphics
  21303. _gl.uniform1i( uniforms.renderType, 1 );
  21304. _gl.disable( _gl.DEPTH_TEST );
  21305. _gl.activeTexture( _gl.TEXTURE1 );
  21306. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21307. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21308. // update object positions
  21309. flare.positionScreen.copy( screenPosition )
  21310. if ( flare.customUpdateCallback ) {
  21311. flare.customUpdateCallback( flare );
  21312. } else {
  21313. flare.updateLensFlares();
  21314. }
  21315. // render flares
  21316. _gl.uniform1i( uniforms.renderType, 2 );
  21317. _gl.enable( _gl.BLEND );
  21318. for ( var j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  21319. var sprite = flare.lensFlares[ j ];
  21320. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  21321. screenPosition.x = sprite.x;
  21322. screenPosition.y = sprite.y;
  21323. screenPosition.z = sprite.z;
  21324. size = sprite.size * sprite.scale / viewportHeight;
  21325. scale.x = size * invAspect;
  21326. scale.y = size;
  21327. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21328. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21329. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21330. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  21331. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  21332. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  21333. _renderer.setTexture( sprite.texture, 1 );
  21334. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21335. }
  21336. }
  21337. }
  21338. }
  21339. // restore gl
  21340. _gl.enable( _gl.CULL_FACE );
  21341. _gl.enable( _gl.DEPTH_TEST );
  21342. _gl.depthMask( true );
  21343. };
  21344. function createProgram ( shader, precision ) {
  21345. var program = _gl.createProgram();
  21346. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21347. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21348. var prefix = "precision " + precision + " float;\n";
  21349. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  21350. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  21351. _gl.compileShader( fragmentShader );
  21352. _gl.compileShader( vertexShader );
  21353. _gl.attachShader( program, fragmentShader );
  21354. _gl.attachShader( program, vertexShader );
  21355. _gl.linkProgram( program );
  21356. return program;
  21357. };
  21358. };
  21359. // File:src/extras/renderers/plugins/ShadowMapPlugin.js
  21360. /**
  21361. * @author alteredq / http://alteredqualia.com/
  21362. */
  21363. THREE.ShadowMapPlugin = function () {
  21364. var _gl,
  21365. _renderer,
  21366. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21367. _frustum = new THREE.Frustum(),
  21368. _projScreenMatrix = new THREE.Matrix4(),
  21369. _min = new THREE.Vector3(),
  21370. _max = new THREE.Vector3(),
  21371. _matrixPosition = new THREE.Vector3(),
  21372. _renderList = [];
  21373. this.init = function ( renderer ) {
  21374. _gl = renderer.context;
  21375. _renderer = renderer;
  21376. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21377. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21378. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21379. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21380. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21381. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21382. _depthMaterial._shadowPass = true;
  21383. _depthMaterialMorph._shadowPass = true;
  21384. _depthMaterialSkin._shadowPass = true;
  21385. _depthMaterialMorphSkin._shadowPass = true;
  21386. };
  21387. this.render = function ( scene, camera ) {
  21388. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  21389. this.update( scene, camera );
  21390. };
  21391. this.update = function ( scene, camera ) {
  21392. var i, il, j, jl, n,
  21393. shadowMap, shadowMatrix, shadowCamera,
  21394. program, buffer, material,
  21395. webglObject, object, light,
  21396. lights = [],
  21397. k = 0,
  21398. fog = null;
  21399. // set GL state for depth map
  21400. _gl.clearColor( 1, 1, 1, 1 );
  21401. _gl.disable( _gl.BLEND );
  21402. _gl.enable( _gl.CULL_FACE );
  21403. _gl.frontFace( _gl.CCW );
  21404. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21405. _gl.cullFace( _gl.FRONT );
  21406. } else {
  21407. _gl.cullFace( _gl.BACK );
  21408. }
  21409. _renderer.setDepthTest( true );
  21410. // preprocess lights
  21411. // - skip lights that are not casting shadows
  21412. // - create virtual lights for cascaded shadow maps
  21413. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  21414. light = scene.__lights[ i ];
  21415. if ( ! light.castShadow ) continue;
  21416. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  21417. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  21418. var virtualLight;
  21419. if ( ! light.shadowCascadeArray[ n ] ) {
  21420. virtualLight = createVirtualLight( light, n );
  21421. virtualLight.originalCamera = camera;
  21422. var gyro = new THREE.Gyroscope();
  21423. gyro.position.copy( light.shadowCascadeOffset );
  21424. gyro.add( virtualLight );
  21425. gyro.add( virtualLight.target );
  21426. camera.add( gyro );
  21427. light.shadowCascadeArray[ n ] = virtualLight;
  21428. console.log( "Created virtualLight", virtualLight );
  21429. } else {
  21430. virtualLight = light.shadowCascadeArray[ n ];
  21431. }
  21432. updateVirtualLight( light, n );
  21433. lights[ k ] = virtualLight;
  21434. k ++;
  21435. }
  21436. } else {
  21437. lights[ k ] = light;
  21438. k ++;
  21439. }
  21440. }
  21441. // render depth map
  21442. for ( i = 0, il = lights.length; i < il; i ++ ) {
  21443. light = lights[ i ];
  21444. if ( ! light.shadowMap ) {
  21445. var shadowFilter = THREE.LinearFilter;
  21446. if ( _renderer.shadowMapType === THREE.PCFSoftShadowMap ) {
  21447. shadowFilter = THREE.NearestFilter;
  21448. }
  21449. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  21450. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  21451. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  21452. light.shadowMatrix = new THREE.Matrix4();
  21453. }
  21454. if ( ! light.shadowCamera ) {
  21455. if ( light instanceof THREE.SpotLight ) {
  21456. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  21457. } else if ( light instanceof THREE.DirectionalLight ) {
  21458. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  21459. } else {
  21460. console.error( "Unsupported light type for shadow" );
  21461. continue;
  21462. }
  21463. scene.add( light.shadowCamera );
  21464. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  21465. }
  21466. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  21467. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  21468. light.shadowCamera.add( light.cameraHelper );
  21469. }
  21470. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  21471. updateShadowCamera( camera, light );
  21472. }
  21473. shadowMap = light.shadowMap;
  21474. shadowMatrix = light.shadowMatrix;
  21475. shadowCamera = light.shadowCamera;
  21476. shadowCamera.position.setFromMatrixPosition( light.matrixWorld );
  21477. _matrixPosition.setFromMatrixPosition( light.target.matrixWorld );
  21478. shadowCamera.lookAt( _matrixPosition );
  21479. shadowCamera.updateMatrixWorld();
  21480. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  21481. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  21482. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  21483. // compute shadow matrix
  21484. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  21485. 0.0, 0.5, 0.0, 0.5,
  21486. 0.0, 0.0, 0.5, 0.5,
  21487. 0.0, 0.0, 0.0, 1.0 );
  21488. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  21489. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  21490. // update camera matrices and frustum
  21491. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  21492. _frustum.setFromMatrix( _projScreenMatrix );
  21493. // render shadow map
  21494. _renderer.setRenderTarget( shadowMap );
  21495. _renderer.clear();
  21496. // set object matrices & frustum culling
  21497. _renderList.length = 0;
  21498. projectObject(scene,scene,shadowCamera);
  21499. // render regular objects
  21500. var objectMaterial, useMorphing, useSkinning;
  21501. for ( j = 0, jl = _renderList.length; j < jl; j ++ ) {
  21502. webglObject = _renderList[ j ];
  21503. object = webglObject.object;
  21504. buffer = webglObject.buffer;
  21505. // culling is overriden globally for all objects
  21506. // while rendering depth map
  21507. // need to deal with MeshFaceMaterial somehow
  21508. // in that case just use the first of material.materials for now
  21509. // (proper solution would require to break objects by materials
  21510. // similarly to regular rendering and then set corresponding
  21511. // depth materials per each chunk instead of just once per object)
  21512. objectMaterial = getObjectMaterial( object );
  21513. useMorphing = object.geometry.morphTargets !== undefined && object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21514. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21515. if ( object.customDepthMaterial ) {
  21516. material = object.customDepthMaterial;
  21517. } else if ( useSkinning ) {
  21518. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21519. } else if ( useMorphing ) {
  21520. material = _depthMaterialMorph;
  21521. } else {
  21522. material = _depthMaterial;
  21523. }
  21524. _renderer.setMaterialFaces( objectMaterial );
  21525. if ( buffer instanceof THREE.BufferGeometry ) {
  21526. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  21527. } else {
  21528. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  21529. }
  21530. }
  21531. // set matrices and render immediate objects
  21532. var renderList = scene.__webglObjectsImmediate;
  21533. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21534. webglObject = renderList[ j ];
  21535. object = webglObject.object;
  21536. if ( object.visible && object.castShadow ) {
  21537. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21538. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  21539. }
  21540. }
  21541. }
  21542. // restore GL state
  21543. var clearColor = _renderer.getClearColor(),
  21544. clearAlpha = _renderer.getClearAlpha();
  21545. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21546. _gl.enable( _gl.BLEND );
  21547. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21548. _gl.cullFace( _gl.BACK );
  21549. }
  21550. };
  21551. function projectObject(scene, object,shadowCamera){
  21552. if ( object.visible ) {
  21553. var webglObjects = scene.__webglObjects[object.id];
  21554. if (webglObjects && object.castShadow && (object.frustumCulled === false || _frustum.intersectsObject( object ) === true) ) {
  21555. for (var i = 0, l = webglObjects.length; i < l; i++){
  21556. var webglObject = webglObjects[i];
  21557. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21558. _renderList.push(webglObject);
  21559. }
  21560. }
  21561. for(var i = 0, l = object.children.length; i < l; i++) {
  21562. projectObject(scene, object.children[i],shadowCamera);
  21563. }
  21564. }
  21565. }
  21566. function createVirtualLight( light, cascade ) {
  21567. var virtualLight = new THREE.DirectionalLight();
  21568. virtualLight.isVirtual = true;
  21569. virtualLight.onlyShadow = true;
  21570. virtualLight.castShadow = true;
  21571. virtualLight.shadowCameraNear = light.shadowCameraNear;
  21572. virtualLight.shadowCameraFar = light.shadowCameraFar;
  21573. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  21574. virtualLight.shadowCameraRight = light.shadowCameraRight;
  21575. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  21576. virtualLight.shadowCameraTop = light.shadowCameraTop;
  21577. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21578. virtualLight.shadowDarkness = light.shadowDarkness;
  21579. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21580. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  21581. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  21582. virtualLight.pointsWorld = [];
  21583. virtualLight.pointsFrustum = [];
  21584. var pointsWorld = virtualLight.pointsWorld,
  21585. pointsFrustum = virtualLight.pointsFrustum;
  21586. for ( var i = 0; i < 8; i ++ ) {
  21587. pointsWorld[ i ] = new THREE.Vector3();
  21588. pointsFrustum[ i ] = new THREE.Vector3();
  21589. }
  21590. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21591. var farZ = light.shadowCascadeFarZ[ cascade ];
  21592. pointsFrustum[ 0 ].set( - 1, - 1, nearZ );
  21593. pointsFrustum[ 1 ].set( 1, - 1, nearZ );
  21594. pointsFrustum[ 2 ].set( - 1, 1, nearZ );
  21595. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  21596. pointsFrustum[ 4 ].set( - 1, - 1, farZ );
  21597. pointsFrustum[ 5 ].set( 1, - 1, farZ );
  21598. pointsFrustum[ 6 ].set( - 1, 1, farZ );
  21599. pointsFrustum[ 7 ].set( 1, 1, farZ );
  21600. return virtualLight;
  21601. }
  21602. // Synchronize virtual light with the original light
  21603. function updateVirtualLight( light, cascade ) {
  21604. var virtualLight = light.shadowCascadeArray[ cascade ];
  21605. virtualLight.position.copy( light.position );
  21606. virtualLight.target.position.copy( light.target.position );
  21607. virtualLight.lookAt( virtualLight.target );
  21608. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21609. virtualLight.shadowDarkness = light.shadowDarkness;
  21610. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21611. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21612. var farZ = light.shadowCascadeFarZ[ cascade ];
  21613. var pointsFrustum = virtualLight.pointsFrustum;
  21614. pointsFrustum[ 0 ].z = nearZ;
  21615. pointsFrustum[ 1 ].z = nearZ;
  21616. pointsFrustum[ 2 ].z = nearZ;
  21617. pointsFrustum[ 3 ].z = nearZ;
  21618. pointsFrustum[ 4 ].z = farZ;
  21619. pointsFrustum[ 5 ].z = farZ;
  21620. pointsFrustum[ 6 ].z = farZ;
  21621. pointsFrustum[ 7 ].z = farZ;
  21622. }
  21623. // Fit shadow camera's ortho frustum to camera frustum
  21624. function updateShadowCamera( camera, light ) {
  21625. var shadowCamera = light.shadowCamera,
  21626. pointsFrustum = light.pointsFrustum,
  21627. pointsWorld = light.pointsWorld;
  21628. _min.set( Infinity, Infinity, Infinity );
  21629. _max.set( - Infinity, - Infinity, - Infinity );
  21630. for ( var i = 0; i < 8; i ++ ) {
  21631. var p = pointsWorld[ i ];
  21632. p.copy( pointsFrustum[ i ] );
  21633. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  21634. p.applyMatrix4( shadowCamera.matrixWorldInverse );
  21635. if ( p.x < _min.x ) _min.x = p.x;
  21636. if ( p.x > _max.x ) _max.x = p.x;
  21637. if ( p.y < _min.y ) _min.y = p.y;
  21638. if ( p.y > _max.y ) _max.y = p.y;
  21639. if ( p.z < _min.z ) _min.z = p.z;
  21640. if ( p.z > _max.z ) _max.z = p.z;
  21641. }
  21642. shadowCamera.left = _min.x;
  21643. shadowCamera.right = _max.x;
  21644. shadowCamera.top = _max.y;
  21645. shadowCamera.bottom = _min.y;
  21646. // can't really fit near/far
  21647. //shadowCamera.near = _min.z;
  21648. //shadowCamera.far = _max.z;
  21649. shadowCamera.updateProjectionMatrix();
  21650. }
  21651. // For the moment just ignore objects that have multiple materials with different animation methods
  21652. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  21653. function getObjectMaterial( object ) {
  21654. return object.material instanceof THREE.MeshFaceMaterial
  21655. ? object.material.materials[ 0 ]
  21656. : object.material;
  21657. };
  21658. };
  21659. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  21660. // File:src/extras/renderers/plugins/SpritePlugin.js
  21661. /**
  21662. * @author mikael emtinger / http://gomo.se/
  21663. * @author alteredq / http://alteredqualia.com/
  21664. */
  21665. THREE.SpritePlugin = function () {
  21666. var _gl, _renderer, _texture;
  21667. var sprites = [];
  21668. var vertices, faces, vertexBuffer, elementBuffer;
  21669. var program, attributes, uniforms;
  21670. this.init = function ( renderer ) {
  21671. _gl = renderer.context;
  21672. _renderer = renderer;
  21673. vertices = new Float32Array( [
  21674. - 0.5, - 0.5, 0, 0,
  21675. 0.5, - 0.5, 1, 0,
  21676. 0.5, 0.5, 1, 1,
  21677. - 0.5, 0.5, 0, 1
  21678. ] );
  21679. faces = new Uint16Array( [
  21680. 0, 1, 2,
  21681. 0, 2, 3
  21682. ] );
  21683. vertexBuffer = _gl.createBuffer();
  21684. elementBuffer = _gl.createBuffer();
  21685. _gl.bindBuffer( _gl.ARRAY_BUFFER, vertexBuffer );
  21686. _gl.bufferData( _gl.ARRAY_BUFFER, vertices, _gl.STATIC_DRAW );
  21687. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  21688. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faces, _gl.STATIC_DRAW );
  21689. program = createProgram();
  21690. attributes = {
  21691. position: _gl.getAttribLocation ( program, 'position' ),
  21692. uv: _gl.getAttribLocation ( program, 'uv' )
  21693. };
  21694. uniforms = {
  21695. uvOffset: _gl.getUniformLocation( program, 'uvOffset' ),
  21696. uvScale: _gl.getUniformLocation( program, 'uvScale' ),
  21697. rotation: _gl.getUniformLocation( program, 'rotation' ),
  21698. scale: _gl.getUniformLocation( program, 'scale' ),
  21699. color: _gl.getUniformLocation( program, 'color' ),
  21700. map: _gl.getUniformLocation( program, 'map' ),
  21701. opacity: _gl.getUniformLocation( program, 'opacity' ),
  21702. modelViewMatrix: _gl.getUniformLocation( program, 'modelViewMatrix' ),
  21703. projectionMatrix: _gl.getUniformLocation( program, 'projectionMatrix' ),
  21704. fogType: _gl.getUniformLocation( program, 'fogType' ),
  21705. fogDensity: _gl.getUniformLocation( program, 'fogDensity' ),
  21706. fogNear: _gl.getUniformLocation( program, 'fogNear' ),
  21707. fogFar: _gl.getUniformLocation( program, 'fogFar' ),
  21708. fogColor: _gl.getUniformLocation( program, 'fogColor' ),
  21709. alphaTest: _gl.getUniformLocation( program, 'alphaTest' )
  21710. };
  21711. var canvas = document.createElement( 'canvas' );
  21712. canvas.width = 8;
  21713. canvas.height = 8;
  21714. var context = canvas.getContext( '2d' );
  21715. context.fillStyle = 'white';
  21716. context.fillRect( 0, 0, 8, 8 );
  21717. _texture = new THREE.Texture( canvas );
  21718. _texture.needsUpdate = true;
  21719. };
  21720. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21721. sprites.length = 0;
  21722. scene.traverseVisible( function ( child ) {
  21723. if ( child instanceof THREE.Sprite ) {
  21724. sprites.push( child );
  21725. }
  21726. } );
  21727. if ( sprites.length === 0 ) return;
  21728. // setup gl
  21729. _gl.useProgram( program );
  21730. _gl.enableVertexAttribArray( attributes.position );
  21731. _gl.enableVertexAttribArray( attributes.uv );
  21732. _gl.disable( _gl.CULL_FACE );
  21733. _gl.enable( _gl.BLEND );
  21734. _gl.bindBuffer( _gl.ARRAY_BUFFER, vertexBuffer );
  21735. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21736. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21737. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  21738. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  21739. _gl.activeTexture( _gl.TEXTURE0 );
  21740. _gl.uniform1i( uniforms.map, 0 );
  21741. var oldFogType = 0;
  21742. var sceneFogType = 0;
  21743. var fog = scene.fog;
  21744. if ( fog ) {
  21745. _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  21746. if ( fog instanceof THREE.Fog ) {
  21747. _gl.uniform1f( uniforms.fogNear, fog.near );
  21748. _gl.uniform1f( uniforms.fogFar, fog.far );
  21749. _gl.uniform1i( uniforms.fogType, 1 );
  21750. oldFogType = 1;
  21751. sceneFogType = 1;
  21752. } else if ( fog instanceof THREE.FogExp2 ) {
  21753. _gl.uniform1f( uniforms.fogDensity, fog.density );
  21754. _gl.uniform1i( uniforms.fogType, 2 );
  21755. oldFogType = 2;
  21756. sceneFogType = 2;
  21757. }
  21758. } else {
  21759. _gl.uniform1i( uniforms.fogType, 0 );
  21760. oldFogType = 0;
  21761. sceneFogType = 0;
  21762. }
  21763. // update positions and sort
  21764. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  21765. var sprite = sprites[ i ];
  21766. var material = sprite.material;
  21767. sprite._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  21768. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  21769. }
  21770. sprites.sort( painterSortStable );
  21771. // render all sprites
  21772. var scale = [];
  21773. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  21774. var sprite = sprites[ i ];
  21775. var material = sprite.material;
  21776. _gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  21777. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  21778. scale[ 0 ] = sprite.scale.x;
  21779. scale[ 1 ] = sprite.scale.y;
  21780. var fogType = 0;
  21781. if ( scene.fog && material.fog ) {
  21782. fogType = sceneFogType;
  21783. }
  21784. if ( oldFogType !== fogType ) {
  21785. _gl.uniform1i( uniforms.fogType, fogType );
  21786. oldFogType = fogType;
  21787. }
  21788. if ( material.map !== null ) {
  21789. _gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y );
  21790. _gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y );
  21791. } else {
  21792. _gl.uniform2f( uniforms.uvOffset, 0, 0 );
  21793. _gl.uniform2f( uniforms.uvScale, 1, 1 );
  21794. }
  21795. _gl.uniform1f( uniforms.opacity, material.opacity );
  21796. _gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  21797. _gl.uniform1f( uniforms.rotation, material.rotation );
  21798. _gl.uniform2fv( uniforms.scale, scale );
  21799. _renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  21800. _renderer.setDepthTest( material.depthTest );
  21801. _renderer.setDepthWrite( material.depthWrite );
  21802. if ( material.map && material.map.image && material.map.image.width ) {
  21803. _renderer.setTexture( material.map, 0 );
  21804. } else {
  21805. _renderer.setTexture( _texture, 0 );
  21806. }
  21807. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21808. }
  21809. // restore gl
  21810. _gl.enable( _gl.CULL_FACE );
  21811. };
  21812. function createProgram () {
  21813. var program = _gl.createProgram();
  21814. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21815. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21816. _gl.shaderSource( vertexShader, [
  21817. 'precision ' + _renderer.getPrecision() + ' float;',
  21818. 'uniform mat4 modelViewMatrix;',
  21819. 'uniform mat4 projectionMatrix;',
  21820. 'uniform float rotation;',
  21821. 'uniform vec2 scale;',
  21822. 'uniform vec2 uvOffset;',
  21823. 'uniform vec2 uvScale;',
  21824. 'attribute vec2 position;',
  21825. 'attribute vec2 uv;',
  21826. 'varying vec2 vUV;',
  21827. 'void main() {',
  21828. 'vUV = uvOffset + uv * uvScale;',
  21829. 'vec2 alignedPosition = position * scale;',
  21830. 'vec2 rotatedPosition;',
  21831. 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  21832. 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  21833. 'vec4 finalPosition;',
  21834. 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  21835. 'finalPosition.xy += rotatedPosition;',
  21836. 'finalPosition = projectionMatrix * finalPosition;',
  21837. 'gl_Position = finalPosition;',
  21838. '}'
  21839. ].join( '\n' ) );
  21840. _gl.shaderSource( fragmentShader, [
  21841. 'precision ' + _renderer.getPrecision() + ' float;',
  21842. 'uniform vec3 color;',
  21843. 'uniform sampler2D map;',
  21844. 'uniform float opacity;',
  21845. 'uniform int fogType;',
  21846. 'uniform vec3 fogColor;',
  21847. 'uniform float fogDensity;',
  21848. 'uniform float fogNear;',
  21849. 'uniform float fogFar;',
  21850. 'uniform float alphaTest;',
  21851. 'varying vec2 vUV;',
  21852. 'void main() {',
  21853. 'vec4 texture = texture2D( map, vUV );',
  21854. 'if ( texture.a < alphaTest ) discard;',
  21855. 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  21856. 'if ( fogType > 0 ) {',
  21857. 'float depth = gl_FragCoord.z / gl_FragCoord.w;',
  21858. 'float fogFactor = 0.0;',
  21859. 'if ( fogType == 1 ) {',
  21860. 'fogFactor = smoothstep( fogNear, fogFar, depth );',
  21861. '} else {',
  21862. 'const float LOG2 = 1.442695;',
  21863. 'float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );',
  21864. 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  21865. '}',
  21866. 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );',
  21867. '}',
  21868. '}'
  21869. ].join( '\n' ) );
  21870. _gl.compileShader( vertexShader );
  21871. _gl.compileShader( fragmentShader );
  21872. _gl.attachShader( program, vertexShader );
  21873. _gl.attachShader( program, fragmentShader );
  21874. _gl.linkProgram( program );
  21875. return program;
  21876. };
  21877. function painterSortStable ( a, b ) {
  21878. if ( a.z !== b.z ) {
  21879. return b.z - a.z;
  21880. } else {
  21881. return b.id - a.id;
  21882. }
  21883. };
  21884. };
  21885. // File:src/extras/renderers/plugins/DepthPassPlugin.js
  21886. /**
  21887. * @author alteredq / http://alteredqualia.com/
  21888. */
  21889. THREE.DepthPassPlugin = function () {
  21890. this.enabled = false;
  21891. this.renderTarget = null;
  21892. var _gl,
  21893. _renderer,
  21894. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21895. _frustum = new THREE.Frustum(),
  21896. _projScreenMatrix = new THREE.Matrix4(),
  21897. _renderList = [];
  21898. this.init = function ( renderer ) {
  21899. _gl = renderer.context;
  21900. _renderer = renderer;
  21901. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21902. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21903. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21904. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21905. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21906. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21907. _depthMaterial._shadowPass = true;
  21908. _depthMaterialMorph._shadowPass = true;
  21909. _depthMaterialSkin._shadowPass = true;
  21910. _depthMaterialMorphSkin._shadowPass = true;
  21911. };
  21912. this.render = function ( scene, camera ) {
  21913. if ( ! this.enabled ) return;
  21914. this.update( scene, camera );
  21915. };
  21916. this.update = function ( scene, camera ) {
  21917. var i, il, j, jl, n,
  21918. program, buffer, material,
  21919. webglObject, object, light,
  21920. renderList,
  21921. fog = null;
  21922. // set GL state for depth map
  21923. _gl.clearColor( 1, 1, 1, 1 );
  21924. _gl.disable( _gl.BLEND );
  21925. _renderer.setDepthTest( true );
  21926. // update scene
  21927. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  21928. // update camera matrices and frustum
  21929. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  21930. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  21931. _frustum.setFromMatrix( _projScreenMatrix );
  21932. // render depth map
  21933. _renderer.setRenderTarget( this.renderTarget );
  21934. _renderer.clear();
  21935. // set object matrices & frustum culling
  21936. _renderList.length = 0;
  21937. projectObject(scene,scene,camera);
  21938. // render regular objects
  21939. var objectMaterial, useMorphing, useSkinning;
  21940. for ( j = 0, jl = _renderList.length; j < jl; j ++ ) {
  21941. webglObject = _renderList[ j ];
  21942. object = webglObject.object;
  21943. buffer = webglObject.buffer;
  21944. // todo: create proper depth material for particles
  21945. if ( object instanceof THREE.PointCloud && ! object.customDepthMaterial ) continue;
  21946. objectMaterial = getObjectMaterial( object );
  21947. if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
  21948. useMorphing = object.geometry.morphTargets !== undefined && object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21949. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21950. if ( object.customDepthMaterial ) {
  21951. material = object.customDepthMaterial;
  21952. } else if ( useSkinning ) {
  21953. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21954. } else if ( useMorphing ) {
  21955. material = _depthMaterialMorph;
  21956. } else {
  21957. material = _depthMaterial;
  21958. }
  21959. if ( buffer instanceof THREE.BufferGeometry ) {
  21960. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  21961. } else {
  21962. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  21963. }
  21964. }
  21965. // set matrices and render immediate objects
  21966. renderList = scene.__webglObjectsImmediate;
  21967. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21968. webglObject = renderList[ j ];
  21969. object = webglObject.object;
  21970. if ( object.visible ) {
  21971. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  21972. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  21973. }
  21974. }
  21975. // restore GL state
  21976. var clearColor = _renderer.getClearColor(),
  21977. clearAlpha = _renderer.getClearAlpha();
  21978. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21979. _gl.enable( _gl.BLEND );
  21980. };
  21981. function projectObject(scene, object,camera){
  21982. if ( object.visible ) {
  21983. var webglObjects = scene.__webglObjects[object.id];
  21984. if (webglObjects && (object.frustumCulled === false || _frustum.intersectsObject( object ) === true) ) {
  21985. for (var i = 0, l = webglObjects.length; i < l; i++){
  21986. var webglObject = webglObjects[i];
  21987. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  21988. _renderList.push(webglObject);
  21989. }
  21990. }
  21991. for(var i = 0, l = object.children.length; i < l; i++) {
  21992. projectObject(scene, object.children[i], camera);
  21993. }
  21994. }
  21995. }
  21996. // For the moment just ignore objects that have multiple materials with different animation methods
  21997. // Only the first material will be taken into account for deciding which depth material to use
  21998. function getObjectMaterial( object ) {
  21999. return object.material instanceof THREE.MeshFaceMaterial
  22000. ? object.material.materials[ 0 ]
  22001. : object.material;
  22002. };
  22003. };
  22004. // File:src/extras/shaders/ShaderFlares.js
  22005. /**
  22006. * @author mikael emtinger / http://gomo.se/
  22007. */
  22008. THREE.ShaderFlares = {
  22009. 'lensFlareVertexTexture': {
  22010. vertexShader: [
  22011. "uniform lowp int renderType;",
  22012. "uniform vec3 screenPosition;",
  22013. "uniform vec2 scale;",
  22014. "uniform float rotation;",
  22015. "uniform sampler2D occlusionMap;",
  22016. "attribute vec2 position;",
  22017. "attribute vec2 uv;",
  22018. "varying vec2 vUV;",
  22019. "varying float vVisibility;",
  22020. "void main() {",
  22021. "vUV = uv;",
  22022. "vec2 pos = position;",
  22023. "if( renderType == 2 ) {",
  22024. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  22025. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  22026. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  22027. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  22028. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  22029. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  22030. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  22031. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  22032. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  22033. "vVisibility = visibility.r / 9.0;",
  22034. "vVisibility *= 1.0 - visibility.g / 9.0;",
  22035. "vVisibility *= visibility.b / 9.0;",
  22036. "vVisibility *= 1.0 - visibility.a / 9.0;",
  22037. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  22038. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  22039. "}",
  22040. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  22041. "}"
  22042. ].join( "\n" ),
  22043. fragmentShader: [
  22044. "uniform lowp int renderType;",
  22045. "uniform sampler2D map;",
  22046. "uniform float opacity;",
  22047. "uniform vec3 color;",
  22048. "varying vec2 vUV;",
  22049. "varying float vVisibility;",
  22050. "void main() {",
  22051. // pink square
  22052. "if( renderType == 0 ) {",
  22053. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  22054. // restore
  22055. "} else if( renderType == 1 ) {",
  22056. "gl_FragColor = texture2D( map, vUV );",
  22057. // flare
  22058. "} else {",
  22059. "vec4 texture = texture2D( map, vUV );",
  22060. "texture.a *= opacity * vVisibility;",
  22061. "gl_FragColor = texture;",
  22062. "gl_FragColor.rgb *= color;",
  22063. "}",
  22064. "}"
  22065. ].join( "\n" )
  22066. },
  22067. 'lensFlare': {
  22068. vertexShader: [
  22069. "uniform lowp int renderType;",
  22070. "uniform vec3 screenPosition;",
  22071. "uniform vec2 scale;",
  22072. "uniform float rotation;",
  22073. "attribute vec2 position;",
  22074. "attribute vec2 uv;",
  22075. "varying vec2 vUV;",
  22076. "void main() {",
  22077. "vUV = uv;",
  22078. "vec2 pos = position;",
  22079. "if( renderType == 2 ) {",
  22080. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  22081. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  22082. "}",
  22083. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  22084. "}"
  22085. ].join( "\n" ),
  22086. fragmentShader: [
  22087. "precision mediump float;",
  22088. "uniform lowp int renderType;",
  22089. "uniform sampler2D map;",
  22090. "uniform sampler2D occlusionMap;",
  22091. "uniform float opacity;",
  22092. "uniform vec3 color;",
  22093. "varying vec2 vUV;",
  22094. "void main() {",
  22095. // pink square
  22096. "if( renderType == 0 ) {",
  22097. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  22098. // restore
  22099. "} else if( renderType == 1 ) {",
  22100. "gl_FragColor = texture2D( map, vUV );",
  22101. // flare
  22102. "} else {",
  22103. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a;",
  22104. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a;",
  22105. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a;",
  22106. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  22107. "visibility = ( 1.0 - visibility / 4.0 );",
  22108. "vec4 texture = texture2D( map, vUV );",
  22109. "texture.a *= opacity * visibility;",
  22110. "gl_FragColor = texture;",
  22111. "gl_FragColor.rgb *= color;",
  22112. "}",
  22113. "}"
  22114. ].join( "\n" )
  22115. }
  22116. };